@beamimpact/web-sdk 1.45.3 → 1.46.0

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 (184) hide show
  1. package/dist/chunks/_share-dialog-dependencies--DwhY4w7.esm.js +2 -0
  2. package/dist/chunks/_share-dialog-dependencies--DwhY4w7.esm.js.map +1 -0
  3. package/dist/chunks/_share-dialog-dependencies-XEpMl5XM.esm.js +2 -0
  4. package/dist/chunks/_share-dialog-dependencies-XEpMl5XM.esm.js.map +1 -0
  5. package/dist/chunks/{cart-contents-HAPzwbeL.esm.d.ts → cart-contents-MrYQNVDx.esm.d.ts} +1 -1
  6. package/dist/chunks/{events-fqRWfo7p.esm.d.ts → events--Qgk7Mel.esm.d.ts} +1 -1
  7. package/dist/chunks/{index-IujuLxUV.esm.js → index-2sMT9J8K.esm.js} +2 -2
  8. package/dist/chunks/{index-IujuLxUV.esm.js.map → index-2sMT9J8K.esm.js.map} +1 -1
  9. package/dist/chunks/index-4kINfIHU.esm.js +2 -0
  10. package/dist/chunks/index-4kINfIHU.esm.js.map +1 -0
  11. package/dist/chunks/{index-MSoONvC5.esm.d.ts → index-8gDNc2to.esm.d.ts} +1 -1
  12. package/dist/chunks/index-COmf0U0P.esm.js +2 -0
  13. package/dist/chunks/index-COmf0U0P.esm.js.map +1 -0
  14. package/dist/chunks/{index-XN6JUoCQ.esm.js → index-Fmt8u1QB.esm.js} +2 -2
  15. package/dist/chunks/{index-XN6JUoCQ.esm.js.map → index-Fmt8u1QB.esm.js.map} +1 -1
  16. package/dist/chunks/index-H8fABpZF.esm.js +2 -0
  17. package/dist/chunks/index-H8fABpZF.esm.js.map +1 -0
  18. package/dist/chunks/index-HzqAV0Ls.esm.js +2 -0
  19. package/dist/chunks/index-HzqAV0Ls.esm.js.map +1 -0
  20. package/dist/chunks/{index-qt5iD9Ok.esm.d.ts → index-Ie9en2n6.esm.d.ts} +1 -1
  21. package/dist/chunks/{index-SExnliMs.esm.d.ts → index-S_lCvtkH.esm.d.ts} +1 -1
  22. package/dist/chunks/{index-JG4nmG9U.esm.d.ts → index-gQHtJWVP.esm.d.ts} +1 -1
  23. package/dist/chunks/{index-tdUx2WLc.esm.d.ts → index-ikzViFqS.esm.d.ts} +4 -4
  24. package/dist/chunks/{index-7mukhxz_.esm.d.ts → index-wqLh9Pnq.esm.d.ts} +1 -1
  25. package/dist/chunks/index-y4dGW0m2.esm.js +2 -0
  26. package/dist/chunks/index-y4dGW0m2.esm.js.map +1 -0
  27. package/dist/chunks/index-yhi0tTdC.esm.js +2 -0
  28. package/dist/chunks/index-yhi0tTdC.esm.js.map +1 -0
  29. package/dist/chunks/localize-m-_ESmpk.esm.js.map +1 -1
  30. package/dist/chunks/localize-o-cYvHQf.esm.js.map +1 -1
  31. package/dist/chunks/{openapi-spec-RlP2IT1i.esm.d.ts → openapi-spec--os_utEo.esm.d.ts} +55 -1
  32. package/dist/chunks/{order-page-Qptp0Cgw.esm.js → order-page--Xn2Rb6J.esm.js} +2 -2
  33. package/dist/chunks/{order-page-Qptp0Cgw.esm.js.map → order-page--Xn2Rb6J.esm.js.map} +1 -1
  34. package/dist/chunks/{order-page-FLhpaZg2.esm.d.ts → order-page-GwRa273v.esm.d.ts} +3 -3
  35. package/dist/chunks/{order-page-fVZWjxXw.esm.js → order-page-uEOo5EPy.esm.js} +2 -2
  36. package/dist/chunks/{order-page-fVZWjxXw.esm.js.map → order-page-uEOo5EPy.esm.js.map} +1 -1
  37. package/dist/chunks/{promo-pill-label-58PJRvSl.esm.js → promo-pill-label-P1X4xeAx.esm.js} +4 -3
  38. package/dist/chunks/promo-pill-label-P1X4xeAx.esm.js.map +1 -0
  39. package/dist/chunks/{routes-kK10CmJz.esm.js → routes-F1ZIumMP.esm.js} +2 -2
  40. package/dist/chunks/{routes-kK10CmJz.esm.js.map → routes-F1ZIumMP.esm.js.map} +1 -1
  41. package/dist/chunks/{routes-NIuAzAOC.esm.d.ts → routes-iurI6dvR.esm.d.ts} +71 -1
  42. package/dist/chunks/{routes-4z90Ks28.esm.js → routes-sQWfbAoi.esm.js} +2 -2
  43. package/dist/chunks/{routes-4z90Ks28.esm.js.map → routes-sQWfbAoi.esm.js.map} +1 -1
  44. package/dist/chunks/{share-button-RG2BkqMA.esm.js → share-button-2RaDSzSs.esm.js} +3 -4
  45. package/dist/chunks/{share-button-RG2BkqMA.esm.js.map → share-button-2RaDSzSs.esm.js.map} +1 -1
  46. package/dist/chunks/{share-button-K_FE0-s2.esm.js → share-button-_QWVlCcB.esm.js} +3 -4
  47. package/dist/chunks/{share-button-K_FE0-s2.esm.js.map → share-button-_QWVlCcB.esm.js.map} +1 -1
  48. package/dist/chunks/{shoelace-components-522x2Yt1.esm.js → shoelace-components-9s7uTeO6.esm.js} +2 -2
  49. package/dist/chunks/{shoelace-components-522x2Yt1.esm.js.map → shoelace-components-9s7uTeO6.esm.js.map} +1 -1
  50. package/dist/chunks/{shoelace-components-59LxBr67.esm.js → shoelace-components-tjFhbEiI.esm.js} +2 -2
  51. package/dist/chunks/{shoelace-components-59LxBr67.esm.js.map → shoelace-components-tjFhbEiI.esm.js.map} +1 -1
  52. package/dist/chunks/{update-cart-Hebtxhto.esm.d.ts → update-cart-KjKc8Cls.esm.d.ts} +1 -1
  53. package/dist/chunks/{update-cart-BcLkAJSc.esm.js → update-cart-T7h4g2nt.esm.js} +2 -2
  54. package/dist/chunks/{update-cart-BcLkAJSc.esm.js.map → update-cart-T7h4g2nt.esm.js.map} +1 -1
  55. package/dist/chunks/{update-cart-eodNhDjI.esm.js → update-cart-WyIeEybK.esm.js} +2 -2
  56. package/dist/chunks/{update-cart-eodNhDjI.esm.js.map → update-cart-WyIeEybK.esm.js.map} +1 -1
  57. package/dist/components/community-impact.esm.js +1 -1
  58. package/dist/components/community-impact.js +1 -1
  59. package/dist/components/cumulative-impact.esm.js +1 -1
  60. package/dist/components/cumulative-impact.esm.js.map +1 -1
  61. package/dist/components/cumulative-impact.js +1 -1
  62. package/dist/components/cumulative-impact.js.map +1 -1
  63. package/dist/components/impact-overview.d.ts +5 -1
  64. package/dist/components/impact-overview.esm.js +31 -25
  65. package/dist/components/impact-overview.esm.js.map +1 -1
  66. package/dist/components/impact-overview.js +31 -25
  67. package/dist/components/impact-overview.js.map +1 -1
  68. package/dist/components/index.d.ts +3 -3
  69. package/dist/components/index.esm.js +1 -1
  70. package/dist/components/index.js +1 -1
  71. package/dist/components/post-purchase.d.ts +5 -3
  72. package/dist/components/post-purchase.esm.js +1 -1
  73. package/dist/components/post-purchase.js +1 -1
  74. package/dist/components/product-details-page.d.ts +7 -2
  75. package/dist/components/product-details-page.esm.js +106 -33
  76. package/dist/components/product-details-page.esm.js.map +1 -1
  77. package/dist/components/product-details-page.js +106 -33
  78. package/dist/components/product-details-page.js.map +1 -1
  79. package/dist/components/redeem-transaction.d.ts +3 -3
  80. package/dist/components/redeem-transaction.esm.js +2 -2
  81. package/dist/components/redeem-transaction.esm.js.map +1 -1
  82. package/dist/components/redeem-transaction.js +2 -2
  83. package/dist/components/redeem-transaction.js.map +1 -1
  84. package/dist/components/select-nonprofit.d.ts +3 -3
  85. package/dist/components/select-nonprofit.esm.js +4 -4
  86. package/dist/components/select-nonprofit.esm.js.map +1 -1
  87. package/dist/components/select-nonprofit.js +4 -4
  88. package/dist/components/select-nonprofit.js.map +1 -1
  89. package/dist/components/select-subscription-nonprofit.d.ts +1 -1
  90. package/dist/components/select-subscription-nonprofit.esm.js +6 -4
  91. package/dist/components/select-subscription-nonprofit.esm.js.map +1 -1
  92. package/dist/components/select-subscription-nonprofit.js +6 -4
  93. package/dist/components/select-subscription-nonprofit.js.map +1 -1
  94. package/dist/components/shopify.d.ts +6 -6
  95. package/dist/components/shopify.esm.js +1 -1
  96. package/dist/components/shopify.js +1 -1
  97. package/dist/components/social-share.esm.js +1 -1
  98. package/dist/components/social-share.js +1 -1
  99. package/dist/components/subscription-impact.d.ts +3 -1
  100. package/dist/components/subscription-impact.esm.js +1 -1
  101. package/dist/components/subscription-impact.js +1 -1
  102. package/dist/components/subscription-management.d.ts +7 -4
  103. package/dist/components/subscription-management.esm.js +10 -10
  104. package/dist/components/subscription-management.esm.js.map +1 -1
  105. package/dist/components/subscription-management.js +10 -10
  106. package/dist/components/subscription-management.js.map +1 -1
  107. package/dist/index.d.ts +12 -12
  108. package/dist/index.esm.js +1 -1
  109. package/dist/index.js +1 -1
  110. package/dist/integrations/beam.esm.js +1 -1
  111. package/dist/integrations/beam.js +1 -1
  112. package/dist/integrations/cart.d.ts +3 -3
  113. package/dist/integrations/cart.esm.js +1 -1
  114. package/dist/integrations/cart.js +1 -1
  115. package/dist/integrations/index.d.ts +10 -10
  116. package/dist/integrations/index.esm.js +1 -1
  117. package/dist/integrations/index.js +1 -1
  118. package/dist/integrations/logs.d.ts +2 -2
  119. package/dist/integrations/logs.esm.js +1 -1
  120. package/dist/integrations/logs.js +1 -1
  121. package/dist/integrations/shopify.d.ts +5 -5
  122. package/dist/integrations/shopify.esm.js +1 -1
  123. package/dist/integrations/shopify.js +1 -1
  124. package/dist/integrations/statsig.d.ts +3 -0
  125. package/dist/integrations/statsig.esm.js +3 -3
  126. package/dist/integrations/statsig.esm.js.map +1 -1
  127. package/dist/integrations/statsig.js +3 -3
  128. package/dist/integrations/statsig.js.map +1 -1
  129. package/dist/integrations/utils.d.ts +3 -3
  130. package/dist/react/community-impact.esm.js +1 -1
  131. package/dist/react/community-impact.js +1 -1
  132. package/dist/react/cumulative-impact.esm.js +1 -1
  133. package/dist/react/cumulative-impact.js +1 -1
  134. package/dist/react/impact-overview.esm.js +1 -1
  135. package/dist/react/impact-overview.js +1 -1
  136. package/dist/react/index.d.ts +4 -4
  137. package/dist/react/index.esm.js +1 -1
  138. package/dist/react/index.js +1 -1
  139. package/dist/react/post-purchase.d.ts +2 -2
  140. package/dist/react/post-purchase.esm.js +1 -1
  141. package/dist/react/post-purchase.js +1 -1
  142. package/dist/react/product-details-page.d.ts +2 -0
  143. package/dist/react/product-details-page.esm.js +1 -1
  144. package/dist/react/product-details-page.esm.js.map +1 -1
  145. package/dist/react/product-details-page.js +1 -1
  146. package/dist/react/product-details-page.js.map +1 -1
  147. package/dist/react/redeem-transaction.d.ts +3 -3
  148. package/dist/react/redeem-transaction.esm.js +1 -1
  149. package/dist/react/redeem-transaction.js +1 -1
  150. package/dist/react/select-nonprofit.d.ts +3 -3
  151. package/dist/react/select-nonprofit.esm.js +1 -1
  152. package/dist/react/select-nonprofit.js +1 -1
  153. package/dist/react/select-subscription-nonprofit.d.ts +3 -3
  154. package/dist/react/select-subscription-nonprofit.esm.js +1 -1
  155. package/dist/react/select-subscription-nonprofit.js +1 -1
  156. package/dist/react/social-share.esm.js +1 -1
  157. package/dist/react/social-share.js +1 -1
  158. package/dist/react/subscription-impact.esm.js +1 -1
  159. package/dist/react/subscription-impact.js +1 -1
  160. package/dist/react/subscription-management.d.ts +3 -3
  161. package/dist/react/subscription-management.esm.js +1 -1
  162. package/dist/react/subscription-management.js +1 -1
  163. package/dist/utils/events.d.ts +3 -3
  164. package/dist/utils/index.d.ts +3 -3
  165. package/dist/utils/local-storage.esm.js.map +1 -1
  166. package/dist/utils/local-storage.js.map +1 -1
  167. package/package.json +1 -1
  168. package/dist/chunks/_share-dialog-dependencies-FXJR0ESq.esm.js +0 -2
  169. package/dist/chunks/_share-dialog-dependencies-FXJR0ESq.esm.js.map +0 -1
  170. package/dist/chunks/_share-dialog-dependencies-VM-oSkel.esm.js +0 -2
  171. package/dist/chunks/_share-dialog-dependencies-VM-oSkel.esm.js.map +0 -1
  172. package/dist/chunks/index-4Fvcu3-v.esm.js +0 -2
  173. package/dist/chunks/index-4Fvcu3-v.esm.js.map +0 -1
  174. package/dist/chunks/index-KQ5XYf5e.esm.js +0 -2
  175. package/dist/chunks/index-KQ5XYf5e.esm.js.map +0 -1
  176. package/dist/chunks/index-Uos3T3K9.esm.js +0 -2
  177. package/dist/chunks/index-Uos3T3K9.esm.js.map +0 -1
  178. package/dist/chunks/index-WibiKAEy.esm.js +0 -2
  179. package/dist/chunks/index-WibiKAEy.esm.js.map +0 -1
  180. package/dist/chunks/index-qOqcMZym.esm.js +0 -2
  181. package/dist/chunks/index-qOqcMZym.esm.js.map +0 -1
  182. package/dist/chunks/index-xJ0ZfjZW.esm.js +0 -2
  183. package/dist/chunks/index-xJ0ZfjZW.esm.js.map +0 -1
  184. package/dist/chunks/promo-pill-label-58PJRvSl.esm.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"order-page-Qptp0Cgw.esm.js","sources":["../../src/integrations/shopify/cart-page.ts","../../src/integrations/shopify/order-page.ts"],"sourcesContent":["/* eslint-disable camelcase */\nimport isEqual from \"lodash-es/isEqual\";\nimport { logger, memoizeLast } from \"../../utils\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { initNetworkListeners } from \"../../utils/network-listeners\";\nimport {\n BeamCartChangeEvent,\n BeamNetworkCallEvent,\n BeamNonprofitSelectEvent,\n BeamNonprofitSelectionRemovedEvent,\n} from \"../../utils/events\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { BEAM_CART_COOKIE_NAME, TBeamCartLocalStorage, TCart, TCartApi, TCartItems } from \"../../shared/cart-contents\";\nimport { BeamCartAPIConfig, updateCart } from \"../cart\";\nimport { WIDGET_NAMES } from \"../../api-sdk/constants\";\nimport { getBeamCartId, getExternalCartId } from \"../../utils/cart\";\n\nexport type BeamShopifyCartIntegrationConfig = BeamCartAPIConfig & {\n storeId: number; // will be added to cart custom_attributes, and used in cart API call\n chainId?: number; // will be added to cart custom_attributes\n};\n\ntype ShopifyDiscountApplication = {\n title: string;\n value: string;\n};\n\ntype ShopifyLineLevelDiscountAllocations = {\n amount?: string;\n discount_application: ShopifyDiscountApplication;\n};\n\nconst SHOPIFY_BASE_URL = window.Shopify?.routes?.root || \"/\"; // see window.d.ts\n\nlet isBeamCartIntegrationRegistered = false; // Skip registering event listeners if already set up\n\nconst SHOPIFY_CART_COOKIE_NAME = \"cart\";\n\n/**\n * @main registerCartIntegration - set up event listeners to integrate Beam with Shopify cart\n * @return {boolean} returns true if NEW listeners were created, false if setup was already done\n */\nasync function registerCartIntegration(config: BeamShopifyCartIntegrationConfig) {\n if (isBeamCartIntegrationRegistered) {\n return false; // Do nothing if listeners are already attached\n }\n\n // Handle full-page load, ie, first-time page load and reloads from form submit events\n // This creates a GET to /cart.js\n const currentCart = await getCurrentCart(config);\n const cartCookie = getCookieValue(SHOPIFY_CART_COOKIE_NAME);\n // only update on initial load if Shopify cart has changed since last visit\n if (currentCart.cart.cartId !== cartCookie) {\n await updateCart(config, currentCart.cart);\n }\n // pre load beam cart attribute to save statsig info\n await addBeamAttributesToCart({});\n // Set up event listeners for AJAX events\n initNetworkListeners();\n\n window.addEventListener(BeamNetworkCallEvent.eventName, async (_event: Event) => {\n const event = _event as BeamNetworkCallEvent;\n const cartChangePaths = /cart\\/(add|change|update|clear)/;\n // note: response urls below follow redirects\n const requestUrlStr = event.detail.type === \"xhr\" ? event.detail.xhr.responseURL : event.detail.response.url;\n const url = new URL(requestUrlStr);\n if (!cartChangePaths.test(url.pathname)) {\n return;\n }\n const currentCart = await getCurrentCart(config);\n if (!currentCart.changed) {\n return;\n }\n const eventDetail: TCartApi = {\n schema: currentCart.cart.schema as any, // TS union type can't figure out what variant applies here\n content: {\n items: currentCart.cart.content.items as any,\n discounts: currentCart.cart.content.discounts as any,\n },\n };\n window.dispatchEvent(new BeamCartChangeEvent(eventDetail));\n // Send cart to Beam to update timestamp, which is used for cart abandonment / ROI calc\n await updateCart(config, currentCart.cart);\n });\n\n // Listen to Beam's own events to integrate Beam data into Shopify order\n let lastNonprofitId: number | null | undefined;\n let lastSelectionId: string | null | undefined;\n window.addEventListener(BeamNonprofitSelectEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectEvent;\n const { source, selectedNonprofitId, selectionId } = event.detail;\n\n if (source === WIDGET_NAMES.select_nonprofit) {\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config); // Shopify cart ID\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config); // Beam cart ID\n const { chainId, storeId } = config;\n // Skip update if nothing changed (can happen if widget is re-initialized and\n // emits event after cache restoration, i.e., on cart re-render).\n if (lastNonprofitId === selectedNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId: beamCartId ? beamCartId : undefined,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = selectedNonprofitId;\n }\n });\n\n /**\n * Upon removal of the selected nonprofit from the widget and local storage,\n * an event is emitted and that event is then used to update the cart attributes accordingly\n * This event listener updates the cart attributes based on the emitted event\n */\n window.addEventListener(BeamNonprofitSelectionRemovedEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectionRemovedEvent;\n const { newNonprofitId, selectionId } = event.detail;\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config);\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n const { chainId, storeId } = config;\n if (lastNonprofitId === newNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId: newNonprofitId,\n beamCartId: beamCartId ? beamCartId : undefined,\n selectionId,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = newNonprofitId;\n });\n\n isBeamCartIntegrationRegistered = true;\n\n return true;\n}\n\n/* ***************************************** HELPER FUNCTIONS *****************************************\n These may be used individually to integrate with carts if the registerCartIntegration\n script doesn't work for some reason.\n ****************************************************************************************************/\n\n/**\n * Detects change in cart since last page load,\n * by calling GET /cart.js, and returns cart values.\n * Used for:\n * - Form-based carts where the page refreshes to modify cart instead of using AJAX calls\n * - Hydrogen/GraphQL based carts (needs to be integrated manually)\n */\nasync function getCurrentCart(config: BeamShopifyCartIntegrationConfig): Promise<{\n changed: boolean;\n cart: {\n cartId: string;\n subtotal: number;\n itemCount: number;\n currencyCode: string;\n } & TCart;\n}> {\n const {\n token, // equal to \"cart\" cookie\n total_price, // this is the pretax value, after discounts, and multiplied by 100 (integer from decimal)\n item_count,\n currency,\n items,\n cart_level_discount_applications,\n } = await window\n .fetch(SHOPIFY_BASE_URL + \"cart.js\", {\n method: \"GET\",\n headers: { \"Content-Type\": \"application/json\" },\n })\n .then((res) => res.json());\n\n let changed = false;\n\n const localStorage = createScopedLocalStorage(config);\n\n // The cart cache is used to detect changes after page refreshes / across tabs\n const cachedCart: TBeamCartLocalStorage | null = localStorage.getItemJson(\"cart\");\n // The Beam cart cookie is used to identify the cart across subdomains\n // Use explicit null if empty because API requires it\n const beamCartId: string | null = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n\n const cart = {\n cartId: token,\n beamCartId,\n subtotal: total_price / 100,\n itemCount: item_count,\n currencyCode: currency,\n schema: { source: \"generic\" } as const,\n content: {\n // pull out minimal fields from full line items\n items: (items as TCartItems).map(({ sku, final_line_price, product_id, line_level_discount_allocations }) => {\n const remoteProductIdentifier = sku || String(product_id);\n const localAmount = final_line_price / 100;\n const discounts = (line_level_discount_allocations as ShopifyLineLevelDiscountAllocations[])?.map(\n ({ discount_application }) => {\n return { code: discount_application?.title, applicable: true };\n }\n );\n return { remoteProductIdentifier, localAmount, discounts };\n }),\n discounts: (cart_level_discount_applications as ShopifyDiscountApplication[]).map(({ title }) => {\n return { code: title, applicable: true };\n }),\n },\n };\n\n if (\n !isEqual(cart, {\n ...cachedCart,\n beamCartId: cachedCart?.beamCartId,\n })\n ) {\n changed = true;\n }\n\n return { changed, cart };\n}\n\n/**\n * trackCart - Backwards-compatible alias for updateCart\n */\nconst trackCart = updateCart;\n\n/**\n * Sends Beam data to Shopify to integrate with order as custom attributes.\n * Memoized so that calls with the same data as the previous don't create additional API calls to Shopify.\n */\nconst addBeamAttributesToCart = memoizeLast(async function addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId,\n cartId,\n chainId,\n storeId,\n}: {\n selectedNonprofitId?: number | null;\n selectionId?: string;\n beamCartId?: string;\n cartId?: string;\n chainId?: number;\n storeId?: number;\n}) {\n let showBeam;\n let remoteSessionId;\n try {\n if (window.statsig) {\n const statsig = window.statsig as any;\n showBeam = statsig.getLayer(\"beam_trial_layer\").get(\"show_beam\", false /* default to hide */) as boolean;\n remoteSessionId = statsig.getStableID();\n }\n } catch (e) {\n logger.error(e);\n }\n const beamCartAttrs = {\n beam: JSON.stringify({\n nonprofit_id: selectedNonprofitId,\n selection_id: selectionId,\n beam_cart_id: beamCartId,\n shopify_cart_id: cartId,\n chain_id: chainId,\n store_id: storeId,\n show_beam: showBeam,\n remote_session_id: remoteSessionId,\n }),\n };\n\n try {\n await window.fetch(SHOPIFY_BASE_URL + \"cart/update.js\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ attributes: beamCartAttrs }),\n });\n } catch (err) {\n logger.error(err); // don't throw, allow later calls to continue\n }\n});\n\ndeclare global {\n interface Window {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n statsig?: any; // attached by Statsig CDN script\n }\n}\nexport { trackCart, getCurrentCart, addBeamAttributesToCart, registerCartIntegration };\n","import \"../../components/post-purchase\";\nimport { postTransaction } from \"../../api-sdk/v3/routes\";\nimport { DEFAULT_BASE_URL } from \"../../api-sdk/constants\";\nimport { LANGUAGES, TUrl } from \"../../api-sdk/types\";\nimport { waitForElement } from \"../../utils/wait-for-element\";\nimport { BeamError } from \"../../utils/beam-errors\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { TCart } from \"../../shared/cart-contents\";\n\n// Shopify admin page: admin/settings/checkout\n\nexport type TBeamOrderPageParams = Parameters<typeof postTransaction>[0][\"requestBody\"] & {\n // Either storeId or postalCode + countryCode must be provided\n storeId?: number;\n postalCode?: string;\n countryCode?: string;\n orderId: string;\n email: string;\n cartTotal: number;\n cart: TCart;\n discountCodes: string[];\n currencyCode: string;\n parentSelector: string; // CSS Selector for parent of widget to be inserted into DOM\n apiKey: string;\n baseUrl: TUrl;\n domain?: string; // Base domain for setting cookies\n lang: LANGUAGES;\n debug: boolean;\n};\n\nexport async function showBeamOrderPageWidgets({\n parentSelector = \".step__sections\",\n apiKey,\n baseUrl = DEFAULT_BASE_URL,\n storeId,\n postalCode,\n countryCode,\n orderId,\n email,\n cartTotal,\n cart,\n discountCodes,\n currencyCode = \"USD\",\n domain,\n lang = \"en\",\n debug = false,\n}: TBeamOrderPageParams) {\n const parentElement = document.querySelector(parentSelector) || (await waitForElement(parentSelector));\n if (!parentElement) {\n throw new BeamError(\n `Timed out waiting for selector '${parentSelector}'. Could not render Beam post-purchase widget.`\n );\n }\n\n // If checkout and order page are on different subdomains, we can't access localStorage\n // We can make postTransaction work by copying the cart cookie to the expected localStorage key on the current domain\n const cartId = await getCookieValue(\"cart\"); // Shopify-only cart identifier\n if (cartId) {\n const beamLocalStorage = createScopedLocalStorage({ apiKey });\n const existingValue = beamLocalStorage.getItemJson(\"cart\") || {};\n beamLocalStorage.setItemJson(\"cart\", { ...existingValue, cartId });\n }\n\n // Note: assign properties one by one instead of bulk Object.assign to type check assignments\n const widget = document.createElement(\"beam-post-purchase\");\n widget.apiKey = apiKey;\n widget.baseUrl = baseUrl;\n widget.storeId = storeId;\n widget.postalCode = postalCode;\n widget.countryCode = countryCode;\n widget.orderId = String(orderId);\n widget.email = email;\n widget.cartTotal = cartTotal;\n widget.cart = cart;\n widget.discountCodes = discountCodes;\n widget.currencyCode = currencyCode;\n widget.domain = domain;\n widget.lang = lang;\n widget.debug = debug;\n\n // Insert widget into DOM\n parentElement.appendChild(widget);\n}\n"],"names":["SHOPIFY_BASE_URL","isBeamCartIntegrationRegistered","SHOPIFY_CART_COOKIE_NAME","registerCartIntegration","config","currentCart","getCurrentCart","cartCookie","getCookieValue","updateCart","addBeamAttributesToCart","initNetworkListeners","BeamNetworkCallEvent","_event","event","cartChangePaths","requestUrlStr","url","eventDetail","BeamCartChangeEvent","lastNonprofitId","lastSelectionId","BeamNonprofitSelectEvent","source","selectedNonprofitId","selectionId","WIDGET_NAMES","cartId","getExternalCartId","beamCartId","getBeamCartId","BEAM_CART_COOKIE_NAME","chainId","storeId","BeamNonprofitSelectionRemovedEvent","newNonprofitId","token","total_price","item_count","currency","items","cart_level_discount_applications","res","changed","cachedCart","createScopedLocalStorage","cart","sku","final_line_price","product_id","line_level_discount_allocations","remoteProductIdentifier","localAmount","discounts","discount_application","title","isEqual","trackCart","memoizeLast","showBeam","remoteSessionId","statsig","e","logger","beamCartAttrs","err","showBeamOrderPageWidgets","parentSelector","apiKey","baseUrl","DEFAULT_BASE_URL","postalCode","countryCode","orderId","email","cartTotal","discountCodes","currencyCode","domain","lang","debug","parentElement","waitForElement","BeamError","beamLocalStorage","existingValue","widget"],"mappings":"0yBAgCA,MAAMA,EAAmB,OAAO,SAAS,QAAQ,MAAQ,IAEzD,IAAIC,EAAkC,GAEtC,MAAMC,EAA2B,OAMjC,eAAeC,EAAwBC,EAA0C,CAC/E,GAAIH,EACF,MAAO,GAKT,MAAMI,EAAc,MAAMC,EAAeF,CAAM,EACzCG,EAAaC,EAAeN,CAAwB,EAEtDG,EAAY,KAAK,SAAWE,GAC9B,MAAME,EAAWL,EAAQC,EAAY,IAAI,EAG3C,MAAMK,EAAwB,CAAE,CAAA,EAEhCC,EAAqB,EAErB,OAAO,iBAAiBC,EAAqB,UAAW,MAAOC,GAAkB,CAC/E,MAAMC,EAAQD,EACRE,EAAkB,kCAElBC,EAAgBF,EAAM,OAAO,OAAS,MAAQA,EAAM,OAAO,IAAI,YAAcA,EAAM,OAAO,SAAS,IACnGG,EAAM,IAAI,IAAID,CAAa,EACjC,GAAI,CAACD,EAAgB,KAAKE,EAAI,QAAQ,EACpC,OAEF,MAAMZ,EAAc,MAAMC,EAAeF,CAAM,EAC/C,GAAI,CAACC,EAAY,QACf,OAEF,MAAMa,EAAwB,CAC5B,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2D,EAAS,SAAS,cAAc,oBAAoB,EAC1DA,EAAO,OAASlB,EAChBkB,EAAO,QAAUjB,EACjBiB,EAAO,QAAUrD,EACjBqD,EAAO,WAAaf,EACpBe,EAAO,YAAcd,EACrBc,EAAO,QAAU,OAAOb,CAAO,EAC/Ba,EAAO,MAAQZ,EACfY,EAAO,UAAYX,EACnBW,EAAO,KAAOxC,EACdwC,EAAO,cAAgBV,EACvBU,EAAO,aAAeT,EACtBS,EAAO,OAASR,EAChBQ,EAAO,KAAOP,EACdO,EAAO,MAAQN,EAGfC,EAAc,YAAYK,CAAM,CAClC"}
