@ubnt/store.core 9.40.1-new-design → 9.41.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 (696) hide show
  1. package/CHANGELOG.md +3 -42
  2. package/lib/apis/smartcat.js.map +1 -1
  3. package/lib/apis/smartcat.mjs.map +1 -1
  4. package/lib/assets/close2.svg +2 -3
  5. package/lib/assets/close3.svg +3 -2
  6. package/lib/assets/icons/menu/{icon-location-pin.svg.js → icon-globe.svg.js} +6 -6
  7. package/lib/assets/icons/menu/icon-globe.svg.js.map +1 -0
  8. package/lib/assets/icons/menu/icon-globe.svg.mjs +3 -0
  9. package/lib/assets/icons/menu/icon-globe.svg.mjs.map +1 -0
  10. package/lib/assets/logoUnifi.svg +2 -10
  11. package/lib/components/Accordion/Accordion.js.map +1 -1
  12. package/lib/components/Accordion/Accordion.mjs.map +1 -1
  13. package/lib/components/Accordion/Accordion.styles.js.map +1 -1
  14. package/lib/components/Accordion/Accordion.styles.mjs.map +1 -1
  15. package/lib/components/Avatar/Avatar.js.map +1 -1
  16. package/lib/components/Avatar/Avatar.mjs.map +1 -1
  17. package/lib/components/BackInStock/BackInStock.types.d.ts +0 -1
  18. package/lib/components/Banner/Banner.styles.js.map +1 -1
  19. package/lib/components/Banner/Banner.styles.mjs.map +1 -1
  20. package/lib/components/Button/Button.js +0 -7
  21. package/lib/components/Button/Button.js.map +1 -1
  22. package/lib/components/Button/Button.mjs +1 -8
  23. package/lib/components/Button/Button.mjs.map +1 -1
  24. package/lib/components/Button/CartButton.d.ts +1 -3
  25. package/lib/components/Button/CartButton.js +4 -9
  26. package/lib/components/Button/CartButton.js.map +1 -1
  27. package/lib/components/Button/CartButton.mjs +4 -8
  28. package/lib/components/Button/CartButton.mjs.map +1 -1
  29. package/lib/components/ButtonGroup/ButtonGroup.js.map +1 -1
  30. package/lib/components/ButtonGroup/ButtonGroup.mjs.map +1 -1
  31. package/lib/components/ButtonGroup/ButtonGroup.styles.js.map +1 -1
  32. package/lib/components/ButtonGroup/ButtonGroup.styles.mjs.map +1 -1
  33. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.d.ts +1 -1
  34. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.js +4 -16
  35. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.js.map +1 -1
  36. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.mjs +5 -17
  37. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.mjs.map +1 -1
  38. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.d.ts +1 -5
  39. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.js +17 -82
  40. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.js.map +1 -1
  41. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.mjs +17 -82
  42. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.mjs.map +1 -1
  43. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.types.d.ts +0 -4
  44. package/lib/components/CardSection/CardSection.styles.d.ts +1 -1
  45. package/lib/components/CategoryTabs/CategoryTabs.styles.d.ts +2 -4
  46. package/lib/components/CategoryTabs/CategoryTabs.styles.js +5 -8
  47. package/lib/components/CategoryTabs/CategoryTabs.styles.js.map +1 -1
  48. package/lib/components/CategoryTabs/CategoryTabs.styles.mjs +6 -7
  49. package/lib/components/CategoryTabs/CategoryTabs.styles.mjs.map +1 -1
  50. package/lib/components/CloserLookSection/CloserLookSection.js.map +1 -1
  51. package/lib/components/CloserLookSection/CloserLookSection.mjs.map +1 -1
  52. package/lib/components/CloserLookSection/CloserLookSection.styles.js.map +1 -1
  53. package/lib/components/CloserLookSection/CloserLookSection.styles.mjs.map +1 -1
  54. package/lib/components/Compare/Compare.styles.d.ts +5 -5
  55. package/lib/components/Container/Container.d.ts +1 -1
  56. package/lib/components/Container/Container.js +3 -4
  57. package/lib/components/Container/Container.js.map +1 -1
  58. package/lib/components/Container/Container.mjs +4 -5
  59. package/lib/components/Container/Container.mjs.map +1 -1
  60. package/lib/components/Container/Container.styles.js.map +1 -1
  61. package/lib/components/Container/Container.styles.mjs.map +1 -1
  62. package/lib/components/CustomImage/CustomImage.js +1 -1
  63. package/lib/components/CustomImage/CustomImage.js.map +1 -1
  64. package/lib/components/CustomImage/CustomImage.mjs +1 -1
  65. package/lib/components/CustomImage/CustomImage.mjs.map +1 -1
  66. package/lib/components/CustomImage/CustomImage.styles.js.map +1 -1
  67. package/lib/components/CustomImage/CustomImage.styles.mjs.map +1 -1
  68. package/lib/components/Explore/Explore.js.map +1 -1
  69. package/lib/components/Explore/Explore.mjs.map +1 -1
  70. package/lib/components/Explore/ExploreData.js +12 -12
  71. package/lib/components/Explore/ExploreData.js.map +1 -1
  72. package/lib/components/Explore/ExploreData.mjs +12 -12
  73. package/lib/components/Explore/ExploreData.mjs.map +1 -1
  74. package/lib/components/FeaturesSection_deprecated/FeaturesSection.js +1 -1
  75. package/lib/components/FeaturesSection_deprecated/FeaturesSection.js.map +1 -1
  76. package/lib/components/FeaturesSection_deprecated/FeaturesSection.mjs +1 -1
  77. package/lib/components/FeaturesSection_deprecated/FeaturesSection.mjs.map +1 -1
  78. package/lib/components/FeaturesSection_deprecated/FeaturesSection.styles.js.map +1 -1
  79. package/lib/components/FeaturesSection_deprecated/FeaturesSection.styles.mjs.map +1 -1
  80. package/lib/components/FeaturesSection_deprecated/assets/close.svg.js +1 -1
  81. package/lib/components/FeaturesSection_deprecated/assets/close.svg.mjs +2 -2
  82. package/lib/components/Footer/Footer.js +1 -1
  83. package/lib/components/Footer/Footer.js.map +1 -1
  84. package/lib/components/Footer/Footer.mjs +1 -1
  85. package/lib/components/Footer/Footer.mjs.map +1 -1
  86. package/lib/components/Footer/Footer.styles.js.map +1 -1
  87. package/lib/components/Footer/Footer.styles.mjs.map +1 -1
  88. package/lib/components/Gallery/Gallery.js.map +1 -1
  89. package/lib/components/Gallery/Gallery.mjs.map +1 -1
  90. package/lib/components/Gallery/Gallery.styles.js.map +1 -1
  91. package/lib/components/Gallery/Gallery.styles.mjs.map +1 -1
  92. package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.js.map +1 -1
  93. package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.mjs.map +1 -1
  94. package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.styles.js.map +1 -1
  95. package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.styles.mjs.map +1 -1
  96. package/lib/components/GradientButton/GradientButton.styles.js.map +1 -1
  97. package/lib/components/GradientButton/GradientButton.styles.mjs.map +1 -1
  98. package/lib/components/GridGallery/GridGallery.js.map +1 -1
  99. package/lib/components/GridGallery/GridGallery.mjs.map +1 -1
  100. package/lib/components/Header/AccountFrame/AccountFrame.js.map +1 -1
  101. package/lib/components/Header/AccountFrame/AccountFrame.mjs.map +1 -1
  102. package/lib/components/Header/AccountFrame/AccountFrame.styles.js.map +1 -1
  103. package/lib/components/Header/AccountFrame/AccountFrame.styles.mjs.map +1 -1
  104. package/lib/components/Header/AccountMenu/AccountMenu.js +1 -11
  105. package/lib/components/Header/AccountMenu/AccountMenu.js.map +1 -1
  106. package/lib/components/Header/AccountMenu/AccountMenu.mjs +3 -13
  107. package/lib/components/Header/AccountMenu/AccountMenu.mjs.map +1 -1
  108. package/lib/components/Header/AccountMenu/megaphone.http.service.js.map +1 -1
  109. package/lib/components/Header/AccountMenu/megaphone.http.service.mjs.map +1 -1
  110. package/lib/components/Header/CartModalV2/Item/Item.js.map +1 -1
  111. package/lib/components/Header/CartModalV2/Item/Item.mjs.map +1 -1
  112. package/lib/components/Header/CartModalV2/Item/Item.styles.d.ts +1 -1
  113. package/lib/components/Header/Header.js +9 -9
  114. package/lib/components/Header/Header.js.map +1 -1
  115. package/lib/components/Header/Header.mjs +9 -9
  116. package/lib/components/Header/Header.mjs.map +1 -1
  117. package/lib/components/Header/Header.styles.d.ts +12 -7
  118. package/lib/components/Header/Header.styles.js +32 -10
  119. package/lib/components/Header/Header.styles.js.map +1 -1
  120. package/lib/components/Header/Header.styles.mjs +31 -10
  121. package/lib/components/Header/Header.styles.mjs.map +1 -1
  122. package/lib/components/Header/Header.types.d.ts +5 -29
  123. package/lib/components/Header/Header.types.js +1 -2
  124. package/lib/components/Header/Header.types.js.map +1 -1
  125. package/lib/components/Header/Header.types.mjs +1 -2
  126. package/lib/components/Header/Header.types.mjs.map +1 -1
  127. package/lib/components/Header/IsolatedHeader.d.ts +0 -1
  128. package/lib/components/Header/IsolatedHeader.js +44 -44
  129. package/lib/components/Header/IsolatedHeader.js.map +1 -1
  130. package/lib/components/Header/IsolatedHeader.mjs +46 -47
  131. package/lib/components/Header/IsolatedHeader.mjs.map +1 -1
  132. package/lib/components/Header/LanguageFrame/LanguageFrame.js.map +1 -1
  133. package/lib/components/Header/LanguageFrame/LanguageFrame.mjs.map +1 -1
  134. package/lib/components/Header/LanguageFrame/LanguageFrame.styles.js.map +1 -1
  135. package/lib/components/Header/LanguageFrame/LanguageFrame.styles.mjs.map +1 -1
  136. package/lib/components/Header/MenuItem/MenuItem.styles.d.ts +1 -1
  137. package/lib/components/Header/MenuItem/MenuItem.styles.js +3 -3
  138. package/lib/components/Header/MenuItem/MenuItem.styles.js.map +1 -1
  139. package/lib/components/Header/MenuItem/MenuItem.styles.mjs +3 -3
  140. package/lib/components/Header/MenuItem/MenuItem.styles.mjs.map +1 -1
  141. package/lib/components/Header/MenuItem/MenuItem.types.d.ts +0 -1
  142. package/lib/components/Header/Navigation/Carousel/Carousel.js.map +1 -1
  143. package/lib/components/Header/Navigation/Carousel/Carousel.mjs.map +1 -1
  144. package/lib/components/Header/Navigation/MicrositeMenu/MicrositeMenu.styles.d.ts +1 -1
  145. package/lib/components/Header/Navigation/MobileMenu/MobileMenu.styles.d.ts +1 -1
  146. package/lib/components/Header/Navigation/MobileMenu/MobileMenu.styles.js.map +1 -1
  147. package/lib/components/Header/Navigation/MobileMenu/MobileMenu.styles.mjs.map +1 -1
  148. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.d.ts +1 -1
  149. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js +103 -110
  150. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js.map +1 -1
  151. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs +104 -111
  152. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs.map +1 -1
  153. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.d.ts +0 -9
  154. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js +1 -15
  155. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js.map +1 -1
  156. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs +2 -13
  157. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs.map +1 -1
  158. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.types.d.ts +6 -12
  159. package/lib/components/Header/ProHeader/ProHeader.d.ts +5 -9
  160. package/lib/components/Header/ProHeader/ProHeader.js +168 -249
  161. package/lib/components/Header/ProHeader/ProHeader.js.map +1 -1
  162. package/lib/components/Header/ProHeader/ProHeader.mjs +170 -250
  163. package/lib/components/Header/ProHeader/ProHeader.mjs.map +1 -1
  164. package/lib/components/Header/ProHeader/ProHeader.styles.d.ts +25 -30
  165. package/lib/components/Header/ProHeader/ProHeader.styles.js +66 -119
  166. package/lib/components/Header/ProHeader/ProHeader.styles.js.map +1 -1
  167. package/lib/components/Header/ProHeader/ProHeader.styles.mjs +65 -112
  168. package/lib/components/Header/ProHeader/ProHeader.styles.mjs.map +1 -1
  169. package/lib/components/Header/translations/ar.json.js +1 -4
  170. package/lib/components/Header/translations/ar.json.js.map +1 -1
  171. package/lib/components/Header/translations/ar.json.mjs +2 -4
  172. package/lib/components/Header/translations/ar.json.mjs.map +1 -1
  173. package/lib/components/Header/translations/de.json.js +1 -4
  174. package/lib/components/Header/translations/de.json.js.map +1 -1
  175. package/lib/components/Header/translations/de.json.mjs +2 -4
  176. package/lib/components/Header/translations/de.json.mjs.map +1 -1
  177. package/lib/components/Header/translations/el.json.js +1 -4
  178. package/lib/components/Header/translations/el.json.js.map +1 -1
  179. package/lib/components/Header/translations/el.json.mjs +2 -4
  180. package/lib/components/Header/translations/el.json.mjs.map +1 -1
  181. package/lib/components/Header/translations/en.json.js +1 -7
  182. package/lib/components/Header/translations/en.json.js.map +1 -1
  183. package/lib/components/Header/translations/en.json.mjs +2 -6
  184. package/lib/components/Header/translations/en.json.mjs.map +1 -1
  185. package/lib/components/Header/translations/es.json.js +1 -4
  186. package/lib/components/Header/translations/es.json.js.map +1 -1
  187. package/lib/components/Header/translations/es.json.mjs +2 -4
  188. package/lib/components/Header/translations/es.json.mjs.map +1 -1
  189. package/lib/components/Header/translations/fr.json.js +1 -4
  190. package/lib/components/Header/translations/fr.json.js.map +1 -1
  191. package/lib/components/Header/translations/fr.json.mjs +2 -4
  192. package/lib/components/Header/translations/fr.json.mjs.map +1 -1
  193. package/lib/components/Header/translations/it.json.js +1 -4
  194. package/lib/components/Header/translations/it.json.js.map +1 -1
  195. package/lib/components/Header/translations/it.json.mjs +2 -4
  196. package/lib/components/Header/translations/it.json.mjs.map +1 -1
  197. package/lib/components/Header/translations/ja.json.js +1 -4
  198. package/lib/components/Header/translations/ja.json.js.map +1 -1
  199. package/lib/components/Header/translations/ja.json.mjs +2 -4
  200. package/lib/components/Header/translations/ja.json.mjs.map +1 -1
  201. package/lib/components/Header/translations/pt-BR.json.js +1 -4
  202. package/lib/components/Header/translations/pt-BR.json.js.map +1 -1
  203. package/lib/components/Header/translations/pt-BR.json.mjs +2 -4
  204. package/lib/components/Header/translations/pt-BR.json.mjs.map +1 -1
  205. package/lib/components/Header/translations/zh-Hans.json.js +1 -4
  206. package/lib/components/Header/translations/zh-Hans.json.js.map +1 -1
  207. package/lib/components/Header/translations/zh-Hans.json.mjs +2 -4
  208. package/lib/components/Header/translations/zh-Hans.json.mjs.map +1 -1
  209. package/lib/components/Header/translations/zh-Hant-TW.json.js +1 -4
  210. package/lib/components/Header/translations/zh-Hant-TW.json.js.map +1 -1
  211. package/lib/components/Header/translations/zh-Hant-TW.json.mjs +2 -4
  212. package/lib/components/Header/translations/zh-Hant-TW.json.mjs.map +1 -1
  213. package/lib/components/Hero/Hero.js.map +1 -1
  214. package/lib/components/Hero/Hero.mjs.map +1 -1
  215. package/lib/components/Hero/Hero.styles.d.ts +2 -2
  216. package/lib/components/Hero/Hero.styles.js.map +1 -1
  217. package/lib/components/Hero/Hero.styles.mjs.map +1 -1
  218. package/lib/components/HeroFadeGallery/HeroFadeGallery.styles.d.ts +1 -1
  219. package/lib/components/HowToUseSection/HowToUseSection.styles.d.ts +2 -2
  220. package/lib/components/ImageCarousel/ImageCarousel.styles.js.map +1 -1
  221. package/lib/components/ImageCarousel/ImageCarousel.styles.mjs.map +1 -1
  222. package/lib/components/LandingPage/Cards/Card/Card.js.map +1 -1
  223. package/lib/components/LandingPage/Cards/Card/Card.mjs.map +1 -1
  224. package/lib/components/LandingPage/Cards/Cards.js.map +1 -1
  225. package/lib/components/LandingPage/Cards/Cards.mjs.map +1 -1
  226. package/lib/components/LandingPage/Cards/Cards.styles.js.map +1 -1
  227. package/lib/components/LandingPage/Cards/Cards.styles.mjs.map +1 -1
  228. package/lib/components/LandingPage/LandingPage.js.map +1 -1
  229. package/lib/components/LandingPage/LandingPage.mjs.map +1 -1
  230. package/lib/components/LandingPagePro/LandingPagePro.js.map +1 -1
  231. package/lib/components/LandingPagePro/LandingPagePro.mjs.map +1 -1
  232. package/lib/components/LandingPagePro/LandingPagePro.styles.d.ts +1 -1
  233. package/lib/components/LandingPageSearch/Modal/Modal.js.map +1 -1
  234. package/lib/components/LandingPageSearch/Modal/Modal.mjs.map +1 -1
  235. package/lib/components/LandingPageSidebar/LandingPageSidebar.js.map +1 -1
  236. package/lib/components/LandingPageSidebar/LandingPageSidebar.mjs.map +1 -1
  237. package/lib/components/LandingPageSidebar/LandingPageSidebar.styles.js.map +1 -1
  238. package/lib/components/LandingPageSidebar/LandingPageSidebar.styles.mjs.map +1 -1
  239. package/lib/components/LayoutRenderer/LayoutRenderer.styles.d.ts +1 -1
  240. package/lib/components/LayoutRendererV1/LayoutRenderer.styles.d.ts +3 -3
  241. package/lib/components/LayoutRendererV2/LayoutRenderer.styles.d.ts +3 -3
  242. package/lib/components/LoaderDots/LoaderDots.d.ts +1 -1
  243. package/lib/components/LoaderDots/LoaderDots.js +1 -3
  244. package/lib/components/LoaderDots/LoaderDots.js.map +1 -1
  245. package/lib/components/LoaderDots/LoaderDots.mjs +1 -3
  246. package/lib/components/LoaderDots/LoaderDots.mjs.map +1 -1
  247. package/lib/components/LoaderDots/LoaderDots.styles.d.ts +1 -2
  248. package/lib/components/LoaderDots/LoaderDots.styles.js +1 -11
  249. package/lib/components/LoaderDots/LoaderDots.styles.js.map +1 -1
  250. package/lib/components/LoaderDots/LoaderDots.styles.mjs +1 -11
  251. package/lib/components/LoaderDots/LoaderDots.styles.mjs.map +1 -1
  252. package/lib/components/LoaderDots/LoaderDots.types.d.ts +0 -2
  253. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.helpers.js.map +1 -1
  254. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.helpers.mjs.map +1 -1
  255. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.styles.d.ts +1 -1
  256. package/lib/components/MicrositeExploreCards/MicrositeExploreCards.styles.js.map +1 -1
  257. package/lib/components/MicrositeExploreCards/MicrositeExploreCards.styles.mjs.map +1 -1
  258. package/lib/components/MicrositeFeatureList/MicrositeFeatureList.styles.js.map +1 -1
  259. package/lib/components/MicrositeFeatureList/MicrositeFeatureList.styles.mjs.map +1 -1
  260. package/lib/components/MicrositeHero/MicrositeHero.js.map +1 -1
  261. package/lib/components/MicrositeHero/MicrositeHero.mjs.map +1 -1
  262. package/lib/components/MicrositeHero/MicrositeHero.styles.js.map +1 -1
  263. package/lib/components/MicrositeHero/MicrositeHero.styles.mjs.map +1 -1
  264. package/lib/components/MicrositeMediaGrid/MicrositeMediaGrid.styles.js.map +1 -1
  265. package/lib/components/MicrositeMediaGrid/MicrositeMediaGrid.styles.mjs.map +1 -1
  266. package/lib/components/MicrositeProductGrid/MicrositeProductGrid.styles.js.map +1 -1
  267. package/lib/components/MicrositeProductGrid/MicrositeProductGrid.styles.mjs.map +1 -1
  268. package/lib/components/MicrositeProductLearnMoreBlock/MicrositeProductLearnMoreBlockWrap.js.map +1 -1
  269. package/lib/components/MicrositeProductLearnMoreBlock/MicrositeProductLearnMoreBlockWrap.mjs.map +1 -1
  270. package/lib/components/MicrositeSectionWrap/MicrositeSectionWrap.styles.d.ts +1 -1
  271. package/lib/components/Microsites/MicrositeProductPage.js.map +1 -1
  272. package/lib/components/Microsites/MicrositeProductPage.mjs.map +1 -1
  273. package/lib/components/MobileModal/MobileModal.styles.js.map +1 -1
  274. package/lib/components/MobileModal/MobileModal.styles.mjs.map +1 -1
  275. package/lib/components/ModelCompareV3/HeaderShadow.js.map +1 -1
  276. package/lib/components/ModelCompareV3/HeaderShadow.mjs.map +1 -1
  277. package/lib/components/ModelCompareV3/ModelCompareV3.js.map +1 -1
  278. package/lib/components/ModelCompareV3/ModelCompareV3.mjs.map +1 -1
  279. package/lib/components/ModelCompareV3/ModelCompareV3.styles.js.map +1 -1
  280. package/lib/components/ModelCompareV3/ModelCompareV3.styles.mjs.map +1 -1
  281. package/lib/components/ModelCompareV3/data/products/UispRouter.js.map +1 -1
  282. package/lib/components/ModelCompareV3/data/products/UispRouter.mjs.map +1 -1
  283. package/lib/components/ModelCompareV3/data/products/UispRouterPro.js.map +1 -1
  284. package/lib/components/ModelCompareV3/data/products/UispRouterPro.mjs.map +1 -1
  285. package/lib/components/ModelCompareV3/data/products/airFiber11.js.map +1 -1
  286. package/lib/components/ModelCompareV3/data/products/airFiber11.mjs.map +1 -1
  287. package/lib/components/ModelCompareV3/data/products/airFiber24.js.map +1 -1
  288. package/lib/components/ModelCompareV3/data/products/airFiber24.mjs.map +1 -1
  289. package/lib/components/ModelCompareV3/data/products/airFiber24HiDensity.js.map +1 -1
  290. package/lib/components/ModelCompareV3/data/products/airFiber24HiDensity.mjs.map +1 -1
  291. package/lib/components/ModelCompareV3/data/products/airFiber2X.js.map +1 -1
  292. package/lib/components/ModelCompareV3/data/products/airFiber2X.mjs.map +1 -1
  293. package/lib/components/ModelCompareV3/data/products/airFiber5.js.map +1 -1
  294. package/lib/components/ModelCompareV3/data/products/airFiber5.mjs.map +1 -1
  295. package/lib/components/ModelCompareV3/data/products/airMAX5GHz16dBi120Sector.js.map +1 -1
  296. package/lib/components/ModelCompareV3/data/products/airMAX5GHz16dBi120Sector.mjs.map +1 -1
  297. package/lib/components/ModelCompareV3/data/products/airMAX5GHz17dBi90Sector.js.map +1 -1
  298. package/lib/components/ModelCompareV3/data/products/airMAX5GHz17dBi90Sector.mjs.map +1 -1
  299. package/lib/components/ModelCompareV3/data/products/airMAX5GHz19dBi120Sector.js.map +1 -1
  300. package/lib/components/ModelCompareV3/data/products/airMAX5GHz19dBi120Sector.mjs.map +1 -1
  301. package/lib/components/ModelCompareV3/data/products/airMAX5GHz20dBi90Sector.js.map +1 -1
  302. package/lib/components/ModelCompareV3/data/products/airMAX5GHz20dBi90Sector.mjs.map +1 -1
  303. package/lib/components/ModelCompareV3/data/products/baseStationXG.js.map +1 -1
  304. package/lib/components/ModelCompareV3/data/products/baseStationXG.mjs.map +1 -1
  305. package/lib/components/ModelCompareV3/data/products/buildingBridge.js.map +1 -1
  306. package/lib/components/ModelCompareV3/data/products/buildingBridge.mjs.map +1 -1
  307. package/lib/components/ModelCompareV3/data/products/buildingBridgeXG.js.map +1 -1
  308. package/lib/components/ModelCompareV3/data/products/buildingBridgeXG.mjs.map +1 -1
  309. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.js +2 -4
  310. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.js.map +1 -1
  311. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.mjs +2 -4
  312. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.mjs.map +1 -1
  313. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.js +2 -2
  314. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.js.map +1 -1
  315. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.mjs +2 -2
  316. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.mjs.map +1 -1
  317. package/lib/components/ModelCompareV3/data/products/e7.js.map +1 -1
  318. package/lib/components/ModelCompareV3/data/products/e7.mjs.map +1 -1
  319. package/lib/components/ModelCompareV3/data/products/edgePointR6.js.map +1 -1
  320. package/lib/components/ModelCompareV3/data/products/edgePointR6.mjs.map +1 -1
  321. package/lib/components/ModelCompareV3/data/products/edgePointR8.js.map +1 -1
  322. package/lib/components/ModelCompareV3/data/products/edgePointR8.mjs.map +1 -1
  323. package/lib/components/ModelCompareV3/data/products/edgePointS16Switch.js.map +1 -1
  324. package/lib/components/ModelCompareV3/data/products/edgePointS16Switch.mjs.map +1 -1
  325. package/lib/components/ModelCompareV3/data/products/edgeRouter10x.js.map +1 -1
  326. package/lib/components/ModelCompareV3/data/products/edgeRouter10x.mjs.map +1 -1
  327. package/lib/components/ModelCompareV3/data/products/edgeRouter12.js.map +1 -1
  328. package/lib/components/ModelCompareV3/data/products/edgeRouter12.mjs.map +1 -1
  329. package/lib/components/ModelCompareV3/data/products/edgeRouter12p.js.map +1 -1
  330. package/lib/components/ModelCompareV3/data/products/edgeRouter12p.mjs.map +1 -1
  331. package/lib/components/ModelCompareV3/data/products/edgeRouter4.js.map +1 -1
  332. package/lib/components/ModelCompareV3/data/products/edgeRouter4.mjs.map +1 -1
  333. package/lib/components/ModelCompareV3/data/products/edgeRouter6Poe.js.map +1 -1
  334. package/lib/components/ModelCompareV3/data/products/edgeRouter6Poe.mjs.map +1 -1
  335. package/lib/components/ModelCompareV3/data/products/edgeRouterInfinity.js.map +1 -1
  336. package/lib/components/ModelCompareV3/data/products/edgeRouterInfinity.mjs.map +1 -1
  337. package/lib/components/ModelCompareV3/data/products/edgeRouterX.js.map +1 -1
  338. package/lib/components/ModelCompareV3/data/products/edgeRouterX.mjs.map +1 -1
  339. package/lib/components/ModelCompareV3/data/products/edgeRouterXSfp.js.map +1 -1
  340. package/lib/components/ModelCompareV3/data/products/edgeRouterXSfp.mjs.map +1 -1
  341. package/lib/components/ModelCompareV3/data/products/edgeSwitch10x.js.map +1 -1
  342. package/lib/components/ModelCompareV3/data/products/edgeSwitch10x.mjs.map +1 -1
  343. package/lib/components/ModelCompareV3/data/products/edgeSwitch10xp.js.map +1 -1
  344. package/lib/components/ModelCompareV3/data/products/edgeSwitch10xp.mjs.map +1 -1
  345. package/lib/components/ModelCompareV3/data/products/edgeSwitch16xg.js.map +1 -1
  346. package/lib/components/ModelCompareV3/data/products/edgeSwitch16xg.mjs.map +1 -1
  347. package/lib/components/ModelCompareV3/data/products/edgeSwitch16xp.js.map +1 -1
  348. package/lib/components/ModelCompareV3/data/products/edgeSwitch16xp.mjs.map +1 -1
  349. package/lib/components/ModelCompareV3/data/products/edgeSwitch16xpoe150.js.map +1 -1
  350. package/lib/components/ModelCompareV3/data/products/edgeSwitch16xpoe150.mjs.map +1 -1
  351. package/lib/components/ModelCompareV3/data/products/edgeSwitch18x.js.map +1 -1
  352. package/lib/components/ModelCompareV3/data/products/edgeSwitch18x.mjs.map +1 -1
  353. package/lib/components/ModelCompareV3/data/products/edgeSwitch24lite.js.map +1 -1
  354. package/lib/components/ModelCompareV3/data/products/edgeSwitch24lite.mjs.map +1 -1
  355. package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe-500.js.map +1 -1
  356. package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe-500.mjs.map +1 -1
  357. package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe.js.map +1 -1
  358. package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe.mjs.map +1 -1
  359. package/lib/components/ModelCompareV3/data/products/edgeSwitch48lite.js.map +1 -1
  360. package/lib/components/ModelCompareV3/data/products/edgeSwitch48lite.mjs.map +1 -1
  361. package/lib/components/ModelCompareV3/data/products/edgeSwitch48poe.js.map +1 -1
  362. package/lib/components/ModelCompareV3/data/products/edgeSwitch48poe.mjs.map +1 -1
  363. package/lib/components/ModelCompareV3/data/products/edgeswitch48poe-750.js.map +1 -1
  364. package/lib/components/ModelCompareV3/data/products/edgeswitch48poe-750.mjs.map +1 -1
  365. package/lib/components/ModelCompareV3/data/products/edgeswitch5xp.js.map +1 -1
  366. package/lib/components/ModelCompareV3/data/products/edgeswitch5xp.mjs.map +1 -1
  367. package/lib/components/ModelCompareV3/data/products/edgeswitch8poe.js.map +1 -1
  368. package/lib/components/ModelCompareV3/data/products/edgeswitch8poe.mjs.map +1 -1
  369. package/lib/components/ModelCompareV3/data/products/express.js +3 -3
  370. package/lib/components/ModelCompareV3/data/products/express.js.map +1 -1
  371. package/lib/components/ModelCompareV3/data/products/express.mjs +3 -3
  372. package/lib/components/ModelCompareV3/data/products/express.mjs.map +1 -1
  373. package/lib/components/ModelCompareV3/data/products/fiberInstant.js.map +1 -1
  374. package/lib/components/ModelCompareV3/data/products/fiberInstant.mjs.map +1 -1
  375. package/lib/components/ModelCompareV3/data/products/fiberNanog.js.map +1 -1
  376. package/lib/components/ModelCompareV3/data/products/fiberNanog.mjs.map +1 -1
  377. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.js +2 -4
  378. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.js.map +1 -1
  379. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.mjs +2 -4
  380. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.mjs.map +1 -1
  381. package/lib/components/ModelCompareV3/data/products/gatewayLite.js +2 -4
  382. package/lib/components/ModelCompareV3/data/products/gatewayLite.js.map +1 -1
  383. package/lib/components/ModelCompareV3/data/products/gatewayLite.mjs +2 -4
  384. package/lib/components/ModelCompareV3/data/products/gatewayLite.mjs.map +1 -1
  385. package/lib/components/ModelCompareV3/data/products/gatewayMax.js +2 -4
  386. package/lib/components/ModelCompareV3/data/products/gatewayMax.js.map +1 -1
  387. package/lib/components/ModelCompareV3/data/products/gatewayMax.mjs +2 -4
  388. package/lib/components/ModelCompareV3/data/products/gatewayMax.mjs.map +1 -1
  389. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.js +2 -4
  390. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.js.map +1 -1
  391. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.mjs +2 -4
  392. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.mjs.map +1 -1
  393. package/lib/components/ModelCompareV3/data/products/ltuExtremeRange.js.map +1 -1
  394. package/lib/components/ModelCompareV3/data/products/ltuExtremeRange.mjs.map +1 -1
  395. package/lib/components/ModelCompareV3/data/products/ltuLongRange.js.map +1 -1
  396. package/lib/components/ModelCompareV3/data/products/ltuLongRange.mjs.map +1 -1
  397. package/lib/components/ModelCompareV3/data/products/ltuPro.js.map +1 -1
  398. package/lib/components/ModelCompareV3/data/products/ltuPro.mjs.map +1 -1
  399. package/lib/components/ModelCompareV3/data/products/nanoStation5AC.js.map +1 -1
  400. package/lib/components/ModelCompareV3/data/products/nanoStation5AC.mjs.map +1 -1
  401. package/lib/components/ModelCompareV3/data/products/nanoStation5ACLoco.js.map +1 -1
  402. package/lib/components/ModelCompareV3/data/products/nanoStation5ACLoco.mjs.map +1 -1
  403. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.js +1 -3
  404. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.js.map +1 -1
  405. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.mjs +1 -3
  406. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.mjs.map +1 -1
  407. package/lib/components/ModelCompareV3/data/products/prismStation5AC.js.map +1 -1
  408. package/lib/components/ModelCompareV3/data/products/prismStation5AC.mjs.map +1 -1
  409. package/lib/components/ModelCompareV3/data/products/ucgMax.js +1 -1
  410. package/lib/components/ModelCompareV3/data/products/ucgMax.js.map +1 -1
  411. package/lib/components/ModelCompareV3/data/products/ucgMax.mjs +1 -1
  412. package/lib/components/ModelCompareV3/data/products/ucgMax.mjs.map +1 -1
  413. package/lib/components/ModelCompareV3/data/products/ucgUltra.js +3 -3
  414. package/lib/components/ModelCompareV3/data/products/ucgUltra.js.map +1 -1
  415. package/lib/components/ModelCompareV3/data/products/ucgUltra.mjs +3 -3
  416. package/lib/components/ModelCompareV3/data/products/ucgUltra.mjs.map +1 -1
  417. package/lib/components/ModelCompareV3/data/products/udb.js.map +1 -1
  418. package/lib/components/ModelCompareV3/data/products/udb.mjs.map +1 -1
  419. package/lib/components/ModelCompareV3/data/products/udbPro.js.map +1 -1
  420. package/lib/components/ModelCompareV3/data/products/udbPro.mjs.map +1 -1
  421. package/lib/components/ModelCompareV3/data/products/udmPro.js +3 -3
  422. package/lib/components/ModelCompareV3/data/products/udmPro.js.map +1 -1
  423. package/lib/components/ModelCompareV3/data/products/udmPro.mjs +3 -3
  424. package/lib/components/ModelCompareV3/data/products/udmPro.mjs.map +1 -1
  425. package/lib/components/ModelCompareV3/data/products/udmProMax.js +3 -3
  426. package/lib/components/ModelCompareV3/data/products/udmProMax.js.map +1 -1
  427. package/lib/components/ModelCompareV3/data/products/udmProMax.mjs +3 -3
  428. package/lib/components/ModelCompareV3/data/products/udmProMax.mjs.map +1 -1
  429. package/lib/components/ModelCompareV3/data/products/udmProSpecial.js +3 -3
  430. package/lib/components/ModelCompareV3/data/products/udmProSpecial.js.map +1 -1
  431. package/lib/components/ModelCompareV3/data/products/udmProSpecial.mjs +3 -3
  432. package/lib/components/ModelCompareV3/data/products/udmProSpecial.mjs.map +1 -1
  433. package/lib/components/ModelCompareV3/data/products/udr.js +41 -5
  434. package/lib/components/ModelCompareV3/data/products/udr.js.map +1 -1
  435. package/lib/components/ModelCompareV3/data/products/udr.mjs +21 -5
  436. package/lib/components/ModelCompareV3/data/products/udr.mjs.map +1 -1
  437. package/lib/components/ModelCompareV3/data/products/udw.js +3 -3
  438. package/lib/components/ModelCompareV3/data/products/udw.js.map +1 -1
  439. package/lib/components/ModelCompareV3/data/products/udw.mjs +3 -3
  440. package/lib/components/ModelCompareV3/data/products/udw.mjs.map +1 -1
  441. package/lib/components/ModelCompareV3/data/products/uispSwitch.js.map +1 -1
  442. package/lib/components/ModelCompareV3/data/products/uispSwitch.mjs.map +1 -1
  443. package/lib/components/Pagination/Pagination.js.map +1 -1
  444. package/lib/components/Pagination/Pagination.mjs.map +1 -1
  445. package/lib/components/PriceRangeSlider/PriceRangeSlider.js.map +1 -1
  446. package/lib/components/PriceRangeSlider/PriceRangeSlider.mjs.map +1 -1
  447. package/lib/components/ProductCard/ProductCard.js.map +1 -1
  448. package/lib/components/ProductCard/ProductCard.mjs.map +1 -1
  449. package/lib/components/ProductCardPopup/ProductCardPopup.js.map +1 -1
  450. package/lib/components/ProductCardPopup/ProductCardPopup.mjs.map +1 -1
  451. package/lib/components/ProductGrid/ProductGrid.js.map +1 -1
  452. package/lib/components/ProductGrid/ProductGrid.mjs.map +1 -1
  453. package/lib/components/ProductSectionNavigation/ProductSectionNavigation.styles.d.ts +1 -1
  454. package/lib/components/ProductSectionNavigationV2/ProductSectionNavigation.styles.d.ts +1 -1
  455. package/lib/components/ProductSectionTabs/ProductSectionTabs.js.map +1 -1
  456. package/lib/components/ProductSectionTabs/ProductSectionTabs.mjs.map +1 -1
  457. package/lib/components/ProductTechSpecs/ProductTechSpecs.styles.d.ts +2 -2
  458. package/lib/components/ProductTechSpecs/ProductTechSpecs.styles.js.map +1 -1
  459. package/lib/components/ProductTechSpecs/ProductTechSpecs.styles.mjs.map +1 -1
  460. package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.js.map +1 -1
  461. package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.mjs.map +1 -1
  462. package/lib/components/RelatedProducts/RelatedProducts.js.map +1 -1
  463. package/lib/components/RelatedProducts/RelatedProducts.mjs.map +1 -1
  464. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.js.map +1 -1
  465. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.mjs.map +1 -1
  466. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/HddSlots/HddSlots.js.map +1 -1
  467. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/HddSlots/HddSlots.mjs.map +1 -1
  468. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.js.map +1 -1
  469. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.mjs.map +1 -1
  470. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/Layout.styles.js.map +1 -1
  471. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/Layout.styles.mjs.map +1 -1
  472. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.js +1 -1
  473. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.js.map +1 -1
  474. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.mjs +1 -1
  475. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.mjs.map +1 -1
  476. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerConfigurator.js.map +1 -1
  477. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerConfigurator.mjs.map +1 -1
  478. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.js.map +1 -1
  479. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.mjs.map +1 -1
  480. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/RecommendedPoeSwitches.js.map +1 -1
  481. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/RecommendedPoeSwitches.mjs.map +1 -1
  482. package/lib/components/ScrollWrapper/ScrollWrapper.d.ts +1 -1
  483. package/lib/components/ScrollWrapper/ScrollWrapper.js +8 -16
  484. package/lib/components/ScrollWrapper/ScrollWrapper.js.map +1 -1
  485. package/lib/components/ScrollWrapper/ScrollWrapper.mjs +8 -16
  486. package/lib/components/ScrollWrapper/ScrollWrapper.mjs.map +1 -1
  487. package/lib/components/ScrollWrapper/ScrollWrapper.styles.js.map +1 -1
  488. package/lib/components/ScrollWrapper/ScrollWrapper.styles.mjs.map +1 -1
  489. package/lib/components/ScrollWrapper/ScrollWrapper.types.d.ts +0 -2
  490. package/lib/components/Search/Input/Input.d.ts +1 -1
  491. package/lib/components/Search/Input/Input.js +4 -4
  492. package/lib/components/Search/Input/Input.js.map +1 -1
  493. package/lib/components/Search/Input/Input.mjs +4 -4
  494. package/lib/components/Search/Input/Input.mjs.map +1 -1
  495. package/lib/components/Search/Input/Input.styles.js +1 -0
  496. package/lib/components/Search/Input/Input.styles.js.map +1 -1
  497. package/lib/components/Search/Input/Input.styles.mjs +1 -0
  498. package/lib/components/Search/Input/Input.styles.mjs.map +1 -1
  499. package/lib/components/Search/Input/Input.types.d.ts +2 -3
  500. package/lib/components/Search/Modal/Modal.js.map +1 -1
  501. package/lib/components/Search/Modal/Modal.mjs.map +1 -1
  502. package/lib/components/SkeletonLoader/SkeletonLoaderTable/SkeletonLoaderTable.js.map +1 -1
  503. package/lib/components/SkeletonLoader/SkeletonLoaderTable/SkeletonLoaderTable.mjs.map +1 -1
  504. package/lib/components/StorageSliders/StorageSliders.utils.js.map +1 -1
  505. package/lib/components/StorageSliders/StorageSliders.utils.mjs.map +1 -1
  506. package/lib/components/StyleableSvgImage/StyleableSvgImage.js.map +1 -1
  507. package/lib/components/StyleableSvgImage/StyleableSvgImage.mjs.map +1 -1
  508. package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.js.map +1 -1
  509. package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.mjs.map +1 -1
  510. package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.styles.js.map +1 -1
  511. package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.styles.mjs.map +1 -1
  512. package/lib/components/VariantSelector/Variant/Variant.js.map +1 -1
  513. package/lib/components/VariantSelector/Variant/Variant.mjs.map +1 -1
  514. package/lib/components/VariantSelector/VariantSelector.constants.js.map +1 -1
  515. package/lib/components/VariantSelector/VariantSelector.constants.mjs.map +1 -1
  516. package/lib/components/VideoPlayerNew/VideoPlayer.js +1 -1
  517. package/lib/components/VideoPlayerNew/VideoPlayer.mjs +1 -1
  518. package/lib/components/VideoPlayerNew/assets/close.svg.js +1 -1
  519. package/lib/components/VideoPlayerNew/assets/close.svg.mjs +2 -2
  520. package/lib/constants/icons/options/colors/black.svg.js +5 -5
  521. package/lib/constants/icons/options/colors/index.js +3 -3
  522. package/lib/constants/icons/options/styles/black.svg.js +5 -5
  523. package/lib/constants/icons/options/styles/index.js +3 -3
  524. package/lib/constants/layout.js.map +1 -1
  525. package/lib/constants/layout.mjs.map +1 -1
  526. package/lib/constants/optionIcons.js +6 -6
  527. package/lib/constants/optionIcons.mjs +4 -4
  528. package/lib/constants/postalCode.js.map +1 -1
  529. package/lib/constants/postalCode.mjs.map +1 -1
  530. package/lib/constants/proStoreCategories/mapping/filters.d.ts +0 -16
  531. package/lib/constants/proStoreCategories/mapping/filters.js +0 -16
  532. package/lib/constants/proStoreCategories/mapping/filters.js.map +1 -1
  533. package/lib/constants/proStoreCategories/mapping/filters.mjs +0 -16
  534. package/lib/constants/proStoreCategories/mapping/filters.mjs.map +1 -1
  535. package/lib/constants/proStoreCategories/mapping/index.d.ts +2 -3
  536. package/lib/constants/proStoreCategories/mapping/index.js +51 -45
  537. package/lib/constants/proStoreCategories/mapping/index.js.map +1 -1
  538. package/lib/constants/proStoreCategories/mapping/index.mjs +49 -44
  539. package/lib/constants/proStoreCategories/mapping/index.mjs.map +1 -1
  540. package/lib/constants/proStoreCategories/mapping/mapping.d.ts +0 -5
  541. package/lib/constants/proStoreCategories/mapping/redirects.js +3 -18
  542. package/lib/constants/proStoreCategories/mapping/redirects.js.map +1 -1
  543. package/lib/constants/proStoreCategories/mapping/redirects.mjs +3 -18
  544. package/lib/constants/proStoreCategories/mapping/redirects.mjs.map +1 -1
  545. package/lib/constants/proStoreCategories/mapping/unifi.d.ts +9 -8
  546. package/lib/constants/proStoreCategories/mapping/unifi.js +9 -8
  547. package/lib/constants/proStoreCategories/mapping/unifi.js.map +1 -1
  548. package/lib/constants/proStoreCategories/mapping/unifi.mjs +9 -8
  549. package/lib/constants/proStoreCategories/mapping/unifi.mjs.map +1 -1
  550. package/lib/constants/proStoreCategories/translations/ar.json.js +3 -4
  551. package/lib/constants/proStoreCategories/translations/ar.json.js.map +1 -1
  552. package/lib/constants/proStoreCategories/translations/ar.json.mjs +3 -4
  553. package/lib/constants/proStoreCategories/translations/ar.json.mjs.map +1 -1
  554. package/lib/constants/proStoreCategories/translations/de.json.js +3 -4
  555. package/lib/constants/proStoreCategories/translations/de.json.js.map +1 -1
  556. package/lib/constants/proStoreCategories/translations/de.json.mjs +3 -4
  557. package/lib/constants/proStoreCategories/translations/de.json.mjs.map +1 -1
  558. package/lib/constants/proStoreCategories/translations/el.json.js +3 -4
  559. package/lib/constants/proStoreCategories/translations/el.json.js.map +1 -1
  560. package/lib/constants/proStoreCategories/translations/el.json.mjs +3 -4
  561. package/lib/constants/proStoreCategories/translations/el.json.mjs.map +1 -1
  562. package/lib/constants/proStoreCategories/translations/en.json.js +2 -3
  563. package/lib/constants/proStoreCategories/translations/en.json.js.map +1 -1
  564. package/lib/constants/proStoreCategories/translations/en.json.mjs +2 -3
  565. package/lib/constants/proStoreCategories/translations/en.json.mjs.map +1 -1
  566. package/lib/constants/proStoreCategories/translations/es.json.js +3 -4
  567. package/lib/constants/proStoreCategories/translations/es.json.js.map +1 -1
  568. package/lib/constants/proStoreCategories/translations/es.json.mjs +3 -4
  569. package/lib/constants/proStoreCategories/translations/es.json.mjs.map +1 -1
  570. package/lib/constants/proStoreCategories/translations/fr.json.js +3 -4
  571. package/lib/constants/proStoreCategories/translations/fr.json.js.map +1 -1
  572. package/lib/constants/proStoreCategories/translations/fr.json.mjs +3 -4
  573. package/lib/constants/proStoreCategories/translations/fr.json.mjs.map +1 -1
  574. package/lib/constants/proStoreCategories/translations/it.json.js +3 -4
  575. package/lib/constants/proStoreCategories/translations/it.json.js.map +1 -1
  576. package/lib/constants/proStoreCategories/translations/it.json.mjs +3 -4
  577. package/lib/constants/proStoreCategories/translations/it.json.mjs.map +1 -1
  578. package/lib/constants/proStoreCategories/translations/ja.json.js +3 -4
  579. package/lib/constants/proStoreCategories/translations/ja.json.js.map +1 -1
  580. package/lib/constants/proStoreCategories/translations/ja.json.mjs +3 -4
  581. package/lib/constants/proStoreCategories/translations/ja.json.mjs.map +1 -1
  582. package/lib/constants/proStoreCategories/translations/pt-BR.json.js +3 -4
  583. package/lib/constants/proStoreCategories/translations/pt-BR.json.js.map +1 -1
  584. package/lib/constants/proStoreCategories/translations/pt-BR.json.mjs +3 -4
  585. package/lib/constants/proStoreCategories/translations/pt-BR.json.mjs.map +1 -1
  586. package/lib/constants/proStoreCategories/translations/zh-Hans.json.js +3 -4
  587. package/lib/constants/proStoreCategories/translations/zh-Hans.json.js.map +1 -1
  588. package/lib/constants/proStoreCategories/translations/zh-Hans.json.mjs +3 -4
  589. package/lib/constants/proStoreCategories/translations/zh-Hans.json.mjs.map +1 -1
  590. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.js +3 -4
  591. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.js.map +1 -1
  592. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.mjs +3 -4
  593. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.mjs.map +1 -1
  594. package/lib/constants/proStoreFilters/mapping.d.ts +3 -45
  595. package/lib/constants/proStoreFilters/mapping.js +9 -119
  596. package/lib/constants/proStoreFilters/mapping.js.map +1 -1
  597. package/lib/constants/proStoreFilters/mapping.mjs +9 -119
  598. package/lib/constants/proStoreFilters/mapping.mjs.map +1 -1
  599. package/lib/constants/theme.js +0 -4
  600. package/lib/constants/theme.js.map +1 -1
  601. package/lib/constants/theme.mjs +0 -4
  602. package/lib/constants/theme.mjs.map +1 -1
  603. package/lib/contexts/MenuContext/context.js +1 -1
  604. package/lib/contexts/MenuContext/context.js.map +1 -1
  605. package/lib/contexts/MenuContext/context.mjs +1 -1
  606. package/lib/contexts/MenuContext/context.mjs.map +1 -1
  607. package/lib/contexts/MenuContext/mapping.js.map +1 -1
  608. package/lib/contexts/MenuContext/mapping.mjs.map +1 -1
  609. package/lib/contexts/MenuContext/utils.js.map +1 -1
  610. package/lib/contexts/MenuContext/utils.mjs.map +1 -1
  611. package/lib/helpers/time.js.map +1 -1
  612. package/lib/helpers/time.mjs.map +1 -1
  613. package/lib/helpers/ux.d.ts +1 -9
  614. package/lib/helpers/ux.js +0 -15
  615. package/lib/helpers/ux.js.map +1 -1
  616. package/lib/helpers/ux.mjs +1 -15
  617. package/lib/helpers/ux.mjs.map +1 -1
  618. package/lib/hooks/useTranslation.js.map +1 -1
  619. package/lib/hooks/useTranslation.mjs.map +1 -1
  620. package/lib/utils/address.js.map +1 -1
  621. package/lib/utils/address.mjs.map +1 -1
  622. package/lib/utils/money/allocators/fixedAmount.js.map +1 -1
  623. package/lib/utils/money/allocators/fixedAmount.mjs.map +1 -1
  624. package/lib/utils/money/format.js +2 -1
  625. package/lib/utils/money/format.js.map +1 -1
  626. package/lib/utils/money/format.mjs +2 -1
  627. package/lib/utils/money/format.mjs.map +1 -1
  628. package/lib/utils/money/misc.js.map +1 -1
  629. package/lib/utils/money/misc.mjs.map +1 -1
  630. package/lib/utils/nextjs/createInlineScript.js.map +1 -1
  631. package/lib/utils/nextjs/createInlineScript.mjs.map +1 -1
  632. package/lib/utils/nextjs/index.d.ts +3 -0
  633. package/lib/utils/nextjs/index.js +5 -0
  634. package/lib/utils/nextjs/index.js.map +1 -1
  635. package/lib/utils/nextjs/index.mjs +3 -0
  636. package/lib/utils/nextjs/index.mjs.map +1 -1
  637. package/lib/utils/nextjs/patch.d.ts +1 -0
  638. package/lib/utils/nextjs/patch.js +53 -0
  639. package/lib/utils/nextjs/patch.js.map +1 -0
  640. package/lib/utils/nextjs/patch.mjs +41 -0
  641. package/lib/utils/nextjs/patch.mjs.map +1 -0
  642. package/lib/utils/nextjs/plugin.d.ts +14 -0
  643. package/lib/utils/nextjs/plugin.js +41 -0
  644. package/lib/utils/nextjs/plugin.js.map +1 -0
  645. package/lib/utils/nextjs/plugin.mjs +39 -0
  646. package/lib/utils/nextjs/plugin.mjs.map +1 -0
  647. package/lib/utils/nextjs/ssr/constants.d.ts +8 -0
  648. package/lib/utils/nextjs/ssr/constants.js +8 -0
  649. package/lib/utils/nextjs/ssr/constants.js.map +1 -0
  650. package/lib/utils/nextjs/ssr/constants.mjs +6 -0
  651. package/lib/utils/nextjs/ssr/constants.mjs.map +1 -0
  652. package/lib/utils/nextjs/ssr/registry.d.ts +52 -0
  653. package/lib/utils/nextjs/ssr/registry.js +22 -0
  654. package/lib/utils/nextjs/ssr/registry.js.map +1 -0
  655. package/lib/utils/nextjs/ssr/registry.mjs +20 -0
  656. package/lib/utils/nextjs/ssr/registry.mjs.map +1 -0
  657. package/lib/utils/nextjs/ssr/style-inject.d.ts +21 -0
  658. package/lib/utils/nextjs/ssr/style-inject.js +47 -0
  659. package/lib/utils/nextjs/ssr/style-inject.js.map +1 -0
  660. package/lib/utils/nextjs/ssr/style-inject.mjs +43 -0
  661. package/lib/utils/nextjs/ssr/style-inject.mjs.map +1 -0
  662. package/lib/utils/nextjs/ssr/transform-css-module.d.ts +11 -0
  663. package/lib/utils/nextjs/ssr/transform-css-module.js +115 -0
  664. package/lib/utils/nextjs/ssr/transform-css-module.js.map +1 -0
  665. package/lib/utils/nextjs/ssr/transform-css-module.mjs +87 -0
  666. package/lib/utils/nextjs/ssr/transform-css-module.mjs.map +1 -0
  667. package/lib/utils/nextjs/ssr/transform-css-module.test.d.ts +1 -0
  668. package/lib/utils/nextjs/ssr/types.d.ts +10 -0
  669. package/lib/utils/nextjs/stringifyForInject.js.map +1 -1
  670. package/lib/utils/nextjs/stringifyForInject.mjs.map +1 -1
  671. package/lib/utils/number.js.map +1 -1
  672. package/lib/utils/number.mjs.map +1 -1
  673. package/lib/utils/tax/brazil.js.map +1 -1
  674. package/lib/utils/tax/brazil.mjs.map +1 -1
  675. package/lib/utils/wattage.js.map +1 -1
  676. package/lib/utils/wattage.mjs.map +1 -1
  677. package/package.json +3 -1
  678. package/lib/assets/cart-secondary.svg +0 -5
  679. package/lib/assets/icon-location-pin.svg +0 -5
  680. package/lib/assets/icons/cart-secondary.svg.js +0 -27
  681. package/lib/assets/icons/cart-secondary.svg.js.map +0 -1
  682. package/lib/assets/icons/cart-secondary.svg.mjs +0 -3
  683. package/lib/assets/icons/cart-secondary.svg.mjs.map +0 -1
  684. package/lib/assets/icons/menu/icon-location-pin.svg.js.map +0 -1
  685. package/lib/assets/icons/menu/icon-location-pin.svg.mjs +0 -3
  686. package/lib/assets/icons/menu/icon-location-pin.svg.mjs.map +0 -1
  687. package/lib/components/Header/LogoIcon/LogoIcon.d.ts +0 -7
  688. package/lib/components/Header/LogoIcon/LogoIcon.js +0 -46
  689. package/lib/components/Header/LogoIcon/LogoIcon.js.map +0 -1
  690. package/lib/components/Header/LogoIcon/LogoIcon.mjs +0 -36
  691. package/lib/components/Header/LogoIcon/LogoIcon.mjs.map +0 -1
  692. package/lib/components/Header/LogoIcon/index.d.ts +0 -1
  693. package/lib/components/Header/LogoIcon/index.js +0 -6
  694. package/lib/components/Header/LogoIcon/index.js.map +0 -1
  695. package/lib/components/Header/LogoIcon/index.mjs +0 -3
  696. package/lib/components/Header/LogoIcon/index.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"address.js","sources":["../../src/utils/address.ts"],"sourcesContent":["import type { ZodErrorMap } from \"zod\";\nimport { z } from \"zod\";\n\nimport { AddressType, AddressUsageType, CountryCode } from \"../types\";\nimport type { Country } from \"./countriesAndZones\";\nimport { address2SuperRefinement } from \"./validations/address2SuperRefinement\";\nimport { businessNameSuperRefinement } from \"./validations/businessNameSuperRefinement\";\nimport { neighborhoodSuperRefinement } from \"./validations/neighborhoodSuperRefinement\";\nimport { phoneNumberSuperRefinement } from \"./validations/phoneNumberSuperRefinement\";\nimport { postalCodeSuperRefinement } from \"./validations/postalCodeSuperRefinement\";\nimport { getProvinceSuperRefinement } from \"./validations/provinceSuperRefinement\";\nimport { createStateRegistrationNumberSuperRefinement } from \"./validations/stateRegistrationNumberSuperRefinement\";\nimport { createTaxIdSuperRefinement } from \"./validations/taxIdSuperRefinement\";\nimport type { ValidateTaxIdExternally } from \"./validations/taxIdSuperRefinement\";\n\nexport type BaseAddressSchemaArgs = {\n countries: Country[];\n errorMap?: ZodErrorMap;\n addressUsageType?: AddressUsageType;\n};\n\nexport type AddressSchemaArgs = BaseAddressSchemaArgs & {\n validateTaxIdExternally?: ValidateTaxIdExternally;\n};\n\nconst COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER = new Set([\n CountryCode.Br,\n]);\n\nconst COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE = new Map<\n CountryCode,\n Array<keyof z.infer<ReturnType<typeof getAddressSchema>>>\n>([\n [\n CountryCode.Br,\n [\"stateRegistrationNumber\", \"neighborhood\", \"additionalInfo\"],\n ],\n]);\n\n/**\n * If it returns `true`, the `address1` field will be used for the street name\n * and `address2` field will be used for the house/apartment number.\n */\nexport const shouldAddressHaveSeparatedStreetAndHouseNumber = (\n country: CountryCode,\n) => COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER.has(country);\n\n/**\n * Returns address form field paths for country-specific fields.\n */\nexport const getCountrySpecificAddressFormFields = <TPathPrefix extends string>(\n country: CountryCode,\n { pathPrefix }: { pathPrefix: TPathPrefix },\n) => {\n const fields = COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE.get(country);\n\n if (!fields) {\n return [];\n }\n\n return fields.map((field) => `${pathPrefix}${field}` as const);\n};\n\nconst DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE = AddressUsageType.Shipping;\n// #############################################################################\n// Base Address Schema\n// #############################################################################\nexport const getBaseAddressSchema = ({\n countries,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: BaseAddressSchemaArgs) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n return schema\n .object({\n address1:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().min(1).max(35)\n : z.string().trim().min(1).max(255),\n address2:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().max(35).nullish()\n : z.string().trim().max(255).nullish(),\n city: z.string().trim().min(1).max(255),\n province: z.string().trim().nullish(),\n country: z.nativeEnum(CountryCode),\n postalCode: z.string().trim().max(255).nullish(),\n neighborhood: z.string().trim().max(255).nullish(),\n })\n .superRefine(getProvinceSuperRefinement(countries))\n .superRefine(postalCodeSuperRefinement)\n .superRefine(neighborhoodSuperRefinement)\n .superRefine(address2SuperRefinement);\n};\n\n// #############################################################################\n// Address Schema\n// #############################################################################\nexport const getAddressSchema = ({\n countries,\n validateTaxIdExternally,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: AddressSchemaArgs) => {\n return z\n .object({\n type: z.nativeEnum(AddressType),\n businessName: z.string().trim().max(255).nullish(),\n /**\n * @deprecated Use `taxId` instead (currently backwards supported with `taxId ?? businessVatId`)\n */\n businessVatId: z.string().trim().max(255).nullish(),\n taxId: z.string().trim().max(255).nullish(),\n firstName: z.string().trim().min(1).max(255),\n lastName: z.string().trim().min(1).max(255),\n phoneNumber: z.string().trim().min(1).max(255),\n stateRegistrationNumber: z.string().trim().max(255).nullish(),\n additionalInfo: z.string().trim().max(255).nullish(),\n })\n .and(getBaseAddressSchema({ countries, errorMap, addressUsageType }))\n .superRefine(phoneNumberSuperRefinement)\n .superRefine(businessNameSuperRefinement)\n .superRefine(\n createTaxIdSuperRefinement({ addressUsageType, validateTaxIdExternally }),\n )\n .superRefine(\n createStateRegistrationNumberSuperRefinement({ addressUsageType }),\n );\n};\n\n// #############################################################################\n// Create Customer Address Schema\n// #############################################################################\nexport const getCreateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n isDefault: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Update Customer Address Schema\n// #############################################################################\nexport const getUpdateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n id: z.string().trim().uuid().nullish(),\n })\n .and(getCreateCustomerAddressSchema(args));\n};\n\n// #############################################################################\n// Update Order Address Schema\n// #############################################################################\nexport const getUpdateOrderAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n customerAddressId: z.string().trim().uuid().nullish(),\n saveForFutureUse: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Address Fields uniform validation\n// #############################################################################\n/**\n * Need to use this schema for uniform validation of address fields in SF\n */\nexport const getAddressFieldsSchema = (args: AddressSchemaArgs) => {\n return getUpdateCustomerAddressSchema(args).and(\n getUpdateOrderAddressSchema(args),\n );\n};\n\n// #############################################################################\n// Email and Accepts marketing validation\n// #############################################################################\n/**\n * Stored as a separate schema because of schema differences in BE and SF.\n * @param {boolean} nullish !!! Use with caution since it is only meant for BE where fields can be optional\n * @see https://github.com/colinhacks/zod/issues/2281#issuecomment-1492082268\n */\n\nexport const getEmailAndMarketingSchema = <Nullish extends boolean = false>(\n {\n errorMap,\n nullish,\n }: {\n errorMap?: ZodErrorMap;\n nullish?: Nullish;\n } = {\n nullish: false as Nullish,\n },\n) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n const email = (\n nullish ? z.string().email().nullish() : z.string().email()\n ) as Nullish extends true\n ? z.ZodOptional<z.ZodNullable<z.ZodString>>\n : z.ZodString;\n\n const acceptsMarketing = (\n nullish ? z.boolean().optional() : z.boolean()\n ) as Nullish extends true ? z.ZodOptional<z.ZodBoolean> : z.ZodBoolean;\n\n return schema.object({\n email,\n acceptsMarketing,\n });\n};\n"],"names":["COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER","Set","CountryCode","Br","COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE","Map","shouldAddressHaveSeparatedStreetAndHouseNumber","country","has","getCountrySpecificAddressFormFields","pathPrefix","fields","get","map","field","DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE","AddressUsageType","Shipping","getBaseAddressSchema","countries","errorMap","addressUsageType","schema","z","setErrorMap","object","address1","ReturnShipping","string","trim","min","max","address2","nullish","city","province","nativeEnum","postalCode","neighborhood","superRefine","getProvinceSuperRefinement","postalCodeSuperRefinement","neighborhoodSuperRefinement","address2SuperRefinement","getAddressSchema","validateTaxIdExternally","type","AddressType","businessName","businessVatId","taxId","firstName","lastName","phoneNumber","stateRegistrationNumber","additionalInfo","and","phoneNumberSuperRefinement","businessNameSuperRefinement","createTaxIdSuperRefinement","createStateRegistrationNumberSuperRefinement","getCreateCustomerAddressSchema","args","isDefault","boolean","getUpdateCustomerAddressSchema","id","uuid","getUpdateOrderAddressSchema","customerAddressId","saveForFutureUse","getAddressFieldsSchema","getEmailAndMarketingSchema","email","acceptsMarketing","optional"],"mappings":";;;;;;;;;;;;;;;AAyBA,MAAMA,gDAAA,GAAA,mBAAuDC,GAAI,CAAA,CA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AA;AAC/B,CAAA;AAQa,MAAAS,sBAAA,GAA0BT,IAA4B,IAAA;EAC1D,OAAAG,8BAAA,CAA+BH,IAAI,CAAE,CAAAN,GAAA,CAC1CY,4BAA4BN,IAAI,CAAA,CAClC;AACF,CAAA;AAWO,MAAMU,6BAA6BA,CACxC;EACEpD,QAAA;EACAa;AACF,CAGI,GAAA;EACFA,OAAS,EAAA;AACX,CACG,KAAA;EACH,MAAMX,MAAS,GAAAC,GAAAA,CAAAA,CAAA;EAEf,IAAIH,QAAU,EAAA;IACZE,MAAA,CAAOE,YAAYJ,QAAQ,CAAA;EAC7B;EAEA,MAAMqD,KACJ,GAAAxC,OAAA,GAAUV,GAAE,CAAAA,CAAA,CAAAK,MAAA,CAAA,CAAS,CAAA6C,KAAA,EAAQ,CAAAxC,OAAA,CAAY,CAAA,GAAAV,GAAA,CAAAA,CAAA,CAAEK,MAAO,CAAA,CAAA,CAAE6C,KAAM,CAAA,CAAA;EAKtD,MAAAC,gBAAA,GACJzC,UAAUV,KAAE,CAAAyC,OAAA,GAAUW,QAAS,CAAA,CAAA,GAAIpD,MAAEyC,OAAQ,EAAA;EAG/C,OAAO1C,OAAOG,MAAO,CAAA;IACnBgD,KAAA;IACAC;EAAA,CACD,CAAA;AACH,CAAA;;;;;;;;;"}