1
+ {"version":3,"file":"order-page--Xn2Rb6J.esm.js","sources":["../../src/integrations/shopify/cart-page.ts","../../src/integrations/shopify/order-page.ts"],"sourcesContent":["/* eslint-disable camelcase */\nimport isEqual from \"lodash-es/isEqual\";\nimport { logger, memoizeLast } from \"../../utils\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { initNetworkListeners } from \"../../utils/network-listeners\";\nimport {\n BeamCartChangeEvent,\n BeamNetworkCallEvent,\n BeamNonprofitSelectEvent,\n BeamNonprofitSelectionRemovedEvent,\n} from \"../../utils/events\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { BEAM_CART_COOKIE_NAME, TBeamCartLocalStorage, TCart, TCartApi, TCartItems } from \"../../shared/cart-contents\";\nimport { BeamCartAPIConfig, updateCart } from \"../cart\";\nimport { WIDGET_NAMES } from \"../../api-sdk/constants\";\nimport { getBeamCartId, getExternalCartId } from \"../../utils/cart\";\n\nexport type BeamShopifyCartIntegrationConfig = BeamCartAPIConfig & {\n storeId: number; // will be added to cart custom_attributes, and used in cart API call\n chainId?: number; // will be added to cart custom_attributes\n};\n\ntype ShopifyDiscountApplication = {\n title: string;\n value: string;\n};\n\ntype ShopifyLineLevelDiscountAllocations = {\n amount?: string;\n discount_application: ShopifyDiscountApplication;\n};\n\nconst SHOPIFY_BASE_URL = window.Shopify?.routes?.root || \"/\"; // see window.d.ts\n\nlet isBeamCartIntegrationRegistered = false; // Skip registering event listeners if already set up\n\nconst SHOPIFY_CART_COOKIE_NAME = \"cart\";\n\n/**\n * @main registerCartIntegration - set up event listeners to integrate Beam with Shopify cart\n * @return {boolean} returns true if NEW listeners were created, false if setup was already done\n */\nasync function registerCartIntegration(config: BeamShopifyCartIntegrationConfig) {\n if (isBeamCartIntegrationRegistered) {\n return false; // Do nothing if listeners are already attached\n }\n\n // Handle full-page load, ie, first-time page load and reloads from form submit events\n // This creates a GET to /cart.js\n const currentCart = await getCurrentCart(config);\n const cartCookie = getCookieValue(SHOPIFY_CART_COOKIE_NAME);\n // only update on initial load if Shopify cart has changed since last visit\n if (currentCart.cart.cartId !== cartCookie) {\n await updateCart(config, currentCart.cart);\n }\n // pre load beam cart attribute to save statsig info\n await addBeamAttributesToCart({});\n // Set up event listeners for AJAX events\n initNetworkListeners();\n\n window.addEventListener(BeamNetworkCallEvent.eventName, async (_event: Event) => {\n const event = _event as BeamNetworkCallEvent;\n const cartChangePaths = /cart\\/(add|change|update|clear)/;\n // note: response urls below follow redirects\n const requestUrlStr = event.detail.type === \"xhr\" ? event.detail.xhr.responseURL : event.detail.response.url;\n const url = new URL(requestUrlStr);\n if (!cartChangePaths.test(url.pathname)) {\n return;\n }\n const currentCart = await getCurrentCart(config);\n if (!currentCart.changed) {\n return;\n }\n const eventDetail: TCartApi = {\n schema: currentCart.cart.schema as any, // TS union type can't figure out what variant applies here\n content: {\n items: currentCart.cart.content.items as any,\n discounts: currentCart.cart.content.discounts as any,\n },\n };\n window.dispatchEvent(new BeamCartChangeEvent(eventDetail));\n // Send cart to Beam to update timestamp, which is used for cart abandonment / ROI calc\n await updateCart(config, currentCart.cart);\n });\n\n // Listen to Beam's own events to integrate Beam data into Shopify order\n let lastNonprofitId: number | null | undefined;\n let lastSelectionId: string | null | undefined;\n window.addEventListener(BeamNonprofitSelectEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectEvent;\n const { source, selectedNonprofitId, selectionId } = event.detail;\n\n if (source === WIDGET_NAMES.select_nonprofit) {\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config); // Shopify cart ID\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config); // Beam cart ID\n const { chainId, storeId } = config;\n // Skip update if nothing changed (can happen if widget is re-initialized and\n // emits event after cache restoration, i.e., on cart re-render).\n if (lastNonprofitId === selectedNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId: beamCartId ? beamCartId : undefined,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = selectedNonprofitId;\n }\n });\n\n /**\n * Upon removal of the selected nonprofit from the widget and local storage,\n * an event is emitted and that event is then used to update the cart attributes accordingly\n * This event listener updates the cart attributes based on the emitted event\n */\n window.addEventListener(BeamNonprofitSelectionRemovedEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectionRemovedEvent;\n const { newNonprofitId, selectionId } = event.detail;\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config);\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n const { chainId, storeId } = config;\n if (lastNonprofitId === newNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId: newNonprofitId,\n beamCartId: beamCartId ? beamCartId : undefined,\n selectionId,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = newNonprofitId;\n });\n\n isBeamCartIntegrationRegistered = true;\n\n return true;\n}\n\n/* ***************************************** HELPER FUNCTIONS *****************************************\n These may be used individually to integrate with carts if the registerCartIntegration\n script doesn't work for some reason.\n ****************************************************************************************************/\n\n/**\n * Detects change in cart since last page load,\n * by calling GET /cart.js, and returns cart values.\n * Used for:\n * - Form-based carts where the page refreshes to modify cart instead of using AJAX calls\n * - Hydrogen/GraphQL based carts (needs to be integrated manually)\n */\nasync function getCurrentCart(config: BeamShopifyCartIntegrationConfig): Promise<{\n changed: boolean;\n cart: {\n cartId: string;\n subtotal: number;\n itemCount: number;\n currencyCode: string;\n } & TCart;\n}> {\n const {\n token, // equal to \"cart\" cookie\n total_price, // this is the pretax value, after discounts, and multiplied by 100 (integer from decimal)\n item_count,\n currency,\n items,\n cart_level_discount_applications,\n } = await window\n .fetch(SHOPIFY_BASE_URL + \"cart.js\", {\n method: \"GET\",\n headers: { \"Content-Type\": \"application/json\" },\n })\n .then((res) => res.json());\n\n let changed = false;\n\n const localStorage = createScopedLocalStorage(config);\n\n // The cart cache is used to detect changes after page refreshes / across tabs\n const cachedCart: TBeamCartLocalStorage | null = localStorage.getItemJson(\"cart\");\n // The Beam cart cookie is used to identify the cart across subdomains\n // Use explicit null if empty because API requires it\n const beamCartId: string | null = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n\n const cart = {\n cartId: token,\n beamCartId,\n subtotal: total_price / 100,\n itemCount: item_count,\n currencyCode: currency,\n schema: { source: \"generic\" } as const,\n content: {\n // pull out minimal fields from full line items\n items: (items as TCartItems).map(({ sku, final_line_price, product_id, line_level_discount_allocations }) => {\n const remoteProductIdentifier = sku || String(product_id);\n const localAmount = final_line_price / 100;\n const discounts = (line_level_discount_allocations as ShopifyLineLevelDiscountAllocations[])?.map(\n ({ discount_application }) => {\n return { code: discount_application?.title, applicable: true };\n }\n );\n return { remoteProductIdentifier, localAmount, discounts };\n }),\n discounts: (cart_level_discount_applications as ShopifyDiscountApplication[]).map(({ title }) => {\n return { code: title, applicable: true };\n }),\n },\n };\n\n if (\n !isEqual(cart, {\n ...cachedCart,\n beamCartId: cachedCart?.beamCartId,\n })\n ) {\n changed = true;\n }\n\n return { changed, cart };\n}\n\n/**\n * trackCart - Backwards-compatible alias for updateCart\n */\nconst trackCart = updateCart;\n\n/**\n * Sends Beam data to Shopify to integrate with order as custom attributes.\n * Memoized so that calls with the same data as the previous don't create additional API calls to Shopify.\n */\nconst addBeamAttributesToCart = memoizeLast(async function addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId,\n cartId,\n chainId,\n storeId,\n}: {\n selectedNonprofitId?: number | null;\n selectionId?: string;\n beamCartId?: string;\n cartId?: string;\n chainId?: number;\n storeId?: number;\n}) {\n let showBeam;\n let remoteSessionId;\n try {\n if (window.statsig) {\n const statsig = window.statsig as any;\n showBeam = statsig.getLayer(\"beam_trial_layer\").get(\"show_beam\", false /* default to hide */) as boolean;\n remoteSessionId = statsig.getStableID();\n }\n } catch (e) {\n logger.error(e);\n }\n const beamCartAttrs = {\n beam: JSON.stringify({\n nonprofit_id: selectedNonprofitId,\n selection_id: selectionId,\n beam_cart_id: beamCartId,\n shopify_cart_id: cartId,\n chain_id: chainId,\n store_id: storeId,\n show_beam: showBeam,\n remote_session_id: remoteSessionId,\n }),\n };\n\n try {\n await window.fetch(SHOPIFY_BASE_URL + \"cart/update.js\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ attributes: beamCartAttrs }),\n });\n } catch (err) {\n logger.error(err); // don't throw, allow later calls to continue\n }\n});\n\ndeclare global {\n interface Window {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n statsig?: any; // attached by Statsig CDN script\n }\n}\nexport { trackCart, getCurrentCart, addBeamAttributesToCart, registerCartIntegration };\n","import \"../../components/post-purchase\";\nimport { postTransaction } from \"../../api-sdk/v3/routes\";\nimport { DEFAULT_BASE_URL } from \"../../api-sdk/constants\";\nimport { LANGUAGES, TUrl } from \"../../api-sdk/types\";\nimport { waitForElement } from \"../../utils/wait-for-element\";\nimport { BeamError } from \"../../utils/beam-errors\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { TCart } from \"../../shared/cart-contents\";\n\n// Shopify admin page: admin/settings/checkout\n\nexport type TBeamOrderPageParams = Parameters<typeof postTransaction>[0][\"requestBody\"] & {\n // Either storeId or postalCode + countryCode must be provided\n storeId?: number;\n postalCode?: string;\n countryCode?: string;\n orderId: string;\n email: string;\n cartTotal: number;\n cart: TCart;\n discountCodes: string[];\n currencyCode: string;\n parentSelector: string; // CSS Selector for parent of widget to be inserted into DOM\n apiKey: string;\n baseUrl: TUrl;\n domain?: string; // Base domain for setting cookies\n lang: LANGUAGES;\n debug: boolean;\n};\n\nexport async function showBeamOrderPageWidgets({\n parentSelector = \".step__sections\",\n apiKey,\n baseUrl = DEFAULT_BASE_URL,\n storeId,\n postalCode,\n countryCode,\n orderId,\n email,\n cartTotal,\n cart,\n discountCodes,\n currencyCode = \"USD\",\n domain,\n lang = \"en\",\n debug = false,\n}: TBeamOrderPageParams) {\n const parentElement = document.querySelector(parentSelector) || (await waitForElement(parentSelector));\n if (!parentElement) {\n throw new BeamError(\n `Timed out waiting for selector '${parentSelector}'. Could not render Beam post-purchase widget.`\n );\n }\n\n // If checkout and order page are on different subdomains, we can't access localStorage\n // We can make postTransaction work by copying the cart cookie to the expected localStorage key on the current domain\n const cartId = await getCookieValue(\"cart\"); // Shopify-only cart identifier\n if (cartId) {\n const beamLocalStorage = createScopedLocalStorage({ apiKey });\n const existingValue = beamLocalStorage.getItemJson(\"cart\") || {};\n beamLocalStorage.setItemJson(\"cart\", { ...existingValue, cartId });\n }\n\n // Note: assign properties one by one instead of bulk Object.assign to type check assignments\n const widget = document.createElement(\"beam-post-purchase\");\n widget.apiKey = apiKey;\n widget.baseUrl = baseUrl;\n widget.storeId = storeId;\n widget.postalCode = postalCode;\n widget.countryCode = countryCode;\n widget.orderId = String(orderId);\n widget.email = email;\n widget.cartTotal = cartTotal;\n widget.cart = cart;\n widget.discountCodes = discountCodes;\n widget.currencyCode = currencyCode;\n widget.domain = domain;\n widget.lang = lang;\n widget.debug = debug;\n\n // Insert widget into DOM\n parentElement.appendChild(widget);\n}\n"],"names":["SHOPIFY_BASE_URL","isBeamCartIntegrationRegistered","SHOPIFY_CART_COOKIE_NAME","registerCartIntegration","config","currentCart","getCurrentCart","cartCookie","getCookieValue","updateCart","addBeamAttributesToCart","initNetworkListeners","BeamNetworkCallEvent","_event","event","cartChangePaths","requestUrlStr","url","eventDetail","BeamCartChangeEvent","lastNonprofitId","lastSelectionId","BeamNonprofitSelectEvent","source","selectedNonprofitId","selectionId","WIDGET_NAMES","cartId","getExternalCartId","beamCartId","getBeamCartId","BEAM_CART_COOKIE_NAME","chainId","storeId","BeamNonprofitSelectionRemovedEvent","newNonprofitId","token","total_price","item_count","currency","items","cart_level_discount_applications","res","changed","cachedCart","createScopedLocalStorage","cart","sku","final_line_price","product_id","line_level_discount_allocations","remoteProductIdentifier","localAmount","discounts","discount_application","title","isEqual","trackCart","memoizeLast","showBeam","remoteSessionId","statsig","e","logger","beamCartAttrs","err","showBeamOrderPageWidgets","parentSelector","apiKey","baseUrl","DEFAULT_BASE_URL","postalCode","countryCode","orderId","email","cartTotal","discountCodes","currencyCode","domain","lang","debug","parentElement","waitForElement","BeamError","beamLocalStorage","existingValue","widget"],"mappings":"0yBAgCA,MAAMA,EAAmB,OAAO,SAAS,QAAQ,MAAQ,IAEzD,IAAIC,EAAkC,GAEtC,MAAMC,EAA2B,OAMjC,eAAeC,EAAwBC,EAA0C,CAC/E,GAAIH,EACF,MAAO,GAKT,MAAMI,EAAc,MAAMC,EAAeF,CAAM,EACzCG,EAAaC,EAAeN,CAAwB,EAEtDG,EAAY,KAAK,SAAWE,GAC9B,MAAME,EAAWL,EAAQC,EAAY,IAAI,EAG3C,MAAMK,EAAwB,CAAE,CAAA,EAEhCC,EAAqB,EAErB,OAAO,iBAAiBC,EAAqB,UAAW,MAAOC,GAAkB,CAC/E,MAAMC,EAAQD,EACRE,EAAkB,kCAElBC,EAAgBF,EAAM,OAAO,OAAS,MAAQA,EAAM,OAAO,IAAI,YAAcA,EAAM,OAAO,SAAS,IACnGG,EAAM,IAAI,IAAID,CAAa,EACjC,GAAI,CAACD,EAAgB,KAAKE,EAAI,QAAQ,EACpC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M,GAAK,CAAC,EAC/DA,EAAiB,YAAY,OAAQ,CAAE,GAAGC,EAAe,OAAA1D,CAAO,CAAC,CACnE,CAGA,MAAM2D,EAAS,SAAS,cAAc,oBAAoB,EAC1DA,EAAO,OAASlB,EAChBkB,EAAO,QAAUjB,EACjBiB,EAAO,QAAUrD,EACjBqD,EAAO,WAAaf,EACpBe,EAAO,YAAcd,EACrBc,EAAO,QAAU,OAAOb,CAAO,EAC/Ba,EAAO,MAAQZ,EACfY,EAAO,UAAYX,EACnBW,EAAO,KAAOxC,EACdwC,EAAO,cAAgBV,EACvBU,EAAO,aAAeT,EACtBS,EAAO,OAASR,EAChBQ,EAAO,KAAOP,EACdO,EAAO,MAAQN,EAGfC,EAAc,YAAYK,CAAM,CAClC"}
@@ -1,8 +1,8 @@
1
1
  import * as lodash from 'lodash';