1
+ {"version":3,"file":"address.js","sources":["../../src/utils/address.ts"],"sourcesContent":["import type { ZodErrorMap } from \"zod\";\nimport { z } from \"zod\";\n\nimport { AddressType, AddressUsageType, CountryCode } from \"../types\";\nimport type { Country } from \"./countriesAndZones\";\nimport { address2SuperRefinement } from \"./validations/address2SuperRefinement\";\nimport { businessNameSuperRefinement } from \"./validations/businessNameSuperRefinement\";\nimport { neighborhoodSuperRefinement } from \"./validations/neighborhoodSuperRefinement\";\nimport { phoneNumberSuperRefinement } from \"./validations/phoneNumberSuperRefinement\";\nimport { postalCodeSuperRefinement } from \"./validations/postalCodeSuperRefinement\";\nimport { getProvinceSuperRefinement } from \"./validations/provinceSuperRefinement\";\nimport { createStateRegistrationNumberSuperRefinement } from \"./validations/stateRegistrationNumberSuperRefinement\";\nimport { createTaxIdSuperRefinement } from \"./validations/taxIdSuperRefinement\";\nimport type { ValidateTaxIdExternally } from \"./validations/taxIdSuperRefinement\";\n\nexport type BaseAddressSchemaArgs = {\n countries: Country[];\n errorMap?: ZodErrorMap;\n addressUsageType?: AddressUsageType;\n};\n\nexport type AddressSchemaArgs = BaseAddressSchemaArgs & {\n validateTaxIdExternally?: ValidateTaxIdExternally;\n};\n\nconst COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER = new Set([\n CountryCode.Br,\n]);\n\nconst COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE = new Map<\n CountryCode,\n Array<keyof z.infer<ReturnType<typeof getAddressSchema>>>\n>([\n [\n CountryCode.Br,\n [\"stateRegistrationNumber\", \"neighborhood\", \"additionalInfo\"],\n ],\n]);\n\n/**\n * If it returns `true`, the `address1` field will be used for the street name\n * and `address2` field will be used for the house/apartment number.\n */\nexport const shouldAddressHaveSeparatedStreetAndHouseNumber = (\n country: CountryCode,\n) => COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER.has(country);\n\n/**\n * Returns address form field paths for country-specific fields.\n */\nexport const getCountrySpecificAddressFormFields = <TPathPrefix extends string>(\n country: CountryCode,\n { pathPrefix }: { pathPrefix: TPathPrefix },\n) => {\n const fields = COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE.get(country);\n\n if (!fields) {\n return [];\n }\n\n return fields.map((field) => `${pathPrefix}${field}` as const);\n};\n\nconst DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE = AddressUsageType.Shipping;\n// #############################################################################\n// Base Address Schema\n// #############################################################################\nexport const getBaseAddressSchema = ({\n countries,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: BaseAddressSchemaArgs) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n return schema\n .object({\n address1:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().min(1).max(35)\n : z.string().trim().min(1).max(255),\n address2:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().max(35).nullish()\n : z.string().trim().max(255).nullish(),\n city: z.string().trim().min(1).max(255),\n province: z.string().trim().nullish(),\n country: z.nativeEnum(CountryCode),\n postalCode: z.string().trim().max(255).nullish(),\n neighborhood: z.string().trim().max(255).nullish(),\n })\n .superRefine(getProvinceSuperRefinement(countries))\n .superRefine(postalCodeSuperRefinement)\n .superRefine(neighborhoodSuperRefinement)\n .superRefine(address2SuperRefinement);\n};\n\n// #############################################################################\n// Address Schema\n// #############################################################################\nexport const getAddressSchema = ({\n countries,\n validateTaxIdExternally,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: AddressSchemaArgs) => {\n return z\n .object({\n type: z.nativeEnum(AddressType),\n businessName: z.string().trim().max(255).nullish(),\n /**\n * @deprecated Use `taxId` instead (currently backwards supported with `taxId ?? businessVatId`)\n */\n businessVatId: z.string().trim().max(255).nullish(),\n taxId: z.string().trim().max(255).nullish(),\n firstName: z.string().trim().min(1).max(255),\n lastName: z.string().trim().min(1).max(255),\n phoneNumber: z.string().trim().min(1).max(255),\n stateRegistrationNumber: z.string().trim().max(255).nullish(),\n additionalInfo: z.string().trim().max(255).nullish(),\n })\n .and(getBaseAddressSchema({ countries, errorMap, addressUsageType }))\n .superRefine(phoneNumberSuperRefinement)\n .superRefine(businessNameSuperRefinement)\n .superRefine(\n createTaxIdSuperRefinement({ addressUsageType, validateTaxIdExternally }),\n )\n .superRefine(\n createStateRegistrationNumberSuperRefinement({ addressUsageType }),\n );\n};\n\n// #############################################################################\n// Create Customer Address Schema\n// #############################################################################\nexport const getCreateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n isDefault: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Update Customer Address Schema\n// #############################################################################\nexport const getUpdateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n id: z.string().trim().uuid().nullish(),\n })\n .and(getCreateCustomerAddressSchema(args));\n};\n\n// #############################################################################\n// Update Order Address Schema\n// #############################################################################\nexport const getUpdateOrderAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n customerAddressId: z.string().trim().uuid().nullish(),\n saveForFutureUse: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Address Fields uniform validation\n// #############################################################################\n/**\n * Need to use this schema for uniform validation of address fields in SF\n */\nexport const getAddressFieldsSchema = (args: AddressSchemaArgs) => {\n return getUpdateCustomerAddressSchema(args).and(\n getUpdateOrderAddressSchema(args),\n );\n};\n\n// #############################################################################\n// Email and Accepts marketing validation\n// #############################################################################\n/**\n * Stored as a separate schema because of schema differences in BE and SF.\n * @param {boolean} nullish !!! Use with caution since it is only meant for BE where fields can be optional\n * @see https://github.com/colinhacks/zod/issues/2281#issuecomment-1492082268\n */\n\nexport const getEmailAndMarketingSchema = <Nullish extends boolean = false>(\n {\n errorMap,\n nullish,\n }: {\n errorMap?: ZodErrorMap;\n nullish?: Nullish;\n } = {\n nullish: false as Nullish,\n },\n) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n const email = (\n nullish ? z.string().email().nullish() : z.string().email()\n ) as Nullish extends true\n ? z.ZodOptional<z.ZodNullable<z.ZodString>>\n : z.ZodString;\n\n const acceptsMarketing = (\n nullish ? z.boolean().optional() : z.boolean()\n ) as Nullish extends true ? z.ZodOptional<z.ZodBoolean> : z.ZodBoolean;\n\n return schema.object({\n email,\n acceptsMarketing,\n });\n};\n"],"names":["COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER","Set","CountryCode","Br","COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE","Map","shouldAddressHaveSeparatedStreetAndHouseNumber","country","has","getCountrySpecificAddressFormFields","pathPrefix","fields","get","map","field","DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE","AddressUsageType","Shipping","getBaseAddressSchema","countries","errorMap","addressUsageType","schema","z","setErrorMap","object","address1","ReturnShipping","string","trim","min","max","address2","nullish","city","province","nativeEnum","postalCode","neighborhood","superRefine","getProvinceSuperRefinement","postalCodeSuperRefinement","neighborhoodSuperRefinement","address2SuperRefinement","getAddressSchema","validateTaxIdExternally","type","AddressType","businessName","businessVatId","taxId","firstName","lastName","phoneNumber","stateRegistrationNumber","additionalInfo","and","phoneNumberSuperRefinement","businessNameSuperRefinement","createTaxIdSuperRefinement","createStateRegistrationNumberSuperRefinement","getCreateCustomerAddressSchema","args","isDefault","boolean","getUpdateCustomerAddressSchema","id","uuid","getUpdateOrderAddressSchema","customerAddressId","saveForFutureUse","getAddressFieldsSchema","getEmailAndMarketingSchema","email","acceptsMarketing","optional"],"mappings":";;;;;;;;;;;;;;;AAyBA,MAAMA,gDAAA,GAAA,mBAAuDC,GAAI,CAAA,CAC/DC,SAAAA,CAAAA,WAAY,CAAAC,EAAA,CACb,CAAA;AAED,MAAMC,+CAAA,GAAA,mBAAsDC,GAG1D,CAAA,CACA,CACEH,SAAAA,CAAAA,WAAY,CAAAC,EAAA,EACZ,CAAC,yBAA2B,EAAA,cAAA,EAAgB,gBAAgB,CAAA,CAC9D,CACD,CAAA;AAMM,MAAMG,8CAAiD,GAC5DC,OACG,IAAAP,gDAAA,CAAiDQ,IAAID,OAAO,CAAA;AAK1D,MAAME,mCAAsC,GAAAA,CACjDF,OACA,EAAA;EAAEG;CACC,KAAA;EACG,MAAAC,MAAA,GAASP,+CAAgD,CAAAQ,GAAA,CAAIL,OAAO,CAAA;EAE1E,IAAI,CAACI,MAAQ,EAAA;IACX,OAAO,EAAC;EACV;EAEO,OAAAA,MAAA,CAAOE,IAAKC,KAAA,IAAU,GAAGJ,UAAU,GAAGI,KAAK,EAAW,CAAA;AAC/D,CA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AE6C,KAAM,CAAA,CAAA;EAKtD,MAAAC,gBAAA,GACJzC,UAAUV,KAAE,CAAAyC,OAAA,GAAUW,QAAS,CAAA,CAAA,GAAIpD,MAAEyC,OAAQ,EAAA;EAG/C,OAAO1C,OAAOG,MAAO,CAAA;IACnBgD,KAAA;IACAC;EAAA,CACD,CAAA;AACH,CAAA;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"address.mjs","sources":["../../src/utils/address.ts"],"sourcesContent":["import type { ZodErrorMap } from \"zod\";\nimport { z } from \"zod\";\n\nimport { AddressType, AddressUsageType, CountryCode } from \"../types\";\nimport type { Country } from \"./countriesAndZones\";\nimport { address2SuperRefinement } from \"./validations/address2SuperRefinement\";\nimport { businessNameSuperRefinement } from \"./validations/businessNameSuperRefinement\";\nimport { neighborhoodSuperRefinement } from \"./validations/neighborhoodSuperRefinement\";\nimport { phoneNumberSuperRefinement } from \"./validations/phoneNumberSuperRefinement\";\nimport { postalCodeSuperRefinement } from \"./validations/postalCodeSuperRefinement\";\nimport { getProvinceSuperRefinement } from \"./validations/provinceSuperRefinement\";\nimport { createStateRegistrationNumberSuperRefinement } from \"./validations/stateRegistrationNumberSuperRefinement\";\nimport { createTaxIdSuperRefinement } from \"./validations/taxIdSuperRefinement\";\nimport type { ValidateTaxIdExternally } from \"./validations/taxIdSuperRefinement\";\n\nexport type BaseAddressSchemaArgs = {\n countries: Country[];\n errorMap?: ZodErrorMap;\n addressUsageType?: AddressUsageType;\n};\n\nexport type AddressSchemaArgs = BaseAddressSchemaArgs & {\n validateTaxIdExternally?: ValidateTaxIdExternally;\n};\n\nconst COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER = new Set([\n CountryCode.Br,\n]);\n\nconst COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE = new Map<\n CountryCode,\n Array<keyof z.infer<ReturnType<typeof getAddressSchema>>>\n>([\n [\n CountryCode.Br,\n [\"stateRegistrationNumber\", \"neighborhood\", \"additionalInfo\"],\n ],\n]);\n\n/**\n * If it returns `true`, the `address1` field will be used for the street name\n * and `address2` field will be used for the house/apartment number.\n */\nexport const shouldAddressHaveSeparatedStreetAndHouseNumber = (\n country: CountryCode,\n) => COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER.has(country);\n\n/**\n * Returns address form field paths for country-specific fields.\n */\nexport const getCountrySpecificAddressFormFields = <TPathPrefix extends string>(\n country: CountryCode,\n { pathPrefix }: { pathPrefix: TPathPrefix },\n) => {\n const fields = COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE.get(country);\n\n if (!fields) {\n return [];\n }\n\n return fields.map((field) => `${pathPrefix}${field}` as const);\n};\n\nconst DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE = AddressUsageType.Shipping;\n// #############################################################################\n// Base Address Schema\n// #############################################################################\nexport const getBaseAddressSchema = ({\n countries,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: BaseAddressSchemaArgs) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n return schema\n .object({\n address1:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().min(1).max(35)\n : z.string().trim().min(1).max(255),\n address2:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().max(35).nullish()\n : z.string().trim().max(255).nullish(),\n city: z.string().trim().min(1).max(255),\n province: z.string().trim().nullish(),\n country: z.nativeEnum(CountryCode),\n postalCode: z.string().trim().max(255).nullish(),\n neighborhood: z.string().trim().max(255).nullish(),\n })\n .superRefine(getProvinceSuperRefinement(countries))\n .superRefine(postalCodeSuperRefinement)\n .superRefine(neighborhoodSuperRefinement)\n .superRefine(address2SuperRefinement);\n};\n\n// #############################################################################\n// Address Schema\n// #############################################################################\nexport const getAddressSchema = ({\n countries,\n validateTaxIdExternally,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: AddressSchemaArgs) => {\n return z\n .object({\n type: z.nativeEnum(AddressType),\n businessName: z.string().trim().max(255).nullish(),\n /**\n * @deprecated Use `taxId` instead (currently backwards supported with `taxId ?? businessVatId`)\n */\n businessVatId: z.string().trim().max(255).nullish(),\n taxId: z.string().trim().max(255).nullish(),\n firstName: z.string().trim().min(1).max(255),\n lastName: z.string().trim().min(1).max(255),\n phoneNumber: z.string().trim().min(1).max(255),\n stateRegistrationNumber: z.string().trim().max(255).nullish(),\n additionalInfo: z.string().trim().max(255).nullish(),\n })\n .and(getBaseAddressSchema({ countries, errorMap, addressUsageType }))\n .superRefine(phoneNumberSuperRefinement)\n .superRefine(businessNameSuperRefinement)\n .superRefine(\n createTaxIdSuperRefinement({ addressUsageType, validateTaxIdExternally }),\n )\n .superRefine(\n createStateRegistrationNumberSuperRefinement({ addressUsageType }),\n );\n};\n\n// #############################################################################\n// Create Customer Address Schema\n// #############################################################################\nexport const getCreateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n isDefault: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Update Customer Address Schema\n// #############################################################################\nexport const getUpdateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n id: z.string().trim().uuid().nullish(),\n })\n .and(getCreateCustomerAddressSchema(args));\n};\n\n// #############################################################################\n// Update Order Address Schema\n// #############################################################################\nexport const getUpdateOrderAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n customerAddressId: z.string().trim().uuid().nullish(),\n saveForFutureUse: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Address Fields uniform validation\n// #############################################################################\n/**\n * Need to use this schema for uniform validation of address fields in SF\n */\nexport const getAddressFieldsSchema = (args: AddressSchemaArgs) => {\n return getUpdateCustomerAddressSchema(args).and(\n getUpdateOrderAddressSchema(args),\n );\n};\n\n// #############################################################################\n// Email and Accepts marketing validation\n// #############################################################################\n/**\n * Stored as a separate schema because of schema differences in BE and SF.\n * @param {boolean} nullish !!! Use with caution since it is only meant for BE where fields can be optional\n * @see https://github.com/colinhacks/zod/issues/2281#issuecomment-1492082268\n */\n\nexport const getEmailAndMarketingSchema = <Nullish extends boolean = false>(\n {\n errorMap,\n nullish,\n }: {\n errorMap?: ZodErrorMap;\n nullish?: Nullish;\n } = {\n nullish: false as Nullish,\n },\n) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n const email = (\n nullish ? z.string().email().nullish() : z.string().email()\n ) as Nullish extends true\n ? z.ZodOptional<z.ZodNullable<z.ZodString>>\n : z.ZodString;\n\n const acceptsMarketing = (\n nullish ? z.boolean().optional() : z.boolean()\n ) as Nullish extends true ? z.ZodOptional<z.ZodBoolean> : z.ZodBoolean;\n\n return schema.object({\n email,\n acceptsMarketing,\n });\n};\n"],"names":["COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER","Set","CountryCode","Br","COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE","Map","shouldAddressHaveSeparatedStreetAndHouseNumber","country","has","getCountrySpecificAddressFormFields","pathPrefix","fields","get","map","field","DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE","AddressUsageType","Shipping","getBaseAddressSchema","countries","errorMap","addressUsageType","schema","z","setErrorMap","object","address1","ReturnShipping","string","trim","min","max","address2","nullish","city","province","nativeEnum","postalCode","neighborhood","superRefine","getProvinceSuperRefinement","postalCodeSuperRefinement","neighborhoodSuperRefinement","address2SuperRefinement","getAddressSchema","validateTaxIdExternally","type","AddressType","businessName","businessVatId","taxId","firstName","lastName","phoneNumber","stateRegistrationNumber","additionalInfo","and","phoneNumberSuperRefinement","businessNameSuperRefinement","createTaxIdSuperRefinement","createStateRegistrationNumberSuperRefinement","getCreateCustomerAddressSchema","args","isDefault","boolean","getUpdateCustomerAddressSchema","id","uuid","getUpdateOrderAddressSchema","customerAddressId","saveForFutureUse","getAddressFieldsSchema","getEm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AAMqD,KACJ,GAAAxC,OAAA,GAAUV,CAAE,CAAAK,MAAA,CAAA,CAAS,CAAA6C,KAAA,EAAQ,CAAAxC,OAAA,CAAY,CAAA,GAAAV,CAAA,CAAEK,MAAO,CAAA,CAAA,CAAE6C,KAAM,CAAA,CAAA;EAKtD,MAAAC,gBAAA,GACJzC,UAAUV,CAAE,CAAAyC,OAAA,GAAUW,QAAS,CAAA,CAAA,GAAIpD,EAAEyC,OAAQ,EAAA;EAG/C,OAAO1C,OAAOG,MAAO,CAAA;IACnBgD,KAAA;IACAC;EAAA,CACD,CAAA;AACH,CAAA;"}
1
+ {"version":3,"file":"address.mjs","sources":["../../src/utils/address.ts"],"sourcesContent":["import type { ZodErrorMap } from \"zod\";\nimport { z } from \"zod\";\n\nimport { AddressType, AddressUsageType, CountryCode } from \"../types\";\nimport type { Country } from \"./countriesAndZones\";\nimport { address2SuperRefinement } from \"./validations/address2SuperRefinement\";\nimport { businessNameSuperRefinement } from \"./validations/businessNameSuperRefinement\";\nimport { neighborhoodSuperRefinement } from \"./validations/neighborhoodSuperRefinement\";\nimport { phoneNumberSuperRefinement } from \"./validations/phoneNumberSuperRefinement\";\nimport { postalCodeSuperRefinement } from \"./validations/postalCodeSuperRefinement\";\nimport { getProvinceSuperRefinement } from \"./validations/provinceSuperRefinement\";\nimport { createStateRegistrationNumberSuperRefinement } from \"./validations/stateRegistrationNumberSuperRefinement\";\nimport { createTaxIdSuperRefinement } from \"./validations/taxIdSuperRefinement\";\nimport type { ValidateTaxIdExternally } from \"./validations/taxIdSuperRefinement\";\n\nexport type BaseAddressSchemaArgs = {\n countries: Country[];\n errorMap?: ZodErrorMap;\n addressUsageType?: AddressUsageType;\n};\n\nexport type AddressSchemaArgs = BaseAddressSchemaArgs & {\n validateTaxIdExternally?: ValidateTaxIdExternally;\n};\n\nconst COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER = new Set([\n CountryCode.Br,\n]);\n\nconst COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE = new Map<\n CountryCode,\n Array<keyof z.infer<ReturnType<typeof getAddressSchema>>>\n>([\n [\n CountryCode.Br,\n [\"stateRegistrationNumber\", \"neighborhood\", \"additionalInfo\"],\n ],\n]);\n\n/**\n * If it returns `true`, the `address1` field will be used for the street name\n * and `address2` field will be used for the house/apartment number.\n */\nexport const shouldAddressHaveSeparatedStreetAndHouseNumber = (\n country: CountryCode,\n) => COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER.has(country);\n\n/**\n * Returns address form field paths for country-specific fields.\n */\nexport const getCountrySpecificAddressFormFields = <TPathPrefix extends string>(\n country: CountryCode,\n { pathPrefix }: { pathPrefix: TPathPrefix },\n) => {\n const fields = COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE.get(country);\n\n if (!fields) {\n return [];\n }\n\n return fields.map((field) => `${pathPrefix}${field}` as const);\n};\n\nconst DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE = AddressUsageType.Shipping;\n// #############################################################################\n// Base Address Schema\n// #############################################################################\nexport const getBaseAddressSchema = ({\n countries,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: BaseAddressSchemaArgs) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n return schema\n .object({\n address1:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().min(1).max(35)\n : z.string().trim().min(1).max(255),\n address2:\n addressUsageType === AddressUsageType.ReturnShipping\n ? z.string().trim().max(35).nullish()\n : z.string().trim().max(255).nullish(),\n city: z.string().trim().min(1).max(255),\n province: z.string().trim().nullish(),\n country: z.nativeEnum(CountryCode),\n postalCode: z.string().trim().max(255).nullish(),\n neighborhood: z.string().trim().max(255).nullish(),\n })\n .superRefine(getProvinceSuperRefinement(countries))\n .superRefine(postalCodeSuperRefinement)\n .superRefine(neighborhoodSuperRefinement)\n .superRefine(address2SuperRefinement);\n};\n\n// #############################################################################\n// Address Schema\n// #############################################################################\nexport const getAddressSchema = ({\n countries,\n validateTaxIdExternally,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: AddressSchemaArgs) => {\n return z\n .object({\n type: z.nativeEnum(AddressType),\n businessName: z.string().trim().max(255).nullish(),\n /**\n * @deprecated Use `taxId` instead (currently backwards supported with `taxId ?? businessVatId`)\n */\n businessVatId: z.string().trim().max(255).nullish(),\n taxId: z.string().trim().max(255).nullish(),\n firstName: z.string().trim().min(1).max(255),\n lastName: z.string().trim().min(1).max(255),\n phoneNumber: z.string().trim().min(1).max(255),\n stateRegistrationNumber: z.string().trim().max(255).nullish(),\n additionalInfo: z.string().trim().max(255).nullish(),\n })\n .and(getBaseAddressSchema({ countries, errorMap, addressUsageType }))\n .superRefine(phoneNumberSuperRefinement)\n .superRefine(businessNameSuperRefinement)\n .superRefine(\n createTaxIdSuperRefinement({ addressUsageType, validateTaxIdExternally }),\n )\n .superRefine(\n createStateRegistrationNumberSuperRefinement({ addressUsageType }),\n );\n};\n\n// #############################################################################\n// Create Customer Address Schema\n// #############################################################################\nexport const getCreateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n isDefault: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Update Customer Address Schema\n// #############################################################################\nexport const getUpdateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n id: z.string().trim().uuid().nullish(),\n })\n .and(getCreateCustomerAddressSchema(args));\n};\n\n// #############################################################################\n// Update Order Address Schema\n// #############################################################################\nexport const getUpdateOrderAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n customerAddressId: z.string().trim().uuid().nullish(),\n saveForFutureUse: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Address Fields uniform validation\n// #############################################################################\n/**\n * Need to use this schema for uniform validation of address fields in SF\n */\nexport const getAddressFieldsSchema = (args: AddressSchemaArgs) => {\n return getUpdateCustomerAddressSchema(args).and(\n getUpdateOrderAddressSchema(args),\n );\n};\n\n// #############################################################################\n// Email and Accepts marketing validation\n// #############################################################################\n/**\n * Stored as a separate schema because of schema differences in BE and SF.\n * @param {boolean} nullish !!! Use with caution since it is only meant for BE where fields can be optional\n * @see https://github.com/colinhacks/zod/issues/2281#issuecomment-1492082268\n */\n\nexport const getEmailAndMarketingSchema = <Nullish extends boolean = false>(\n {\n errorMap,\n nullish,\n }: {\n errorMap?: ZodErrorMap;\n nullish?: Nullish;\n } = {\n nullish: false as Nullish,\n },\n) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n const email = (\n nullish ? z.string().email().nullish() : z.string().email()\n ) as Nullish extends true\n ? z.ZodOptional<z.ZodNullable<z.ZodString>>\n : z.ZodString;\n\n const acceptsMarketing = (\n nullish ? z.boolean().optional() : z.boolean()\n ) as Nullish extends true ? z.ZodOptional<z.ZodBoolean> : z.ZodBoolean;\n\n return schema.object({\n email,\n acceptsMarketing,\n });\n};\n"],"names":["COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER","Set","CountryCode","Br","COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE","Map","shouldAddressHaveSeparatedStreetAndHouseNumber","country","has","getCountrySpecificAddressFormFields","pathPrefix","fields","get","map","field","DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE","AddressUsageType","Shipping","getBaseAddressSchema","countries","errorMap","addressUsageType","schema","z","setErrorMap","object","address1","ReturnShipping","string","trim","min","max","address2","nullish","city","province","nativeEnum","postalCode","neighborhood","superRefine","getProvinceSuperRefinement","postalCodeSuperRefinement","neighborhoodSuperRefinement","address2SuperRefinement","getAddressSchema","validateTaxIdExternally","type","AddressType","businessName","businessVatId","taxId","firstName","lastName","phoneNumber","stateRegistrationNumber","additionalInfo","and","phoneNumberSuperRefinement","businessNameSuperRefinement","createTaxIdSuperRefinement","createStateRegistrationNumberSuperRefinement","getCreateCustomerAddressSchema","args","isDefault","boolean","getUpdateCustomerAddressSchema","id","uuid","getUpdateOrderAddressSchema","customerAddressId","saveForFutureUse","getAddressFieldsSchema","getEmailAndMarketingSchema","email","acceptsMarketing","optional"],"mappings":";;;;;;;;;;;;;AAyBA,MAAMA,gDAAA,GAAA,mBAAuDC,GAAI,CAAA,CAC/DC,WAAY,CAAAC,EAAA,CACb,CAAA;AAED,MAAMC,+CAAA,GAAA,mBAAsDC,GAG1D,CAAA,CACA,CACEH,WAAY,CAAAC,EAAA,EACZ,CAAC,yBAA2B,EAAA,cAAA,EAAgB,gBAAgB,CAAA,CAC9D,CACD,CAAA;AAMM,MAAMG,8CAAiD,GAC5DC,OACG,IAAAP,gDAAA,CAAiDQ,IAAID,OAAO,CAAA;AAK1D,MAAME,mCAAsC,GAAAA,CACjDF,OACA,EAAA;EAAEG;CACC,KAAA;EACG,MAAAC,MAAA,GAASP,+CAAgD,CAAAQ,GAAA,CAAIL,OAAO,CAAA;EAE1E,IAAI,CAACI,MAAQ,EAAA;IACX,OAAO,EAAC;EACV;EAEO,OAAAA,MAAA,CAAOE,IAAKC,KAAA,IAAU,GAAGJ,UAAU,GAAGI,KAAK,EAAW,CAAA;AAC/D,CAAA;AAEA,MAAMC,wCAAwCC,gBAAiB,CAAAC,QAAA;AAIxD,MAAMC,uBAAuBA,CAAC;EACnCC,SAAA;EACAC,QAAA;EACAC,gBAAmB,GAAAN;AACrB,CAA6B,KAAA;EAC3B,MAAMO,MAAS,GAAAC,CAAA;EAEf,IAAIH,QAAU,EAAA;IACZE,MAAA,CAAOE,YAAYJ,QAAQ,CAAA;EAC7B;EAEA,OAAOE,OACJG,MAAO,CAAA;IACNC,QAAA,EACEL,gBAAqB,KAAAL,gBAAA,CAAiBW,cAClC,GAAAJ,CAAA,CAAEK,QAAS,CAAAC,IAAA,CAAA,CAAO,CAAAC,GAAA,CAAI,CAAC,CAAA,CAAEC,IAAI,EAAE,CAAA,GAC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AS,EAAA;AACX,CACG,KAAA;EACH,MAAMX,MAAS,GAAAC,CAAA;EAEf,IAAIH,QAAU,EAAA;IACZE,MAAA,CAAOE,YAAYJ,QAAQ,CAAA;EAC7B;EAEA,MAAMqD,KACJ,GAAAxC,OAAA,GAAUV,CAAE,CAAAK,MAAA,CAAA,CAAS,CAAA6C,KAAA,EAAQ,CAAAxC,OAAA,CAAY,CAAA,GAAAV,CAAA,CAAEK,MAAO,CAAA,CAAA,CAAE6C,KAAM,CAAA,CAAA;EAKtD,MAAAC,gBAAA,GACJzC,UAAUV,CAAE,CAAAyC,OAAA,GAAUW,QAAS,CAAA,CAAA,GAAIpD,EAAEyC,OAAQ,EAAA;EAG/C,OAAO1C,OAAOG,MAAO,CAAA;IACnBgD,KAAA;IACAC;EAAA,CACD,CAAA;AACH,CAAA;"}
@@ -1 +1 @@
1
- {"version":3,"file":"fixedAmount.js","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IACAC;EAAA,CAKC,EAAA;IAfH;AAAA;AAAA;IAAOC,aAAA,CAAA,IAAA,EAAA,2BAAA,CAAA;IAIP;AAAA;AAAA;IAAOA,aAAA,CAAA,IAAA,EAAA,sBAAA,CAAA;IACAA,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA;IAWA,IAAA,CAAAC,yBAAA,GAA4BC,IAAAA,CAAAA,SAAU,CAAAL,qBAAA,EAAuBE,QAAQ,CAAA;IACrE,IAAA,CAAAI,oBAAA,GAAuBD,IAAAA,CAAAA,SAAU,CAAAJ,kBAAA,EAAoBC,QAAQ,CAAA;IAC7D,IAAA,CAAAA,QAAA,GAAWK,uBAAkBL,QAAQ,CAAA;EAC5C;EAAA;AAAA;AAAA;EAKAM,QAAAA,CAASC,eAAsBP,QAA0B,EAAA;IACvDQ,MAAA,CAAAA,MAAA,CACE,IAAA,CAAKR,SAASS,IAAS,KAAAT,QAAA,EACQ,+BAAAA,QAAiB,SAAA,IAAA,CAAKA,SAASS,IAAI,EAAA,CACpE;IACM,MAAAC,mBAAA,GAAsBP,IAAAA,CAAAA,SAAU,CAAAI,aAAA,EAAeP,QAAQ,CAAA;IAK7D,IAAIO,kBAAkB,CAAG,EAAA;MAChB,OAAAG,mBAAA;IACT;IAEM,MAAA,CAACC,gBAAkB,EAAAT,yBAAyB,CAAI,GAAAI,SAAA,CAAAA,QAAA,CACpD,IAAK,CAAAJ,yBAAA,EACL,CACEK,aAAA,EACAK,KAAKC,GAAI,CAAAC,WAAA,CAAO,KAAKV,oBAAoB,CAAA,GAAIG,eAAe,CAAC,CAAA,CAC/D,CACF;IAEOC,MAAAA,CAAAA,MAAA,CAAA,CAAC,CAACG,gBAAA,EAAkB,2BAA2B,CAAA;IACtDH,MAAA,CAAAA,MAAA,CACE,CAAC,CAACN,yBAAA,EACF,wCAAA,CACF;IAEA,IAAA,CAAKA,yBAA4B,GAAAA,yBAAA;IACjC,IAAA,CAAKE,oBAAuB,GAAAW,SAAA,CAAAA,QAAA,CAC1B,IAAK,CAAAX,oBAAA,EACLM,mBAAA,CACF;IAMA,OAAOM,SAAY,CAAAA,WAAA,CAAAL,gBAAA,EAAkBD,mBAAmB,CAAA,GACpDA,mBACA,GAAAC,gBAAA;EACN;AACF;"}
1
+ {"version":3,"file":"fixedAmount.js","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IACAC;EAAA,CAKC,EAAA;IAfH;AAAA;AAAA;IAAOC,aAAA,CAAA,IAAA,EAAA,2BAAA,CAAA;IAIP;AAAA;AAAA;IAAOA,aAAA,CAAA,IAAA,EAAA,sBAAA,CAAA;IACAA,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA;IAWA,IAAA,CAAAC,yBAAA,GAA4BC,IAAAA,CAAAA,SAAU,CAAAL,qBAAA,EAAuBE,QAAQ,CAAA;IACrE,IAAA,CAAAI,oBAAA,GAAuBD,IAAAA,CAAAA,SAAU,CAAAJ,kBAAA,EAAoBC,QAAQ,CAAA;IAC7D,IAAA,CAAAA,QAAA,GAAWK,uBAAkBL,QAAQ,CAAA;EAC5C;EAAA;AAAA;AAAA;EAKAM,QAAAA,CAASC,eAAsBP,QAA0B,EAAA;IACvDQ,MAAA,CAAAA,MAAA,CACE,IAAA,CAAKR,SAASS,IAAS,KAAAT,QAAA,EACvB,+BAA+BA,QAAQ,SAAS,IAAA,CAAKA,SAASS,IAAI,EAAA,CACpE;IACM,MAAAC,mBAAA,GAAsBP,IAAAA,CAAAA,SAAU,CAAAI,aAAA,EAAeP,QAAQ,CAAA;IAK7D,IAAIO,kBAAkB,CAAG,EAAA;MAChB,OAAAG,mBAAA;IACT;IAEM,MAAA,CAACC,gBAAkB,EAAAT,yBAAyB,CAAI,GAAAI,SAAA,CAAAA,QAAA,CACpD,IAAK,CAAAJ,yBAAA,EACL,CACEK,aAAA,EACAK,KAAKC,GAAI,CAAAC,WAAA,CAAO,KAAKV,oBAAoB,CAAA,GAAIG,eAAe,CAAC,CAAA,CAC/D,CACF;IAEOC,MAAAA,CAAAA,MAAA,CAAA,CAAC,CAACG,gBAAA,EAAkB,2BAA2B,CAAA;IACtDH,MAAA,CAAAA,MAAA,CACE,CAAC,CAACN,yBAAA,EACF,wCAAA,CACF;IAEA,IAAA,CAAKA,yBAA4B,GAAAA,yBAAA;IACjC,IAAA,CAAKE,oBAAuB,GAAAW,SAAA,CAAAA,QAAA,CAC1B,IAAK,CAAAX,oBAAA,EACLM,mBAAA,CACF;IAMA,OAAOM,SAAY,CAAAA,WAAA,CAAAL,gBAAA,EAAkBD,mBAAmB,CAAA,GACpDA,mBACA,GAAAC,gBAAA;EACN;AACF;"}
@@ -1 +1 @@
1
- {"version":3,"file":"fixedAmount.mjs","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IACAC;EAAA,CAKC,EAAA;IAfH;AAAA;AAAA;IAAOC,aAAA,CAAA,IAAA,EAAA,2BAAA,CAAA;IAIP;AAAA;AAAA;IAAOA,aAAA,CAAA,IAAA,EAAA,sBAAA,CAAA;IACAA,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA;IAWA,IAAA,CAAAC,yBAAA,GAA4BC,SAAU,CAAAL,qBAAA,EAAuBE,QAAQ,CAAA;IACrE,IAAA,CAAAI,oBAAA,GAAuBD,SAAU,CAAAJ,kBAAA,EAAoBC,QAAQ,CAAA;IAC7D,IAAA,CAAAA,QAAA,GAAWK,kBAAkBL,QAAQ,CAAA;EAC5C;EAAA;AAAA;AAAA;EAKAM,QAAAA,CAASC,eAAsBP,QAA0B,EAAA;IACvDQ,MAAA,CACE,IAAA,CAAKR,SAASS,IAAS,KAAAT,QAAA,EACQ,+BAAAA,QAAiB,SAAA,IAAA,CAAKA,SAASS,IAAI,EAAA,CACpE;IACM,MAAAC,mBAAA,GAAsBP,SAAU,CAAAI,aAAA,EAAeP,QAAQ,CAAA;IAK7D,IAAIO,kBAAkB,CAAG,EAAA;MAChB,OAAAG,mBAAA;IACT;IAEM,MAAA,CAACC,gBAAkB,EAAAT,yBAAyB,CAAI,GAAAI,QAAA,CACpD,IAAK,CAAAJ,yBAAA,EACL,CACEK,aAAA,EACAK,KAAKC,GAAI,CAAAC,MAAA,CAAO,KAAKV,oBAAoB,CAAA,GAAIG,eAAe,CAAC,CAAA,CAC/D,CACF;IAEOC,MAAA,CAAA,CAAC,CAACG,gBAAA,EAAkB,2BAA2B,CAAA;IACtDH,MAAA,CACE,CAAC,CAACN,yBAAA,EACF,wCAAA,CACF;IAEA,IAAA,CAAKA,yBAA4B,GAAAA,yBAAA;IACjC,IAAA,CAAKE,oBAAuB,GAAAW,QAAA,CAC1B,IAAK,CAAAX,oBAAA,EACLM,mBAAA,CACF;IAMA,OAAOM,WAAY,CAAAL,gBAAA,EAAkBD,mBAAmB,CAAA,GACpDA,mBACA,GAAAC,gBAAA;EACN;AACF;"}
1
+ {"version":3,"file":"fixedAmount.mjs","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IAC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ACA,GAAAC,gBAAA;EACN;AACF;"}
@@ -47,7 +47,8 @@ function formatPriceRaw(dinero, locale, options) {
47
47
  */
48
48
  formatted.replace(
49
49
  // For some reason `\.` need to be double-escaped `\\` when creating the regex from template string
50
- new RegExp(`(\\.|,)${// Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
50
+ new RegExp(`(\\.|,)${
51
+ // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
51
52
  options?.removeFractions ? "\\d" : 0}{0,${currency.exponent}}(\\s\\D)?$`),
52
53
  // In the replaced using "last capture group" (if-exists) so we restore the trailing currency sign
53
54
  "$2")) : formatted;
@@ -1 +1 @@
1
- {"version":3,"file":"format.js","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,SAAAA,CAAAA,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;EACT;EAEYA,SAAA,GAAA,IAAIC,IAAK,CAAAC,YAAA,CAAaJ,MAAQ,EAAA;IACxCK,KAAO,EAAA,UAAA;IACPC,QAAU,EAAAZ,YAAA;IAAA;AAAA;AAAA;AAAA;AAAA;IAMVa,YAAc,EAAA,UAAA;IACdC,eAAiB,EAAA;EAAA,CAClB,CAAA;EACsBX,sBAAA,CAAAY,GAAA,CAAIR,UAAUC,SAAS,CAAA;EAEvC,OAAAA,SAAA;AACT,CAAA;AAoCgB,SAAAQ,cAAAA,CACdC,MACA,EAAAX,MAAA,EACAY,OACQ,EAAA;EACR,OAAOC,mB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,eAAe,EAAI,EAAA;UACd,OAAAE,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMC,oBAAoB,CAAA;QAAA,CACtD,MAAA,IAAWJ,eAAe,EAAI,EAAA;UACrB,OAAAE,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAME,qBAAqB,CAAA;QAAA,CACvD,MAAA,IAAWL,eAAe,EAAI,EAAA;UACrB,OAAAE,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;QAAA,CACnC,MAAA;UACE,OAAAJ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMI,eAAe,CAAA;QACjD;MACF;IACA;MAAS;QAEH,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAd,KAAK,CAAG,EAAA;UAChB,OAAAA,KAAA;QACT;QAEA,MAAMe,mCAAmCC,SAAAA,CAAAA,mBAAoB,CAAAjD,GAAA,CAC3DkC,UAAUxB,QAAS,CAAAS,IAAA,CACrB;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,SAAO,CAAAA,MAAA,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;;;;"}
1
+ {"version":3,"file":"format.js","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,SAAAA,CAAAA,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,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AA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;;;;"}
@@ -45,7 +45,8 @@ function formatPriceRaw(dinero, locale, options) {
45
45
  */
46
46
  formatted.replace(
47
47
  // For some reason `\.` need to be double-escaped `\\` when creating the regex from template string
48
- new RegExp(`(\\.|,)${// Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
48
+ new RegExp(`(\\.|,)${
49
+ // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
49
50
  options?.removeFractions ? "\\d" : 0}{0,${currency.exponent}}(\\s\\D)?$`),
50
51
  // In the replaced using "last capture group" (if-exists) so we restore the trailing currency sign
51
52
  "$2")) : formatted;
@@ -1 +1 @@
1
- {"version":3,"file":"format.mjs","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;EACT;EAEYA,SAAA,GAAA,IAAIC,IAAK,CAAAC,YAAA,CAAaJ,MAAQ,EAAA;IACxCK,KAAO,EAAA,UAAA;IACPC,QAAU,EAAAZ,YAAA;IAAA;AAAA;AAAA;AAAA;AAAA;IAMVa,YAAc,EAAA,UAAA;IACdC,eAAiB,EAAA;EAAA,CAClB,CAAA;EACsBX,sBAAA,CAAAY,GAAA,CAAIR,UAAUC,SAAS,CAAA;EAEvC,OAAAA,SAAA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OAAOP,KAAK,CAAA;QAEjC,IAAIM,eAAe,EAAI,EAAA;UACd,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMC,oBAAoB,CAAA;QAAA,CACtD,MAAA,IAAWJ,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAME,qBAAqB,CAAA;QAAA,CACvD,MAAA,IAAWL,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;QAAA,CACnC,MAAA;UACE,OAAAJ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMI,eAAe,CAAA;QACjD;MACF;IACA;MAAS;QAEH,IAAA,CAACC,WAAY,CAAAd,KAAK,CAAG,EAAA;UAChB,OAAAA,KAAA;QACT;QAEA,MAAMe,mCAAmCC,mBAAoB,CAAAjD,GAAA,CAC3DkC,UAAUxB,QAAS,CAAAS,IAAA,CACrB;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,MAAO,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;"}
1
+ {"version":3,"file":"format.mjs","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;E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ClBY,OAAA,CACF;AACF,CAAA;AAMa,MAAAgB,aAAA,GAAiBC,KAAsB,IAAA;EAC5C,MAAAC,SAAA,GAAYD,MAAME,MAAO,EAAA;EAEvB,QAAAD,SAAA,CAAUxB,SAASS,IAAM;IAAA;IAE/B,KAAKiB,GAAI,CAAAjB,IAAA;IACT,KAAKkB,GAAI,CAAAlB,IAAA;IACT,KAAKmB,IAAInB,IAAM;MAAA;QACP,MAAAoB,YAAA,GAAeC,OAAOP,KAAK,CAAA;QAEjC,IAAIM,eAAe,EAAI,EAAA;UACd,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMC,oBAAoB,CAAA;QAAA,CACtD,MAAA,IAAWJ,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAME,qBAAqB,CAAA;QAAA,CACvD,MAAA,IAAWL,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;QAAA,CACnC,MAAA;UACE,OAAAJ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMI,eAAe,CAAA;QACjD;MACF;IACA;MAAS;QAEH,IAAA,CAACC,WAAY,CAAAd,KAAK,CAAG,EAAA;UAChB,OAAAA,KAAA;QACT;QAEA,MAAMe,mCAAmCC,mBAAoB,CAAAjD,GAAA,CAC3DkC,UAAUxB,QAAS,CAAAS,IAAA,CACrB;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,MAAO,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;"}
@@ -1 +1 @@
1
- {"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,SAAA,CAAAA,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AAUa,MAAAM,iBAAA,GAAqBH,SAAqC,IAAA;EAC/D,MAAAI,cAAA,GAAiBC,YAAAA,CAAAA,sBAAuB,CAAAN,GAAA,CAAIC,SAAQ,CAAA;EAC1DM,MAAA,CAAAA,MAA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;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,SAAA,CAAAA,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AAUa,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,gBAAmB,GAAAG,QAAA,CAAS3D,QAAS,CAAAiC,IAAA,IAAQ0B,SAAS3D,QAAS,CAAA6B,QACjE,CAAA;IACA7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;;;;;;;;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"misc.mjs","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,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U2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;"}
1
+ {"version":3,"file":"misc.mjs","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AA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ourcesContent":["import { createHash } from \"crypto\";\nimport { minify } from \"terser\";\n\n/**\n * Returns a SHA256 hash using SHA-2 for the given `content`.\n * @private Internal library method!\n * @see https://en.wikipedia.org/wiki/SHA-2\n * @See https://futurestud.io/tutorials/node-js-calculate-a-sha256-hash\n */\nexport const _cspHash = (scriptContent: string): string => {\n if (\n // Naive approach but it sufficiernt for our use case\n scriptContent.startsWith(\"<script\") ||\n scriptContent.endsWith(\"</script>\")\n ) {\n throw new Error(\n \"Inline script should not be wrapped inside of <script><script/>\",\n );\n }\n const hash = createHash(\"sha256\").update(scriptContent).digest(\"base64\");\n return `'sha256-${hash}'`;\n};\n\n/**\n * Minifies the inline script for \"machine\" consumption\n * Uses `terser` (webpack minifier of choice) to minify the script\n * @private Internal library method!\n * @see https://github.com/terser/terser\n */\nexport const _minifyScript = async (scriptContent: string): Promise<string> => {\n const minifiedContent = (await minify(scriptContent, {})).code;\n if (!minifiedContent) {\n throw new Error(\n \"Missing minified code for some reason, check input for script content\",\n );\n }\n return minifiedContent;\n};\n\n/**\n * Utility to create safe & optimized inline-script\n * It does two things:\n * 1. Optimizes the minifies script as bundlers don't do that\n * 2. Creates `'sha256 ...'` (already escaped!) to use in CSP header\n */\nexport const createInlineScript = async (inlineScriptContent: string) => {\n const optimizedInlineScriptContent = await _minifyScript(inlineScriptContent);\n\n return {\n cspSha: _cspHash(optimizedInlineScriptContent),\n inlineScript: optimizedInlineScriptContent,\n };\n};\n"],"names":["_cspHash","scriptContent","startsWith","endsWith","Error","hash","createHash","update","digest","_minifyScript","minifiedContent","minify","code","createInlineScript","inlineScriptContent","optimizedInlineScriptContent","cspSha","inlineScript"],"mappings":";;;;;AASa,MAAAA,QAAA,GAAYC,aAAkC,IAAA;EACzD;EAAA;EAEEA,cAAcC,UAAW,CAAA,SAAS,CAClC,IAAAD,aAAA,CAAcE,SAAS,YAAW,CAAA,EAClC;IACA,MAAM,IAAIC,KAAA,CACR,iEAAA,CACF;EACF;EACM,MAAAC,IAAA,GAAOC,kBAAW,QAAQ,CAAA,CAAEC,OAAON,aAAa,CAAA,CAAEO,OAAO,QAAQ,CAAA;EACvE,kBAAkBH,IAAI,GAAA;AACxB,CAAA;AAQa,MAAAI,aAAA,GAAgB,MAAOR,aAA2C,IAAA;EAC7E,MAAMS,mBAAmB,MAAMC,MAAAA,CAAAA,MAAA,CAAOV,aAAe,EAAA,CAAA,CAAE,CAAG,EAAAW,IAAA;EAC1D,IAAI,CAACF,eAAiB,EAAA;IACpB,MAAM,IAAIN,KAAA,CACR,uEAAA,CACF;EACF;EACO,OAAAM,eAAA;AACT,CAAA;AAQa,MAAAG,kBAAA,GAAqB,MAAOC,mBAAgC,IAAA;EACjE,MAAAC,4BAAA,GAA+B,MAAMN,aAAA,CAAcK,mBAAmB,CAAA;EAErE,OAAA;IACLE,MAAA,EAAQhB,SAASe,4BAA4B,CAAA;IAC7CE,YAAc,EAAAF;EAAA,CAChB;AACF,CAAA;;;"}
1
+ {"version":3,"file":"createInlineScript.js","sources":["../../../src/utils/nextjs/createInlineScript.ts"],"sourcesContent":["import { createHash } from \"crypto\";\nimport { minify } from \"terser\";\n\n/**\n * Returns a SHA256 hash using SHA-2 for the given `content`.\n * @private Internal library method!\n * @see https://en.wikipedia.org/wiki/SHA-2\n * @See https://futurestud.io/tutorials/node-js-calculate-a-sha256-hash\n */\nexport const _cspHash = (scriptContent: string): string => {\n if (\n // Naive approach but it sufficiernt for our use case\n scriptContent.startsWith(\"<script\") ||\n scriptContent.endsWith(\"</script>\")\n ) {\n throw new Error(\n \"Inline script should not be wrapped inside of <script><script/>\",\n );\n }\n const hash = createHash(\"sha256\").update(scriptContent).digest(\"base64\");\n return `'sha256-${hash}'`;\n};\n\n/**\n * Minifies the inline script for \"machine\" consumption\n * Uses `terser` (webpack minifier of choice) to minify the script\n * @private Internal library method!\n * @see https://github.com/terser/terser\n */\nexport const _minifyScript = async (scriptContent: string): Promise<string> => {\n const minifiedContent = (await minify(scriptContent, {})).code;\n if (!minifiedContent) {\n throw new Error(\n \"Missing minified code for some reason, check input for script content\",\n );\n }\n return minifiedContent;\n};\n\n/**\n * Utility to create safe & optimized inline-script\n * It does two things:\n * 1. Optimizes the minifies script as bundlers don't do that\n * 2. Creates `'sha256 ...'` (already escaped!) to use in CSP header\n */\nexport const createInlineScript = async (inlineScriptContent: string) => {\n const optimizedInlineScriptContent = await _minifyScript(inlineScriptContent);\n\n return {\n cspSha: _cspHash(optimizedInlineScriptContent),\n inlineScript: optimizedInlineScriptContent,\n };\n};\n"],"names":["_cspHash","scriptContent","startsWith","endsWith","Error","hash","createHash","update","digest","_minifyScript","minifiedContent","minify","code","createInlineScript","inlineScriptContent","optimizedInlineScriptContent","cspSha","inlineScript"],"mappings":";;;;;AASa,MAAAA,QAAA,GAAYC,aAAkC,IAAA;EACzD;EAAA;EAEEA,cAAcC,UAAW,CAAA,SAAS,CAClC,IAAAD,aAAA,CAAcE,SAAS,YAAW,CAAA,EAClC;IACA,MAAM,IAAIC,KAAA,CACR,iEAAA,CACF;EACF;EACM,MAAAC,IAAA,GAAOC,kBAAW,QAAQ,CAAA,CAAEC,OAAON,aAAa,CAAA,CAAEO,OAAO,QAAQ,CAAA;EACvE,OAAO,WAAWH,IAAI,GAAA;AACxB,CAAA;AAQa,MAAAI,aAAA,GAAgB,MAAOR,aAA2C,IAAA;EAC7E,MAAMS,mBAAmB,MAAMC,MAAAA,CAAAA,MAAA,CAAOV,aAAe,EAAA,CAAA,CAAE,CAAG,EAAAW,IAAA;EAC1D,IAAI,CAACF,eAAiB,EAAA;IACpB,MAAM,IAAIN,KAAA,CACR,uEAAA,CACF;EACF;EACO,OAAAM,eAAA;AACT,CAAA;AAQa,MAAAG,kBAAA,GAAqB,MAAOC,mBAAgC,IAAA;EACjE,MAAAC,4BAAA,GAA+B,MAAMN,aAAA,CAAcK,mBAAmB,CAAA;EAErE,OAAA;IACLE,MAAA,EAAQhB,SAASe,4BAA4B,CAAA;IAC7CE,YAAc,EAAAF;EAAA,CAChB;AACF,CAAA;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"createInlineScript.mjs","sources":["../../../src/utils/nextjs/createInlineScript.ts"],"sourcesContent":["import { createHash } from \"crypto\";\nimport { minify } from \"terser\";\n\n/**\n * Returns a SHA256 hash using SHA-2 for the given `content`.\n * @private Internal library method!\n * @see https://en.wikipedia.org/wiki/SHA-2\n * @See https://futurestud.io/tutorials/node-js-calculate-a-sha256-hash\n */\nexport const _cspHash = (scriptContent: string): string => {\n if (\n // Naive approach but it sufficiernt for our use case\n scriptContent.startsWith(\"<script\") ||\n scriptContent.endsWith(\"</script>\")\n ) {\n throw new Error(\n \"Inline script should not be wrapped inside of <script><script/>\",\n );\n }\n const hash = createHash(\"sha256\").update(scriptContent).digest(\"base64\");\n return `'sha256-${hash}'`;\n};\n\n/**\n * Minifies the inline script for \"machine\" consumption\n * Uses `terser` (webpack minifier of choice) to minify the script\n * @private Internal library method!\n * @see https://github.com/terser/terser\n */\nexport const _minifyScript = async (scriptContent: string): Promise<string> => {\n const minifiedContent = (await minify(scriptContent, {})).code;\n if (!minifiedContent) {\n throw new Error(\n \"Missing minified code for some reason, check input for script content\",\n );\n }\n return minifiedContent;\n};\n\n/**\n * Utility to create safe & optimized inline-script\n * It does two things:\n * 1. Optimizes the minifies script as bundlers don't do that\n * 2. Creates `'sha256 ...'` (already escaped!) to use in CSP header\n */\nexport const createInlineScript = async (inlineScriptContent: string) => {\n const optimizedInlineScriptContent = await _minifyScript(inlineScriptContent);\n\n return {\n cspSha: _cspHash(optimizedInlineScriptContent),\n inlineScript: optimizedInlineScriptContent,\n };\n};\n"],"names":["_cspHash","scriptContent","startsWith","endsWith","Error","hash","createHash","update","digest","_minifyScript","minifiedContent","minify","code","createInlineScript","inlineScriptContent","optimizedInlineScriptContent","cspSha","inlineScript"],"mappings":";;;AASa,MAAAA,QAAA,GAAYC,aAAkC,IAAA;EACzD;EAAA;EAEEA,cAAcC,UAAW,CAAA,SAAS,CAClC,IAAAD,aAAA,CAAcE,SAAS,YAAW,CAAA,EAClC;IACA,MAAM,IAAIC,KAAA,CACR,iEAAA,CACF;EACF;EACM,MAAAC,IAAA,GAAOC,WAAW,QAAQ,CAAA,CAAEC,OAAON,aAAa,CAAA,CAAEO,OAAO,QAAQ,CAAA;EACvE,kBAAkBH,IAAI,GAAA;AACxB,CAAA;AAQa,MAAAI,aAAA,GAAgB,MAAOR,aAA2C,IAAA;EAC7E,MAAMS,mBAAmB,MAAMC,MAAA,CAAOV,aAAe,EAAA,CAAA,CAAE,CAAG,EAAAW,IAAA;EAC1D,IAAI,CAACF,eAAiB,EAAA;IACpB,MAAM,IAAIN,KAAA,CACR,uEAAA,CACF;EACF;EACO,OAAAM,eAAA;AACT,CAAA;AAQa,MAAAG,kBAAA,GAAqB,MAAOC,mBAAgC,IAAA;EACjE,MAAAC,4BAAA,GAA+B,MAAMN,aAAA,CAAcK,mBAAmB,CAAA;EAErE,OAAA;IACLE,MAAA,EAAQhB,SAASe,4BAA4B,CAAA;IAC7CE,YAAc,EAAAF;EAAA,CAChB;AACF,CAAA;"}
1
+ {"version":3,"file":"createInlineScript.mjs","sources":["../../../src/utils/nextjs/createInlineScript.ts"],"sourcesContent":["import { createHash } from \"crypto\";\nimport { minify } from \"terser\";\n\n/**\n * Returns a SHA256 hash using SHA-2 for the given `content`.\n * @private Internal library method!\n * @see https://en.wikipedia.org/wiki/SHA-2\n * @See https://futurestud.io/tutorials/node-js-calculate-a-sha256-hash\n */\nexport const _cspHash = (scriptContent: string): string => {\n if (\n // Naive approach but it sufficiernt for our use case\n scriptContent.startsWith(\"<script\") ||\n scriptContent.endsWith(\"</script>\")\n ) {\n throw new Error(\n \"Inline script should not be wrapped inside of <script><script/>\",\n );\n }\n const hash = createHash(\"sha256\").update(scriptContent).digest(\"base64\");\n return `'sha256-${hash}'`;\n};\n\n/**\n * Minifies the inline script for \"machine\" consumption\n * Uses `terser` (webpack minifier of choice) to minify the script\n * @private Internal library method!\n * @see https://github.com/terser/terser\n */\nexport const _minifyScript = async (scriptContent: string): Promise<string> => {\n const minifiedContent = (await minify(scriptContent, {})).code;\n if (!minifiedContent) {\n throw new Error(\n \"Missing minified code for some reason, check input for script content\",\n );\n }\n return minifiedContent;\n};\n\n/**\n * Utility to create safe & optimized inline-script\n * It does two things:\n * 1. Optimizes the minifies script as bundlers don't do that\n * 2. Creates `'sha256 ...'` (already escaped!) to use in CSP header\n */\nexport const createInlineScript = async (inlineScriptContent: string) => {\n const optimizedInlineScriptContent = await _minifyScript(inlineScriptContent);\n\n return {\n cspSha: _cspHash(optimizedInlineScriptContent),\n inlineScript: optimizedInlineScriptContent,\n };\n};\n"],"names":["_cspHash","scriptContent","startsWith","endsWith","Error","hash","createHash","update","digest","_minifyScript","minifiedContent","minify","code","createInlineScript","inlineScriptContent","optimizedInlineScriptContent","cspSha","inlineScript"],"mappings":";;;AASa,MAAAA,QAAA,GAAYC,aAAkC,IAAA;EACzD;EAAA;EAEEA,cAAcC,UAAW,CAAA,SAAS,CAClC,IAAAD,aAAA,CAAcE,SAAS,YAAW,CAAA,EAClC;IACA,MAAM,IAAIC,KAAA,CACR,iEAAA,CACF;EACF;EACM,MAAAC,IAAA,GAAOC,WAAW,QAAQ,CAAA,CAAEC,OAAON,aAAa,CAAA,CAAEO,OAAO,QAAQ,CAAA;EACvE,OAAO,WAAWH,IAAI,GAAA;AACxB,CAAA;AAQa,MAAAI,aAAA,GAAgB,MAAOR,aAA2C,IAAA;EAC7E,MAAMS,mBAAmB,MAAMC,MAAA,CAAOV,aAAe,EAAA,CAAA,CAAE,CAAG,EAAAW,IAAA;EAC1D,IAAI,CAACF,eAAiB,EAAA;IACpB,MAAM,IAAIN,KAAA,CACR,uEAAA,CACF;EACF;EACO,OAAAM,eAAA;AACT,CAAA;AAQa,MAAAG,kBAAA,GAAqB,MAAOC,mBAAgC,IAAA;EACjE,MAAAC,4BAAA,GAA+B,MAAMN,aAAA,CAAcK,mBAAmB,CAAA;EAErE,OAAA;IACLE,MAAA,EAAQhB,SAASe,4BAA4B,CAAA;IAC7CE,YAAc,EAAAF;EAAA,CAChB;AACF,CAAA;"}
@@ -2,4 +2,7 @@ export { createInlineScript } from "./createInlineScript";
2
2
  export { stringifyForInject } from "./stringifyForInject";
3
3
  export { mergeCspDirectives } from "./mergeCspDirectives";
4
4
  export { sanitizeImageDomains } from "./sanitizeImageDomains";
5
+ export { withUbntLibraries } from "./plugin";
6
+ export { UiComponentsSsrStyleRegistryPagesRouter } from "./ssr/registry";
7
+ import "./ssr/style-inject";
5
8
  export * from "./navigationPresets";
@@ -4,12 +4,17 @@ var createInlineScript = require('./createInlineScript.js');
4
4
  var stringifyForInject = require('./stringifyForInject.js');
5
5
  var mergeCspDirectives = require('./mergeCspDirectives.js');
6
6
  var sanitizeImageDomains = require('./sanitizeImageDomains.js');
7
+ var plugin = require('./plugin.js');
8
+ var registry = require('./ssr/registry.js');
9
+ require('./ssr/style-inject.js');
7
10
  var navigationPresets = require('./navigationPresets.js');
8
11
  "use strict";
9
12
  exports.createInlineScript = createInlineScript.createInlineScript;
10
13
  exports.stringifyForInject = stringifyForInject.stringifyForInject;
11
14
  exports.mergeCspDirectives = mergeCspDirectives.mergeCspDirectives;
12
15
  exports.sanitizeImageDomains = sanitizeImageDomains.sanitizeImageDomains;
16
+ exports.withUbntLibraries = plugin.withUbntLibraries;
17
+ exports.UiComponentsSsrStyleRegistryPagesRouter = registry.UiComponentsSsrStyleRegistryPagesRouter;
13
18
  exports.getGlobalSiteConfigByEnv = navigationPresets.getGlobalSiteConfigByEnv;
14
19
  exports.getStoreRootUrlsByEnv = navigationPresets.getStoreRootUrlsByEnv;
15
20
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;"}
@@ -2,6 +2,9 @@ export { createInlineScript } from './createInlineScript.mjs';
2
2
  export { stringifyForInject } from './stringifyForInject.mjs';
3
3
  export { mergeCspDirectives } from './mergeCspDirectives.mjs';
4
4
  export { sanitizeImageDomains } from './sanitizeImageDomains.mjs';
5
+ export { withUbntLibraries } from './plugin.mjs';
6
+ export { UiComponentsSsrStyleRegistryPagesRouter } from './ssr/registry.mjs';
7
+ import './ssr/style-inject.mjs';
5
8
  export { getGlobalSiteConfigByEnv, getStoreRootUrlsByEnv } from './navigationPresets.mjs';
6
9
  "use strict";
7
10
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
@@ -0,0 +1 @@
1
+ export default function patchUiComponentsAndIcons(): void;