2
- import { B as BeamCartAPIConfig, a as BeamCartValues } from './update-cart-Hebtxhto.esm.js';
3
- import { T as TCart } from './cart-contents-HAPzwbeL.esm.js';
2
+ import { B as BeamCartAPIConfig, a as BeamCartValues } from './update-cart-KjKc8Cls.esm.js';
3
+ import { T as TCart } from './cart-contents-MrYQNVDx.esm.js';
4
4
  import '../components/post-purchase.js';
5
- import { p as postTransaction } from './routes-NIuAzAOC.esm.js';
5
+ import { p as postTransaction } from './routes-iurI6dvR.esm.js';
6
6
  import { T as TUrl, L as LANGUAGES } from './types-aju0qrRe.esm.js';
7
7
 
8
8
  type BeamShopifyCartIntegrationConfig = BeamCartAPIConfig & {
@@ -1,2 +1,2 @@
1
- import{i as J}from"./lodash-P8OIs-at.esm.js";import{b as O,d as j,c as k,g as D}from"./events-_4nImo3u.esm.js";import{logger as N}from"../utils/logger.js";import{initNetworkListeners as K}from"../utils/network-listeners.js";import{createScopedLocalStorage as S}from"../utils/local-storage.js";import{getCookieValue as B}from"../utils/cookies.js";import{memoizeLast as R}from"../utils/memoize-last.js";import{B as y}from"./cart-contents-h60geKWa.esm.js";import{K as C}from"./update-cart-eodNhDjI.esm.js";import{W as x,D as q}from"./routes-kK10CmJz.esm.js";import{getExternalCartId as L,getBeamCartId as b}from"../utils/cart.js";import"../components/post-purchase.js";import{waitForElement as M}from"../utils/wait-for-element.js";import{B as P}from"./beam-errors-P-Lu07Ce.esm.js";const T=window.Shopify?.routes?.root||"/";let A=!1;const E="cart";async function W(t){if(A)return!1;const l=await v(t),p=B(E);l.cart.cartId!==p&&await C(t,l.cart),await _({}),K(),window.addEventListener(O.eventName,async s=>{const n=s,r=/cart\/(add|change|update|clear)/,a=n.detail.type==="xhr"?n.detail.xhr.responseURL:n.detail.response.url,e=new URL(a);if(!r.test(e.pathname))return;const i=await v(t);if(!i.changed)return;const c={schema:i.cart.schema,content:{items:i.cart.content.items,discounts:i.cart.content.discounts}};window.dispatchEvent(new j(c)),await C(t,i.cart)});let d,m;return window.addEventListener(k.eventName,async s=>{const n=s,{source:r,selectedNonprofitId:a,selectionId:e}=n.detail;if(r===x.select_nonprofit){const i=L(E,t),c=b(y,t),{chainId:u,storeId:I}=t;if(d===a&&m===e)return;await _({selectedNonprofitId:a,selectionId:e,beamCartId:c||void 0,cartId:i||void 0,chainId:u,storeId:I}),m=e,d=a}}),window.addEventListener(D.eventName,async s=>{const n=s,{newNonprofitId:r,selectionId:a}=n.detail,e=L(E,t),i=b(y,t),{chainId:c,storeId:u}=t;d===r&&m===a||(await _({selectedNonprofitId:r,beamCartId:i||void 0,selectionId:a,cartId:e||void 0,chainId:c,storeId:u}),m=a,d=r)}),A=!0,!0}async function v(t){const{token:l,total_price:p,item_count:d,currency:m,items:s,cart_level_discount_applications:n}=await window.fetch(T+"cart.js",{method:"GET",headers:{"Content-Type":"application/json"}}).then(c=>c.json());let r=!1;const a=S(t).getItemJson("cart"),e=b(y,t),i={cartId:l,beamCartId:e,subtotal:p/100,itemCount:d,currencyCode:m,schema:{source:"generic"},content:{items:s.map(({sku:c,final_line_price:u,product_id:I,line_level_discount_allocations:g})=>{const f=c||String(I),w=u/100,o=g?.map(({discount_application:h})=>({code:h?.title,applicable:!0}));return{remoteProductIdentifier:f,localAmount:w,discounts:o}}),discounts:n.map(({title:c})=>({code:c,applicable:!0}))}};return J(i,{...a,beamCartId:a?.beamCartId})||(r=!0),{changed:r,cart:i}}const F=C,_=R(async function({selectedNonprofitId:t,selectionId:l,beamCartId:p,cartId:d,chainId:m,storeId:s}){let n,r;try{if(window.statsig){const e=window.statsig;n=e.getLayer("beam_trial_layer").get("show_beam",!1),r=e.getStableID()}}catch(e){N.error(e)}const a={beam:JSON.stringify({nonprofit_id:t,selection_id:l,beam_cart_id:p,shopify_cart_id:d,chain_id:m,store_id:s,show_beam:n,remote_session_id:r})};try{await window.fetch(T+"cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes:a})})}catch(e){N.error(e)}});async function G({parentSelector:t=".step__sections",apiKey:l,baseUrl:p=q,storeId:d,postalCode:m,countryCode:s,orderId:n,email:r,cartTotal:a,cart:e,discountCodes:i,currencyCode:c="USD",domain:u,lang:I="en",debug:g=!1}){const f=document.querySelector(t)||await M(t);if(!f)throw new P(`Timed out waiting for selector '${t}'. Could not render Beam post-purchase widget.`);const w=await B("cart");if(w){const h=S({apiKey:l}),U=h.getItemJson("cart")||{};h.setItemJson("cart",{...U,cartId:w})}const o=document.createElement("beam-post-purchase");o.apiKey=l,o.baseUrl=p,o.storeId=d,o.postalCode=m,o.countryCode=s,o.orderId=String(n),o.email=r,o.cartTotal=a,o.cart=e,o.discountCodes=i,o.currencyCode=c,o.domain=u,o.lang=I,o.debug=g,f.appendChild(o)}export{W as J,_ as p,F as q,G as s,v as w};
2
- //# sourceMappingURL=order-page-fVZWjxXw.esm.js.map
1
+ import{i as J}from"./lodash-P8OIs-at.esm.js";import{b as O,d as j,c as k,g as D}from"./events-_4nImo3u.esm.js";import{logger as N}from"../utils/logger.js";import{initNetworkListeners as K}from"../utils/network-listeners.js";import{createScopedLocalStorage as S}from"../utils/local-storage.js";import{getCookieValue as B}from"../utils/cookies.js";import{memoizeLast as R}from"../utils/memoize-last.js";import{B as y}from"./cart-contents-h60geKWa.esm.js";import{K as C}from"./update-cart-WyIeEybK.esm.js";import{W as x,D as q}from"./routes-F1ZIumMP.esm.js";import{getExternalCartId as L,getBeamCartId as b}from"../utils/cart.js";import"../components/post-purchase.js";import{waitForElement as M}from"../utils/wait-for-element.js";import{B as P}from"./beam-errors-P-Lu07Ce.esm.js";const T=window.Shopify?.routes?.root||"/";let A=!1;const E="cart";async function W(t){if(A)return!1;const l=await v(t),p=B(E);l.cart.cartId!==p&&await C(t,l.cart),await _({}),K(),window.addEventListener(O.eventName,async s=>{const n=s,r=/cart\/(add|change|update|clear)/,a=n.detail.type==="xhr"?n.detail.xhr.responseURL:n.detail.response.url,e=new URL(a);if(!r.test(e.pathname))return;const i=await v(t);if(!i.changed)return;const c={schema:i.cart.schema,content:{items:i.cart.content.items,discounts:i.cart.content.discounts}};window.dispatchEvent(new j(c)),await C(t,i.cart)});let d,m;return window.addEventListener(k.eventName,async s=>{const n=s,{source:r,selectedNonprofitId:a,selectionId:e}=n.detail;if(r===x.select_nonprofit){const i=L(E,t),c=b(y,t),{chainId:u,storeId:I}=t;if(d===a&&m===e)return;await _({selectedNonprofitId:a,selectionId:e,beamCartId:c||void 0,cartId:i||void 0,chainId:u,storeId:I}),m=e,d=a}}),window.addEventListener(D.eventName,async s=>{const n=s,{newNonprofitId:r,selectionId:a}=n.detail,e=L(E,t),i=b(y,t),{chainId:c,storeId:u}=t;d===r&&m===a||(await _({selectedNonprofitId:r,beamCartId:i||void 0,selectionId:a,cartId:e||void 0,chainId:c,storeId:u}),m=a,d=r)}),A=!0,!0}async function v(t){const{token:l,total_price:p,item_count:d,currency:m,items:s,cart_level_discount_applications:n}=await window.fetch(T+"cart.js",{method:"GET",headers:{"Content-Type":"application/json"}}).then(c=>c.json());let r=!1;const a=S(t).getItemJson("cart"),e=b(y,t),i={cartId:l,beamCartId:e,subtotal:p/100,itemCount:d,currencyCode:m,schema:{source:"generic"},content:{items:s.map(({sku:c,final_line_price:u,product_id:I,line_level_discount_allocations:g})=>{const f=c||String(I),w=u/100,o=g?.map(({discount_application:h})=>({code:h?.title,applicable:!0}));return{remoteProductIdentifier:f,localAmount:w,discounts:o}}),discounts:n.map(({title:c})=>({code:c,applicable:!0}))}};return J(i,{...a,beamCartId:a?.beamCartId})||(r=!0),{changed:r,cart:i}}const F=C,_=R(async function({selectedNonprofitId:t,selectionId:l,beamCartId:p,cartId:d,chainId:m,storeId:s}){let n,r;try{if(window.statsig){const e=window.statsig;n=e.getLayer("beam_trial_layer").get("show_beam",!1),r=e.getStableID()}}catch(e){N.error(e)}const a={beam:JSON.stringify({nonprofit_id:t,selection_id:l,beam_cart_id:p,shopify_cart_id:d,chain_id:m,store_id:s,show_beam:n,remote_session_id:r})};try{await window.fetch(T+"cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes:a})})}catch(e){N.error(e)}});async function G({parentSelector:t=".step__sections",apiKey:l,baseUrl:p=q,storeId:d,postalCode:m,countryCode:s,orderId:n,email:r,cartTotal:a,cart:e,discountCodes:i,currencyCode:c="USD",domain:u,lang:I="en",debug:g=!1}){const f=document.querySelector(t)||await M(t);if(!f)throw new P(`Timed out waiting for selector '${t}'. Could not render Beam post-purchase widget.`);const w=await B("cart");if(w){const h=S({apiKey:l}),U=h.getItemJson("cart")||{};h.setItemJson("cart",{...U,cartId:w})}const o=document.createElement("beam-post-purchase");o.apiKey=l,o.baseUrl=p,o.storeId=d,o.postalCode=m,o.countryCode=s,o.orderId=String(n),o.email=r,o.cartTotal=a,o.cart=e,o.discountCodes=i,o.currencyCode=c,o.domain=u,o.lang=I,o.debug=g,f.appendChild(o)}export{W as J,_ as p,F as q,G as s,v as w};
2
+ //# sourceMappingURL=order-page-uEOo5EPy.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"order-page-fVZWjxXw.esm.js","sources":["../../src/integrations/shopify/cart-page.ts","../../src/integrations/shopify/order-page.ts"],"sourcesContent":["/* eslint-disable camelcase */\nimport isEqual from \"lodash-es/isEqual\";\nimport { logger, memoizeLast } from \"../../utils\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { initNetworkListeners } from \"../../utils/network-listeners\";\nimport {\n BeamCartChangeEvent,\n BeamNetworkCallEvent,\n BeamNonprofitSelectEvent,\n BeamNonprofitSelectionRemovedEvent,\n} from \"../../utils/events\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { BEAM_CART_COOKIE_NAME, TBeamCartLocalStorage, TCart, TCartApi, TCartItems } from \"../../shared/cart-contents\";\nimport { BeamCartAPIConfig, updateCart } from \"../cart\";\nimport { WIDGET_NAMES } from \"../../api-sdk/constants\";\nimport { getBeamCartId, getExternalCartId } from \"../../utils/cart\";\n\nexport type BeamShopifyCartIntegrationConfig = BeamCartAPIConfig & {\n storeId: number; // will be added to cart custom_attributes, and used in cart API call\n chainId?: number; // will be added to cart custom_attributes\n};\n\ntype ShopifyDiscountApplication = {\n title: string;\n value: string;\n};\n\ntype ShopifyLineLevelDiscountAllocations = {\n amount?: string;\n discount_application: ShopifyDiscountApplication;\n};\n\nconst SHOPIFY_BASE_URL = window.Shopify?.routes?.root || \"/\"; // see window.d.ts\n\nlet isBeamCartIntegrationRegistered = false; // Skip registering event listeners if already set up\n\nconst SHOPIFY_CART_COOKIE_NAME = \"cart\";\n\n/**\n * @main registerCartIntegration - set up event listeners to integrate Beam with Shopify cart\n * @return {boolean} returns true if NEW listeners were created, false if setup was already done\n */\nasync function registerCartIntegration(config: BeamShopifyCartIntegrationConfig) {\n if (isBeamCartIntegrationRegistered) {\n return false; // Do nothing if listeners are already attached\n }\n\n // Handle full-page load, ie, first-time page load and reloads from form submit events\n // This creates a GET to /cart.js\n const currentCart = await getCurrentCart(config);\n const cartCookie = getCookieValue(SHOPIFY_CART_COOKIE_NAME);\n // only update on initial load if Shopify cart has changed since last visit\n if (currentCart.cart.cartId !== cartCookie) {\n await updateCart(config, currentCart.cart);\n }\n // pre load beam cart attribute to save statsig info\n await addBeamAttributesToCart({});\n // Set up event listeners for AJAX events\n initNetworkListeners();\n\n window.addEventListener(BeamNetworkCallEvent.eventName, async (_event: Event) => {\n const event = _event as BeamNetworkCallEvent;\n const cartChangePaths = /cart\\/(add|change|update|clear)/;\n // note: response urls below follow redirects\n const requestUrlStr = event.detail.type === \"xhr\" ? event.detail.xhr.responseURL : event.detail.response.url;\n const url = new URL(requestUrlStr);\n if (!cartChangePaths.test(url.pathname)) {\n return;\n }\n const currentCart = await getCurrentCart(config);\n if (!currentCart.changed) {\n return;\n }\n const eventDetail: TCartApi = {\n schema: currentCart.cart.schema as any, // TS union type can't figure out what variant applies here\n content: {\n items: currentCart.cart.content.items as any,\n discounts: currentCart.cart.content.discounts as any,\n },\n };\n window.dispatchEvent(new BeamCartChangeEvent(eventDetail));\n // Send cart to Beam to update timestamp, which is used for cart abandonment / ROI calc\n await updateCart(config, currentCart.cart);\n });\n\n // Listen to Beam's own events to integrate Beam data into Shopify order\n let lastNonprofitId: number | null | undefined;\n let lastSelectionId: string | null | undefined;\n window.addEventListener(BeamNonprofitSelectEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectEvent;\n const { source, selectedNonprofitId, selectionId } = event.detail;\n\n if (source === WIDGET_NAMES.select_nonprofit) {\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config); // Shopify cart ID\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config); // Beam cart ID\n const { chainId, storeId } = config;\n // Skip update if nothing changed (can happen if widget is re-initialized and\n // emits event after cache restoration, i.e., on cart re-render).\n if (lastNonprofitId === selectedNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId: beamCartId ? beamCartId : undefined,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = selectedNonprofitId;\n }\n });\n\n /**\n * Upon removal of the selected nonprofit from the widget and local storage,\n * an event is emitted and that event is then used to update the cart attributes accordingly\n * This event listener updates the cart attributes based on the emitted event\n */\n window.addEventListener(BeamNonprofitSelectionRemovedEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectionRemovedEvent;\n const { newNonprofitId, selectionId } = event.detail;\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config);\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n const { chainId, storeId } = config;\n if (lastNonprofitId === newNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId: newNonprofitId,\n beamCartId: beamCartId ? beamCartId : undefined,\n selectionId,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = newNonprofitId;\n });\n\n isBeamCartIntegrationRegistered = true;\n\n return true;\n}\n\n/* ***************************************** HELPER FUNCTIONS *****************************************\n These may be used individually to integrate with carts if the registerCartIntegration\n script doesn't work for some reason.\n ****************************************************************************************************/\n\n/**\n * Detects change in cart since last page load,\n * by calling GET /cart.js, and returns cart values.\n * Used for:\n * - Form-based carts where the page refreshes to modify cart instead of using AJAX calls\n * - Hydrogen/GraphQL based carts (needs to be integrated manually)\n */\nasync function getCurrentCart(config: BeamShopifyCartIntegrationConfig): Promise<{\n changed: boolean;\n cart: {\n cartId: string;\n subtotal: number;\n itemCount: number;\n currencyCode: string;\n } & TCart;\n}> {\n const {\n token, // equal to \"cart\" cookie\n total_price, // this is the pretax value, after discounts, and multiplied by 100 (integer from decimal)\n item_count,\n currency,\n items,\n cart_level_discount_applications,\n } = await window\n .fetch(SHOPIFY_BASE_URL + \"cart.js\", {\n method: \"GET\",\n headers: { \"Content-Type\": \"application/json\" },\n })\n .then((res) => res.json());\n\n let changed = false;\n\n const localStorage = createScopedLocalStorage(config);\n\n // The cart cache is used to detect changes after page refreshes / across tabs\n const cachedCart: TBeamCartLocalStorage | null = localStorage.getItemJson(\"cart\");\n // The Beam cart cookie is used to identify the cart across subdomains\n // Use explicit null if empty because API requires it\n const beamCartId: string | null = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n\n const cart = {\n cartId: token,\n beamCartId,\n subtotal: total_price / 100,\n itemCount: item_count,\n currencyCode: currency,\n schema: { source: \"generic\" } as const,\n content: {\n // pull out minimal fields from full line items\n items: (items as TCartItems).map(({ sku, final_line_price, product_id, line_level_discount_allocations }) => {\n const remoteProductIdentifier = sku || String(product_id);\n const localAmount = final_line_price / 100;\n const discounts = (line_level_discount_allocations as ShopifyLineLevelDiscountAllocations[])?.map(\n ({ discount_application }) => {\n return { code: discount_application?.title, applicable: true };\n }\n );\n return { remoteProductIdentifier, localAmount, discounts };\n }),\n discounts: (cart_level_discount_applications as ShopifyDiscountApplication[]).map(({ title }) => {\n return { code: title, applicable: true };\n }),\n },\n };\n\n if (\n !isEqual(cart, {\n ...cachedCart,\n beamCartId: cachedCart?.beamCartId,\n })\n ) {\n changed = true;\n }\n\n return { changed, cart };\n}\n\n/**\n * trackCart - Backwards-compatible alias for updateCart\n */\nconst trackCart = updateCart;\n\n/**\n * Sends Beam data to Shopify to integrate with order as custom attributes.\n * Memoized so that calls with the same data as the previous don't create additional API calls to Shopify.\n */\nconst addBeamAttributesToCart = memoizeLast(async function addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId,\n cartId,\n chainId,\n storeId,\n}: {\n selectedNonprofitId?: number | null;\n selectionId?: string;\n beamCartId?: string;\n cartId?: string;\n chainId?: number;\n storeId?: number;\n}) {\n let showBeam;\n let remoteSessionId;\n try {\n if (window.statsig) {\n const statsig = window.statsig as any;\n showBeam = statsig.getLayer(\"beam_trial_layer\").get(\"show_beam\", false /* default to hide */) as boolean;\n remoteSessionId = statsig.getStableID();\n }\n } catch (e) {\n logger.error(e);\n }\n const beamCartAttrs = {\n beam: JSON.stringify({\n nonprofit_id: selectedNonprofitId,\n selection_id: selectionId,\n beam_cart_id: beamCartId,\n shopify_cart_id: cartId,\n chain_id: chainId,\n store_id: storeId,\n show_beam: showBeam,\n remote_session_id: remoteSessionId,\n }),\n };\n\n try {\n await window.fetch(SHOPIFY_BASE_URL + \"cart/update.js\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ attributes: beamCartAttrs }),\n });\n } catch (err) {\n logger.error(err); // don't throw, allow later calls to continue\n }\n});\n\ndeclare global {\n interface Window {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n statsig?: any; // attached by Statsig CDN script\n }\n}\nexport { trackCart, getCurrentCart, addBeamAttributesToCart, registerCartIntegration };\n","import \"../../components/post-purchase\";\nimport { postTransaction } from \"../../api-sdk/v3/routes\";\nimport { DEFAULT_BASE_URL } from \"../../api-sdk/constants\";\nimport { LANGUAGES, TUrl } from \"../../api-sdk/types\";\nimport { waitForElement } from \"../../utils/wait-for-element\";\nimport { BeamError } from \"../../utils/beam-errors\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { TCart } from \"../../shared/cart-contents\";\n\n// Shopify admin page: admin/settings/checkout\n\nexport type TBeamOrderPageParams = Parameters<typeof postTransaction>[0][\"requestBody\"] & {\n // Either storeId or postalCode + countryCode must be provided\n storeId?: number;\n postalCode?: string;\n countryCode?: string;\n orderId: string;\n email: string;\n cartTotal: number;\n cart: TCart;\n discountCodes: string[];\n currencyCode: string;\n parentSelector: string; // CSS Selector for parent of widget to be inserted into DOM\n apiKey: string;\n baseUrl: TUrl;\n domain?: string; // Base domain for setting cookies\n lang: LANGUAGES;\n debug: boolean;\n};\n\nexport async function showBeamOrderPageWidgets({\n parentSelector = \".step__sections\",\n apiKey,\n baseUrl = DEFAULT_BASE_URL,\n storeId,\n postalCode,\n countryCode,\n orderId,\n email,\n cartTotal,\n cart,\n discountCodes,\n currencyCode = \"USD\",\n domain,\n lang = \"en\",\n debug = false,\n}: TBeamOrderPageParams) {\n const parentElement = document.querySelector(parentSelector) || (await waitForElement(parentSelector));\n if (!parentElement) {\n throw new BeamError(\n `Timed out waiting for selector '${parentSelector}'. Could not render Beam post-purchase widget.`\n );\n }\n\n // If checkout and order page are on different subdomains, we can't access localStorage\n // We can make postTransaction work by copying the cart cookie to the expected localStorage key on the current domain\n const cartId = await getCookieValue(\"cart\"); // Shopify-only cart identifier\n if (cartId) {\n const beamLocalStorage = createScopedLocalStorage({ apiKey });\n const existingValue = beamLocalStorage.getItemJson(\"cart\") || {};\n beamLocalStorage.setItemJson(\"cart\", { ...existingValue, cartId });\n }\n\n // Note: assign properties one by one instead of bulk Object.assign to type check assignments\n const widget = document.createElement(\"beam-post-purchase\");\n widget.apiKey = apiKey;\n widget.baseUrl = baseUrl;\n widget.storeId = storeId;\n widget.postalCode = postalCode;\n widget.countryCode = countryCode;\n widget.orderId = String(orderId);\n widget.email = email;\n widget.cartTotal = cartTotal;\n widget.cart = cart;\n widget.discountCodes = discountCodes;\n widget.currencyCode = currencyCode;\n widget.domain = domain;\n widget.lang = lang;\n widget.debug = debug;\n\n // Insert widget into DOM\n parentElement.appendChild(widget);\n}\n"],"names":["SHOPIFY_BASE_URL","isBeamCartIntegrationRegistered","SHOPIFY_CART_COOKIE_NAME","registerCartIntegration","config","currentCart","getCurrentCart","cartCookie","getCookieValue","updateCart","addBeamAttributesToCart","initNetworkListeners","BeamNetworkCallEvent","_event","event","cartChangePaths","requestUrlStr","url","eventDetail","BeamCartChangeEvent","lastNonprofitId","lastSelectionId","BeamNonprofitSelectEvent","source","selectedNonprofitId","selectionId","WIDGET_NAMES","cartId","getExternalCartId","beamCartId","getBeamCartId","BEAM_CART_COOKIE_NAME","chainId","storeId","BeamNonprofitSelectionRemovedEvent","newNonprofitId","token","total_price","item_count","currency","items","cart_level_discount_applications","res","changed","cachedCart","createScopedLocalStorage","cart","sku","final_line_price","product_id","line_level_discount_allocations","remoteProductIdentifier","localAmount","discounts","discount_application","title","isEqual","trackCart","memoizeLast","showBeam","remoteSessionId","statsig","e","logger","beamCartAttrs","err","showBeamOrderPageWidgets","parentSelector","apiKey","baseUrl","DEFAULT_BASE_URL","postalCode","countryCode","orderId","email","cartTotal","discountCodes","currencyCode","domain","lang","debug","parentElement","waitForElement","BeamError","beamLocalStorage","existingValue","widget"],"mappings":"0wBAgCA,MAAMA,EAAmB,OAAO,SAAS,QAAQ,MAAQ,IAEzD,IAAIC,EAAkC,GAEtC,MAAMC,EAA2B,OAMjC,eAAeC,EAAwBC,EAA0C,CAC/E,GAAIH,EACF,MAAO,GAKT,MAAMI,EAAc,MAAMC,EAAeF,CAAM,EACzCG,EAAaC,EAAeN,CAAwB,EAEtDG,EAAY,KAAK,SAAWE,GAC9B,MAAME,EAAWL,EAAQC,EAAY,IAAI,EAG3C,MAAMK,EAAwB,CAAE,CAAA,EAEhCC,EAAqB,EAErB,OAAO,iBAAiBC,EAAqB,UAAW,MAAOC,GAAkB,CAC/E,MAAMC,EAAQD,EACRE,EAAkB,kCAElBC,EAAgBF,EAAM,OAAO,OAAS,MAAQA,EAAM,OAAO,IAAI,YAAcA,EAAM,OAAO,SAAS,IACnGG,EAAM,IAAI,IAAID,CAAa,EACjC,GAAI,CAACD,EAAgB,KAAKE,EAAI,QAAQ,EACpC,OAEF,MAAMZ,EAAc,MAAMC,EAAeF,CAAM,EAC/C,GAAI,CAACC,EAAY,QACf,OAEF,MAAMa,EAAwB,CAC5B,OAAQb,EAAY,KAAK,OACzB,QAAS,CACP,MAAOA,EAAY,KAAK,QAAQ,MAChC,UAAWA,EAAY,KAAK,QAAQ,SACtC,CACF,EACA,OAAO,cAAc,IAAIc,EAAoBD,CAAW,CAAC,EAEzD,MAAMT,EAAWL,EAAQC,EAAY,IAAI,CAC3C,CAAC,EAGD,IAAIe,EACAC,EACJ,OAAA,OAAO,iBAAiBC,EAAyB,UAAW,MAAOT,GAAW,CAC5E,MAAMC,EAAQD,EACR,CAAE,OAAAU,EAAQ,oBAAAC,EAAqB,YAAAC,CAAY,EAAIX,EAAM,OAE3D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
1
+ {"version":3,"file":"order-page-uEOo5EPy.esm.js","sources":["../../src/integrations/shopify/cart-page.ts","../../src/integrations/shopify/order-page.ts"],"sourcesContent":["/* eslint-disable camelcase */\nimport isEqual from \"lodash-es/isEqual\";\nimport { logger, memoizeLast } from \"../../utils\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { initNetworkListeners } from \"../../utils/network-listeners\";\nimport {\n BeamCartChangeEvent,\n BeamNetworkCallEvent,\n BeamNonprofitSelectEvent,\n BeamNonprofitSelectionRemovedEvent,\n} from \"../../utils/events\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { BEAM_CART_COOKIE_NAME, TBeamCartLocalStorage, TCart, TCartApi, TCartItems } from \"../../shared/cart-contents\";\nimport { BeamCartAPIConfig, updateCart } from \"../cart\";\nimport { WIDGET_NAMES } from \"../../api-sdk/constants\";\nimport { getBeamCartId, getExternalCartId } from \"../../utils/cart\";\n\nexport type BeamShopifyCartIntegrationConfig = BeamCartAPIConfig & {\n storeId: number; // will be added to cart custom_attributes, and used in cart API call\n chainId?: number; // will be added to cart custom_attributes\n};\n\ntype ShopifyDiscountApplication = {\n title: string;\n value: string;\n};\n\ntype ShopifyLineLevelDiscountAllocations = {\n amount?: string;\n discount_application: ShopifyDiscountApplication;\n};\n\nconst SHOPIFY_BASE_URL = window.Shopify?.routes?.root || \"/\"; // see window.d.ts\n\nlet isBeamCartIntegrationRegistered = false; // Skip registering event listeners if already set up\n\nconst SHOPIFY_CART_COOKIE_NAME = \"cart\";\n\n/**\n * @main registerCartIntegration - set up event listeners to integrate Beam with Shopify cart\n * @return {boolean} returns true if NEW listeners were created, false if setup was already done\n */\nasync function registerCartIntegration(config: BeamShopifyCartIntegrationConfig) {\n if (isBeamCartIntegrationRegistered) {\n return false; // Do nothing if listeners are already attached\n }\n\n // Handle full-page load, ie, first-time page load and reloads from form submit events\n // This creates a GET to /cart.js\n const currentCart = await getCurrentCart(config);\n const cartCookie = getCookieValue(SHOPIFY_CART_COOKIE_NAME);\n // only update on initial load if Shopify cart has changed since last visit\n if (currentCart.cart.cartId !== cartCookie) {\n await updateCart(config, currentCart.cart);\n }\n // pre load beam cart attribute to save statsig info\n await addBeamAttributesToCart({});\n // Set up event listeners for AJAX events\n initNetworkListeners();\n\n window.addEventListener(BeamNetworkCallEvent.eventName, async (_event: Event) => {\n const event = _event as BeamNetworkCallEvent;\n const cartChangePaths = /cart\\/(add|change|update|clear)/;\n // note: response urls below follow redirects\n const requestUrlStr = event.detail.type === \"xhr\" ? event.detail.xhr.responseURL : event.detail.response.url;\n const url = new URL(requestUrlStr);\n if (!cartChangePaths.test(url.pathname)) {\n return;\n }\n const currentCart = await getCurrentCart(config);\n if (!currentCart.changed) {\n return;\n }\n const eventDetail: TCartApi = {\n schema: currentCart.cart.schema as any, // TS union type can't figure out what variant applies here\n content: {\n items: currentCart.cart.content.items as any,\n discounts: currentCart.cart.content.discounts as any,\n },\n };\n window.dispatchEvent(new BeamCartChangeEvent(eventDetail));\n // Send cart to Beam to update timestamp, which is used for cart abandonment / ROI calc\n await updateCart(config, currentCart.cart);\n });\n\n // Listen to Beam's own events to integrate Beam data into Shopify order\n let lastNonprofitId: number | null | undefined;\n let lastSelectionId: string | null | undefined;\n window.addEventListener(BeamNonprofitSelectEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectEvent;\n const { source, selectedNonprofitId, selectionId } = event.detail;\n\n if (source === WIDGET_NAMES.select_nonprofit) {\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config); // Shopify cart ID\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config); // Beam cart ID\n const { chainId, storeId } = config;\n // Skip update if nothing changed (can happen if widget is re-initialized and\n // emits event after cache restoration, i.e., on cart re-render).\n if (lastNonprofitId === selectedNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId: beamCartId ? beamCartId : undefined,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = selectedNonprofitId;\n }\n });\n\n /**\n * Upon removal of the selected nonprofit from the widget and local storage,\n * an event is emitted and that event is then used to update the cart attributes accordingly\n * This event listener updates the cart attributes based on the emitted event\n */\n window.addEventListener(BeamNonprofitSelectionRemovedEvent.eventName, async (_event) => {\n const event = _event as BeamNonprofitSelectionRemovedEvent;\n const { newNonprofitId, selectionId } = event.detail;\n const cartId = getExternalCartId(SHOPIFY_CART_COOKIE_NAME, config);\n const beamCartId = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n const { chainId, storeId } = config;\n if (lastNonprofitId === newNonprofitId && lastSelectionId === selectionId) {\n return;\n }\n await addBeamAttributesToCart({\n selectedNonprofitId: newNonprofitId,\n beamCartId: beamCartId ? beamCartId : undefined,\n selectionId,\n cartId: cartId ? cartId : undefined,\n chainId,\n storeId,\n });\n lastSelectionId = selectionId;\n lastNonprofitId = newNonprofitId;\n });\n\n isBeamCartIntegrationRegistered = true;\n\n return true;\n}\n\n/* ***************************************** HELPER FUNCTIONS *****************************************\n These may be used individually to integrate with carts if the registerCartIntegration\n script doesn't work for some reason.\n ****************************************************************************************************/\n\n/**\n * Detects change in cart since last page load,\n * by calling GET /cart.js, and returns cart values.\n * Used for:\n * - Form-based carts where the page refreshes to modify cart instead of using AJAX calls\n * - Hydrogen/GraphQL based carts (needs to be integrated manually)\n */\nasync function getCurrentCart(config: BeamShopifyCartIntegrationConfig): Promise<{\n changed: boolean;\n cart: {\n cartId: string;\n subtotal: number;\n itemCount: number;\n currencyCode: string;\n } & TCart;\n}> {\n const {\n token, // equal to \"cart\" cookie\n total_price, // this is the pretax value, after discounts, and multiplied by 100 (integer from decimal)\n item_count,\n currency,\n items,\n cart_level_discount_applications,\n } = await window\n .fetch(SHOPIFY_BASE_URL + \"cart.js\", {\n method: \"GET\",\n headers: { \"Content-Type\": \"application/json\" },\n })\n .then((res) => res.json());\n\n let changed = false;\n\n const localStorage = createScopedLocalStorage(config);\n\n // The cart cache is used to detect changes after page refreshes / across tabs\n const cachedCart: TBeamCartLocalStorage | null = localStorage.getItemJson(\"cart\");\n // The Beam cart cookie is used to identify the cart across subdomains\n // Use explicit null if empty because API requires it\n const beamCartId: string | null = getBeamCartId(BEAM_CART_COOKIE_NAME, config);\n\n const cart = {\n cartId: token,\n beamCartId,\n subtotal: total_price / 100,\n itemCount: item_count,\n currencyCode: currency,\n schema: { source: \"generic\" } as const,\n content: {\n // pull out minimal fields from full line items\n items: (items as TCartItems).map(({ sku, final_line_price, product_id, line_level_discount_allocations }) => {\n const remoteProductIdentifier = sku || String(product_id);\n const localAmount = final_line_price / 100;\n const discounts = (line_level_discount_allocations as ShopifyLineLevelDiscountAllocations[])?.map(\n ({ discount_application }) => {\n return { code: discount_application?.title, applicable: true };\n }\n );\n return { remoteProductIdentifier, localAmount, discounts };\n }),\n discounts: (cart_level_discount_applications as ShopifyDiscountApplication[]).map(({ title }) => {\n return { code: title, applicable: true };\n }),\n },\n };\n\n if (\n !isEqual(cart, {\n ...cachedCart,\n beamCartId: cachedCart?.beamCartId,\n })\n ) {\n changed = true;\n }\n\n return { changed, cart };\n}\n\n/**\n * trackCart - Backwards-compatible alias for updateCart\n */\nconst trackCart = updateCart;\n\n/**\n * Sends Beam data to Shopify to integrate with order as custom attributes.\n * Memoized so that calls with the same data as the previous don't create additional API calls to Shopify.\n */\nconst addBeamAttributesToCart = memoizeLast(async function addBeamAttributesToCart({\n selectedNonprofitId,\n selectionId,\n beamCartId,\n cartId,\n chainId,\n storeId,\n}: {\n selectedNonprofitId?: number | null;\n selectionId?: string;\n beamCartId?: string;\n cartId?: string;\n chainId?: number;\n storeId?: number;\n}) {\n let showBeam;\n let remoteSessionId;\n try {\n if (window.statsig) {\n const statsig = window.statsig as any;\n showBeam = statsig.getLayer(\"beam_trial_layer\").get(\"show_beam\", false /* default to hide */) as boolean;\n remoteSessionId = statsig.getStableID();\n }\n } catch (e) {\n logger.error(e);\n }\n const beamCartAttrs = {\n beam: JSON.stringify({\n nonprofit_id: selectedNonprofitId,\n selection_id: selectionId,\n beam_cart_id: beamCartId,\n shopify_cart_id: cartId,\n chain_id: chainId,\n store_id: storeId,\n show_beam: showBeam,\n remote_session_id: remoteSessionId,\n }),\n };\n\n try {\n await window.fetch(SHOPIFY_BASE_URL + \"cart/update.js\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ attributes: beamCartAttrs }),\n });\n } catch (err) {\n logger.error(err); // don't throw, allow later calls to continue\n }\n});\n\ndeclare global {\n interface Window {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n statsig?: any; // attached by Statsig CDN script\n }\n}\nexport { trackCart, getCurrentCart, addBeamAttributesToCart, registerCartIntegration };\n","import \"../../components/post-purchase\";\nimport { postTransaction } from \"../../api-sdk/v3/routes\";\nimport { DEFAULT_BASE_URL } from \"../../api-sdk/constants\";\nimport { LANGUAGES, TUrl } from \"../../api-sdk/types\";\nimport { waitForElement } from \"../../utils/wait-for-element\";\nimport { BeamError } from \"../../utils/beam-errors\";\nimport { getCookieValue } from \"../../utils/cookies\";\nimport { createScopedLocalStorage } from \"../../utils/local-storage\";\nimport { TCart } from \"../../shared/cart-contents\";\n\n// Shopify admin page: admin/settings/checkout\n\nexport type TBeamOrderPageParams = Parameters<typeof postTransaction>[0][\"requestBody\"] & {\n // Either storeId or postalCode + countryCode must be provided\n storeId?: number;\n postalCode?: string;\n countryCode?: string;\n orderId: string;\n email: string;\n cartTotal: number;\n cart: TCart;\n discountCodes: string[];\n currencyCode: string;\n parentSelector: string; // CSS Selector for parent of widget to be inserted into DOM\n apiKey: string;\n baseUrl: TUrl;\n domain?: string; // Base domain for setting cookies\n lang: LANGUAGES;\n debug: boolean;\n};\n\nexport async function showBeamOrderPageWidgets({\n parentSelector = \".step__sections\",\n apiKey,\n baseUrl = DEFAULT_BASE_URL,\n storeId,\n postalCode,\n countryCode,\n orderId,\n email,\n cartTotal,\n cart,\n discountCodes,\n currencyCode = \"USD\",\n domain,\n lang = \"en\",\n debug = false,\n}: TBeamOrderPageParams) {\n const parentElement = document.querySelector(parentSelector) || (await waitForElement(parentSelector));\n if (!parentElement) {\n throw new BeamError(\n `Timed out waiting for selector '${parentSelector}'. Could not render Beam post-purchase widget.`\n );\n }\n\n // If checkout and order page are on different subdomains, we can't access localStorage\n // We can make postTransaction work by copying the cart cookie to the expected localStorage key on the current domain\n const cartId = await getCookieValue(\"cart\"); // Shopify-only cart identifier\n if (cartId) {\n const beamLocalStorage = createScopedLocalStorage({ apiKey });\n const existingValue = beamLocalStorage.getItemJson(\"cart\") || {};\n beamLocalStorage.setItemJson(\"cart\", { ...existingValue, cartId });\n }\n\n // Note: assign properties one by one instead of bulk Object.assign to type check assignments\n const widget = document.createElement(\"beam-post-purchase\");\n widget.apiKey = apiKey;\n widget.baseUrl = baseUrl;\n widget.storeId = storeId;\n widget.postalCode = postalCode;\n widget.countryCode = countryCode;\n widget.orderId = String(orderId);\n widget.email = email;\n widget.cartTotal = cartTotal;\n widget.cart = cart;\n widget.discountCodes = discountCodes;\n widget.currencyCode = currencyCode;\n widget.domain = domain;\n widget.lang = lang;\n widget.debug = debug;\n\n // Insert widget into DOM\n parentElement.appendChild(widget);\n}\n"],"names":["SHOPIFY_BASE_URL","isBeamCartIntegrationRegistered","SHOPIFY_CART_COOKIE_NAME","registerCartIntegration","config","currentCart","getCurrentCart","cartCookie","getCookieValue","updateCart","addBeamAttributesToCart","initNetworkListeners","BeamNetworkCallEvent","_event","event","cartChangePaths","requestUrlStr","url","eventDetail","BeamCartChangeEvent","lastNonprofitId","lastSelectionId","BeamNonprofitSelectEvent","source","selectedNonprofitId","selectionId","WIDGET_NAMES","cartId","getExternalCartId","beamCartId","getBeamCartId","BEAM_CART_COOKIE_NAME","chainId","storeId","BeamNonprofitSelectionRemovedEvent","newNonprofitId","token","total_price","item_count","currency","items","cart_level_discount_applications","res","changed","cachedCart","createScopedLocalStorage","cart","sku","final_line_price","product_id","line_level_discount_allocations","remoteProductIdentifier","localAmount","discounts","discount_application","title","isEqual","trackCart","memoizeLast","showBeam","remoteSessionId","statsig","e","logger","beamCartAttrs","err","showBeamOrderPageWidgets","parentSelector","apiKey","baseUrl","DEFAULT_BASE_URL","postalCode","countryCode","orderId","email","cartTotal","discountCodes","currencyCode","domain","lang","debug","parentElement","waitForElement","BeamError","beamLocalStorage","existingValue","widget"],"mappings":"0wBAgCA,MAAMA,EAAmB,OAAO,SAAS,QAAQ,MAAQ,IAEzD,IAAIC,EAAkC,GAEtC,MAAMC,EAA2B,OAMjC,eAAeC,EAAwBC,EAA0C,CAC/E,GAAIH,EACF,MAAO,GAKT,MAAMI,EAAc,MAAMC,EAAeF,CAAM,EACzCG,EAAaC,EAAeN,CAAwB,EAEtDG,EAAY,KAAK,SAAWE,GAC9B,MAAME,EAAWL,EAAQC,EAAY,IAAI,EAG3C,MAAMK,EAAwB,CAAE,CAAA,EAEhCC,EAAqB,EAErB,OAAO,iBAAiBC,EAAqB,UAAW,MAAOC,GAAkB,CAC/E,MAAMC,EAAQD,EACRE,EAAkB,kCAElBC,EAAgBF,EAAM,OAAO,OAAS,MAAQA,EAAM,OAAO,IAAI,YAAcA,EAAM,OAAO,SAAS,IACnGG,EAAM,IAAI,IAAID,CAAa,EACjC,GAAI,CAACD,EAAgB,KAAKE,EAAI,QAAQ,EACpC,OAEF,MAAMZ,EAAc,MAAMC,EAAeF,CAAM,EAC/C,GAAI,CAACC,EAAY,QACf,OAEF,MAAMa,EAAwB,CAC5B,OAAQb,EAAY,KAAK,OACzB,QAAS,CACP,MAAOA,EAAY,KAAK,QAAQ,MAChC,UAAWA,EAAY,KAAK,QAAQ,SACtC,CACF,EACA,OAAO,cAAc,IAAIc,EAAoBD,CAAW,CAAC,EAEzD,MAAMT,EAAWL,EAAQC,EAAY,IAAI,CAC3C,CAAC,EAGD,IAAIe,EACAC,EACJ,OAAA,OAAO,iBAAiBC,EAAyB,UAAW,MAAOT,GA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AeT,EACtBS,EAAO,OAASR,EAChBQ,EAAO,KAAOP,EACdO,EAAO,MAAQN,EAGfC,EAAc,YAAYK,CAAM,CAClC"}
@@ -1,4 +1,4 @@
1
- import{h as s,f,y as b,g as p}from"./lit-iNN5L_Qk.esm.js";import"./vendor-GKiOHg2N.esm.js";var P=Object.defineProperty,d=Object.getOwnPropertyDescriptor,n=(l,o,a,e)=>{for(var r=e>1?void 0:e?d(o,a):o,t=l.length-1,m;t>=0;t--)(m=l[t])&&(r=(e?m(o,a,r):m(r))||r);return e&&r&&P(o,a,r),r};class i extends s{constructor(){super(...arguments),this.promo=null,this.shortVersion=!1}static get styles(){return f`
1
+ import{h as s,f as d,y as b,g as p}from"./lit-iNN5L_Qk.esm.js";import"./vendor-GKiOHg2N.esm.js";var f=Object.defineProperty,P=Object.getOwnPropertyDescriptor,n=(l,o,a,e)=>{for(var r=e>1?void 0:e?P(o,a):o,t=l.length-1,i;t>=0;t--)(i=l[t])&&(r=(e?i(o,a,r):i(r))||r);return e&&r&&f(o,a,r),r};class m extends s{constructor(){super(...arguments),this.promo=null,this.shortVersion=!1}static get styles(){return d`
2
2
  sl-badge::part(base) {
3
3
  background-color: var(--beam-promoPillLabel-color-background, #000);
4
4
  color: var(--beam-promoPillLabel-color, #fff);
@@ -9,7 +9,8 @@ import{h as s,f,y as b,g as p}from"./lit-iNN5L_Qk.esm.js";import"./vendor-GKiOHg
9
9
  font-weight: var(--beam-promoPillLabel-font-weight, bold);
10
10
  text-transform: var(--beam-promoPillLabel-text-transform, none);
11
11
  text-wrap: var(--beam-promoPillLabel-text-wrap, wrap);
12
+ padding: var(--beam-promoPillLabel-text-padding);
12
13
  margin: var(--beam-promoPillLabel-border-margin);
13
14
  }
14
- `}render(){if(this.promo){const o=this.shortVersion?this.promo["promo-text-short"]:this.promo["promo-text-long"];return b`<sl-badge pill aria-label="${o}">${o}</sl-badge>`}else return b``}}n([p({type:Object})],i.prototype,"promo",2),n([p({type:Boolean})],i.prototype,"shortVersion",2),customElements.get("beam-promo-info-pill")||customElements.define("beam-promo-info-pill",i);const c={"--beam-promoPillLabel-color-background":"#000","--beam-promoPillLabel-color":"#fff","--beam-promoPillLabel-border":"#000","--beam-promoPillLabel-border-width":"0px","--beam-promoPillLabel-font-size":"11px","--beam-promoPillLabel-font":"inherit","--beam-promoPillLabel-font-weight":"normal","--beam-promoPillLabel-text-transform":"none","--beam-promoPillLabel-text-wrap":"wrap","--beam-promoPillLabel-border-margin":"0px"};export{c as p};
15
- //# sourceMappingURL=promo-pill-label-58PJRvSl.esm.js.map
15
+ `}render(){if(this.promo){const o=this.shortVersion?this.promo["promo-text-short"]:this.promo["promo-text-long"];return b`<sl-badge pill aria-label="${o}">${o}</sl-badge>`}else return b``}}n([p({type:Object})],m.prototype,"promo",2),n([p({type:Boolean})],m.prototype,"shortVersion",2),customElements.get("beam-promo-info-pill")||customElements.define("beam-promo-info-pill",m);const g={"--beam-promoPillLabel-color-background":"#000","--beam-promoPillLabel-color":"#fff","--beam-promoPillLabel-border":"#000","--beam-promoPillLabel-border-width":"0px","--beam-promoPillLabel-font-size":"11px","--beam-promoPillLabel-font":"inherit","--beam-promoPillLabel-font-weight":"bold","--beam-promoPillLabel-text-transform":"none","--beam-promoPillLabel-text-wrap":"wrap","--beam-promoPillLabel-text-padding":"4px 15px","--beam-promoPillLabel-border-margin":"0px"};export{g as p};
16
+ //# sourceMappingURL=promo-pill-label-P1X4xeAx.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promo-pill-label-P1X4xeAx.esm.js","sources":["../../src/shared/components/promo-pill-label.ts"],"sourcesContent":["import { css, html, LitElement } from \"lit\";\nimport { property } from \"lit/decorators/property.js\";\nimport \"@shoelace-style/shoelace/dist/components/badge/badge.js\";\n\ntype Promo = {\n \"promo-text-long\": string;\n \"promo-text-short\": string;\n};\n\nexport class BeamPromoInfoPill extends LitElement {\n @property({ type: Object }) promo: Promo | null = null;\n @property({ type: Boolean }) shortVersion = false;\n\n static get styles() {\n return css`\n sl-badge::part(base) {\n background-color: var(--beam-promoPillLabel-color-background, #000);\n color: var(--beam-promoPillLabel-color, #fff);\n border: var(--beam-promoPillLabel-border-width, 0px) solid var(--beam-promoPillLabel-border, #000);\n border-radius: 18.37px;\n font-family: var(--beam-promoPillLabel-font, inherit);\n font-size: var(--beam-promoPillLabel-font-size, 12px);\n font-weight: var(--beam-promoPillLabel-font-weight, bold);\n text-transform: var(--beam-promoPillLabel-text-transform, none);\n text-wrap: var(--beam-promoPillLabel-text-wrap, wrap);\n padding: var(--beam-promoPillLabel-text-padding);\n margin: var(--beam-promoPillLabel-border-margin);\n }\n `;\n }\n\n render() {\n if (this.promo) {\n const promoText = this.shortVersion ? this.promo[\"promo-text-short\"] : this.promo[\"promo-text-long\"];\n return html`<sl-badge pill aria-label=\"${promoText}\">${promoText}</sl-badge>`;\n } else {\n return html``;\n }\n }\n}\n\ncustomElements.get(\"beam-promo-info-pill\") || customElements.define(\"beam-promo-info-pill\", BeamPromoInfoPill);\n\nexport const promoPillLabelConfigDefaults = {\n \"--beam-promoPillLabel-color-background\": \"#000\",\n \"--beam-promoPillLabel-color\": \"#fff\",\n \"--beam-promoPillLabel-border\": \"#000\",\n \"--beam-promoPillLabel-border-width\": \"0px\",\n \"--beam-promoPillLabel-font-size\": \"11px\",\n \"--beam-promoPillLabel-font\": \"inherit\",\n \"--beam-promoPillLabel-font-weight\": \"bold\",\n \"--beam-promoPillLabel-text-transform\": \"none\",\n \"--beam-promoPillLabel-text-wrap\": \"wrap\",\n \"--beam-promoPillLabel-text-padding\": \"4px 15px\",\n \"--beam-promoPillLabel-border-margin\": \"0px\",\n} as const;\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"beam-promo-info-pill\": BeamPromoInfoPill;\n }\n}\n"],"names":["BeamPromoInfoPill","LitElement","css","promoText","html","__decorateClass","property","promoPillLabelConfigDefaults"],"mappings":"gSASa,MAAAA,UAA0BC,CAAW,CAA3C,aACuB,CAAA,MAAA,GAAA,SAAA,EAAA,KAAA,MAAsB,KACrB,KAAA,aAAe,EAE5C,CAAA,WAAW,QAAS,CAClB,OAAOC;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA,KAeT,CAEA,QAAS,CACP,GAAI,KAAK,MAAO,CACd,MAAMC,EAAY,KAAK,aAAe,KAAK,MAAM,kBAAkB,EAAI,KAAK,MAAM,iBAAiB,EACnG,OAAOC,+BAAkCD,CAAS,KAAKA,CAAS,aAClE,KACE,QAAOC,GAEX,CACF,CA7B8BC,EAAA,CAA3BC,EAAS,CAAE,KAAM,MAAO,CAAC,CAAA,EADfN,EACiB,UACCK,QAAAA,CAAAA,EAAAA,EAAA,CAA5BC,EAAS,CAAE,KAAM,OAAQ,CAAC,CAFhB,EAAAN,EAEkB,4BA8B/B,eAAe,IAAI,sBAAsB,GAAK,eAAe,OAAO,uBAAwBA,CAAiB,EAEtG,MAAMO,EAA+B,CAC1C,yCAA0C,OAC1C,8BAA+B,OAC/B,+BAAgC,OAChC,qCAAsC,MACtC,kCAAmC,OACnC,6BAA8B,UAC9B,oCAAqC,OACrC,uCAAwC,OACxC,kCAAmC,OACnC,qCAAsC,WACtC,sCAAuC,KACzC"}
@@ -1,2 +1,2 @@
1
- import{B as v,N as m}from"./beam-errors-P-Lu07Ce.esm.js";import{logger as p}from"../utils/logger.js";var E="1.45.3",N={"@lit/react":"1.0.0","@lukeed/uuid":"2.0.0","@shoelace-style/shoelace":"2.15.0",lit:"2.6.1","lodash-es":"4.17.21","lucide-static":"0.292.0"};async function w(s,o){const c={method:"GET",...o,headers:{"Content-Type":"application/json",Accept:"application/json","X-Beam-Client":"WebSDK","X-Beam-Client-Version":E,...o?.headers},preflightContinue:!0,mode:o?.mode||"cors",body:o?.body!=null?o.body:void 0};let i;try{i=await fetch(s,c)}catch(e){const a=new v(`Network call failed (${c?.method.toUpperCase()} ${s})`);throw a.cause=e,p.error(a,s),a}let r,n;try{n=await i.text(),n&&(r=JSON.parse(n))}catch(e){let a=e;throw e instanceof SyntaxError&&(a=new m(i,r,`Response invalid. Expected JSON. Received: "${n}"`),a.cause=e),p.error(a),a}if(!i.ok){const e=new m(i,r,"Response was not OK");throw p.error(e),e}return r}const u="https://api.beamimpact.com",C="https://production.beamimpactlogs.com",O={en:"en",fr:"fr",de:"de",es:"es",it:"it",pl:"pl"},T={select_nonprofit:"select-nonprofit",redeem_transaction:"redeem-transaction",impact_overview:"impact-overview",community_impact:"community-impact",cumulative_impact:"cumulative-impact",product_details_page:"product-details-page",subscription_management:"subscription-management",subscription_impact:"subscription-impact",select_subscription_nonprofit:"select-subscription-nonprofit",social_share:"social-share"},t=(s,o,c)=>({[s]:async function({headers:i={},baseUrl:r=u,apiRoot:n="/api/v3",pathParams:e={},queryParams:a={},requestBody:d}){const h=Object.entries(e).reduce((S,[y,_])=>S.replace(`{${y}}`,_),s),f=JSON.parse(JSON.stringify(a)),l=new URLSearchParams(f).toString(),b=r+n+h+(l&&`?${l}`),g={headers:i,method:o,body:JSON.stringify(d)};return w(b,g)}})[s],U=t("/impact","get"),A=t("/chain/{chainId}/cumulativeImpact","get"),D=t("/selectNonprofit","post"),L=t("/transaction","post"),P=t("/transaction/{transactionId}","put"),R=t("/cart","post"),k=t("/chain/findEligibleNonprofitsForCart","post"),x=t("/logs","post"),B=t("/experimentSession","post"),I=t("/subscriptions/updateSubscriptionNonprofit","post"),J=t("/subscriptions/findOrCreateSubscription","post"),F=t("/productDetailsPage","get");export{u as D,O as S,T as W,C as a,R as b,x as c,N as d,B as e,k as f,U as g,J as h,D as i,P as j,F as k,A as l,L as p,I as u};
2
- //# sourceMappingURL=routes-kK10CmJz.esm.js.map
1
+ import{B as v,N as m}from"./beam-errors-P-Lu07Ce.esm.js";import{logger as p}from"../utils/logger.js";var E="1.46.0",N={"@lit/react":"1.0.0","@lukeed/uuid":"2.0.0","@shoelace-style/shoelace":"2.15.0",lit:"2.6.1","lodash-es":"4.17.21","lucide-static":"0.292.0"};async function w(s,o){const c={method:"GET",...o,headers:{"Content-Type":"application/json",Accept:"application/json","X-Beam-Client":"WebSDK","X-Beam-Client-Version":E,...o?.headers},preflightContinue:!0,mode:o?.mode||"cors",body:o?.body!=null?o.body:void 0};let i;try{i=await fetch(s,c)}catch(e){const a=new v(`Network call failed (${c?.method.toUpperCase()} ${s})`);throw a.cause=e,p.error(a,s),a}let r,n;try{n=await i.text(),n&&(r=JSON.parse(n))}catch(e){let a=e;throw e instanceof SyntaxError&&(a=new m(i,r,`Response invalid. Expected JSON. Received: "${n}"`),a.cause=e),p.error(a),a}if(!i.ok){const e=new m(i,r,"Response was not OK");throw p.error(e),e}return r}const u="https://api.beamimpact.com",C="https://production.beamimpactlogs.com",O={en:"en",fr:"fr",de:"de",es:"es",it:"it",pl:"pl"},T={select_nonprofit:"select-nonprofit",redeem_transaction:"redeem-transaction",impact_overview:"impact-overview",community_impact:"community-impact",cumulative_impact:"cumulative-impact",product_details_page:"product-details-page",subscription_management:"subscription-management",subscription_impact:"subscription-impact",select_subscription_nonprofit:"select-subscription-nonprofit",social_share:"social-share"},t=(s,o,c)=>({[s]:async function({headers:i={},baseUrl:r=u,apiRoot:n="/api/v3",pathParams:e={},queryParams:a={},requestBody:d}){const h=Object.entries(e).reduce((S,[y,_])=>S.replace(`{${y}}`,_),s),f=JSON.parse(JSON.stringify(a)),l=new URLSearchParams(f).toString(),b=r+n+h+(l&&`?${l}`),g={headers:i,method:o,body:JSON.stringify(d)};return w(b,g)}})[s],U=t("/impact","get"),A=t("/chain/{chainId}/cumulativeImpact","get"),D=t("/selectNonprofit","post"),L=t("/transaction","post"),P=t("/transaction/{transactionId}","put"),R=t("/cart","post"),k=t("/chain/findEligibleNonprofitsForCart","post"),x=t("/logs","post"),B=t("/experimentSession","post"),I=t("/subscriptions/updateSubscriptionNonprofit","post"),J=t("/subscriptions/findOrCreateSubscription","post"),F=t("/productDetailsPage","get");export{u as D,O as S,T as W,C as a,R as b,x as c,N as d,B as e,k as f,U as g,J as h,D as i,P as j,A as k,F as l,L as p,I as u};
2
+ //# sourceMappingURL=routes-F1ZIumMP.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"routes-kK10CmJz.esm.js","sources":["../../src/api-sdk/fetch-json.ts","../../src/api-sdk/constants.ts","../../src/api-sdk/v3/make-openapi-method.ts","../../src/api-sdk/v3/routes.ts"],"sourcesContent":["/**\n * Wrapper over window.fetch that expects/returns JSON\n */\nimport { BeamError, NetworkError } from \"../utils/beam-errors\";\nimport { logger } from \"../utils/logger\";\nimport { version as pkgVersion } from \"../../package.json\";\n\nexport async function fetchJson<T = unknown>(url: RequestInfo, options?: RequestInit): Promise<T> {\n const fetchOptions = {\n method: \"GET\",\n ...options,\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"X-Beam-Client\": \"WebSDK\",\n \"X-Beam-Client-Version\": pkgVersion,\n ...options?.headers,\n },\n preflightContinue: true,\n mode: options?.mode || \"cors\",\n body: options?.body != null ? options.body : undefined,\n };\n\n let response;\n try {\n response = await fetch(url, fetchOptions);\n // fetch can throw a TypeError if the server can't be reached, catch and log below\n } catch (err) {\n const error = new BeamError(`Network call failed (${fetchOptions?.method.toUpperCase()} ${url})`);\n error.cause = err;\n logger.error(error, url);\n throw error;\n }\n let body;\n let text;\n // This can throw a SyntaxError if response payload is malformed JSON\n try {\n text = await response.text();\n if (text) {\n // (response can be empty)\n body = JSON.parse(text);\n }\n } catch (err) {\n let error = err as Error;\n if (err instanceof SyntaxError) {\n error = new NetworkError(response, body, `Response invalid. Expected JSON. Received: \"${text}\"`);\n error.cause = err;\n }\n logger.error(error);\n throw error;\n }\n // Translate 4xx, 5xx status to runtime error\n if (!response.ok) {\n const error = new NetworkError(response, body, \"Response was not OK\");\n logger.error(error);\n throw error;\n }\n\n return body;\n}\n","import { LANGUAGES, TUrl } from \"./types\";\n\nexport const DEFAULT_BASE_URL: TUrl = \"https://api.beamimpact.com\";\n\nexport const DEFAULT_LOG_URL = \"https://production.beamimpactlogs.com\";\n\nexport const SUPPORTED_LANGUAGES: Record<string, LANGUAGES> = {\n en: \"en\",\n fr: \"fr\",\n de: \"de\",\n es: \"es\",\n it: \"it\",\n pl: \"pl\",\n};\n\nexport const WIDGET_NAMES = {\n select_nonprofit: \"select-nonprofit\",\n redeem_transaction: \"redeem-transaction\",\n impact_overview: \"impact-overview\",\n community_impact: \"community-impact\",\n cumulative_impact: \"cumulative-impact\",\n product_details_page: \"product-details-page\",\n subscription_management: \"subscription-management\",\n subscription_impact: \"subscription-impact\",\n select_subscription_nonprofit: \"select-subscription-nonprofit\",\n social_share: \"social-share\",\n} as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { fetchJson } from \"../fetch-json\";\nimport { DEFAULT_BASE_URL } from \"../constants\";\nimport { THttpMethod } from \"../types\";\nimport { paths } from \"./openapi-spec\";\n\nexport const makeOpenApiMethod = <\n TPathName extends keyof paths,\n TMethod extends keyof paths[TPathName],\n TStatusCode extends paths[TPathName][TMethod] extends { responses: any }\n ? keyof paths[TPathName][TMethod][\"responses\"]\n : never\n>(\n pathName: TPathName,\n method: TMethod,\n okHttpStatus: TStatusCode\n) => {\n type TRouteSpec = paths[typeof pathName];\n type TRouteMethod = TRouteSpec[typeof method];\n type TParams = \"parameters\" extends keyof TRouteMethod ? TRouteMethod[\"parameters\"] : never;\n type TPathParams = TParams extends { path: any } ? TParams[\"path\"] : Record<string, never>;\n type TQueryParams = TParams extends { query: any } ? TParams[\"query\"] : Record<string, never>;\n type TRequestBody = TRouteMethod extends { requestBody: { content: { \"application/json\": any } } }\n ? TRouteMethod[\"requestBody\"][\"content\"][\"application/json\"]\n : never;\n type TAllResponses = TRouteMethod extends { responses: any } ? TRouteMethod[\"responses\"] : never;\n type TOkResponse = TAllResponses[typeof okHttpStatus] extends { content: { \"application/json\": any } }\n ? TAllResponses[typeof okHttpStatus][\"content\"][\"application/json\"]\n : never;\n const openApi = {\n [pathName]: async function ({\n headers = {},\n baseUrl = DEFAULT_BASE_URL,\n apiRoot = \"/api/v3\",\n pathParams = {},\n queryParams = {},\n requestBody,\n }: {\n baseUrl?: string;\n apiRoot?: string;\n pathParams?: TPathParams;\n queryParams?: TQueryParams;\n requestBody?: TRequestBody;\n headers?: Record<string, string>;\n }) {\n const pathWithParams: string = Object.entries(pathParams).reduce((newPath: string, [k, v]) => {\n return newPath.replace(`{${k}}`, v as string);\n }, pathName as string);\n const cleanQueryParams = JSON.parse(JSON.stringify(queryParams));\n const search = new URLSearchParams(cleanQueryParams as unknown as Record<string, string>).toString();\n const url = baseUrl + apiRoot + pathWithParams + (search && `?${search}`);\n const options = { headers, method: method as THttpMethod, body: JSON.stringify(requestBody) };\n\n return fetchJson<TOkResponse>(url, options);\n },\n };\n\n // Use object to create function with dynamic name, for better stacktraces\n return openApi[pathName];\n};\n","import { makeOpenApiMethod } from \"./make-openapi-method\";\n\nexport const getChainNonprofits = makeOpenApiMethod(\"/chain/{chainId}/nonprofits\", \"get\", 200);\n\nexport const getImpact = makeOpenApiMethod(\"/impact\", \"get\", 200);\n\nexport const getCumulativeImpact = makeOpenApiMethod(\"/chain/{chainId}/cumulativeImpact\", \"get\", 200);\n\nexport const postSelectNonprofit = makeOpenApiMethod(\"/selectNonprofit\", \"post\", 201);\n\nexport const postTransaction = makeOpenApiMethod(\"/transaction\", \"post\", 201);\n\nexport const putTransaction = makeOpenApiMethod(\"/transaction/{transactionId}\", \"put\", 204);\n\nexport const postCart = makeOpenApiMethod(\"/cart\", \"post\", 200);\n\nexport const postChainEligibleNonprofitsForCart = makeOpenApiMethod(\n \"/chain/findEligibleNonprofitsForCart\",\n \"post\",\n 200\n);\n\nexport const postLogs = makeOpenApiMethod(\"/logs\", \"post\", 200);\n\nexport const postExperimentSession = makeOpenApiMethod(\"/experimentSession\", \"post\", 200);\n\nexport const updateSubscription = makeOpenApiMethod(\"/subscriptions/updateSubscriptionNonprofit\", \"post\", 200);\n\nexport const postFindOrCreateSubscription = makeOpenApiMethod(\"/subscriptions/findOrCreateSubscription\", \"post\", 200);\n\nexport const getProductDetailsPage = makeOpenApiMethod(\"/productDetailsPage\", \"get\", 200);\n"],"names":["fetchJson","url","options","fetchOptions","pkgVersion","response","err","error","BeamError","logger","body","text","NetworkError","DEFAULT_BASE_URL","DEFAULT_LOG_URL","SUPPORTED_LANGUAGES","WIDGET_NAMES","makeOpenApiMethod","pathName","method","okHttpStatus","headers","baseUrl","apiRoot","pathParams","queryParams","requestBody","pathWithParams","newPath","k","v","cleanQueryParams","search","getImpact","getCumulativeImpact","postSelectNonprofit","postTransaction","putTransaction","postCart","postChainEligibleNonprofitsForCart","postLogs","postExperimentSession","updateSubscription","postFindOrCreateSubscription","getProductDetailsPage"],"mappings":"oQAOA,eAAsBA,EAAuBC,EAAkBC,EAAmC,CAChG,MAAMC,EAAe,CACnB,OAAQ,MACR,GAAGD,EACH,QAAS,CACP,eAAgB,mBAChB,OAAQ,mBACR,gBAAiB,SACjB,wBAAyBE,EACzB,GAAGF,GAAS,OACd,EACA,kBAAmB,GACnB,KAAMA,GAAS,MAAQ,OACvB,KAAMA,GAAS,MAAQ,KAAOA,EAAQ,KAAO,MAC/C,EAEA,IAAIG,EACJ,GAAI,CACFA,EAAW,MAAM,MAAMJ,EAAKE,CAAY,CAE1C,OAASG,EAAK,CACZ,MAAMC,EAAQ,IAAIC,EAAU,wBAAwBL,GAAc,OAAO,YAAa,CAAA,IAAIF,CAAG,GAAG,EAChG,MAAAM,EAAM,MAAQD,EACdG,EAAO,MAAMF,EAAON,CAAG,EACjBM,CACR,CACA,IAAIG,EACAC,EAEJ,GAAI,CACFA,EAAO,MAAMN,EAAS,OAClBM,IAEFD,EAAO,KAAK,MAAMC,CAAI,EAE1B,OAASL,EAAK,CACZ,IAAIC,EAAQD,EACZ,MAAIA,aAAe,cACjBC,EAAQ,IAAIK,EAAaP,EAAUK,EAAM,+CAA+CC,CAAI,GAAG,EAC/FJ,EAAM,MAAQD,GAEhB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B,EAAsBlB,EAAkB,mBAAoB,MAAW,EAEvEmB,EAAkBnB,EAAkB,eAAgB,MAAW,EAE/DoB,EAAiBpB,EAAkB,+BAAgC,KAAU,EAE7EqB,EAAWrB,EAAkB,QAAS,MAAW,EAEjDsB,EAAqCtB,EAChD,uCACA,MAEF,EAEauB,EAAWvB,EAAkB,QAAS,MAAW,EAEjDwB,EAAwBxB,EAAkB,qBAAsB,MAAW,EAE3EyB,EAAqBzB,EAAkB,6CAA8C,MAAW,EAEhG0B,EAA+B1B,EAAkB,0CAA2C,MAAW,EAEvG2B,EAAwB3B,EAAkB,sBAAuB,KAAU"}
1
+ {"version":3,"file":"routes-F1ZIumMP.esm.js","sources":["../../src/api-sdk/fetch-json.ts","../../src/api-sdk/constants.ts","../../src/api-sdk/v3/make-openapi-method.ts","../../src/api-sdk/v3/routes.ts"],"sourcesContent":["/**\n * Wrapper over window.fetch that expects/returns JSON\n */\nimport { BeamError, NetworkError } from \"../utils/beam-errors\";\nimport { logger } from \"../utils/logger\";\nimport { version as pkgVersion } from \"../../package.json\";\n\nexport async function fetchJson<T = unknown>(url: RequestInfo, options?: RequestInit): Promise<T> {\n const fetchOptions = {\n method: \"GET\",\n ...options,\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"X-Beam-Client\": \"WebSDK\",\n \"X-Beam-Client-Version\": pkgVersion,\n ...options?.headers,\n },\n preflightContinue: true,\n mode: options?.mode || \"cors\",\n body: options?.body != null ? options.body : undefined,\n };\n\n let response;\n try {\n response = await fetch(url, fetchOptions);\n // fetch can throw a TypeError if the server can't be reached, catch and log below\n } catch (err) {\n const error = new BeamError(`Network call failed (${fetchOptions?.method.toUpperCase()} ${url})`);\n error.cause = err;\n logger.error(error, url);\n throw error;\n }\n let body;\n let text;\n // This can throw a SyntaxError if response payload is malformed JSON\n try {\n text = await response.text();\n if (text) {\n // (response can be empty)\n body = JSON.parse(text);\n }\n } catch (err) {\n let error = err as Error;\n if (err instanceof SyntaxError) {\n error = new NetworkError(response, body, `Response invalid. Expected JSON. Received: \"${text}\"`);\n error.cause = err;\n }\n logger.error(error);\n throw error;\n }\n // Translate 4xx, 5xx status to runtime error\n if (!response.ok) {\n const error = new NetworkError(response, body, \"Response was not OK\");\n logger.error(error);\n throw error;\n }\n\n return body;\n}\n","import { LANGUAGES, TUrl } from \"./types\";\n\nexport const DEFAULT_BASE_URL: TUrl = \"https://api.beamimpact.com\";\n\nexport const DEFAULT_LOG_URL = \"https://production.beamimpactlogs.com\";\n\nexport const SUPPORTED_LANGUAGES: Record<string, LANGUAGES> = {\n en: \"en\",\n fr: \"fr\",\n de: \"de\",\n es: \"es\",\n it: \"it\",\n pl: \"pl\",\n};\n\nexport const WIDGET_NAMES = {\n select_nonprofit: \"select-nonprofit\",\n redeem_transaction: \"redeem-transaction\",\n impact_overview: \"impact-overview\",\n community_impact: \"community-impact\",\n cumulative_impact: \"cumulative-impact\",\n product_details_page: \"product-details-page\",\n subscription_management: \"subscription-management\",\n subscription_impact: \"subscription-impact\",\n select_subscription_nonprofit: \"select-subscription-nonprofit\",\n social_share: \"social-share\",\n} as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { fetchJson } from \"../fetch-json\";\nimport { DEFAULT_BASE_URL } from \"../constants\";\nimport { THttpMethod } from \"../types\";\nimport { paths } from \"./openapi-spec\";\n\nexport const makeOpenApiMethod = <\n TPathName extends keyof paths,\n TMethod extends keyof paths[TPathName],\n TStatusCode extends paths[TPathName][TMethod] extends { responses: any }\n ? keyof paths[TPathName][TMethod][\"responses\"]\n : never\n>(\n pathName: TPathName,\n method: TMethod,\n okHttpStatus: TStatusCode\n) => {\n type TRouteSpec = paths[typeof pathName];\n type TRouteMethod = TRouteSpec[typeof method];\n type TParams = \"parameters\" extends keyof TRouteMethod ? TRouteMethod[\"parameters\"] : never;\n type TPathParams = TParams extends { path: any } ? TParams[\"path\"] : Record<string, never>;\n type TQueryParams = TParams extends { query: any } ? TParams[\"query\"] : Record<string, never>;\n type TRequestBody = TRouteMethod extends { requestBody: { content: { \"application/json\": any } } }\n ? TRouteMethod[\"requestBody\"][\"content\"][\"application/json\"]\n : never;\n type TAllResponses = TRouteMethod extends { responses: any } ? TRouteMethod[\"responses\"] : never;\n type TOkResponse = TAllResponses[typeof okHttpStatus] extends { content: { \"application/json\": any } }\n ? TAllResponses[typeof okHttpStatus][\"content\"][\"application/json\"]\n : never;\n const openApi = {\n [pathName]: async function ({\n headers = {},\n baseUrl = DEFAULT_BASE_URL,\n apiRoot = \"/api/v3\",\n pathParams = {},\n queryParams = {},\n requestBody,\n }: {\n baseUrl?: string;\n apiRoot?: string;\n pathParams?: TPathParams;\n queryParams?: TQueryParams;\n requestBody?: TRequestBody;\n headers?: Record<string, string>;\n }) {\n const pathWithParams: string = Object.entries(pathParams).reduce((newPath: string, [k, v]) => {\n return newPath.replace(`{${k}}`, v as string);\n }, pathName as string);\n const cleanQueryParams = JSON.parse(JSON.stringify(queryParams));\n const search = new URLSearchParams(cleanQueryParams as unknown as Record<string, string>).toString();\n const url = baseUrl + apiRoot + pathWithParams + (search && `?${search}`);\n const options = { headers, method: method as THttpMethod, body: JSON.stringify(requestBody) };\n\n return fetchJson<TOkResponse>(url, options);\n },\n };\n\n // Use object to create function with dynamic name, for better stacktraces\n return openApi[pathName];\n};\n","import { makeOpenApiMethod } from \"./make-openapi-method\";\n\nexport const getChainNonprofits = makeOpenApiMethod(\"/chain/{chainId}/nonprofits\", \"get\", 200);\n\nexport const getImpact = makeOpenApiMethod(\"/impact\", \"get\", 200);\n\nexport const getCumulativeImpact = makeOpenApiMethod(\"/chain/{chainId}/cumulativeImpact\", \"get\", 200);\n\nexport const postSelectNonprofit = makeOpenApiMethod(\"/selectNonprofit\", \"post\", 201);\n\nexport const postTransaction = makeOpenApiMethod(\"/transaction\", \"post\", 201);\n\nexport const putTransaction = makeOpenApiMethod(\"/transaction/{transactionId}\", \"put\", 204);\n\nexport const postCart = makeOpenApiMethod(\"/cart\", \"post\", 200);\n\nexport const postChainEligibleNonprofitsForCart = makeOpenApiMethod(\n \"/chain/findEligibleNonprofitsForCart\",\n \"post\",\n 200\n);\n\nexport const postLogs = makeOpenApiMethod(\"/logs\", \"post\", 200);\n\nexport const postExperimentSession = makeOpenApiMethod(\"/experimentSession\", \"post\", 200);\n\nexport const updateSubscription = makeOpenApiMethod(\"/subscriptions/updateSubscriptionNonprofit\", \"post\", 200);\n\nexport const postFindOrCreateSubscription = makeOpenApiMethod(\"/subscriptions/findOrCreateSubscription\", \"post\", 200);\n\nexport const getProductDetailsPage = makeOpenApiMethod(\"/productDetailsPage\", \"get\", 200);\n"],"names":["fetchJson","url","options","fetchOptions","pkgVersion","response","err","error","BeamError","logger","body","text","NetworkError","DEFAULT_BASE_URL","DEFAULT_LOG_URL","SUPPORTED_LANGUAGES","WIDGET_NAMES","makeOpenApiMethod","pathName","method","okHttpStatus","headers","baseUrl","apiRoot","pathParams","queryParams","requestBody","pathWithParams","newPath","k","v","cleanQueryParams","search","getImpact","getCumulativeImpact","postSelectNonprofit","postTransaction","putTransaction","postCart","postChainEligibleNonprofitsForCart","postLogs","postExperimentSession","updateSubscription","postFindOrCreateSubscription","getProductDetailsPage"],"mappings":"oQAOA,eAAsBA,EAAuBC,EAAkBC,EAAmC,CAChG,MAAMC,EAAe,CACnB,OAAQ,MACR,GAAGD,EACH,QAAS,CACP,eAAgB,mBAChB,OAAQ,mBACR,gBAAiB,SACjB,wBAAyBE,EACzB,GAAGF,GAAS,OACd,EACA,kBAAmB,GACnB,KAAMA,GAAS,MAAQ,OACvB,KAAMA,GAAS,MAAQ,KAAOA,EAAQ,KAAO,MAC/C,EAEA,IAAIG,EACJ,GAAI,CACFA,EAAW,MAAM,MAAMJ,EAAKE,CAAY,CAE1C,OAASG,EAAK,CACZ,MAAMC,EAAQ,IAAIC,EAAU,wBAAwBL,GAAc,OAAO,YAAa,CAAA,IAAIF,CAAG,GAAG,EAChG,MAAAM,EAAM,MAAQD,EACdG,EAAO,MAAMF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B,EAAUC,EAAUI,GAAkBK,GAAU,IAAIA,CAAM,IAChE9B,EAAU,CAAE,QAAAmB,EAAS,OAAQF,EAAuB,KAAM,KAAK,UAAUO,CAAW,CAAE,EAE5F,OAAO1B,EAAuBC,EAAKC,CAAO,CAC5C,CACF,GAGegB,CAAQ,ECvDZe,EAAYhB,EAAkB,UAAW,KAAU,EAEnDiB,EAAsBjB,EAAkB,oCAAqC,KAAU,EAEvFkB,EAAsBlB,EAAkB,mBAAoB,MAAW,EAEvEmB,EAAkBnB,EAAkB,eAAgB,MAAW,EAE/DoB,EAAiBpB,EAAkB,+BAAgC,KAAU,EAE7EqB,EAAWrB,EAAkB,QAAS,MAAW,EAEjDsB,EAAqCtB,EAChD,uCACA,MAEF,EAEauB,EAAWvB,EAAkB,QAAS,MAAW,EAEjDwB,EAAwBxB,EAAkB,qBAAsB,MAAW,EAE3EyB,EAAqBzB,EAAkB,6CAA8C,MAAW,EAEhG0B,EAA+B1B,EAAkB,0CAA2C,MAAW,EAEvG2B,EAAwB3B,EAAkB,sBAAuB,KAAU"}
@@ -86,6 +86,7 @@ declare const getChainNonprofits: ({ headers, baseUrl, apiRoot, pathParams, quer
86
86
  extensibility?: {
87
87
  causeIconUrl?: string | null | undefined;
88
88
  causeIconSelectedUrl?: string | null | undefined;
89
+ causeIconAndBackgroundUrl?: string | null | undefined;
89
90
  } | undefined;
90
91
  website: string | null;
91
92
  websiteLinkText: string;
@@ -198,6 +199,7 @@ declare const getImpact: ({ headers, baseUrl, apiRoot, pathParams, queryParams,
198
199
  extensibility?: {
199
200
  causeIconUrl?: string | null | undefined;
200
201
  causeIconSelectedUrl?: string | null | undefined;
202
+ causeIconAndBackgroundUrl?: string | null | undefined;
201
203
  } | undefined;
202
204
  website: string | null;
203
205
  websiteLinkText: string;
@@ -227,6 +229,7 @@ declare const getImpact: ({ headers, baseUrl, apiRoot, pathParams, queryParams,
227
229
  extensibility?: {
228
230
  causeIconUrl?: string | null | undefined;
229
231
  causeIconSelectedUrl?: string | null | undefined;
232
+ causeIconAndBackgroundUrl?: string | null | undefined;
230
233
  } | undefined;
231
234
  website: string | null;
232
235
  websiteLinkText: string;
@@ -363,6 +366,7 @@ declare const postTransaction: ({ headers, baseUrl, apiRoot, pathParams, queryPa
363
366
  }[] | undefined;
364
367
  };
365
368
  } | undefined;
369
+ remoteSessionId?: string | undefined;
366
370
  options?: {
367
371
  response?: {
368
372
  personalImpact?: boolean | undefined;
@@ -403,6 +407,7 @@ declare const postTransaction: ({ headers, baseUrl, apiRoot, pathParams, queryPa
403
407
  extensibility?: {
404
408
  causeIconUrl?: string | null | undefined;
405
409
  causeIconSelectedUrl?: string | null | undefined;
410
+ causeIconAndBackgroundUrl?: string | null | undefined;
406
411
  } | undefined;
407
412
  website: string | null;
408
413
  websiteLinkText: string;
@@ -432,6 +437,7 @@ declare const postTransaction: ({ headers, baseUrl, apiRoot, pathParams, queryPa
432
437
  extensibility?: {
433
438
  causeIconUrl?: string | null | undefined;
434
439
  causeIconSelectedUrl?: string | null | undefined;
440
+ causeIconAndBackgroundUrl?: string | null | undefined;
435
441
  } | undefined;
436
442
  website: string | null;
437
443
  websiteLinkText: string;
@@ -474,5 +480,69 @@ declare const postTransaction: ({ headers, baseUrl, apiRoot, pathParams, queryPa
474
480
  } | undefined;
475
481
  } | undefined;
476
482
  }>;
483
+ declare const getProductDetailsPage: ({ headers, baseUrl, apiRoot, pathParams, queryParams, requestBody, }: {
484
+ baseUrl?: string | undefined;
485
+ apiRoot?: string | undefined;
486
+ pathParams?: Record<string, never> | undefined;
487
+ queryParams?: {
488
+ lang?: "en" | "fr" | "de" | "es" | "it" | "pl" | undefined;
489
+ version: string;
490
+ storeId: number;
491
+ draftConfig?: boolean | undefined;
492
+ widgetName?: "impact-overview" | "community-impact" | "subscription-impact" | "subscription-management" | "select-nonprofit" | "redeem-transaction" | "cumulative-impact" | "product-details-page" | "select-subscription-nonprofit" | "select-nonprofit-cta" | "mobile-full-screen-nonprofit-selection" | "mobile-impact-list" | "mobile-minimal-nonprofit-selection" | "mobile-personal-impact" | "mobile-selected-nonprofit" | "mobile-progress-bar" | "mobile-share-button" | undefined;
493
+ remoteProductIdentifier?: string | undefined;
494
+ } | undefined;
495
+ requestBody?: undefined;
496
+ headers?: Record<string, string> | undefined;
497
+ }) => Promise<{
498
+ config: {
499
+ web: {
500
+ title: string;
501
+ description: string;
502
+ promoDescriptionPrefix?: string | undefined;
503
+ promoDescription?: string | undefined;
504
+ confirmButton?: string | undefined;
505
+ confirmedButton?: string | undefined;
506
+ collapsedButton?: string | undefined;
507
+ theme?: {
508
+ [key: string]: unknown;
509
+ } | null | undefined;
510
+ nonprofitSelectedHeader?: string | undefined;
511
+ nonprofitUnselectedHeader?: string | undefined;
512
+ dynamicStrings?: {
513
+ [key: string]: string;
514
+ } | null | undefined;
515
+ additionalStrings?: {
516
+ [key: string]: string;
517
+ } | null | undefined;
518
+ disableAnimation?: boolean | undefined;
519
+ promo?: {
520
+ "promo-text-long": string;
521
+ "promo-text-short": string;
522
+ "promo-cause-alt-text": string;
523
+ } | undefined;
524
+ };
525
+ mobileWeb?: {
526
+ title: string;
527
+ description: string;
528
+ nonprofitSelectedHeader?: string | undefined;
529
+ nonprofitUnselectedHeader?: string | undefined;
530
+ } | undefined;
531
+ mobile: {
532
+ title: string;
533
+ description: string;
534
+ nonprofitSelectedHeader?: string | undefined;
535
+ nonprofitUnselectedHeader?: string | undefined;
536
+ };
537
+ enableNonprofitDeselection?: boolean | undefined;
538
+ };
539
+ ppgfDisclosure?: {
540
+ copy: string;
541
+ } | undefined;
542
+ ppgfDisclosureHyperlink?: {
543
+ url: string;
544
+ copy: string;
545
+ } | undefined;
546
+ }>;
477
547
 
478
- export { getChainNonprofits as a, getImpact as g, postTransaction as p };
548
+ export { getChainNonprofits as a, getProductDetailsPage as b, getImpact as g, postTransaction as p };
@@ -1,2 +1,2 @@
1
- import{B as v,N as m}from"./beam-errors-P-Lu07Ce.esm.js";import{logger as p}from"../utils/logger.esm.js";var E="1.45.3",N={"@lit/react":"1.0.0","@lukeed/uuid":"2.0.0","@shoelace-style/shoelace":"2.15.0",lit:"2.6.1","lodash-es":"4.17.21","lucide-static":"0.292.0"};async function w(s,o){const c={method:"GET",...o,headers:{"Content-Type":"application/json",Accept:"application/json","X-Beam-Client":"WebSDK","X-Beam-Client-Version":E,...o?.headers},preflightContinue:!0,mode:o?.mode||"cors",body:o?.body!=null?o.body:void 0};let i;try{i=await fetch(s,c)}catch(e){const a=new v(`Network call failed (${c?.method.toUpperCase()} ${s})`);throw a.cause=e,p.error(a,s),a}let r,n;try{n=await i.text(),n&&(r=JSON.parse(n))}catch(e){let a=e;throw e instanceof SyntaxError&&(a=new m(i,r,`Response invalid. Expected JSON. Received: "${n}"`),a.cause=e),p.error(a),a}if(!i.ok){const e=new m(i,r,"Response was not OK");throw p.error(e),e}return r}const u="https://api.beamimpact.com",C="https://production.beamimpactlogs.com",O={en:"en",fr:"fr",de:"de",es:"es",it:"it",pl:"pl"},T={select_nonprofit:"select-nonprofit",redeem_transaction:"redeem-transaction",impact_overview:"impact-overview",community_impact:"community-impact",cumulative_impact:"cumulative-impact",product_details_page:"product-details-page",subscription_management:"subscription-management",subscription_impact:"subscription-impact",select_subscription_nonprofit:"select-subscription-nonprofit",social_share:"social-share"},t=(s,o,c)=>({[s]:async function({headers:i={},baseUrl:r=u,apiRoot:n="/api/v3",pathParams:e={},queryParams:a={},requestBody:d}){const h=Object.entries(e).reduce((S,[y,_])=>S.replace(`{${y}}`,_),s),f=JSON.parse(JSON.stringify(a)),l=new URLSearchParams(f).toString(),b=r+n+h+(l&&`?${l}`),g={headers:i,method:o,body:JSON.stringify(d)};return w(b,g)}})[s],U=t("/impact","get"),A=t("/chain/{chainId}/cumulativeImpact","get"),D=t("/selectNonprofit","post"),L=t("/transaction","post"),P=t("/transaction/{transactionId}","put"),R=t("/cart","post"),k=t("/chain/findEligibleNonprofitsForCart","post"),x=t("/logs","post"),B=t("/experimentSession","post"),I=t("/subscriptions/updateSubscriptionNonprofit","post"),J=t("/subscriptions/findOrCreateSubscription","post"),F=t("/productDetailsPage","get");export{u as D,O as S,T as W,C as a,R as b,x as c,N as d,B as e,k as f,U as g,J as h,D as i,P as j,F as k,A as l,L as p,I as u};
2
- //# sourceMappingURL=routes-4z90Ks28.esm.js.map
1
+ import{B as v,N as m}from"./beam-errors-P-Lu07Ce.esm.js";import{logger as p}from"../utils/logger.esm.js";var E="1.46.0",N={"@lit/react":"1.0.0","@lukeed/uuid":"2.0.0","@shoelace-style/shoelace":"2.15.0",lit:"2.6.1","lodash-es":"4.17.21","lucide-static":"0.292.0"};async function w(s,o){const c={method:"GET",...o,headers:{"Content-Type":"application/json",Accept:"application/json","X-Beam-Client":"WebSDK","X-Beam-Client-Version":E,...o?.headers},preflightContinue:!0,mode:o?.mode||"cors",body:o?.body!=null?o.body:void 0};let i;try{i=await fetch(s,c)}catch(e){const a=new v(`Network call failed (${c?.method.toUpperCase()} ${s})`);throw a.cause=e,p.error(a,s),a}let r,n;try{n=await i.text(),n&&(r=JSON.parse(n))}catch(e){let a=e;throw e instanceof SyntaxError&&(a=new m(i,r,`Response invalid. Expected JSON. Received: "${n}"`),a.cause=e),p.error(a),a}if(!i.ok){const e=new m(i,r,"Response was not OK");throw p.error(e),e}return r}const u="https://api.beamimpact.com",C="https://production.beamimpactlogs.com",O={en:"en",fr:"fr",de:"de",es:"es",it:"it",pl:"pl"},T={select_nonprofit:"select-nonprofit",redeem_transaction:"redeem-transaction",impact_overview:"impact-overview",community_impact:"community-impact",cumulative_impact:"cumulative-impact",product_details_page:"product-details-page",subscription_management:"subscription-management",subscription_impact:"subscription-impact",select_subscription_nonprofit:"select-subscription-nonprofit",social_share:"social-share"},t=(s,o,c)=>({[s]:async function({headers:i={},baseUrl:r=u,apiRoot:n="/api/v3",pathParams:e={},queryParams:a={},requestBody:d}){const h=Object.entries(e).reduce((S,[y,_])=>S.replace(`{${y}}`,_),s),f=JSON.parse(JSON.stringify(a)),l=new URLSearchParams(f).toString(),b=r+n+h+(l&&`?${l}`),g={headers:i,method:o,body:JSON.stringify(d)};return w(b,g)}})[s],U=t("/impact","get"),A=t("/chain/{chainId}/cumulativeImpact","get"),D=t("/selectNonprofit","post"),L=t("/transaction","post"),P=t("/transaction/{transactionId}","put"),R=t("/cart","post"),k=t("/chain/findEligibleNonprofitsForCart","post"),x=t("/logs","post"),B=t("/experimentSession","post"),I=t("/subscriptions/updateSubscriptionNonprofit","post"),J=t("/subscriptions/findOrCreateSubscription","post"),F=t("/productDetailsPage","get");export{u as D,O as S,T as W,C as a,R as b,x as c,N as d,B as e,k as f,U as g,J as h,D as i,P as j,A as k,F as l,L as p,I as u};
2
+ //# sourceMappingURL=routes-sQWfbAoi.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"routes-4z90Ks28.esm.js","sources":["../../src/api-sdk/fetch-json.ts","../../src/api-sdk/constants.ts","../../src/api-sdk/v3/make-openapi-method.ts","../../src/api-sdk/v3/routes.ts"],"sourcesContent":["/**\n * Wrapper over window.fetch that expects/returns JSON\n */\nimport { BeamError, NetworkError } from \"../utils/beam-errors\";\nimport { logger } from \"../utils/logger\";\nimport { version as pkgVersion } from \"../../package.json\";\n\nexport async function fetchJson<T = unknown>(url: RequestInfo, options?: RequestInit): Promise<T> {\n const fetchOptions = {\n method: \"GET\",\n ...options,\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"X-Beam-Client\": \"WebSDK\",\n \"X-Beam-Client-Version\": pkgVersion,\n ...options?.headers,\n },\n preflightContinue: true,\n mode: options?.mode || \"cors\",\n body: options?.body != null ? options.body : undefined,\n };\n\n let response;\n try {\n response = await fetch(url, fetchOptions);\n // fetch can throw a TypeError if the server can't be reached, catch and log below\n } catch (err) {\n const error = new BeamError(`Network call failed (${fetchOptions?.method.toUpperCase()} ${url})`);\n error.cause = err;\n logger.error(error, url);\n throw error;\n }\n let body;\n let text;\n // This can throw a SyntaxError if response payload is malformed JSON\n try {\n text = await response.text();\n if (text) {\n // (response can be empty)\n body = JSON.parse(text);\n }\n } catch (err) {\n let error = err as Error;\n if (err instanceof SyntaxError) {\n error = new NetworkError(response, body, `Response invalid. Expected JSON. Received: \"${text}\"`);\n error.cause = err;\n }\n logger.error(error);\n throw error;\n }\n // Translate 4xx, 5xx status to runtime error\n if (!response.ok) {\n const error = new NetworkError(response, body, \"Response was not OK\");\n logger.error(error);\n throw error;\n }\n\n return body;\n}\n","import { LANGUAGES, TUrl } from \"./types\";\n\nexport const DEFAULT_BASE_URL: TUrl = \"https://api.beamimpact.com\";\n\nexport const DEFAULT_LOG_URL = \"https://production.beamimpactlogs.com\";\n\nexport const SUPPORTED_LANGUAGES: Record<string, LANGUAGES> = {\n en: \"en\",\n fr: \"fr\",\n de: \"de\",\n es: \"es\",\n it: \"it\",\n pl: \"pl\",\n};\n\nexport const WIDGET_NAMES = {\n select_nonprofit: \"select-nonprofit\",\n redeem_transaction: \"redeem-transaction\",\n impact_overview: \"impact-overview\",\n community_impact: \"community-impact\",\n cumulative_impact: \"cumulative-impact\",\n product_details_page: \"product-details-page\",\n subscription_management: \"subscription-management\",\n subscription_impact: \"subscription-impact\",\n select_subscription_nonprofit: \"select-subscription-nonprofit\",\n social_share: \"social-share\",\n} as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { fetchJson } from \"../fetch-json\";\nimport { DEFAULT_BASE_URL } from \"../constants\";\nimport { THttpMethod } from \"../types\";\nimport { paths } from \"./openapi-spec\";\n\nexport const makeOpenApiMethod = <\n TPathName extends keyof paths,\n TMethod extends keyof paths[TPathName],\n TStatusCode extends paths[TPathName][TMethod] extends { responses: any }\n ? keyof paths[TPathName][TMethod][\"responses\"]\n : never\n>(\n pathName: TPathName,\n method: TMethod,\n okHttpStatus: TStatusCode\n) => {\n type TRouteSpec = paths[typeof pathName];\n type TRouteMethod = TRouteSpec[typeof method];\n type TParams = \"parameters\" extends keyof TRouteMethod ? TRouteMethod[\"parameters\"] : never;\n type TPathParams = TParams extends { path: any } ? TParams[\"path\"] : Record<string, never>;\n type TQueryParams = TParams extends { query: any } ? TParams[\"query\"] : Record<string, never>;\n type TRequestBody = TRouteMethod extends { requestBody: { content: { \"application/json\": any } } }\n ? TRouteMethod[\"requestBody\"][\"content\"][\"application/json\"]\n : never;\n type TAllResponses = TRouteMethod extends { responses: any } ? TRouteMethod[\"responses\"] : never;\n type TOkResponse = TAllResponses[typeof okHttpStatus] extends { content: { \"application/json\": any } }\n ? TAllResponses[typeof okHttpStatus][\"content\"][\"application/json\"]\n : never;\n const openApi = {\n [pathName]: async function ({\n headers = {},\n baseUrl = DEFAULT_BASE_URL,\n apiRoot = \"/api/v3\",\n pathParams = {},\n queryParams = {},\n requestBody,\n }: {\n baseUrl?: string;\n apiRoot?: string;\n pathParams?: TPathParams;\n queryParams?: TQueryParams;\n requestBody?: TRequestBody;\n headers?: Record<string, string>;\n }) {\n const pathWithParams: string = Object.entries(pathParams).reduce((newPath: string, [k, v]) => {\n return newPath.replace(`{${k}}`, v as string);\n }, pathName as string);\n const cleanQueryParams = JSON.parse(JSON.stringify(queryParams));\n const search = new URLSearchParams(cleanQueryParams as unknown as Record<string, string>).toString();\n const url = baseUrl + apiRoot + pathWithParams + (search && `?${search}`);\n const options = { headers, method: method as THttpMethod, body: JSON.stringify(requestBody) };\n\n return fetchJson<TOkResponse>(url, options);\n },\n };\n\n // Use object to create function with dynamic name, for better stacktraces\n return openApi[pathName];\n};\n","import { makeOpenApiMethod } from \"./make-openapi-method\";\n\nexport const getChainNonprofits = makeOpenApiMethod(\"/chain/{chainId}/nonprofits\", \"get\", 200);\n\nexport const getImpact = makeOpenApiMethod(\"/impact\", \"get\", 200);\n\nexport const getCumulativeImpact = makeOpenApiMethod(\"/chain/{chainId}/cumulativeImpact\", \"get\", 200);\n\nexport const postSelectNonprofit = makeOpenApiMethod(\"/selectNonprofit\", \"post\", 201);\n\nexport const postTransaction = makeOpenApiMethod(\"/transaction\", \"post\", 201);\n\nexport const putTransaction = makeOpenApiMethod(\"/transaction/{transactionId}\", \"put\", 204);\n\nexport const postCart = makeOpenApiMethod(\"/cart\", \"post\", 200);\n\nexport const postChainEligibleNonprofitsForCart = makeOpenApiMethod(\n \"/chain/findEligibleNonprofitsForCart\",\n \"post\",\n 200\n);\n\nexport const postLogs = makeOpenApiMethod(\"/logs\", \"post\", 200);\n\nexport const postExperimentSession = makeOpenApiMethod(\"/experimentSession\", \"post\", 200);\n\nexport const updateSubscription = makeOpenApiMethod(\"/subscriptions/updateSubscriptionNonprofit\", \"post\", 200);\n\nexport const postFindOrCreateSubscription = makeOpenApiMethod(\"/subscriptions/findOrCreateSubscription\", \"post\", 200);\n\nexport const getProductDetailsPage = makeOpenApiMethod(\"/productDetailsPage\", \"get\", 200);\n"],"names":["fetchJson","url","options","fetchOptions","pkgVersion","response","err","error","BeamError","logger","body","text","NetworkError","DEFAULT_BASE_URL","DEFAULT_LOG_URL","SUPPORTED_LANGUAGES","WIDGET_NAMES","makeOpenApiMethod","pathName","method","okHttpStatus","headers","baseUrl","apiRoot","pathParams","queryParams","requestBody","pathWithParams","newPath","k","v","cleanQueryParams","search","getImpact","getCumulativeImpact","postSelectNonprofit","postTransaction","putTransaction","postCart","postChainEligibleNonprofitsForCart","postLogs","postExperimentSession","updateSubscription","postFindOrCreateSubscription","getProductDetailsPage"],"mappings":"wQAOA,eAAsBA,EAAuBC,EAAkBC,EAAmC,CAChG,MAAMC,EAAe,CACnB,OAAQ,MACR,GAAGD,EACH,QAAS,CACP,eAAgB,mBAChB,OAAQ,mBACR,gBAAiB,SACjB,wBAAyBE,EACzB,GAAGF,GAAS,OACd,EACA,kBAAmB,GACnB,KAAMA,GAAS,MAAQ,OACvB,KAAMA,GAAS,MAAQ,KAAOA,EAAQ,KAAO,MAC/C,EAEA,IAAIG,EACJ,GAAI,CACFA,EAAW,MAAM,MAAMJ,EAAKE,CAAY,CAE1C,OAASG,EAAK,CACZ,MAAMC,EAAQ,IAAIC,EAAU,wBAAwBL,GAA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,UAAUN,CAAW,CAAC,EACzDO,EAAS,IAAI,gBAAgBD,CAAqD,EAAE,SACpF9B,EAAAA,EAAMqB,EAAUC,EAAUI,GAAkBK,GAAU,IAAIA,CAAM,IAChE9B,EAAU,CAAE,QAAAmB,EAAS,OAAQF,EAAuB,KAAM,KAAK,UAAUO,CAAW,CAAE,EAE5F,OAAO1B,EAAuBC,EAAKC,CAAO,CAC5C,CACF,GAGegB,CAAQ,ECvDZe,EAAYhB,EAAkB,UAAW,KAAU,EAEnDiB,EAAsBjB,EAAkB,oCAAqC,KAAU,EAEvFkB,EAAsBlB,EAAkB,mBAAoB,MAAW,EAEvEmB,EAAkBnB,EAAkB,eAAgB,MAAW,EAE/DoB,EAAiBpB,EAAkB,+BAAgC,KAAU,EAE7EqB,EAAWrB,EAAkB,QAAS,MAAW,EAEjDsB,EAAqCtB,EAChD,uCACA,MAEF,EAEauB,EAAWvB,EAAkB,QAAS,MAAW,EAEjDwB,EAAwBxB,EAAkB,qBAAsB,MAAW,EAE3EyB,EAAqBzB,EAAkB,6CAA8C,MAAW,EAEhG0B,EAA+B1B,EAAkB,0CAA2C,MAAW,EAEvG2B,EAAwB3B,EAAkB,sBAAuB,KAAU"}
1
+ {"version":3,"file":"routes-sQWfbAoi.esm.js","sources":["../../src/api-sdk/fetch-json.ts","../../src/api-sdk/constants.ts","../../src/api-sdk/v3/make-openapi-method.ts","../../src/api-sdk/v3/routes.ts"],"sourcesContent":["/**\n * Wrapper over window.fetch that expects/returns JSON\n */\nimport { BeamError, NetworkError } from \"../utils/beam-errors\";\nimport { logger } from \"../utils/logger\";\nimport { version as pkgVersion } from \"../../package.json\";\n\nexport async function fetchJson<T = unknown>(url: RequestInfo, options?: RequestInit): Promise<T> {\n const fetchOptions = {\n method: \"GET\",\n ...options,\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"X-Beam-Client\": \"WebSDK\",\n \"X-Beam-Client-Version\": pkgVersion,\n ...options?.headers,\n },\n preflightContinue: true,\n mode: options?.mode || \"cors\",\n body: options?.body != null ? options.body : undefined,\n };\n\n let response;\n try {\n response = await fetch(url, fetchOptions);\n // fetch can throw a TypeError if the server can't be reached, catch and log below\n } catch (err) {\n const error = new BeamError(`Network call failed (${fetchOptions?.method.toUpperCase()} ${url})`);\n error.cause = err;\n logger.error(error, url);\n throw error;\n }\n let body;\n let text;\n // This can throw a SyntaxError if response payload is malformed JSON\n try {\n text = await response.text();\n if (text) {\n // (response can be empty)\n body = JSON.parse(text);\n }\n } catch (err) {\n let error = err as Error;\n if (err instanceof SyntaxError) {\n error = new NetworkError(response, body, `Response invalid. Expected JSON. Received: \"${text}\"`);\n error.cause = err;\n }\n logger.error(error);\n throw error;\n }\n // Translate 4xx, 5xx status to runtime error\n if (!response.ok) {\n const error = new NetworkError(response, body, \"Response was not OK\");\n logger.error(error);\n throw error;\n }\n\n return body;\n}\n","import { LANGUAGES, TUrl } from \"./types\";\n\nexport const DEFAULT_BASE_URL: TUrl = \"https://api.beamimpact.com\";\n\nexport const DEFAULT_LOG_URL = \"https://production.beamimpactlogs.com\";\n\nexport const SUPPORTED_LANGUAGES: Record<string, LANGUAGES> = {\n en: \"en\",\n fr: \"fr\",\n de: \"de\",\n es: \"es\",\n it: \"it\",\n pl: \"pl\",\n};\n\nexport const WIDGET_NAMES = {\n select_nonprofit: \"select-nonprofit\",\n redeem_transaction: \"redeem-transaction\",\n impact_overview: \"impact-overview\",\n community_impact: \"community-impact\",\n cumulative_impact: \"cumulative-impact\",\n product_details_page: \"product-details-page\",\n subscription_management: \"subscription-management\",\n subscription_impact: \"subscription-impact\",\n select_subscription_nonprofit: \"select-subscription-nonprofit\",\n social_share: \"social-share\",\n} as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { fetchJson } from \"../fetch-json\";\nimport { DEFAULT_BASE_URL } from \"../constants\";\nimport { THttpMethod } from \"../types\";\nimport { paths } from \"./openapi-spec\";\n\nexport const makeOpenApiMethod = <\n TPathName extends keyof paths,\n TMethod extends keyof paths[TPathName],\n TStatusCode extends paths[TPathName][TMethod] extends { responses: any }\n ? keyof paths[TPathName][TMethod][\"responses\"]\n : never\n>(\n pathName: TPathName,\n method: TMethod,\n okHttpStatus: TStatusCode\n) => {\n type TRouteSpec = paths[typeof pathName];\n type TRouteMethod = TRouteSpec[typeof method];\n type TParams = \"parameters\" extends keyof TRouteMethod ? TRouteMethod[\"parameters\"] : never;\n type TPathParams = TParams extends { path: any } ? TParams[\"path\"] : Record<string, never>;\n type TQueryParams = TParams extends { query: any } ? TParams[\"query\"] : Record<string, never>;\n type TRequestBody = TRouteMethod extends { requestBody: { content: { \"application/json\": any } } }\n ? TRouteMethod[\"requestBody\"][\"content\"][\"application/json\"]\n : never;\n type TAllResponses = TRouteMethod extends { responses: any } ? TRouteMethod[\"responses\"] : never;\n type TOkResponse = TAllResponses[typeof okHttpStatus] extends { content: { \"application/json\": any } }\n ? TAllResponses[typeof okHttpStatus][\"content\"][\"application/json\"]\n : never;\n const openApi = {\n [pathName]: async function ({\n headers = {},\n baseUrl = DEFAULT_BASE_URL,\n apiRoot = \"/api/v3\",\n pathParams = {},\n queryParams = {},\n requestBody,\n }: {\n baseUrl?: string;\n apiRoot?: string;\n pathParams?: TPathParams;\n queryParams?: TQueryParams;\n requestBody?: TRequestBody;\n headers?: Record<string, string>;\n }) {\n const pathWithParams: string = Object.entries(pathParams).reduce((newPath: string, [k, v]) => {\n return newPath.replace(`{${k}}`, v as string);\n }, pathName as string);\n const cleanQueryParams = JSON.parse(JSON.stringify(queryParams));\n const search = new URLSearchParams(cleanQueryParams as unknown as Record<string, string>).toString();\n const url = baseUrl + apiRoot + pathWithParams + (search && `?${search}`);\n const options = { headers, method: method as THttpMethod, body: JSON.stringify(requestBody) };\n\n return fetchJson<TOkResponse>(url, options);\n },\n };\n\n // Use object to create function with dynamic name, for better stacktraces\n return openApi[pathName];\n};\n","import { makeOpenApiMethod } from \"./make-openapi-method\";\n\nexport const getChainNonprofits = makeOpenApiMethod(\"/chain/{chainId}/nonprofits\", \"get\", 200);\n\nexport const getImpact = makeOpenApiMethod(\"/impact\", \"get\", 200);\n\nexport const getCumulativeImpact = makeOpenApiMethod(\"/chain/{chainId}/cumulativeImpact\", \"get\", 200);\n\nexport const postSelectNonprofit = makeOpenApiMethod(\"/selectNonprofit\", \"post\", 201);\n\nexport const postTransaction = makeOpenApiMethod(\"/transaction\", \"post\", 201);\n\nexport const putTransaction = makeOpenApiMethod(\"/transaction/{transactionId}\", \"put\", 204);\n\nexport const postCart = makeOpenApiMethod(\"/cart\", \"post\", 200);\n\nexport const postChainEligibleNonprofitsForCart = makeOpenApiMethod(\n \"/chain/findEligibleNonprofitsForCart\",\n \"post\",\n 200\n);\n\nexport const postLogs = makeOpenApiMethod(\"/logs\", \"post\", 200);\n\nexport const postExperimentSession = makeOpenApiMethod(\"/experimentSession\", \"post\", 200);\n\nexport const updateSubscription = makeOpenApiMethod(\"/subscriptions/updateSubscriptionNonprofit\", \"post\", 200);\n\nexport const postFindOrCreateSubscription = makeOpenApiMethod(\"/subscriptions/findOrCreateSubscription\", \"post\", 200);\n\nexport const getProductDetailsPage = makeOpenApiMethod(\"/productDetailsPage\", \"get\", 200);\n"],"names":["fetchJson","url","options","fetchOptions","pkgVersion","response","err","error","BeamError","logger","body","text","NetworkError","DEFAULT_BASE_URL","DEFAULT_LOG_URL","SUPPORTED_LANGUAGES","WIDGET_NAMES","makeOpenApiMethod","pathName","method","okHttpStatus","headers","baseUrl","apiRoot","pathParams","queryParams","requestBody","pathWithParams","newPath","k","v","cleanQueryParams","search","getImpact","getCumulativeImpact","postSelectNonprofit","postTransaction","putTransaction","postCart","postChainEligibleNonprofitsForCart","postLogs","postExperimentSession","updateSubscription","postFindOrCreateSubscription","getProductDetailsPage"],"mappings":"wQAOA,eAAsBA,EAAuBC,EAAkBC,EAAmC,CAChG,MAAMC,EAAe,CACnB,OAAQ,MACR,GAAGD,EACH,QAAS,CACP,eAAgB,mBAChB,OAAQ,mBACR,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AUT,EACV,QAAAU,EAAU,UACV,WAAAC,EAAa,CACb,EAAA,YAAAC,EAAc,CAAA,EACd,YAAAC,CACF,EAOG,CACD,MAAMC,EAAyB,OAAO,QAAQH,CAAU,EAAE,OAAO,CAACI,EAAiB,CAACC,EAAGC,CAAC,IAC/EF,EAAQ,QAAQ,IAAIC,CAAC,IAAKC,CAAW,EAC3CZ,CAAkB,EACfa,EAAmB,KAAK,MAAM,KAAK,UAAUN,CAAW,CAAC,EACzDO,EAAS,IAAI,gBAAgBD,CAAqD,EAAE,SACpF9B,EAAAA,EAAMqB,EAAUC,EAAUI,GAAkBK,GAAU,IAAIA,CAAM,IAChE9B,EAAU,CAAE,QAAAmB,EAAS,OAAQF,EAAuB,KAAM,KAAK,UAAUO,CAAW,CAAE,EAE5F,OAAO1B,EAAuBC,EAAKC,CAAO,CAC5C,CACF,GAGegB,CAAQ,ECvDZe,EAAYhB,EAAkB,UAAW,KAAU,EAEnDiB,EAAsBjB,EAAkB,oCAAqC,KAAU,EAEvFkB,EAAsBlB,EAAkB,mBAAoB,MAAW,EAEvEmB,EAAkBnB,EAAkB,eAAgB,MAAW,EAE/DoB,EAAiBpB,EAAkB,+BAAgC,KAAU,EAE7EqB,EAAWrB,EAAkB,QAAS,MAAW,EAEjDsB,EAAqCtB,EAChD,uCACA,MAEF,EAEauB,EAAWvB,EAAkB,QAAS,MAAW,EAEjDwB,EAAwBxB,EAAkB,qBAAsB,MAAW,EAE3EyB,EAAqBzB,EAAkB,6CAA8C,MAAW,EAEhG0B,EAA+B1B,EAAkB,0CAA2C,MAAW,EAEvG2B,EAAwB3B,EAAkB,sBAAuB,KAAU"}
@@ -1,4 +1,4 @@
1
- import{i as f}from"./is-all-html-elements-SdSkxirh.esm.js";import{h as x,y as m,Z as v,g as l}from"./lit-iNN5L_Qk.esm.js";import"./vendor-GKiOHg2N.esm.js";import{u as d,s as o}from"./share-button-SNvuFDC9.esm.js";const y=(i,{source:t="contentLength"}={})=>{const a=i instanceof NodeList?Array.from(i):i;if(a.length===0||!f(a))return;const r=(t==="contentLength"?a.sort((e,n)=>n.innerText.length-e.innerText.length)[0]:a.sort((e,n)=>n.clientHeight-e.clientHeight)[0])?.clientHeight||0;for(const e of a)e.clientHeight!==r&&(e.style.height=r+"px")};function S(){return/Android|iPhone/i.test(navigator.userAgent)}var w=Object.defineProperty,k=Object.getOwnPropertyDescriptor,c=(i,t,a,r)=>{for(var e=r>1?void 0:r?k(t,a):t,n=i.length-1,h;n>=0;n--)(h=i[n])&&(e=(r?h(t,a,e):h(e))||e);return r&&e&&w(t,a,e),e};class s extends x{constructor(){super(...arguments),this.shareIcon=null,this.imageUrl=null,this.brandName=null,this.buttonText=null,this.configLang="en"}connectedCallback(){super.connectedCallback()}async handleShareClick(){try{if(!this.imageUrl||!this.brandName||!this.configLang)return;await import("./_share-dialog-dependencies-FXJR0ESq.esm.js"),S()?this.openSystemShareSheet(this.imageUrl):this.handleShareDialog(this.imageUrl,this.brandName)}catch(t){console.error("Error sharing impact:",t)}}async handleShareDialog(t,a){if(!t)return;const r=this.shadowRoot?.querySelector("sl-dialog");if(r){r.show();return}await import("./_share-dialog-dependencies-FXJR0ESq.esm.js");const e=this.shadowRoot?.querySelector("#modal-root"),n=await d(t),h=URL.createObjectURL(n),b=()=>{this.shadowRoot?.querySelector("sl-dialog")?.hide()},g=async()=>{await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),setTimeout(b,250)},u=()=>{setTimeout(b,250)},p=m`
1
+ import{i as f}from"./is-all-html-elements-SdSkxirh.esm.js";import{h as x,y as m,Z as v,g as l}from"./lit-iNN5L_Qk.esm.js";import"./vendor-GKiOHg2N.esm.js";import{u as d,s as o}from"./share-button-SNvuFDC9.esm.js";const y=(i,{source:t="contentLength"}={})=>{const a=i instanceof NodeList?Array.from(i):i;if(a.length===0||!f(a))return;const r=(t==="contentLength"?a.sort((e,n)=>n.innerText.length-e.innerText.length)[0]:a.sort((e,n)=>n.clientHeight-e.clientHeight)[0])?.clientHeight||0;for(const e of a)e.clientHeight!==r&&(e.style.height=r+"px")};function S(){return/Android|iPhone/i.test(navigator.userAgent)}var w=Object.defineProperty,C=Object.getOwnPropertyDescriptor,c=(i,t,a,r)=>{for(var e=r>1?void 0:r?C(t,a):t,n=i.length-1,h;n>=0;n--)(h=i[n])&&(e=(r?h(t,a,e):h(e))||e);return r&&e&&w(t,a,e),e};class s extends x{constructor(){super(...arguments),this.shareIcon=null,this.imageUrl=null,this.brandName=null,this.buttonText=null,this.configLang="en"}connectedCallback(){super.connectedCallback()}async handleShareClick(){try{if(!this.imageUrl||!this.brandName||!this.configLang)return;await import("./_share-dialog-dependencies-XEpMl5XM.esm.js"),S()?this.openSystemShareSheet(this.imageUrl):this.handleShareDialog(this.imageUrl,this.brandName)}catch(t){console.error("Error sharing impact:",t)}}async handleShareDialog(t,a){if(!t)return;const r=this.shadowRoot?.querySelector("sl-dialog");if(r){r.show();return}await import("./_share-dialog-dependencies-XEpMl5XM.esm.js");const e=this.shadowRoot?.querySelector("#modal-root"),n=await d(t),h=URL.createObjectURL(n),b=()=>{this.shadowRoot?.querySelector("sl-dialog")?.hide()},g=async()=>{await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),setTimeout(b,250)},u=()=>{setTimeout(b,250)},p=m`
2
2
  <style>
3
3
  .plain-button {
4
4
  border: none;
@@ -118,7 +118,6 @@ import{i as f}from"./is-all-html-elements-SdSkxirh.esm.js";import{h as x,y as m,
118
118
  margin-bottom: var(--beam-share-button-marginBottom);
119
119
  text-transform: var(--beam-share-button-textTransform);
120
120
  line-height: var(--beam-share-button-lineHeight);
121
- /* TODO: extract palette variable - sky-100 color */
122
121
  background-color: var(--beam-share-button-backgroundColor);
123
122
  color: var(--beam-share-button-color, inherit);
124
123
  border-radius: var(--beam-share-button-borderRadius);
@@ -160,5 +159,5 @@ import{i as f}from"./is-all-html-elements-SdSkxirh.esm.js";import{h as x,y as m,
160
159
  <span class="share-button-text">${this.buttonText||o[this.configLang].impactShareButton()}</span>
161
160
  </button>
162
161
  <div id="modal-root"></div>
163
- `}}c([l({type:String})],s.prototype,"shareIcon",2),c([l({type:String})],s.prototype,"imageUrl",2),c([l({type:String})],s.prototype,"brandName",2),c([l({type:String})],s.prototype,"buttonText",2),c([l({type:String})],s.prototype,"configLang",2),customElements.get("beam-share-button")||customElements.define("beam-share-button",s);const C={"--beam-share-button-fontFamily":"inherit","--beam-share-button-fontSize":"14px","--beam-share-button-fontWeight":"600","--beam-share-button-textTransform":"none","--beam-share-button-marginTop":"10px","--beam-share-button-marginBottom":"10px","--beam-share-button-padding":"8px 18px 8px 16px","--beam-share-button-lineHeight":"inherit","--beam-share-button-color":"#0A323C","--beam-share-button-backgroundColor":"#fff","--beam-share-button-borderRadius":"30px","--beam-share-button-borderColor":"#0A323C","--beam-share-button-borderWidth":"1px","--beam-share-button-width":"auto","--beam-share-button-hover-borderColor":"transparent","--beam-share-button-hover-backgroundColor":"#0A323C","--beam-share-button-hover-color":"#fff","--beam-share-button-icon-size":"16px","--beam-share-button-text-textDecoration":"none","--beam-share-dialog-padding":"30px 30px","--beam-share-title-fontSize":"30px","--beam-share-title-fontWeight":"bold","--beam-share-text-fontSize":"16px","--beam-share-text-lineHeight":"1.3","--beam-share-text-marginTop":"10px","--beam-share-image-borderRadius":"4px","--beam-share-image-width":"200px","--beam-share-image-margin":"20px","--beam-share-actions-margin":"30px 60px","--beam-share-action-icon-size":"32px","--beam-share-action-text-fontSize":"16px","--beam-share-action-text-lineHeight":"1.3","--beam-share-text-action-marginTop":"10px","--beam-share-close-backgroundColor":"#ffd522","--beam-share-close-text-color":"#000","--beam-share-close-padding":"12px","--beam-share-close-borderRadius":"4px","--beam-share-close-fontSize":"16px","--beam-share-close-fontWeight":"bold","--beam-share-close-focus-borderColor":"#c2dcff"};export{C as a,y as s};
164
- //# sourceMappingURL=share-button-RG2BkqMA.esm.js.map
162
+ `}}c([l({type:String})],s.prototype,"shareIcon",2),c([l({type:String})],s.prototype,"imageUrl",2),c([l({type:String})],s.prototype,"brandName",2),c([l({type:String})],s.prototype,"buttonText",2),c([l({type:String})],s.prototype,"configLang",2),customElements.get("beam-share-button")||customElements.define("beam-share-button",s);const k={"--beam-share-button-fontFamily":"inherit","--beam-share-button-fontSize":"14px","--beam-share-button-fontWeight":"600","--beam-share-button-textTransform":"none","--beam-share-button-marginTop":"10px","--beam-share-button-marginBottom":"10px","--beam-share-button-padding":"8px 18px 8px 16px","--beam-share-button-lineHeight":"inherit","--beam-share-button-color":"#0A323C","--beam-share-button-backgroundColor":"#fff","--beam-share-button-borderRadius":"30px","--beam-share-button-borderColor":"#0A323C","--beam-share-button-borderWidth":"1px","--beam-share-button-width":"auto","--beam-share-button-hover-borderColor":"transparent","--beam-share-button-hover-backgroundColor":"#0A323C","--beam-share-button-hover-color":"#fff","--beam-share-button-icon-size":"16px","--beam-share-button-text-textDecoration":"none","--beam-share-dialog-padding":"30px 30px","--beam-share-title-fontSize":"30px","--beam-share-title-fontWeight":"bold","--beam-share-text-fontSize":"16px","--beam-share-text-lineHeight":"1.3","--beam-share-text-marginTop":"10px","--beam-share-image-borderRadius":"4px","--beam-share-image-width":"200px","--beam-share-image-margin":"20px","--beam-share-actions-margin":"30px 60px","--beam-share-action-icon-size":"32px","--beam-share-action-text-fontSize":"16px","--beam-share-action-text-lineHeight":"1.3","--beam-share-text-action-marginTop":"10px","--beam-share-close-backgroundColor":"#ffd522","--beam-share-close-text-color":"#000","--beam-share-close-padding":"12px","--beam-share-close-borderRadius":"4px","--beam-share-close-fontSize":"16px","--beam-share-close-fontWeight":"bold","--beam-share-close-focus-borderColor":"#c2dcff"};export{k as a,y as s};
163
+ //# sourceMappingURL=share-button-2RaDSzSs.esm.js.map