@kanorio/elements 1.2.0 → 1.3.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 (337) hide show
  1. package/README.md +1 -1
  2. package/dist/CustomerAccountPanel-FXJEOS4F.js +2 -0
  3. package/dist/CustomerAccountPanel-LK4GSYYU.js +2 -0
  4. package/dist/{FormAddressField-QR7ZCH77.js → FormAddressField-NH5LD6K7.js} +2 -2
  5. package/dist/{FormAddressField-C6VN7J6I.js → FormAddressField-Z5XT2ELO.js} +2 -2
  6. package/dist/FormFileField-5YFTKIRZ.js +2 -0
  7. package/dist/FormFileField-D2XIGIML.js +2 -0
  8. package/dist/{FormTaxIdField-K34MDUPW.js → FormTaxIdField-GGBQOVZE.js} +2 -2
  9. package/dist/{FormTaxIdField-XMK5WRQO.js → FormTaxIdField-XJSMW3II.js} +2 -2
  10. package/dist/KanorioAccount-GXRAMZCI.js +2 -0
  11. package/dist/KanorioAccount-P6IIPIZ2.js +2 -0
  12. package/dist/KanorioAnalytics-KYTK3T2L.js +2 -0
  13. package/dist/KanorioAnalytics-XHKBWYTS.js +2 -0
  14. package/dist/KanorioCurriculum-3TLNLUL4.js +2 -0
  15. package/dist/KanorioCurriculum-SQ4S3U5T.js +2 -0
  16. package/dist/KanorioForm-FDS5UKUT.js +2 -0
  17. package/dist/KanorioForm-K3H3YUQH.js +2 -0
  18. package/dist/KanorioLightbox-QPJQJLNO.js +2 -0
  19. package/dist/KanorioLightbox-WBMR7MLG.js +2 -0
  20. package/dist/KanorioLogin-JMHHBRU7.js +2 -0
  21. package/dist/KanorioLogin-QMPBTK55.js +2 -0
  22. package/dist/KanorioMedia-5P63OK4U.js +2 -0
  23. package/dist/KanorioMedia-LONTU7H2.js +2 -0
  24. package/dist/KanorioReviews-AAQ27MYU.js +2 -0
  25. package/dist/KanorioReviews-LUB4KF23.js +2 -0
  26. package/dist/KanorioUnit-ADFQ7POH.js +2 -0
  27. package/dist/KanorioUnit-YBKFHGLB.js +2 -0
  28. package/dist/{MediaPlayer-F43FPK4E.js → MediaPlayer-C5KI6N5V.js} +2 -2
  29. package/dist/{MediaPlayer-JHFZFOOG.js → MediaPlayer-PMAEZSCZ.js} +2 -2
  30. package/dist/{PDFViewerFull-INVHZL4V.js → PDFViewerFull-6MZJTHN2.js} +2 -2
  31. package/dist/{PDFViewerFull-CB44M7GW.js → PDFViewerFull-P3HCVGDZ.js} +2 -2
  32. package/dist/account.d.ts +3 -2
  33. package/dist/account.js +1 -1
  34. package/dist/analytics.js +1 -1
  35. package/dist/ar-JXAEXYYY.js +2 -0
  36. package/dist/ar-UXUCJCPY.js +2 -0
  37. package/dist/bg-EUIPVVBX.js +2 -0
  38. package/dist/bg-HEU3KGAJ.js +2 -0
  39. package/dist/{bn-BHRS66N3.js → bn-L35GOE5D.js} +2 -2
  40. package/dist/{bn-DM5WNGJ5.js → bn-LMQOF3SO.js} +2 -2
  41. package/dist/bot-protection.d.ts +67 -36
  42. package/dist/bot-protection.js +1 -1
  43. package/dist/chunk-2H3LTDAA.js +2 -0
  44. package/dist/chunk-3NXF6SCJ.js +2 -0
  45. package/dist/{chunk-EE4S6NRV.js → chunk-4OC7BRQS.js} +2 -2
  46. package/dist/{chunk-DTBRUBPG.js → chunk-56UUP6CI.js} +2 -2
  47. package/dist/{chunk-IAXVJLJ3.js → chunk-65RP744E.js} +2 -2
  48. package/dist/chunk-APWDEDWM.js +2 -0
  49. package/dist/{chunk-H7VP4BYY.js → chunk-CD7JDUB6.js} +2 -2
  50. package/dist/{chunk-4KA3HSRQ.js → chunk-CIVS7LYU.js} +2 -2
  51. package/dist/chunk-CMYBXWO5.js +3 -0
  52. package/dist/{chunk-WM5S3YN5.js → chunk-CTMHQZAU.js} +2 -2
  53. package/dist/chunk-D4KDA3KL.js +2 -0
  54. package/dist/{chunk-36YEGBKK.js → chunk-EGJ6SNTR.js} +2 -2
  55. package/dist/chunk-G5673RJK.js +3 -0
  56. package/dist/{chunk-2ONAW3CA.js → chunk-GWUOOGNK.js} +2 -2
  57. package/dist/{chunk-FQCA2VGY.js → chunk-HAHAYDYM.js} +2 -2
  58. package/dist/chunk-IDY2ZCXL.js +2 -0
  59. package/dist/{chunk-NGRNPVON.js → chunk-II7PVZWZ.js} +2 -2
  60. package/dist/chunk-J5SMJRYC.js +2 -0
  61. package/dist/{chunk-N5PIQM4L.js → chunk-KW2CH7SS.js} +2 -2
  62. package/dist/chunk-KYXZNMNA.js +2 -0
  63. package/dist/{chunk-QOQQCCID.js → chunk-L3BUSP27.js} +2 -2
  64. package/dist/{chunk-B7KLKVIM.js → chunk-L66F3USG.js} +2 -2
  65. package/dist/{chunk-NBDRYQZV.js → chunk-OLGITMLA.js} +2 -2
  66. package/dist/{chunk-BGVTMWPN.js → chunk-OWXGUUSI.js} +2 -2
  67. package/dist/chunk-Q4APVE7S.js +2 -0
  68. package/dist/chunk-QF55WZDP.js +2 -0
  69. package/dist/{chunk-4MOCTNN7.js → chunk-QRKYFFDH.js} +2 -2
  70. package/dist/chunk-QYTK2CW3.js +2 -0
  71. package/dist/chunk-R5M6FXXQ.js +2 -0
  72. package/dist/chunk-RI64PHGM.js +2 -0
  73. package/dist/chunk-RNRIZCZS.js +2 -0
  74. package/dist/chunk-RTF2NUMK.js +3 -0
  75. package/dist/chunk-SB5665ZK.js +2 -0
  76. package/dist/{chunk-5HWAL7VK.js → chunk-SGFVHVLE.js} +2 -2
  77. package/dist/{chunk-K4VRRKYJ.js → chunk-UDNUWN4W.js} +2 -2
  78. package/dist/{chunk-AF46NLXK.js → chunk-UITC3NFQ.js} +2 -2
  79. package/dist/chunk-VGQ2N7JH.js +2 -0
  80. package/dist/chunk-WJPCDZSL.js +2 -0
  81. package/dist/{chunk-LWRWKZBC.js → chunk-WKKPZXK3.js} +2 -2
  82. package/dist/{chunk-Z4OV6QHI.js → chunk-Y5JA6B5O.js} +2 -2
  83. package/dist/cs-LY4LE4NI.js +2 -0
  84. package/dist/cs-MGLMNU2K.js +2 -0
  85. package/dist/curriculum.d.ts +3 -2
  86. package/dist/curriculum.js +1 -1
  87. package/dist/da-LQTLZNBW.js +2 -0
  88. package/dist/da-X5HKEDEL.js +2 -0
  89. package/dist/de-M3M4VBDR.js +2 -0
  90. package/dist/de-Y5ELIZBU.js +2 -0
  91. package/dist/{deliverables-C5RD2ASE.js → deliverables-EOIAZFWB.js} +25 -25
  92. package/dist/{deliverables-BDS7WMBC.js → deliverables-NO5NEFRM.js} +2 -2
  93. package/dist/{el-SMBF7FG4.js → el-7YYYEHW6.js} +2 -2
  94. package/dist/{el-G2AWU43W.js → el-YZGS3PLP.js} +2 -2
  95. package/dist/elements.css +1 -1
  96. package/dist/en-AU-IUEA3YQP.js +2 -0
  97. package/dist/en-AU-RQ2DVIXE.js +2 -0
  98. package/dist/en-CA-OFK46Q44.js +2 -0
  99. package/dist/en-CA-QDP57WHG.js +2 -0
  100. package/dist/en-GB-URCOTEDK.js +2 -0
  101. package/dist/en-GB-VNG2IO2E.js +2 -0
  102. package/dist/en-JSBHSC4K.js +2 -0
  103. package/dist/en-MCRNEXQP.js +2 -0
  104. package/dist/en-US-5RT4SJ3V.js +2 -0
  105. package/dist/en-US-IWMVMSUT.js +2 -0
  106. package/dist/es-419-53Z5HI6Z.js +2 -0
  107. package/dist/es-419-JFUQ3D4V.js +2 -0
  108. package/dist/es-ES-BMD6JJEO.js +2 -0
  109. package/dist/es-ES-PBIVNTAT.js +2 -0
  110. package/dist/fa-57P7R77M.js +2 -0
  111. package/dist/{fa-OYP2Q5EV.js → fa-NE4XJTHW.js} +2 -2
  112. package/dist/fi-G5MG7VJ2.js +2 -0
  113. package/dist/fi-SCTIKRMX.js +2 -0
  114. package/dist/form.d.ts +393 -23
  115. package/dist/form.js +1 -1
  116. package/dist/{forms-answers-address-7P6EVFY5.js → forms-answers-address-5MXQYIH3.js} +2 -2
  117. package/dist/{forms-answers-address-IQV2Y56H.js → forms-answers-address-BGBI445K.js} +2 -2
  118. package/dist/{forms-answers-tax-id-WJD7K3PG.js → forms-answers-tax-id-3AYXCNP5.js} +2 -2
  119. package/dist/{forms-answers-tax-id-D4GOUC6N.js → forms-answers-tax-id-LSWOEHJ4.js} +2 -2
  120. package/dist/fr-CA-4X7URW4M.js +2 -0
  121. package/dist/fr-CA-RQDI3NIQ.js +2 -0
  122. package/dist/fr-FR-EDVHTVOW.js +2 -0
  123. package/dist/fr-FR-KGXOTINP.js +2 -0
  124. package/dist/{gu-BREQK3GJ.js → gu-7AJCL43I.js} +2 -2
  125. package/dist/{gu-RNCZTEOA.js → gu-QE53XIWR.js} +2 -2
  126. package/dist/he-UWYKIUPF.js +2 -0
  127. package/dist/he-VLGZUN42.js +2 -0
  128. package/dist/{hi-DKG5TPYX.js → hi-5M4U37GW.js} +2 -2
  129. package/dist/{hi-F7Y62LAZ.js → hi-KXKJMKZF.js} +2 -2
  130. package/dist/{hu-3Y5YEIFL.js → hu-JU7V3YQX.js} +2 -2
  131. package/dist/{hu-L6W5O2G5.js → hu-YRF3KPIJ.js} +2 -2
  132. package/dist/id-IRL2KCIE.js +2 -0
  133. package/dist/id-SXO4Z54V.js +2 -0
  134. package/dist/index.d.ts +5 -3
  135. package/dist/index.js +1 -1
  136. package/dist/it-55QCLHB7.js +2 -0
  137. package/dist/it-RBRELRA3.js +2 -0
  138. package/dist/ja-2WRUVHKU.js +2 -0
  139. package/dist/ja-3HZPHYZS.js +2 -0
  140. package/dist/kanorio-elements.js +1 -1
  141. package/dist/{km-HPCMYWAG.js → km-EW4ISUB7.js} +2 -2
  142. package/dist/{km-PHVYTPLT.js → km-SL6MZB3H.js} +2 -2
  143. package/dist/{kn-QAWBGLHG.js → kn-RUSRJNGR.js} +2 -2
  144. package/dist/kn-YGEU3PSD.js +2 -0
  145. package/dist/ko-2GI6Z5YH.js +2 -0
  146. package/dist/ko-QK33QMU2.js +2 -0
  147. package/dist/{lightbox-DEvsB5dB.d.ts → lightbox-BmkHgtZg.d.ts} +1 -1
  148. package/dist/lightbox.d.ts +4 -3
  149. package/dist/lightbox.js +1 -1
  150. package/dist/{lo-JNUKFIQV.js → lo-PPDKXTQQ.js} +2 -2
  151. package/dist/{lo-YRHYLRZC.js → lo-ZRV6OAH6.js} +2 -2
  152. package/dist/login.d.ts +3 -2
  153. package/dist/login.js +1 -1
  154. package/dist/media.d.ts +3 -2
  155. package/dist/media.js +1 -1
  156. package/dist/{ml-QO64O4H6.js → ml-BIZEFHNR.js} +2 -2
  157. package/dist/{ml-3LXSDTNF.js → ml-KO2JGAL5.js} +2 -2
  158. package/dist/{mr-PLM72664.js → mr-J4AGQFC7.js} +2 -2
  159. package/dist/{mr-5WLN37JQ.js → mr-PZNRW5MW.js} +2 -2
  160. package/dist/{ms-PIAATVMD.js → ms-NYWKJQEQ.js} +2 -2
  161. package/dist/{ms-N544Y63H.js → ms-OMUKF5WC.js} +2 -2
  162. package/dist/{my-3J665CWK.js → my-FHI5JEQF.js} +2 -2
  163. package/dist/{my-6IKSM3XW.js → my-R4OXNUDW.js} +2 -2
  164. package/dist/nb-EC6AP76Y.js +2 -0
  165. package/dist/nb-U4QN5GJE.js +2 -0
  166. package/dist/{ne-ASFNHMO3.js → ne-DRPNDCZH.js} +2 -2
  167. package/dist/ne-J3XQJZAY.js +2 -0
  168. package/dist/nl-BE-QIH5K6WQ.js +2 -0
  169. package/dist/nl-BE-VHBDCIRF.js +2 -0
  170. package/dist/nl-NL-FZMZRVH4.js +2 -0
  171. package/dist/nl-NL-USXHXD5U.js +2 -0
  172. package/dist/nn-IPL74C6S.js +2 -0
  173. package/dist/nn-UCSEDGDB.js +2 -0
  174. package/dist/{pa-P2GAYL5A.js → pa-LTF7CWS2.js} +2 -2
  175. package/dist/{pa-VX5TUNDP.js → pa-NTK4KSUF.js} +2 -2
  176. package/dist/{phone-input-Q5AV6KSW.js → phone-input-DOL46AIF.js} +2 -2
  177. package/dist/{phone-input-T6QX2TDS.js → phone-input-PXLNDXAB.js} +2 -2
  178. package/dist/pl-6FXX3WNC.js +2 -0
  179. package/dist/pl-YWCG2YWW.js +2 -0
  180. package/dist/{provider-CMLzyAjJ.d.ts → provider-BYGVc6kS.d.ts} +3 -1
  181. package/dist/provider.d.ts +3 -2
  182. package/dist/provider.js +1 -1
  183. package/dist/pt-BR-5JRKIQVH.js +2 -0
  184. package/dist/pt-BR-CIJCMCLE.js +2 -0
  185. package/dist/pt-PT-A7F2KKCY.js +2 -0
  186. package/dist/pt-PT-Y2UCAKHP.js +2 -0
  187. package/dist/reviews.d.ts +3 -2
  188. package/dist/reviews.js +1 -1
  189. package/dist/ro-6MQF2KY2.js +2 -0
  190. package/dist/ro-YISUN7LU.js +2 -0
  191. package/dist/ru-KGU3SC3S.js +2 -0
  192. package/dist/ru-RMPFJQSL.js +2 -0
  193. package/dist/{si-5VUM5FGR.js → si-CTQN6I2M.js} +2 -2
  194. package/dist/{si-5F7RWQIE.js → si-N5U32GIL.js} +2 -2
  195. package/dist/sv-36EB3HIA.js +2 -0
  196. package/dist/sv-QGZRDKBJ.js +2 -0
  197. package/dist/sw-CWIRVHYD.js +2 -0
  198. package/dist/sw-OUQYTLJF.js +2 -0
  199. package/dist/{ta-MNWTH3F5.js → ta-E3ZBHC6A.js} +2 -2
  200. package/dist/{ta-R73RBA23.js → ta-N7BHKWBO.js} +2 -2
  201. package/dist/{te-5SBVH4OF.js → te-7JC2KGAU.js} +2 -2
  202. package/dist/{te-GVW56XDM.js → te-CTCZQKFU.js} +2 -2
  203. package/dist/{th-G6SY3D2Q.js → th-AN5CLQP6.js} +2 -2
  204. package/dist/{th-2GWK7DBB.js → th-JVK4E2AJ.js} +2 -2
  205. package/dist/tl-BSWGJB7O.js +2 -0
  206. package/dist/tl-X72423V3.js +2 -0
  207. package/dist/tr-22NUPSET.js +2 -0
  208. package/dist/tr-AZ2PLRZY.js +2 -0
  209. package/dist/{uk-PGHXMWJR.js → uk-POKPJJDZ.js} +2 -2
  210. package/dist/uk-UOTQJ3E7.js +2 -0
  211. package/dist/unit.d.ts +3 -1
  212. package/dist/unit.js +1 -1
  213. package/dist/{ur-4CR64XUI.js → ur-6LBRTMAE.js} +2 -2
  214. package/dist/{ur-J5HV4NTW.js → ur-NRHFTLO5.js} +2 -2
  215. package/dist/vi-3ZVAOXIJ.js +2 -0
  216. package/dist/vi-XC4CGJHX.js +2 -0
  217. package/dist/web-components.js +1 -1
  218. package/dist/zh-CN-EKEY2CLM.js +2 -0
  219. package/dist/zh-CN-XW3PLUG5.js +2 -0
  220. package/dist/zh-HK-25OZZBHO.js +2 -0
  221. package/dist/zh-HK-EPQAUBL3.js +2 -0
  222. package/dist/zh-Hant-LFJZCOMK.js +2 -0
  223. package/dist/zh-Hant-RQMTFZSE.js +2 -0
  224. package/package.json +2 -2
  225. package/dist/CustomerAccountPanel-DJKV7LT4.js +0 -2
  226. package/dist/CustomerAccountPanel-RWEHWBJY.js +0 -2
  227. package/dist/FormFileField-LZDCXI2Z.js +0 -2
  228. package/dist/FormFileField-ONL4Q55V.js +0 -2
  229. package/dist/KanorioAccount-EN3TM67X.js +0 -2
  230. package/dist/KanorioAccount-XGVSGVYN.js +0 -2
  231. package/dist/KanorioAnalytics-NEKTFQEE.js +0 -2
  232. package/dist/KanorioAnalytics-UMCUWQM7.js +0 -2
  233. package/dist/KanorioCurriculum-3QSCOHK7.js +0 -2
  234. package/dist/KanorioCurriculum-RUIGZ5X7.js +0 -2
  235. package/dist/KanorioForm-GUA5GEJY.js +0 -2
  236. package/dist/KanorioForm-KXV7D2TU.js +0 -2
  237. package/dist/KanorioLightbox-M72HNQQX.js +0 -2
  238. package/dist/KanorioLightbox-TQ3Q73TD.js +0 -2
  239. package/dist/KanorioLogin-5XFN3YEE.js +0 -2
  240. package/dist/KanorioLogin-AJHHVQGV.js +0 -2
  241. package/dist/KanorioMedia-ADKUDH5C.js +0 -2
  242. package/dist/KanorioMedia-DLBSXCKA.js +0 -2
  243. package/dist/KanorioReviews-42FZSXTI.js +0 -2
  244. package/dist/KanorioReviews-7LD5WKFG.js +0 -2
  245. package/dist/KanorioUnit-NWBX5DEI.js +0 -2
  246. package/dist/KanorioUnit-SIM3344J.js +0 -2
  247. package/dist/ar-3VA7IUCO.js +0 -2
  248. package/dist/ar-AUQCHHZG.js +0 -2
  249. package/dist/bg-IRGRVWOG.js +0 -2
  250. package/dist/bg-QWC2KG3G.js +0 -2
  251. package/dist/chunk-4BBERZ6T.js +0 -2
  252. package/dist/chunk-5AUWUK5R.js +0 -2
  253. package/dist/chunk-66XN5RR4.js +0 -2
  254. package/dist/chunk-EZMTUAQX.js +0 -2
  255. package/dist/chunk-FSY5GB5E.js +0 -3
  256. package/dist/chunk-G4U6BFZY.js +0 -2
  257. package/dist/chunk-GJY6AQIS.js +0 -2
  258. package/dist/chunk-IXDKZO42.js +0 -2
  259. package/dist/chunk-MIQK3T3Y.js +0 -2
  260. package/dist/chunk-QGR3QAQB.js +0 -3
  261. package/dist/chunk-SUXTLVTX.js +0 -2
  262. package/dist/chunk-UIHBR4NU.js +0 -3
  263. package/dist/chunk-WXIUWMFR.js +0 -2
  264. package/dist/cs-3IX2ZQKJ.js +0 -2
  265. package/dist/cs-NZW6FBFY.js +0 -2
  266. package/dist/da-AFMLFM32.js +0 -2
  267. package/dist/da-PZ32KKTE.js +0 -2
  268. package/dist/de-5JPEK4HF.js +0 -2
  269. package/dist/de-MVL4XGYR.js +0 -2
  270. package/dist/en-AIAENVLI.js +0 -2
  271. package/dist/en-AU-LB5UVGIW.js +0 -2
  272. package/dist/en-AU-Q2O2HPJ2.js +0 -2
  273. package/dist/en-CA-AZDOY7PW.js +0 -2
  274. package/dist/en-CA-PVKXM3WS.js +0 -2
  275. package/dist/en-GB-2N4WB6SL.js +0 -2
  276. package/dist/en-GB-Y5QRPC7S.js +0 -2
  277. package/dist/en-SAXQF5YW.js +0 -2
  278. package/dist/en-US-74L4OI3J.js +0 -2
  279. package/dist/en-US-EKS52JBW.js +0 -2
  280. package/dist/es-419-Q5IH6W5F.js +0 -2
  281. package/dist/es-419-VSZWGONE.js +0 -2
  282. package/dist/es-ES-7L55KPLO.js +0 -2
  283. package/dist/es-ES-ETSYFLPQ.js +0 -2
  284. package/dist/fa-WRJCKGS3.js +0 -2
  285. package/dist/fi-44ST6B6Q.js +0 -2
  286. package/dist/fi-J6NJBPNK.js +0 -2
  287. package/dist/fr-CA-KXRNFZBP.js +0 -2
  288. package/dist/fr-CA-PWWAPLBH.js +0 -2
  289. package/dist/fr-FR-FMLQPLOD.js +0 -2
  290. package/dist/fr-FR-MQAFE7IX.js +0 -2
  291. package/dist/he-GNC45OCB.js +0 -2
  292. package/dist/he-VXZCGAHY.js +0 -2
  293. package/dist/id-7DWHYYFC.js +0 -2
  294. package/dist/id-DCV57AQB.js +0 -2
  295. package/dist/it-7RASZ4SK.js +0 -2
  296. package/dist/it-JICU5WVL.js +0 -2
  297. package/dist/ja-4V7QJLTM.js +0 -2
  298. package/dist/ja-52MBIM3T.js +0 -2
  299. package/dist/kn-5DYCOYAN.js +0 -2
  300. package/dist/ko-55JV4VQK.js +0 -2
  301. package/dist/ko-FZIJZG6K.js +0 -2
  302. package/dist/nb-345ACUTX.js +0 -2
  303. package/dist/nb-F33WYJ6T.js +0 -2
  304. package/dist/ne-AAIECB2W.js +0 -2
  305. package/dist/nl-BE-SHZLAL5T.js +0 -2
  306. package/dist/nl-BE-WK4C6XRZ.js +0 -2
  307. package/dist/nl-NL-2YLHGJZL.js +0 -2
  308. package/dist/nl-NL-PHRY43UB.js +0 -2
  309. package/dist/nn-I5A2LCBH.js +0 -2
  310. package/dist/nn-S3SNETRB.js +0 -2
  311. package/dist/pl-4Y4BWTLT.js +0 -2
  312. package/dist/pl-SGPLZAER.js +0 -2
  313. package/dist/pt-BR-CW3MRSRP.js +0 -2
  314. package/dist/pt-BR-WKEKB5CG.js +0 -2
  315. package/dist/pt-PT-AJZQS2C6.js +0 -2
  316. package/dist/pt-PT-ZTPCI2K6.js +0 -2
  317. package/dist/ro-ANISGUFX.js +0 -2
  318. package/dist/ro-HRV64STT.js +0 -2
  319. package/dist/ru-7U566HR4.js +0 -2
  320. package/dist/ru-PKSZKOLH.js +0 -2
  321. package/dist/sv-HZVCM7LG.js +0 -2
  322. package/dist/sv-UOGO55PW.js +0 -2
  323. package/dist/sw-5XU65KFC.js +0 -2
  324. package/dist/sw-KVAYRFED.js +0 -2
  325. package/dist/tl-OCD2O6J3.js +0 -2
  326. package/dist/tl-PZNXANIM.js +0 -2
  327. package/dist/tr-2BDM6H5Q.js +0 -2
  328. package/dist/tr-VFMHVRQX.js +0 -2
  329. package/dist/uk-OQRACKKD.js +0 -2
  330. package/dist/vi-MQSOSIUY.js +0 -2
  331. package/dist/vi-U7OT2LM7.js +0 -2
  332. package/dist/zh-CN-CCYHPSVA.js +0 -2
  333. package/dist/zh-CN-RNW2BEY7.js +0 -2
  334. package/dist/zh-HK-HE2T63O2.js +0 -2
  335. package/dist/zh-HK-RKREDSAO.js +0 -2
  336. package/dist/zh-Hant-GBQLGJDF.js +0 -2
  337. package/dist/zh-Hant-T6KHSA5B.js +0 -2
@@ -1,3 +0,0 @@
1
- import{a as He}from"./chunk-ARU5PTJV.js";import{a as pe,b as ge,c as Ue,d as he,g as ne}from"./chunk-N5PIQM4L.js";import{a as Me,b as Be}from"./chunk-EZMTUAQX.js";import{a as _e}from"./chunk-2J5XQK4H.js";import{b as fe}from"./chunk-2ONAW3CA.js";import{a as te,c as me,d as Oe,e as Le,u as Ie}from"./chunk-QGR3QAQB.js";import{a as Ee}from"./chunk-MXGMJAWS.js";import{a as Pe}from"./chunk-WP7UEAIB.js";import{b as ee}from"./chunk-2E6RCDAA.js";import{a as Ae}from"./chunk-U7KVGD47.js";import{$ as we,A as Re,Y as de,ba as _}from"./chunk-S2NFWI7C.js";import{b as Te}from"./chunk-AFNEGNVJ.js";import{a as N}from"./chunk-OU4IOHLN.js";import{a as ce,b as ke}from"./chunk-DLJDYXKL.js";import{a as it}from"./chunk-NSY72ZYX.js";import{a as W}from"./chunk-6LGTFWQS.js";import{c as h}from"./chunk-CDG7S4P5.js";var U=h(W(),1);var Ve=h(N());var ut=h(N());var Ke=h(N());var De=h(W());var $e=h(N());var m=h(W());var k=h(W()),je=h(it());var x=h(N()),ve='a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';function We({open:e,onClose:n,title:t,closeLabel:s,children:i,footer:a,showHeader:l=!0,dismissible:o=!0,desktopZIndexClassName:u="z-[var(--z-dialog,200)]",drawerZIndexClassName:r="z-[var(--z-dialog,200)]",maxWidthClassName:c="max-w-lg",desktopVariant:f="dialog",surface:v="glass",headerSlot:A,subheader:P,bodyClassName:L,footerClassName:y,id:K}){let g=f==="side",w=_e(),C=Ae(),I=(0,k.useRef)(n),R=(0,k.useRef)(o);(0,k.useEffect)(()=>{I.current=n,R.current=o}),(0,k.useEffect)(()=>{if(!e)return;let S=Ee(),E=j=>{j.key==="Escape"&&R.current&&I.current()};return document.addEventListener("keydown",E),()=>{S(),document.removeEventListener("keydown",E)}},[e]);let T=(0,k.useRef)(null),G=(0,k.useRef)(null),D=(0,k.useRef)(null),Y=(0,k.useRef)(null),B=(0,k.useRef)(null),H=(0,k.useRef)(0),d=w?w.slots.modal:C?document.body:null,O=e&&!!d;(0,k.useEffect)(()=>{if(!O)return;let S=T.current;if(!S)return;let E=document.activeElement instanceof HTMLElement?document.activeElement:null,j=()=>Array.from(S.querySelectorAll(ve)).filter(z=>!z.hasAttribute("disabled")&&z.getAttribute("aria-hidden")!=="true"),le=G.current?.querySelector(ve),st=D.current?.querySelector(ve);(le??st??j()[0]??S).focus({preventScroll:!0});let Ce=z=>{if(z.key!=="Tab")return;let Q=j();if(Q.length===0){z.preventDefault(),S.focus();return}let xe=Q[0],Se=Q[Q.length-1],Z=document.activeElement,Ne=Z instanceof Node&&S.contains(Z);z.shiftKey?(!Ne||Z===xe||Z===S)&&(z.preventDefault(),Se.focus()):(!Ne||Z===Se)&&(z.preventDefault(),xe.focus())};return document.addEventListener("keydown",Ce),()=>{document.removeEventListener("keydown",Ce),E&&E.isConnected&&E.focus({preventScroll:!0})}},[O]);let $=(0,k.useCallback)(S=>{if(!R.current)return;let E=S.target instanceof Node?S.target:null,j=!!E&&!!Y.current?.contains(E),le=(D.current?.scrollTop??0)<=0;!j&&!le||(B.current=S.touches[0].clientY,H.current=0)},[]),q=(0,k.useCallback)(S=>{if(B.current==null)return;let E=S.touches[0].clientY-B.current;if(E<0&&(D.current?.scrollTop??0)>0){B.current=null,T.current&&(T.current.style.transform="");return}H.current=E,E>0&&T.current&&(T.current.style.transform=`translateY(${E}px)`)},[]),X=(0,k.useCallback)(()=>{B.current!=null&&(T.current&&(T.current.style.transform=""),H.current>100&&R.current&&I.current(),B.current=null,H.current=0)},[]);if(!O)return null;let J=(0,x.jsx)("button",{type:"button",onClick:n,className:"relative h-10 w-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors before:absolute before:-inset-0.5 before:content-['']","aria-label":s,children:(0,x.jsx)(de,{className:"h-5 w-5"})}),M=(0,x.jsx)("button",{type:"button",onClick:n,className:"absolute right-2 top-2 z-10 h-9 w-9 flex items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm hover:bg-black/60 transition-colors before:absolute before:-inset-1 before:content-['']","aria-label":s,children:(0,x.jsx)(de,{className:"h-5 w-5"})});return(0,je.createPortal)((0,x.jsxs)("div",{className:_("pointer-events-auto fixed inset-0 flex items-end justify-center",g?"md:items-stretch md:justify-end":"md:items-center md:p-4",u,r),role:"dialog","aria-modal":"true","aria-label":t,children:[(0,x.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:o?n:void 0,"aria-hidden":"true"}),(0,x.jsxs)("div",{id:K,ref:T,tabIndex:-1,onTouchStart:$,onTouchMove:q,onTouchEnd:X,className:_("relative flex w-full flex-col overflow-hidden outline-none transition-transform duration-150 ease-out","max-h-[90dvh] rounded-t-[var(--site-radius-card)]",g?"animate-site-side-panel md:h-full md:max-h-full md:rounded-none md:rounded-l-[var(--site-radius-card)] md:border-y-0 md:border-r-0":"animate-site-sheet-up md:max-h-[80vh] md:rounded-[var(--site-radius-card)]",v==="glass"?"glass-card":"border border-zinc-200/50 bg-white shadow-2xl shadow-black/20 dark:border-zinc-700/50 dark:bg-zinc-900 dark:shadow-black/40","max-md:max-w-none",c),children:[(0,x.jsxs)("div",{ref:Y,className:"flex shrink-0 flex-col",children:[o&&(0,x.jsx)("button",{type:"button",onClick:n,className:"mx-auto mt-1.5 mb-0.5 flex h-4 w-14 shrink-0 items-center justify-center md:hidden","aria-label":s,children:(0,x.jsx)("span",{className:"h-1 w-full rounded-full bg-zinc-400 dark:bg-zinc-500"})}),l?(0,x.jsxs)("div",{className:"flex flex-shrink-0 items-center justify-between border-b border-zinc-200/50 px-4 py-2 dark:border-zinc-700/50",children:[A??(0,x.jsx)("h2",{className:"text-lg font-semibold text-zinc-900 dark:text-zinc-50",children:t}),A&&(0,x.jsx)("h2",{className:"sr-only",children:t}),o&&J]}):o&&M]}),P&&(0,x.jsx)("div",{ref:G,className:"shrink-0",children:P}),(0,x.jsx)("div",{ref:D,className:_("min-h-0 flex-1 overflow-y-auto overscroll-contain kano-scrollbar",l?"p-4":"p-0",L),children:i}),a&&(0,x.jsx)("div",{className:_("flex-shrink-0 border-t border-zinc-200/50 p-4 dark:border-zinc-700/50",y),children:a})]})]}),d)}var Xe=h(W());var b=h(W(),1);var re=h(N(),1),lt=Symbol.for("react.lazy"),oe=b[" use ".trim().toString()];function ct(e){return typeof e=="object"&&e!==null&&"then"in e}function Fe(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===lt&&"_payload"in e&&ct(e._payload)}function dt(e){let n=mt(e),t=b.forwardRef((s,i)=>{let{children:a,...l}=s;Fe(a)&&typeof oe=="function"&&(a=oe(a._payload));let o=b.Children.toArray(a),u=o.find(pt);if(u){let r=u.props.children,c=o.map(f=>f===u?b.Children.count(r)>1?b.Children.only(null):b.isValidElement(r)?r.props.children:null:f);return(0,re.jsx)(n,{...l,ref:i,children:b.isValidElement(r)?b.cloneElement(r,void 0,c):null})}return(0,re.jsx)(n,{...l,ref:i,children:a})});return t.displayName=`${e}.Slot`,t}var Ge=dt("Slot");function mt(e){let n=b.forwardRef((t,s)=>{let{children:i,...a}=t;if(Fe(i)&&typeof oe=="function"&&(i=oe(i._payload)),b.isValidElement(i)){let l=ht(i),o=gt(a,i.props);return i.type!==b.Fragment&&(o.ref=s?He(s,l):l),b.cloneElement(i,o)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${e}.SlotClone`,n}var ft=Symbol("radix.slottable");function pt(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ft}function gt(e,n){let t={...n};for(let s in n){let i=e[s],a=n[s];/^on[A-Z]/.test(s)?i&&a?t[s]=(...o)=>{let u=a(...o);return i(...o),u}:i&&(t[s]=i):s==="style"?t[s]={...i,...a}:s==="className"&&(t[s]=[i,a].filter(Boolean).join(" "))}return{...e,...t}}function ht(e){let n=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=n&&"isReactWarning"in n&&n.isReactWarning;return t?e.ref:(n=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=n&&"isReactWarning"in n&&n.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var Ye=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,qe=we,Ze=(e,n)=>t=>{var s;if(n?.variants==null)return qe(e,t?.class,t?.className);let{variants:i,defaultVariants:a}=n,l=Object.keys(i).map(r=>{let c=t?.[r],f=a?.[r];if(c===null)return null;let v=Ye(c)||Ye(f);return i[r][v]}),o=t&&Object.entries(t).reduce((r,c)=>{let[f,v]=c;return v===void 0||(r[f]=v),r},{}),u=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((r,c)=>{let{class:f,className:v,...A}=c;return Object.entries(A).every(P=>{let[L,y]=P;return Array.isArray(y)?y.includes({...a,...o}[L]):{...a,...o}[L]===y})?[...r,f,v]:r},[]);return qe(e,l,u,t?.class,t?.className)};var Qe=h(N()),vt=Ze("inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-200 hover:scale-[1.02] hover:shadow-md active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 disabled:hover:scale-100 disabled:hover:shadow-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-11 rounded-[var(--site-radius-button)] px-4 py-2",sm:"h-9 rounded-[var(--site-radius-button)] px-3",lg:"h-14 rounded-[var(--site-radius-button)] px-8",icon:"h-11 w-11 rounded-full"}},defaultVariants:{variant:"default",size:"default"}}),Je=Xe.forwardRef(({className:e,variant:n,size:t,asChild:s=!1,...i},a)=>(0,Qe.jsx)(s?Ge:"button",{className:_(vt({variant:n,size:t,className:e})),ref:a,...i}));Je.displayName="Button";var V=h(N()),yt=Pe(()=>import("./CustomerAccountPanel-DJKV7LT4.js").then(e=>e.CustomerAccountPanel),()=>(0,V.jsx)("div",{className:"flex min-h-40 items-center justify-center","aria-busy":"true",children:(0,V.jsx)(Re,{className:"h-5 w-5 animate-spin opacity-50"})}));function bt(){return typeof document>"u"?!1:document.cookie.split(";").some(e=>e.trim().startsWith(`${ge}=`))}function et(){typeof document>"u"||(document.cookie=`${ge}=; Max-Age=0; Path=/; SameSite=Lax`)}var ye=e=>`knr_customer_overview:${e}`;function tt(e){if(e===null)return"";let n=2166136261;for(let t=0;t<e.length;t+=1)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return(n>>>0).toString(36)}function Ct(e,n){try{let t=typeof sessionStorage>"u"?null:sessionStorage.getItem(ye(e));if(!t)return null;let s=JSON.parse(t);return!s||typeof s!="object"||!s.contact||s.session!==tt(n)?null:s}catch{return null}}function F(e,n,t){try{if(typeof sessionStorage>"u")return;if(n){let{id:s,email:i,name:a}=n.contact,l={session:tt(t),contact:{id:s,email:i,name:a},sections:n.sections,landing:n.landing};sessionStorage.setItem(ye(e),JSON.stringify(l))}else sessionStorage.removeItem(ye(e))}catch{}}var xt=[1e3,3e3,1e4],nt=(0,m.createContext)(null);function be({config:e,children:n}){let[t,s]=(0,m.useState)(null),[i,a]=(0,m.useState)([]),[l,o]=(0,m.useState)(null),[u,r]=(0,m.useState)("pending"),[c,f]=(0,m.useState)(!1),[v,A]=(0,m.useState)(!1),[P,L]=(0,m.useState)(0),y=(0,m.useMemo)(()=>e?.transport??he(),[e?.transport]),K=e?.sessionHint??bt,g=e?.siteId??null,w=e?.sessionKey??null,C=(0,m.useRef)(null),I=(0,m.useRef)(w);I.current=w;let R=(0,m.useCallback)(d=>{g&&F(g,d,I.current),s(d?.contact??null),a(d?.sections??[]),o(d?.landing??null),r("done"),d||L(O=>O+1)},[g]),T=(0,m.useCallback)(()=>{r("pending"),L(d=>d+1)},[]);(0,m.useEffect)(()=>{if(g===null)return;let d=C.current;if(C.current={siteId:g,sessionKey:w},!K()){F(g,null,w),f(!1),s(null),a([]),o(null),r("done");return}f(!0),(d===null||d.siteId!==g||d.sessionKey!==w)&&r("pending");let O=Ct(g,w);O?(s(O.contact),a(O.sections??[]),o(O.landing??null)):d!==null&&(d.siteId!==g||d.sessionKey!==null&&d.sessionKey!==w)&&(s(null),a([]),o(null));let $=!1,q=null,X=J=>{y.session().then(M=>{$||(F(g,M,w),M||et(),s(M?.contact??null),a(M?.sections??[]),o(M?.landing??null),r("done"))}).catch(()=>{if($)return;let M=xt[J];if(M!==void 0){q=setTimeout(()=>X(J+1),M);return}r(S=>S==="pending"?"failed":S)})};return X(0),()=>{$=!0,q!==null&&clearTimeout(q)}},[g,w,y,P]),(0,m.useEffect)(()=>{if(!e||typeof document>"u")return;let d=()=>{if(document.visibilityState!=="visible")return;let O=K();O&&t===null&&L($=>$+1),!O&&t!==null&&(F(e.siteId,null,w),s(null),a([]),o(null),r("done"))};return document.addEventListener("visibilitychange",d),window.addEventListener("focus",d),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("focus",d)}},[e,t]);let G=(0,m.useCallback)(async()=>{let d;try{d=await y.session()}catch{r("done");return}g&&F(g,d,I.current),s(d?.contact??null),a(d?.sections??[]),o(d?.landing??null),r("done")},[y,g]),D=(0,m.useCallback)(async()=>{await y.signOut(),g&&F(g,null,I.current),et(),s(null),a([]),o(null),r("done")},[y,g]),Y=(0,m.useCallback)(()=>A(!0),[]),B=(0,m.useCallback)(()=>A(!1),[]),H=(0,m.useMemo)(()=>e?{siteId:e.siteId,siteName:e.siteName,locale:e.locale,siteLocale:e.siteLocale,accountBaseUrl:e.accountBaseUrl,showNavEntry:e.showNavEntry,allowSignup:e.allowSignup,methods:e.methods,messages:e.messages,transport:y,user:t,sections:i,landing:l,checked:u!=="pending",pending:c&&u==="pending"&&t===null,sessionUnavailable:c&&u==="failed"&&t===null,retrySession:T,applySession:R,refresh:G,signOut:D,panelOpen:v,openPanel:Y,closePanel:B}:null,[e,y,t,i,l,u,c,R,T,G,D,v,Y,B]);return(0,V.jsxs)(nt.Provider,{value:H,children:[n,H?(0,V.jsx)(St,{auth:H}):null]})}function se(){return(0,m.useContext)(nt)}function St({auth:e}){let{ui:n}=Te(),t=e.user||e.pending?n.myAccount:ee(e.messages.signInTitle,{siteName:e.siteName});return(0,V.jsx)(We,{id:"customer-account-panel",open:e.panelOpen,onClose:e.closePanel,title:t,closeLabel:n.close,maxWidthClassName:"max-w-md",surface:"solid",bodyClassName:"p-5 sm:p-6",children:(0,V.jsx)(yt,{variant:"panel",auth:e,onNavigate:e.closePanel})})}var p=h(N(),1);function Nt(e){if(e?.startsWith("/"))return e;if(typeof window>"u")return;let n=new URL(window.location.href);for(let t of["token","handoff","error","verify","email"])n.searchParams.delete(t);return`${n.pathname}${n.search}`}function rt(e){return e instanceof te?{ok:!1,code:e.code??"SERVER_ERROR"}:{ok:!1,code:"NETWORK_ERROR"}}var ie=new Map;function lr(e){return ot(e,!1)}function ot(e,n){let t=e.siteUrl.replace(/\/+$/,""),s=me({siteUrl:t,token:e.token}),i=async(o,u)=>{try{return{ok:!0,...await s.post(o,{body:u})}}catch(r){return rt(r)}},a=async o=>{try{return{ok:!0,...await s.get(o,{})}}catch(u){return rt(u)}},l=o=>(o.ok&&o.sessionToken&&e.onToken(o.sessionToken),o);return{altchaChallengeUrl:`${t}/api/form-protection/altcha`,challengeUrl:`${t}/api/form-protection/challenge`,requestChallenge:({email:o,locale:u,returnTo:r,protection:c})=>i("/auth/challenge",{email:o,locale:u,returnTo:r,...c}),verifyCode:async({email:o,code:u})=>l(await i("/auth/verify",{method:"code",email:o,code:u,channel:"bearer"})),verifyToken:async({method:o,token:u})=>l(await i("/auth/verify",{method:o,token:u,channel:"bearer"})),startOauth:({method:o,returnTo:u,locale:r})=>i("/auth/oauth/start",{method:o,returnTo:u,locale:r}),passkeyLoginOptions:()=>i("/auth/passkey/options",{origin:typeof window>"u"?void 0:window.location.origin}),passkeyLoginVerify:async o=>l(await i("/auth/passkey/verify",{...o,channel:"bearer"})),listPasskeys:()=>a("/passkeys"),passkeyRegisterOptions:()=>i("/passkeys/register/options",{origin:typeof window>"u"?void 0:window.location.origin}),passkeyRegister:o=>i("/passkeys/register",o),session:()=>{let o=e.token();if(!o)return Promise.resolve(null);let u=`${t}
2
- ${o}`,r=ie.get(u),c=r??me({siteUrl:t,token:o}).get("/me").then(f=>{let v=f;if(!v.contact)return null;let{id:A,email:P,name:L}=v.contact;return{contact:{id:A,email:P,name:L},sections:v.sections??[],landing:v.landing??"/account"}},f=>{if(f instanceof te&&f.status===401)return null;throw f});return r||(ie.set(u,c),c.then(()=>ie.delete(u),()=>ie.delete(u))),n?c:c.catch(()=>null)},signOut:async()=>{try{await s.delete("/session",{body:{mode:"current"}})}catch{}e.onToken(null)}}}var ae=new Map;function kt(e,n){let t=`${e}|${n}`,s=ae.get(t);if(s)return s;if(!new URLSearchParams(window.location.search).has("code"))return null;let i={result:Le({siteUrl:e,clientId:n}),signedIn:!1};return ae.set(t,i),i.result.then(()=>ae.delete(t),()=>ae.delete(t)),i}function cr({siteName:e,mode:n="direct",redirectUri:t,returnTo:s,onLogin:i,onLogout:a,renderSignedIn:l,className:o,...u}){let r=Ie(u,{needsSite:!0}),c=r.site,[f,v]=(0,U.useState)({busy:!1,error:null}),A=c?.id??"",P=r.setToken;(0,U.useEffect)(()=>{if(n!=="redirect"||!A||typeof window>"u")return;let C=kt(r.siteUrl,A);if(!C)return;let I=!1;return v({busy:!0,error:null}),C.result.then(R=>{if(!I){if(R&&!C.signedIn){C.signedIn=!0,P(R.accessToken);let T={token:R.accessToken,contactId:R.contactId,expiresAt:R.expiresAt};i?.(T),window.dispatchEvent(new CustomEvent(ce,{detail:T}))}v({busy:!1,error:null})}}).catch(R=>{I||v({busy:!1,error:R instanceof te?R.code:"NETWORK_ERROR"})}),()=>{I=!0}},[n,A,r.siteUrl,P]);let[L]=(0,U.useState)(()=>{if(typeof window>"u")return{};let C=new URLSearchParams(window.location.search);return{email:C.get("email")??void 0,token:C.get("token")??void 0,handoff:C.get("handoff")??void 0,verify:C.get("verify")==="1",error:C.get("error")??void 0}}),y=At(r.token),K=(0,U.useMemo)(()=>ot({siteUrl:r.siteUrl,token:()=>y.current,onToken:C=>{y.current=C,P(C)}},!0),[r.siteUrl,P,y]),g=e??c?.brand?.displayName??c?.name??"",w=(0,U.useMemo)(()=>c&&r.messages?{siteId:c.id,siteName:g,locale:r.locale,siteLocale:c.locale??r.locale,accountBaseUrl:r.siteUrl,showNavEntry:c.customerAccess?.showNavEntry===!0,allowSignup:c.customerAccess?.allowSignup===!0,methods:Ue(c.customerAccess?.methods),messages:r.messages.account,transport:K,sessionHint:()=>!!y.current,sessionKey:r.token}:null,[c,r.messages,r.locale,r.siteUrl,r.token,g,K,y]);return r.messages?(0,p.jsx)(fe,{context:r,className:o,children:(0,p.jsx)(Me,{value:Be(c?.botProtection),children:(0,p.jsx)(be,{config:w,children:n==="redirect"?(0,p.jsx)(Rt,{siteUrl:r.siteUrl,siteId:A,siteName:g,redirectUri:t,busy:f.busy,error:f.error,messages:r.messages.account,onLogout:a,renderSignedIn:l}):(0,p.jsx)(wt,{returnTo:Nt(s),initial:L,onLogin:i,onLogout:a,renderSignedIn:l})})})}):(0,p.jsx)(fe,{context:r,className:o,loading:!0})}function Rt({siteUrl:e,siteId:n,siteName:t,redirectUri:s,busy:i,error:a,messages:l,onLogout:o,renderSignedIn:u}){let r=se(),[c,f]=(0,U.useState)(!1);if(!r)return(0,p.jsx)("div",{"aria-busy":"true"});if(r.user)return u?(0,p.jsx)(p.Fragment,{children:u(()=>{r.signOut().then(()=>ue(o))})}):(0,p.jsx)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:(0,p.jsx)(ne,{variant:"panel",auth:r,onSignedOut:()=>ue(o)})});let v=async()=>{if(n){f(!0);try{await Oe({siteUrl:e,clientId:n,redirectUri:s})}catch{f(!1)}}};return r.sessionUnavailable?(0,p.jsxs)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[(0,p.jsx)("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:l.errorServiceUnavailable}),(0,p.jsx)("button",{type:"button",className:pe({block:!0}),onClick:r.retrySession,children:l.contentRetry})]}):(0,p.jsxs)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[a?(0,p.jsx)("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:l.errorGeneric}):null,(0,p.jsx)("button",{type:"button",className:pe({block:!0}),onClick:()=>{v()},disabled:c||i||r.pending||!n,"aria-busy":i||r.pending||void 0,children:i||r.pending?l.sessionChecking:ee(l.signInTitle,{siteName:t})})]})}function wt({returnTo:e,initial:n,onLogin:t,onLogout:s,renderSignedIn:i}){let a=se();return a?a.user&&i?(0,p.jsx)(p.Fragment,{children:i(()=>{a.signOut().then(()=>ue(s))})}):(0,p.jsx)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:(0,p.jsx)(ne,{variant:"panel",auth:a,initial:n,returnTo:e,onSignedIn:l=>{if(!l.sessionToken)return;let o={token:l.sessionToken,contactId:l.contactId??"",expiresAt:l.expiresAt??""};t?.(o),window.dispatchEvent(new CustomEvent(ce,{detail:o}))},onSignedOut:()=>ue(s)})}):(0,p.jsx)("div",{"aria-busy":"true"})}function ue(e){e?.(),window.dispatchEvent(new CustomEvent(ke))}function At(e){let n=(0,U.useState)(()=>({current:e}))[0];return(0,U.useEffect)(()=>{n.current=e},[n,e]),n.current=e,n}export{lr as a,cr as b};
3
- //# sourceMappingURL=chunk-FSY5GB5E.js.map
@@ -1,2 +0,0 @@
1
- import{FORM_ACCENT_ICON,FORM_DANGER,FORM_FG,FORM_FG_MUTED,FORM_FIELD_CLASS,FORM_FIELD_INVALID_CLASS,FORM_SUBMIT_COLORS}from"./chunk-SVWEVSYJ.js";import{NO_HEAVY_FIELD_VALIDATORS,OTHER_OPTION_PLACEHOLDER,countAnswered,hasVisibilityRules,resolveFormPhoneCountry,resolveVisibleFieldIds,sanitizeFormSubmitResponse,validateFormAnswerWith,validateFormAnswersWith}from"./chunk-4BBERZ6T.js";import{isKnownFormFieldType,parseFormRedirectUrl,resolveConsentLabel,resolveFormAvailability,resolveFormDateBound}from"./chunk-66XN5RR4.js";import{onDemand}from"./chunk-E77WGXYW.js";import{useAdoptTypedOnMount,useComposingEnterGuard,useControlRef}from"./chunk-C7HUM2EN.js";import{FORM_SUBMIT_EVENT}from"./chunk-LWKCGUHS.js";import{BotProtectionChallenge,BotProtectionConfigProvider,BotProtectionFields,parsePublicBotProtectionConfig,useBotProtection}from"./chunk-IXDKZO42.js";import{TONE_BG_TINT,TONE_BG_TINT_STRONG_HOVER,TONE_BORDER_STRONG,TONE_TEXT_FAINT}from"./chunk-RKEHHJDU.js";import{EMPTY_VALUE,dateTimeFormat}from"./chunk-4BEKWYEW.js";import{clampText}from"./chunk-O2SYHUQF.js";import{CircleCheck,Heart,LoaderCircle,Star,ThumbsUp}from"./chunk-33AQQY6T.js";import{cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-4MOCTNN7.js";import{loadSiteMeta,useElementContext}from"./chunk-MIQK3T3Y.js";import{useEffect as useEffect2,useState as useState2}from"react";import{useCallback,useContext as useContext2,useEffect,useId,useMemo,useRef as useRef2,useState}from"react";import{useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";function SiteChoiceInput({type,className,...props}){const inputRef=useRef(null);useAdoptTypedOnMount(inputRef,props.onChange);return jsxs("span",{className:cn("relative inline-grid h-[18px] w-[18px] shrink-0 place-items-center",className),children:[jsx("input",{ref:inputRef,type,className:cn("peer col-start-1 row-start-1 m-0 h-[18px] w-[18px] cursor-pointer appearance-none border-2 transition-colors","bg-transparent "+TONE_BORDER_STRONG,"checked:border-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))] checked:bg-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))]","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]","disabled:cursor-not-allowed disabled:opacity-50",type==="radio"?"rounded-full":"rounded-[4px]"),...props}),type==="checkbox"?jsx("svg",{"aria-hidden":true,viewBox:"0 0 16 16",fill:"none",className:"pointer-events-none col-start-1 row-start-1 h-3.5 w-3.5 text-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50",children:jsx("path",{d:"M3.5 8.5l3 3 6-6.5",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})}):jsx("span",{"aria-hidden":true,className:"pointer-events-none col-start-1 row-start-1 h-2 w-2 rounded-full bg-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50"})]})}var DATE_PRESETS={date:{dateStyle:"medium"},dateLong:{dateStyle:"long"},dateTime:{dateStyle:"medium",timeStyle:"short"},dateTimeFull:{dateStyle:"full",timeStyle:"short"},time:{timeStyle:"short"},monthDay:{month:"short",day:"numeric"},monthDayTime:{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"},monthYear:{year:"numeric",month:"long"},dateWithZone:{year:"numeric",month:"long",day:"numeric",timeZoneName:"short"}};var CALENDAR_DATE=/^\d{4}-\d{2}-\d{2}$/;function isCalendarDate(value){return typeof value==="string"&&CALENDAR_DATE.test(value)}function toDate(value){if(value==null||value==="")return null;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?null:date}function formatCalendarDate(value,preset="date",options){if(!isCalendarDate(value))return EMPTY_VALUE;const date=new Date(`${value}T00:00:00Z`);if(Number.isNaN(date.getTime()))return EMPTY_VALUE;return dateTimeFormat(options.locale,{...DATE_PRESETS[preset],timeZone:"UTC"}).format(date)}function toCalendarDateIn(value,timeZone){const date=toDate(value);if(!date)return"";return dateTimeFormat("en-CA",{year:"numeric",month:"2-digit",day:"2-digit",timeZone}).format(date)}var MINUTE=6e4;var HOUR=60*MINUTE;var DAY=24*HOUR;var loaded={...NO_HEAVY_FIELD_VALIDATORS};var pending=new Map;var LOADERS={phone:()=>import("./forms-answers-phone-2VZ46OME.js").then(m=>void(loaded.phone=m.validatePhoneAnswer)),address:()=>import("./forms-answers-address-7P6EVFY5.js").then(m=>void(loaded.address=m.validateAddressAnswer)),tax_id:()=>import("./forms-answers-tax-id-WJD7K3PG.js").then(m=>void(loaded.tax_id=m.validateTaxIdAnswer))};function isHeavyFieldType(type){return Object.hasOwn(LOADERS,type)}function loadedFormFieldValidators(){return loaded}function canValidateFormField(type){return!isHeavyFieldType(type)||loaded[type]!==null}function hasFormFieldValidators(types){for(const type of types)if(!canValidateFormField(type))return false;return true}function loadFormFieldValidators(types){const waits=[];for(const type of new Set(types)){if(!isHeavyFieldType(type)||loaded[type])continue;let wait=pending.get(type);if(!wait){wait=LOADERS[type]().finally(()=>pending.delete(type));pending.set(type,wait)}waits.push(wait)}return Promise.all(waits).then(()=>loaded)}var PAGEVIEW_ATTRIBUTION_PARAMS=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gclid","fbclid","oppref"];var MAX_ATTRIBUTION_VALUE_LENGTH=200;var ATTRIBUTION_VALUE_ALLOWED=/[^\p{L}\p{N} _\-./:+%()&=|]/gu;function sanitizePageviewAttribution(read){const utm={};for(const key of PAGEVIEW_ATTRIBUTION_PARAMS){const raw=read(key);if(typeof raw!=="string"||!raw)continue;const val=clampText(raw.replace(ATTRIBUTION_VALUE_ALLOWED,"").trim(),MAX_ATTRIBUTION_VALUE_LENGTH);if(val)utm[key]=val}return Object.keys(utm).length>0?utm:null}var HOST_RE=/^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/;var LANDING_PATH_MAX=500;function sanitizeHost(raw){if(typeof raw!=="string")return void 0;const host=raw.trim().toLowerCase();return HOST_RE.test(host)?host:void 0}function sanitizeLandingPath(raw){if(typeof raw!=="string")return void 0;const path=raw.trim().split(/[?#]/)[0]??"";if(!path.startsWith("/")||path.startsWith("//")||/[\s\\\0]/.test(path))return void 0;return path.slice(0,LANDING_PATH_MAX)}function sanitizeFormAttribution(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;const input=raw;const utmInput=input.utm&&typeof input.utm==="object"&&!Array.isArray(input.utm)?input.utm:{};const utm=sanitizePageviewAttribution(key=>utmInput[key]);const referrerHost=sanitizeHost(input.referrerHost);const landingPath=sanitizeLandingPath(input.landingPath);const out={};if(utm)out.utm=utm;if(referrerHost)out.referrerHost=referrerHost;if(landingPath)out.landingPath=landingPath;return Object.keys(out).length>0?out:null}function buildFormAttribution(input){let utm=null;try{const params=new URLSearchParams(input.search??"");utm=sanitizePageviewAttribution(key=>params.get(key))}catch{utm=null}let referrerHost;try{referrerHost=input.referrer?new URL(input.referrer).hostname:void 0}catch{referrerHost=void 0}return sanitizeFormAttribution({utm:utm??void 0,referrerHost,landingPath:input.path??void 0})}var SESSION_ATTRIBUTION_KEY="kano-session-attribution";function readSessionAttribution(){if(typeof window==="undefined")return null;try{const raw=window.sessionStorage.getItem(SESSION_ATTRIBUTION_KEY);return raw?sanitizeFormAttribution(JSON.parse(raw)):null}catch{return null}}function currentFormAttribution(){if(typeof window==="undefined")return null;const stored=readSessionAttribution();if(stored)return stored;let referrer=null;try{referrer=document.referrer&&new URL(document.referrer).hostname.toLowerCase()!==window.location.hostname.toLowerCase()?document.referrer:null}catch{referrer=null}return buildFormAttribution({search:window.location.search,referrer,path:window.location.pathname})}var MAX_COLUMNS_FALLBACK={mobile:1,tablet:2,desktop:2};var GRID_COLS={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6"};var SM_GRID_COLS={1:"sm:grid-cols-1",2:"sm:grid-cols-2",3:"sm:grid-cols-3",4:"sm:grid-cols-4",5:"sm:grid-cols-5",6:"sm:grid-cols-6"};var MD_GRID_COLS={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4",5:"md:grid-cols-5",6:"md:grid-cols-6"};function clampColumn(value){const n=Math.max(1,Math.min(6,Math.round(value)));return n}function getGridColumnsClass(maxColumns,itemCount){const resolve=raw=>{const capped=clampColumn(raw);if(itemCount==null)return capped;return clampColumn(Math.min(capped,Math.max(1,itemCount)))};const mobile=resolve(maxColumns?.mobile??MAX_COLUMNS_FALLBACK.mobile);const tablet=resolve(maxColumns?.tablet??MAX_COLUMNS_FALLBACK.tablet);const desktop=resolve(maxColumns?.desktop??MAX_COLUMNS_FALLBACK.desktop);return`${GRID_COLS[mobile]} ${SM_GRID_COLS[tablet]} ${MD_GRID_COLS[desktop]}`}import{createContext}from"react";var FormFieldComponentsContext=createContext(null);var FormFieldUnavailableLabelContext=createContext("");import{useContext}from"react";import{jsx as jsx2,jsxs as jsxs2}from"react/jsx-runtime";function FieldLoading({failed,props}){const unavailableLabel=useContext(FormFieldUnavailableLabelContext);const{inputId}=props;return jsxs2("div",{children:[jsx2("div",{id:inputId,tabIndex:inputId?-1:void 0,className:cn("h-11 w-full",FORM_FIELD_CLASS),"aria-busy":failed?void 0:"true","data-field-unavailable":failed?"":void 0}),failed&&unavailableLabel&&jsx2("p",{role:"alert",className:cn("mt-1.5 text-xs",FORM_DANGER),children:unavailableLabel})]})}var ON_DEMAND_FORM_FIELDS={PhoneInput:onDemand(()=>import("./phone-input-Q5AV6KSW.js").then(m=>m.PhoneInput),FieldLoading),FormAddressField:onDemand(()=>import("./FormAddressField-QR7ZCH77.js").then(m=>m.FormAddressField),FieldLoading),FormTaxIdField:onDemand(()=>import("./FormTaxIdField-XMK5WRQO.js").then(m=>m.FormTaxIdField),FieldLoading),FormFileField:onDemand(()=>import("./FormFileField-LZDCXI2Z.js").then(m=>m.FormFileField),FieldLoading),FormChoiceDropdown:onDemand(()=>import("./FormChoiceDropdown-U3NIOOHG.js").then(m=>m.FormChoiceDropdown),FieldLoading)};var FORM_LIFECYCLE_EVENT="kanorio:form-event";import{forwardRef}from"react";import{jsx as jsx3}from"react/jsx-runtime";var NativeInput=forwardRef(function NativeInput2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("input",{...ime.props,...props,ref:setRef})});var NativeTextarea=forwardRef(function NativeTextarea2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("textarea",{...ime.props,...props,ref:setRef})});import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";var VALIDATOR_WAIT_MS=4e3;var DEFAULT_LABELS={submit:"Submit",submitting:"Submitting\u2026",success:"Thanks! We\u2019ll be in touch soon.",error:"Something went wrong. Please try again.",required:"This field is required.",invalidEmail:"Please enter a valid email address.",invalidPhone:"Please enter a valid phone number.",invalidDate:"Please enter a valid date.",invalidTime:"Please enter a valid time.",tooLong:"This answer is too long.",otherRequired:"Please specify your answer.",duplicate:"This email or phone number has already been used. Only one response per person is allowed.",temporarilyUnavailable:"This form isn\u2019t accepting responses right now. Please try again later.",rateLimited:"Too many submissions. Please wait a moment and try again.",verificationExpired:"Verification expired. Please verify again and resubmit.",outdated:"This form has changed since you opened it. Please refresh the page and submit again.",tooLarge:"Your answers are too long to send. Please shorten them and try again.",redirecting:"Taking you to the next page\u2026",invalid:"Please check this answer.",tooShort:"Please enter at least {min} characters.",invalidNumber:"Please enter a number.",notInteger:"Please enter a whole number.",numberMin:"Please enter {min} or more.",numberMax:"Please enter {max} or less.",numberRange:"Please enter a number from {min} to {max}.",invalidUrl:"Please enter a web address, such as example.com.",dateMin:"Please choose {min} or later.",dateMax:"Please choose {max} or earlier.",dateRange:"Please choose a date from {min} to {max}.",tooFewOptions:"Please select {min} or more.",tooManyOptions:"Please select no more than {max}.",selectPlaceholder:"Select an option",invalidAddress:"Please complete the address.",invalidTaxId:"Please check this tax ID.",taxIdChecking:"Looking up the public registry\u2026",taxIdRegisteredName:"Registered name: {name}",taxIdInactive:"The registry shows this business as suspended or closed. Please check the tax ID.",taxIdSource:"Source: {provider}",invalidPostalCode:"Please check the postal code.",addressCountry:"Country or region",addressRecipient:"Recipient name",addressLine1:"Address",addressLine2:"Apartment, suite, etc. (optional)",addressPostal_postal:"Postal code",addressPostal_zip:"ZIP code",addressPostal_pin:"PIN code",addressPostal_eircode:"Eircode",addressLocality_city:"City",addressLocality_district:"District",addressLocality_post_town:"Town or city",addressLocality_suburb:"Suburb",addressRegion_area:"Area",addressRegion_county:"County",addressRegion_department:"Department",addressRegion_district:"District",addressRegion_do_si:"Province or city",addressRegion_emirate:"Emirate",addressRegion_island:"Island",addressRegion_oblast:"Oblast",addressRegion_parish:"Parish",addressRegion_prefecture:"Prefecture",addressRegion_province:"Province",addressRegion_state:"State",marketingOptIn:"I\u2019d like to receive news and offers from {siteName} by email. I can unsubscribe from any email with one click.",subscribeOnSubmit:"By clicking \u201C{button}\u201D, you agree to receive news and offers from {siteName} by email. You can unsubscribe from any email with one click.",otherOption:"Other",otherPlaceholder:"Please specify",closed:"This form is closed.",notOpenYet:"This form isn\u2019t open yet.",full:"All spots have been filled. Thank you for your interest.",fileChoose:"Choose a file",fileLimitHint:"Up to {max} file(s), {size} each.",fileWaiting:"Waiting for verification\u2026",fileUploading:"Uploading\u2026",fileUploadFailed:"Upload failed. Please try again.",fileTooLarge:"This file is too large.",fileTypeNotAllowed:"This file type isn\u2019t supported.",fileUnavailable:"Attachments can\u2019t be uploaded right now. You can still submit the form.",fileRemove:"Remove",noFormSelected:"Select a form in the panel to display it here.",formNotFound:"The selected form no longer exists.",previewNotice:"Preview only \u2014 submissions are disabled here."};function fill(template,values){return template.replaceAll("{min}",String(values.min??"")).replaceAll("{max}",String(values.max??""))}function errorLabel(code,field,{labels,today,locale}){switch(code){case"invalid_email":return labels.invalidEmail;case"invalid_phone":return labels.invalidPhone;case"invalid_date":return labels.invalidDate;case"invalid_time":return labels.invalidTime;case"too_long":return labels.tooLong;case"too_short":return(field.type==="short_text"||field.type==="long_text")&&field.minLength!==void 0?fill(labels.tooShort,{min:field.minLength}):labels.invalid;case"invalid_format":return field.type==="short_text"&&field.patternMessage?field.patternMessage:labels.invalid;case"other_required":return labels.otherRequired;case"too_few_options":return field.type==="choice"&&field.minSelections!==void 0?fill(labels.tooFewOptions,{min:field.minSelections}):labels.invalid;case"too_many_options":return field.type==="choice"&&field.maxSelections!==void 0?fill(labels.tooManyOptions,{max:field.maxSelections}):labels.invalid;case"invalid_number":return labels.invalidNumber;case"not_integer":return labels.notInteger;case"out_of_range":{if(field.type!=="number")return labels.invalid;const{min,max}=field;if(min!==void 0&&max!==void 0)return fill(labels.numberRange,{min,max});if(min!==void 0)return fill(labels.numberMin,{min});if(max!==void 0)return fill(labels.numberMax,{max});return labels.invalid}case"invalid_url":return labels.invalidUrl;case"date_out_of_range":{if(field.type!=="date")return labels.invalid;const min=resolveFormDateBound(field.range?.min,today);const max=resolveFormDateBound(field.range?.max,today);const show=date=>formatCalendarDate(date,"date",{locale});if(min&&max)return fill(labels.dateRange,{min:show(min),max:show(max)});if(min)return fill(labels.dateMin,{min:show(min)});if(max)return fill(labels.dateMax,{max:show(max)});return labels.invalid}case"invalid_address":return labels.invalidAddress;case"invalid_tax_id":return labels.invalidTaxId;case"invalid_postal_code":return labels.invalidPostalCode;case"invalid":return labels.invalid;case"required":case"invalid_option":return labels.required}}function todayIn(timeZone){const now=new Date;if(timeZone){try{const date=toCalendarDateIn(now,timeZone);if(date)return date}catch{}}const pad=n=>String(n).padStart(2,"0");return`${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`}function submitErrorLabel(error,labels){switch(error){case"outdated":return labels.outdated;case"duplicate":return labels.duplicate;case"daily_limit":case"temporarily_unavailable":return labels.temporarilyUnavailable;case"rate_limited":return labels.rateLimited;case"verification_expired":return labels.verificationExpired;case"too_large":return labels.tooLarge;case"invalid_answers":case"server_error":return labels.error}}function shouldSpanFullRow(field){return field.type==="long_text"||field.type==="file"||field.type==="statement"||field.type==="address"}function onGroupBlur(onBlur){return e=>{if(e.relatedTarget&&e.currentTarget.contains(e.relatedTarget))return;onBlur()}}function dispatchLifecycle(detail){if(typeof window==="undefined")return;window.dispatchEvent(new CustomEvent(FORM_LIFECYCLE_EVENT,{detail}))}var INPUT_CLASS=cn("w-full py-2.5",FORM_FIELD_CLASS);function FormWidget({form,maxColumns,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect=true,hiddenValues:hiddenValuesProp,isEditing=false,labels:labelsProp,locale,websiteName}){const labels=useMemo(()=>({...DEFAULT_LABELS,...labelsProp}),[labelsProp]);const fields=useMemo(()=>form.fields.filter(field=>isKnownFormFieldType(field.type)),[form.fields]);const consentLabel=resolveConsentLabel(form.settings,labels,websiteName);const canSubmit=Boolean(submitUrl)&&!isEditing;const[serverState,setServerState]=useState(null);const availability=serverState??resolveFormAvailability(form);const isClosed=availability!=="open";const[answers,setAnswers]=useState({});const[otherText,setOtherText]=useState({});const[uploadUnavailable,setUploadUnavailable]=useState({});const[uploadBusy,setUploadBusy]=useState({});const anyUploadBusy=Object.values(uploadBusy).some(Boolean);const consentMode=form.settings.marketingConsent;const[marketingOptIn,setMarketingOptIn]=useState(false);const[errors,setErrors]=useState({});const[submitError,setSubmitError]=useState(null);const[status,setStatus]=useState("idle");const[altchaKey,setAltchaKey]=useState(0);const[redirecting,setRedirecting]=useState(false);const hiddenFields=useMemo(()=>form.settings.hiddenFields??[],[form.settings.hiddenFields]);const[urlHiddenValues,setUrlHiddenValues]=useState({});useEffect(()=>{if(hiddenFields.length===0||typeof window==="undefined")return;const params=new URLSearchParams(window.location.search);const next={};for(const hidden of hiddenFields){const value=params.get(hidden.id);if(value)next[hidden.id]=value}setUrlHiddenValues(next)},[hiddenFields]);const hiddenValues=useMemo(()=>({...urlHiddenValues,...hiddenValuesProp??{}}),[urlHiddenValues,hiddenValuesProp]);const hasRules=useMemo(()=>hasVisibilityRules(fields),[fields]);const visibleFields=useMemo(()=>{if(!hasRules)return fields;const visible=resolveVisibleFieldIds(fields,{...hiddenValues,...answers});return fields.filter(field=>visible.has(field.id))},[hasRules,fields,hiddenValues,answers]);const startedRef=useRef2(false);const viewedRef=useRef2(false);const rootRef=useRef2(null);const fieldIdPrefix=`form-${useId().replace(/[^A-Za-z0-9_-]/g,"")}-field`;const protection=useBotProtection({variant:"full",context:form.id,entry:"forms",needsUploadToken:fields.some(field=>field.type==="file"||field.type==="tax_id"),...challengeUrl?{challengeUrl}:{},...altchaChallengeUrl?{altchaChallengeUrl}:{}});const uploadUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/upload-request"):null;const taxIdLookupUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/tax-id-lookup"):null;const taxIdLookupReady=Boolean(taxIdLookupUrl)&&protection.isUploadReady;const getUploadProtectionData=protection.getUploadProtectionData;const lookupTaxId=useCallback(async(fieldId,input)=>{if(!taxIdLookupUrl)return null;try{const res=await fetch(taxIdLookupUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fieldId,...input,...getUploadProtectionData()})});if(!res.ok)return null;const data=await res.json();if(!data||data.ok===false||typeof data.status!=="string")return null;return{...data,ok:true}}catch{return null}},[taxIdLookupUrl,getUploadProtectionData]);useEffect(()=>{if(!canSubmit||viewedRef.current||!rootRef.current)return;const el=rootRef.current;if(typeof IntersectionObserver==="undefined"){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId:form.id});return}const io=new IntersectionObserver(entries=>{if(entries.some(e=>e.isIntersecting)&&!viewedRef.current){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId:form.id});io.disconnect()}},{threshold:.3});io.observe(el);return()=>io.disconnect()},[canSubmit,form.id]);const lastFieldRef=useRef2(null);const abandonRef=useRef2({status,visibleFields,answers});useEffect(()=>{abandonRef.current={status,visibleFields,answers}},[status,visibleFields,answers]);useEffect(()=>{if(!canSubmit||typeof window==="undefined")return;let sent=false;const onPageHide=()=>{const latest=abandonRef.current;if(sent||!startedRef.current||latest.status==="success")return;sent=true;dispatchLifecycle({type:"form_abandon",formId:form.id,lastFieldId:lastFieldRef.current,answeredCount:countAnswered(latest.visibleFields,latest.answers)})};window.addEventListener("pagehide",onPageHide);return()=>window.removeEventListener("pagehide",onPageHide)},[canSubmit,form.id]);const markStarted=useCallback(()=>{protection.registerFocus();if(startedRef.current||!canSubmit)return;startedRef.current=true;dispatchLifecycle({type:"form_start",formId:form.id})},[protection,canSubmit,form.id]);const clearError=useCallback(id=>{setErrors(prev=>{if(!prev[id])return prev;const next={...prev};delete next[id];return next})},[]);const setAnswer=useCallback((id,value)=>{lastFieldRef.current=id;setAnswers(prev=>({...prev,[id]:value}));clearError(id);setSubmitError(null)},[clearError]);const[today,setToday]=useState(null);useEffect(()=>{setToday(todayIn(form.timezone))},[form.timezone]);const fieldTypes=useMemo(()=>Array.from(new Set(fields.map(field=>field.type))),[fields]);useEffect(()=>{loadFormFieldValidators(fieldTypes).catch(()=>void 0)},[fieldTypes]);const[preparing,setPreparing]=useState(false);const preparingRef=useRef2(false);const validationCtx=useMemo(()=>({defaultPhoneCountry:form.defaultPhoneCountry,fileRequired:{exempt:Object.keys(uploadUnavailable).filter(id=>uploadUnavailable[id])},today}),[form.defaultPhoneCountry,uploadUnavailable,today]);const errorCtx=useMemo(()=>({labels,today:today??todayIn(form.timezone),locale:locale||(typeof navigator!=="undefined"?navigator.language:"en")}),[labels,today,form.timezone,locale]);const validateOne=useCallback(field=>{if(!canValidateFormField(field.type))return;const code=validateFormAnswerWith(loadedFormFieldValidators(),field,{answers,otherText},validationCtx);if(code&&code!=="required")setErrors(prev=>({...prev,[field.id]:code}));else clearError(field.id)},[answers,otherText,validationCtx,clearError]);const focusFirstError=useCallback(errorIds=>{const first=visibleFields.find(f=>errorIds.includes(f.id));if(!first||!rootRef.current)return;const el=rootRef.current.querySelector(`#${CSS.escape(`${fieldIdPrefix}-${first.id}`)}`);el?.scrollIntoView({behavior:"smooth",block:"center"});el?.focus({preventScroll:true})},[visibleFields,fieldIdPrefix]);const submitAnswers=useCallback(async validators=>{if(!canSubmit||status==="submitting"||isClosed||anyUploadBusy)return;const validated=validateFormAnswersWith(validators,fields,{answers:{...hiddenValues,...answers},otherText},{...validationCtx,hiddenFields});if(!validated.ok){setErrors(validated.errors);focusFirstError(Object.keys(validated.errors));return}setStatus("submitting");setSubmitError(null);try{await protection.prepare();const res=await fetch(submitUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:validated.answers,...consentMode==="submit"?{consent:"submit_statement",consentTextId:form.consentTextId}:consentMode==="checkbox"&&marketingOptIn?{consent:"checked",consentTextId:form.consentTextId}:{},locale:typeof navigator!=="undefined"?navigator.language:void 0,pagePath:typeof window!=="undefined"?window.location.pathname:void 0,attribution:currentFormAttribution()??void 0,...protection.getProtectionData()})});const data=sanitizeFormSubmitResponse(res.status===429?{ok:false,error:"rate_limited"}:res.status===503?{ok:false,error:"temporarily_unavailable"}:await res.json().catch(()=>null));setStatus("idle");if(!data.ok||data.state){protection.renewCaptcha()}if(data.ok){if(data.state){setServerState(data.state);return}setStatus("success");const redirectUrl=data.redirectUrl??parseFormRedirectUrl(form.redirectUrl)?.url;onSuccess?.({formId:form.id,...redirectUrl?{redirectUrl}:{},...data.submissionId?{submissionId:data.submissionId}:{}});if(redirectUrl&&followRedirect){setRedirecting(true);window.location.assign(redirectUrl)}return}const errorIds=data.error==="invalid_answers"&&data.errors?Object.keys(data.errors):[];const renderedIds=new Set(visibleFields.map(f=>f.id));setSubmitError(errorIds.some(id=>!renderedIds.has(id))?"outdated":data.error);if(errorIds.length>0){setErrors(data.errors);focusFirstError(errorIds)}if(data.error==="verification_expired")setAltchaKey(k=>k+1)}catch{setStatus("idle");setSubmitError("server_error");protection.renewCaptcha()}},[canSubmit,status,isClosed,anyUploadBusy,answers,otherText,validationCtx,focusFirstError,fields,visibleFields,hiddenFields,hiddenValues,form.id,form.redirectUrl,followRedirect,form.consentTextId,submitUrl,consentMode,marketingOptIn,protection,onSuccess]);const submitAnswersRef=useRef2(submitAnswers);useEffect(()=>{submitAnswersRef.current=submitAnswers},[submitAnswers]);const handleSubmit=useCallback(async e=>{e.preventDefault();if(!canSubmit||status==="submitting"||isClosed||anyUploadBusy||preparingRef.current)return;if(hasFormFieldValidators(fieldTypes))return submitAnswers(loadedFormFieldValidators());preparingRef.current=true;setPreparing(true);let timer;try{await Promise.race([loadFormFieldValidators(fieldTypes),new Promise(resolve=>timer=setTimeout(resolve,VALIDATOR_WAIT_MS))])}catch{}finally{clearTimeout(timer);preparingRef.current=false;setPreparing(false)}await submitAnswersRef.current(loadedFormFieldValidators())},[canSubmit,status,isClosed,anyUploadBusy,fieldTypes,submitAnswers]);const autofilledRef=useRef2({});const fillCompanyName=useCallback((targetId,name)=>{setAnswers(prev=>{const currentValue=prev[targetId];const text=typeof currentValue==="string"?currentValue:"";if(text.trim()!==""&&text!==autofilledRef.current[targetId])return prev;autofilledRef.current[targetId]=name;return{...prev,[targetId]:name}})},[]);const setUnavailable=useCallback((id,unavailable)=>{setUploadUnavailable(prev=>prev[id]===unavailable?prev:{...prev,[id]:unavailable})},[]);const setBusy=useCallback((id,busy)=>{setUploadBusy(prev=>prev[id]===busy?prev:{...prev,[id]:busy})},[]);const gridClass=getGridColumnsClass(maxColumns,visibleFields.length);const isPreview=isEditing&&submitUrl===void 0;return jsx4(FormFieldUnavailableLabelContext.Provider,{value:labels.error,children:jsx4("div",{ref:rootRef,className:"w-full min-w-0",children:isClosed?jsx4("p",{className:cn("rounded-lg px-4 py-6 text-center text-sm",TONE_BG_TINT,FORM_FG_MUTED),children:availability==="not_open"?labels.notOpenYet:availability==="full"?labels.full:labels.closed}):status==="success"?jsxs3("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[jsx4(CircleCheck,{className:cn("h-10 w-10",FORM_ACCENT_ICON)}),jsx4("p",{className:cn("whitespace-pre-wrap text-base",FORM_FG),children:form.settings.successMessage||labels.success}),redirecting&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:labels.redirecting})]}):jsxs3("form",{onSubmit:handleSubmit,noValidate:true,className:cn("grid gap-x-8 gap-y-7",gridClass),children:[jsx4(BotProtectionFields,{...protection.fieldProps,renderAltcha:false}),visibleFields.map(field=>jsx4(FieldRow,{idPrefix:fieldIdPrefix,className:shouldSpanFullRow(field)?"col-span-full":void 0,field,value:answers[field.id]??null,otherText:otherText[field.id]??"",onOtherTextChange:v=>{setOtherText(p=>({...p,[field.id]:v}));clearError(field.id)},error:errors[field.id]?errorLabel(errors[field.id],field,errorCtx):void 0,labels,today,phoneCountry:field.type==="phone"?resolveFormPhoneCountry(field,form.defaultPhoneCountry):null,siteCountry:form.defaultPhoneCountry??null,onChange:v=>setAnswer(field.id,v),onFocus:()=>{lastFieldRef.current=field.id;markStarted()},onBlur:()=>validateOne(field),upload:{url:uploadUrl,ready:protection.isUploadReady,getProtectionData:protection.getUploadProtectionData,onUnavailableChange:u=>setUnavailable(field.id,u),onBusyChange:b=>setBusy(field.id,b)},taxId:field.type==="tax_id"?{lookup:taxIdLookupReady?input=>lookupTaxId(field.id,input):void 0,onRegistryName:field.companyNameFieldId?name=>fillCompanyName(field.companyNameFieldId,name):void 0}:void 0},field.id)),consentMode==="checkbox"&&jsxs3("label",{className:cn("col-span-full flex cursor-pointer items-start gap-2.5 pt-1 text-sm",FORM_FG),children:[jsx4(SiteChoiceInput,{type:"checkbox",className:"mt-0.5",checked:marketingOptIn,onFocus:markStarted,onChange:e=>setMarketingOptIn(e.target.checked)}),jsx4("span",{children:consentLabel})]}),jsx4(BotProtectionChallenge,{...protection.challengeProps,locale,className:"col-span-full sm:max-w-sm"},altchaKey),submitError&&jsx4("p",{role:"alert",className:cn("col-span-full text-sm",FORM_DANGER),children:submitErrorLabel(submitError,labels)}),jsxs3("div",{className:"col-span-full flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4",children:[jsxs3("button",{type:"submit",disabled:!canSubmit||status==="submitting"||preparing||!protection.isSubmittable||anyUploadBusy,className:cn("inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-lg px-5 py-2.5 text-[15px] font-medium transition sm:w-auto",FORM_SUBMIT_COLORS,"shadow-md hover:brightness-110 hover:shadow-lg","disabled:cursor-not-allowed disabled:opacity-60"),children:[(status==="submitting"||preparing)&&jsx4(LoaderCircle,{className:"h-4 w-4 animate-spin"}),status==="submitting"||preparing?labels.submitting:form.settings.submitLabel||labels.submit]}),isPreview&&jsx4("p",{className:cn("text-xs",FORM_FG_MUTED),children:labels.previewNotice})]}),consentMode==="submit"&&jsx4("p",{className:cn("col-span-full -mt-4 text-xs leading-relaxed",FORM_FG_MUTED),children:consentLabel})]})})})}function FieldRow({field,idPrefix,className,value,otherText,onOtherTextChange,error,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const inputId=`${idPrefix}-${field.id}`;const errorId=`${inputId}-error`;const describedBy=error?errorId:void 0;if(field.type==="statement"){return jsxs3("div",{className:cn("min-w-0 space-y-1.5",className),children:[jsx4("p",{className:cn("text-base font-semibold leading-snug",FORM_FG),children:field.label}),field.description&&jsx4("p",{className:cn("whitespace-pre-wrap text-sm leading-relaxed",FORM_FG_MUTED),children:field.description})]})}return jsxs3("div",{className:cn("min-w-0 space-y-2",className),children:[jsxs3("label",{htmlFor:inputId,className:cn("block text-base font-semibold leading-snug",FORM_FG),children:[field.label,field.required&&jsx4("span",{"aria-hidden":true,className:cn("ml-0.5",FORM_DANGER),children:"*"})]}),field.description&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:field.description}),jsx4(FieldInput,{field,inputId,describedBy,invalid:Boolean(error),value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}),error&&jsx4("p",{id:errorId,role:"alert",className:cn("text-xs",FORM_DANGER),children:error})]})}function singleLineInputProps(field,today){switch(field.type){case"short_text":return{type:"text",maxLength:field.maxLength,autoComplete:field.contactMapping==="name"?"name":void 0};case"email":return{type:"email",inputMode:"email",autoComplete:"email"};case"date":return{type:"date",min:resolveFormDateBound(field.range?.min,today)??void 0,max:resolveFormDateBound(field.range?.max,today)??void 0};case"time":return{type:"time"};case"number":return{type:"text",inputMode:field.integer&&(field.min??-1)>=0?"numeric":"decimal",autoComplete:"off"};case"url":return{type:"url",inputMode:"url",autoComplete:"url",autoCapitalize:"none",spellCheck:false,placeholder:"https://"};default:return null}}function OtherTextInput({className,placeholder,value,onFocus,onChange}){return jsx4("input",{type:"text",className:cn(INPUT_CLASS,className),placeholder,"aria-label":placeholder,value,onFocus,onChange:e=>onChange(e.target.value)})}function FieldInput({field,inputId,describedBy,invalid,value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const{PhoneInput,FormAddressField,FormTaxIdField,FormFileField,FormChoiceDropdown}=useContext2(FormFieldComponentsContext)??ON_DEMAND_FORM_FIELDS;const common={id:inputId,"aria-describedby":describedBy,"aria-invalid":invalid||void 0,onFocus,onBlur,required:field.required,className:cn(INPUT_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)};const singleLine=singleLineInputProps(field,today);if(singleLine){return jsx4(NativeInput,{...common,...singleLine,value:typeof value==="string"?value:typeof value==="number"?String(value):"",onChange:e=>onChange(e.target.value)})}switch(field.type){case"short_text":case"email":case"date":case"time":case"number":case"url":return null;case"long_text":return jsx4(NativeTextarea,{...common,rows:4,maxLength:field.maxLength,value:typeof value==="string"?value:"",onChange:e=>onChange(e.target.value)});case"phone":return jsx4("div",{id:inputId,onFocus,onBlur:onGroupBlur(onBlur),tabIndex:-1,className:"outline-none",children:jsx4(PhoneInput,{value:typeof value==="string"?value:"",onChange:v=>onChange(v??null),defaultCountry:phoneCountry,error:invalid,controlClassName:cn(FORM_FIELD_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)})});case"statement":return null;case"tax_id":return jsx4(FormTaxIdField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,lookup:taxId?.lookup,onRegistryName:taxId?.onRegistryName,onChange,onFocus,onBlur});case"address":return jsx4(FormAddressField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,onChange,onFocus,onBlur});case"choice":{const selected=Array.isArray(value)?value:typeof value==="string"&&value?[value]:[];const options=[...field.options.map(o=>({id:o.id,label:o.label})),...field.allowOther?[{id:OTHER_OPTION_PLACEHOLDER,label:labels.otherOption}]:[]];const showOther=field.allowOther&&selected.includes(OTHER_OPTION_PLACEHOLDER);if(field.display==="dropdown"&&!field.allowMultiple){return jsxs3("div",{className:"space-y-2.5",onBlur:onGroupBlur(onBlur),children:[jsx4(FormChoiceDropdown,{inputId,describedBy,invalid,value:selected[0]||void 0,options,placeholder:labels.selectPlaceholder,onChange,onFocus}),showOther&&jsx4(OtherTextInput,{placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}return jsxs3("div",{role:field.allowMultiple?"group":"radiogroup","aria-describedby":describedBy,className:"space-y-2.5 pt-0.5",onBlur:onGroupBlur(onBlur),children:[options.map((opt,i)=>{const checked=selected.includes(opt.id);return jsxs3("label",{className:cn("flex cursor-pointer items-center gap-2.5 text-[15px]",FORM_FG),children:[jsx4(SiteChoiceInput,{id:i===0?inputId:void 0,type:field.allowMultiple?"checkbox":"radio",name:inputId,checked,onFocus,onChange:()=>{if(field.allowMultiple){onChange(checked?selected.filter(x=>x!==opt.id):[...selected,opt.id])}else{onChange(opt.id)}}}),jsx4("span",{children:opt.label})]},opt.id)}),showOther&&jsx4(OtherTextInput,{className:"mt-1",placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}case"rating":{const Icon=field.icon==="heart"?Heart:field.icon==="thumb"?ThumbsUp:Star;const current=typeof value==="number"?value:0;return jsx4("div",{role:"radiogroup","aria-describedby":describedBy,className:"flex flex-wrap gap-1.5",onBlur:onGroupBlur(onBlur),children:Array.from({length:field.max},(_,i)=>i+1).map(n=>{const active=n<=current;return jsx4("button",{type:"button",role:"radio","aria-checked":current===n,"aria-label":String(n),id:n===1?inputId:void 0,onFocus,onClick:()=>onChange(current===n?null:n),className:cn("flex h-10 w-10 items-center justify-center rounded-lg transition",TONE_BG_TINT_STRONG_HOVER),children:jsx4(Icon,{className:cn("h-6 w-6 transition",active?"fill-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))] text-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]":TONE_TEXT_FAINT)})},n)})})}case"file":return jsx4(FormFileField,{field,inputId,describedBy,invalid,labels,uploadUrl:upload.url,protectionReady:upload.ready,getProtectionData:upload.getProtectionData,onChange,onUnavailableChange:upload.onUnavailableChange,onBusyChange:upload.onBusyChange,onFocus})}}import{jsx as jsx5}from"react/jsx-runtime";var SITE_RETRY_DELAYS_MS=[1e3,3e3,1e4];function KanorioForm({formId,definition:initialDefinition,maxColumns,siteName,labels,onSuccess,followRedirect,hiddenValues,className,...config}){const ctx=useElementContext(config,{needsSite:true});const{site,siteError,siteUrl}=ctx;const[form,setForm]=useState2(initialDefinition??null);const[loadFailed,setLoadFailed]=useState2(false);const siteMissing=!site&&siteError;const[siteRetries,setSiteRetries]=useState2({siteUrl,count:0});const retried=siteRetries.siteUrl===siteUrl?siteRetries.count:0;useEffect2(()=>{if(!siteMissing)return;const delay=SITE_RETRY_DELAYS_MS[retried];if(delay===void 0)return;const timer=setTimeout(()=>{void loadSiteMeta(siteUrl).then(meta=>{if(meta===null)setSiteRetries({siteUrl,count:retried+1})})},delay);return()=>clearTimeout(timer)},[siteMissing,siteUrl,retried]);useEffect2(()=>{if(initialDefinition){setForm(initialDefinition);setLoadFailed(false);return}if(!formId)return;let cancelled=false;setLoadFailed(false);fetch(`${siteUrl}/api/v1/forms/${encodeURIComponent(formId)}`).then(res=>res.ok?res.json():Promise.reject(new Error(`HTTP ${res.status}`))).then(data=>{if(cancelled)return;const resolved=data&&typeof data==="object"&&"fields"in data?data:data?.form??null;if(resolved)setForm(resolved);else setLoadFailed(true)}).catch(()=>{if(!cancelled)setLoadFailed(true)});return()=>{cancelled=true}},[siteUrl,formId,initialDefinition]);const mergedLabels=ctx.messages?.form||labels?{...ctx.messages?.form??{},...labels??{}}:void 0;if(loadFailed){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"load_failed",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(siteMissing&&retried>=SITE_RETRY_DELAYS_MS.length){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"site_unavailable",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(!form||!ctx.messages||!site){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-loading":"",loading:true})}return jsx5(ElementsRoot,{context:ctx,className,children:jsx5(BotProtectionConfigProvider,{value:parsePublicBotProtectionConfig(site.botProtection),children:jsx5(FormWidget,{form,maxColumns,submitUrl:`${siteUrl}/api/v1/forms/${encodeURIComponent(form.id)}/submit`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,locale:ctx.locale,websiteName:siteName,labels:mergedLabels,followRedirect,hiddenValues,onSuccess:detail=>{if(typeof window!=="undefined"){window.dispatchEvent(new CustomEvent(FORM_SUBMIT_EVENT,{detail}))}onSuccess?.(detail)}})})})}export{SITE_RETRY_DELAYS_MS,KanorioForm};
2
- //# sourceMappingURL=chunk-G4U6BFZY.js.map
@@ -1,2 +0,0 @@
1
- import{a as i}from"./chunk-UM74DXPE.js";function c(t,e=Date.now()){if(t.status==="ARCHIVED")return"closed";let{openAt:n,closeAt:s,maxSubmissions:r}=t.settings;return s&&new Date(s).getTime()<=e?"closed":n&&new Date(n).getTime()>e?"not_open":r!==void 0&&t.submissionCount>=r?"full":"open"}var d=["short_text","long_text","email","phone","choice","date","time","file","rating","number","url","statement","address","tax_id"];function m(t){return typeof t=="string"&&d.includes(t)}function x(t){return m(t)&&t!=="statement"}var E=i("form").map(t=>t.mime),T={PATTERN_MESSAGE_MAX:200,MAX_FIELDS:30,MAX_OPTIONS:20,LABEL_MAX:200,DESCRIPTION_MAX:500,SHORT_TEXT_MAX:500,LONG_TEXT_MAX:5e3,MAX_FILES_PER_FIELD:3,FILE_MAX_BYTES:10*1024*1024,SUBMIT_BODY_MAX_CHARS:256*1024,STATEMENT_MAX:1e3,DATE_OFFSET_MAX:3650,MAX_HIDDEN_FIELDS:10,HIDDEN_VALUE_MAX:500};function y(t,e){if(!t)return null;if(t.type==="date")return t.value;if(!e)return null;let[n,s,r]=e.split("-").map(Number);return!n||!s||!r?null:new Date(Date.UTC(n,s-1,r+t.offsetDays)).toISOString().slice(0,10)}function p(t,e){let n=t.consentText?.[e]?.trim();return n||null}function f(t,e){return t.replaceAll("{siteName}",e.siteName?.trim()||"").replaceAll("{button}",e.button).replace(/\s{2,}/g," ")}function b(t,e,n){let s=t.marketingConsent;if(s==="off")return null;let r=p(t,s);if(r)return r;let o=s==="checkbox"?e.marketingOptIn:e.subscribeOnSubmit;return f(o,{siteName:n,button:t.submitLabel||e.submit})}var g=2048,A="\\{(submissionId|answers\\.([a-z0-9][a-z0-9_-]*))\\}",l=()=>new RegExp(A,"g");function u(t){return l().test(t??"")}function I(t){if(typeof t!="string")return null;let e=t.trim();if(!e||e.length>g||/[\r\n\0\s]/.test(e))return null;let n=u(e),s=n?e.replace(l(),"x"):e;if(/[{}]/.test(s))return null;if(e.startsWith("/"))return e.startsWith("//")||e.startsWith("/\\")||e.includes("\\")?null:{kind:"path",url:e};try{let r=new URL(s);if(r.protocol!=="https:"||r.username||r.password)return null;if(!n)return{kind:"absolute",url:r.toString()};let o=e.slice(8).search(/[/?#]/),a=o===-1?e:e.slice(0,8+o);return!/^https:\/\//i.test(e)||u(a)?null:{kind:"absolute",url:e}}catch{return null}}function S(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.countryCode=="string"&&typeof e.value=="string"}function M(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.countryCode=="string"}export{c as a,m as b,x as c,T as d,y as e,b as f,u as g,I as h,S as i,M as j};
2
- //# sourceMappingURL=chunk-GJY6AQIS.js.map
@@ -1,2 +0,0 @@
1
- import{TONE_BG_TINT_STRONG}from"./chunk-RKEHHJDU.js";import{runAltchaLoadedHook}from"./chunk-JH5D6YJX.js";import{cn}from"./chunk-VUTODQFX.js";import{usePartScope}from"./chunk-763LNERD.js";import{useOptionalSiteLabels}from"./chunk-U7H3W23Q.js";import{createContext,useContext}from"react";import{jsx}from"react/jsx-runtime";var BotProtectionConfigContext=createContext(null);function BotProtectionConfigProvider({value,children}){return jsx(BotProtectionConfigContext.Provider,{value,children})}function useBotProtectionConfig(){return useContext(BotProtectionConfigContext)}function defineProtectionEntry(definition){return definition}var PROTECTION_ENTRIES=[defineProtectionEntry({id:"forms",builtinVariant:"full",providerSelectable:true}),defineProtectionEntry({id:"customer_login",builtinVariant:"full",providerSelectable:true}),defineProtectionEntry({id:"checkout_draft",builtinVariant:"standard",providerSelectable:false})];var SELECTABLE_PROTECTION_ENTRY_IDS=PROTECTION_ENTRIES.filter(entry=>entry.providerSelectable).map(entry=>entry.id);function protectionEntryAction(id){return id}var BOT_PROTECTION_PROVIDERS=["kanorio","turnstile","recaptcha","hcaptcha"];function isBotProtectionProvider(value){return typeof value==="string"&&BOT_PROTECTION_PROVIDERS.includes(value)}function isThirdPartyBotProtectionProvider(value){return isBotProtectionProvider(value)&&value!=="kanorio"}function protectionCData(context){return context.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,255)}var BUILTIN_PUBLIC_BOT_PROTECTION={provider:"kanorio",recaptchaVersion:null,entries:{}};function parsePublicBotProtectionConfig(raw){if(!raw||typeof raw!=="object")return{...BUILTIN_PUBLIC_BOT_PROTECTION,entries:{}};const value=raw;if(!isThirdPartyBotProtectionProvider(value.provider))return{...BUILTIN_PUBLIC_BOT_PROTECTION,entries:{}};const entries={};const rawEntries=value.entries&&typeof value.entries==="object"?value.entries:{};for(const id of SELECTABLE_PROTECTION_ENTRY_IDS){const entry=rawEntries[id];if(entry&&typeof entry.siteKey==="string"&&entry.siteKey){entries[id]={siteKey:entry.siteKey,action:typeof entry.action==="string"?entry.action:protectionEntryAction(id)}}}const recaptchaVersion=value.recaptchaVersion==="v2"||value.recaptchaVersion==="v3"?value.recaptchaVersion:null;if(value.provider==="recaptcha"&&!recaptchaVersion)return{...BUILTIN_PUBLIC_BOT_PROTECTION,entries:{}};return{provider:value.provider,recaptchaVersion:value.provider==="recaptcha"?recaptchaVersion:null,entries}}import{useCallback}from"react";var BOT_PROTECTION_DEFAULTS={MIN_SUBMIT_TIME:5e3,MAX_SUBMIT_TIME:15*60*1e3,TOKEN_EXPIRY:60*60*1e3,INTERACTION_DELAY_MS:2e3};var ALTCHA_CHALLENGE_TTL_MS=10*60*1e3;var ALTCHA_WIDGET_EXPIRE_MS=ALTCHA_CHALLENGE_TTL_MS-60*1e3;var HONEYPOT_FIELD_NAME="_kfp_a";var HONEYPOT_FIELD_WP="_kfp_b";var HONEYPOT_FIELD_CO="_kfp_c";import{useEffect,useRef,createElement,useState}from"react";function resolveAltchaStateChange(detail){if(detail.state==="verified"&&detail.payload){return{kind:"verified",payload:detail.payload}}return{kind:"invalidated",state:detail.state}}var LOADERS={ar:()=>import("./ar-HRZRFWUW.js"),bg:()=>import("./bg-TNDZDXHZ.js"),bn:()=>import("./bn-L44L7SBD.js"),cs:()=>import("./cs-OMRFBZVP.js"),da:()=>import("./da-MEA64IPM.js"),de:()=>import("./de-7GBTXFMH.js"),el:()=>import("./el-BCFO2NS3.js"),en:()=>import("./en-LHV2B2XG.js"),"es-419":()=>import("./es-419-CN2GZEOV.js"),"es-es":()=>import("./es-es-GNKRK4H2.js"),fa:()=>import("./fa-FBR4MORA.js"),fi:()=>import("./fi-BATN376F.js"),"fr-ca":()=>import("./fr-ca-A4GWIOE7.js"),"fr-fr":()=>import("./fr-fr-FEUFFV6I.js"),he:()=>import("./he-RZE7SAH3.js"),hi:()=>import("./hi-G5IRZBZ5.js"),hu:()=>import("./hu-BPCAJCJ3.js"),id:()=>import("./id-E4ZYT3YK.js"),it:()=>import("./it-BGPYU5QL.js"),ja:()=>import("./ja-MA2A5SFZ.js"),ko:()=>import("./ko-G4I5K2UY.js"),mr:()=>import("./mr-HGKBSCPM.js"),nb:()=>import("./nb-ZOWEL6VQ.js"),nl:()=>import("./nl-4KAIKVKC.js"),pl:()=>import("./pl-BRJ5H72A.js"),"pt-br":()=>import("./pt-br-IOF65TN2.js"),"pt-pt":()=>import("./pt-pt-7BYW57KC.js"),ro:()=>import("./ro-GDWJ3F3A.js"),ru:()=>import("./ru-2GEOOKZX.js"),sv:()=>import("./sv-UJ5LCXFA.js"),sw:()=>import("./sw-HPTUVWO6.js"),ta:()=>import("./ta-TOIAFCN5.js"),te:()=>import("./te-PWIXXRJP.js"),th:()=>import("./th-3VH5JHWP.js"),tr:()=>import("./tr-TCPMEXLQ.js"),uk:()=>import("./uk-6S7TMK7C.js"),ur:()=>import("./ur-CV7QI6IC.js"),vi:()=>import("./vi-THIT43PD.js"),"zh-cn":()=>import("./zh-cn-NBHEPFJJ.js"),"zh-tw":()=>import("./zh-tw-HNBFCMMO.js")};var ALIASES={"zh-hant":"zh-tw","zh-hk":"zh-tw","zh-tw":"zh-tw",zh:"zh-cn","zh-cn":"zh-cn","zh-hans":"zh-cn",es:"es-es",fr:"fr-fr",pt:"pt-pt","nl-nl":"nl","nl-be":"nl","en-us":"en","en-gb":"en","en-au":"en","en-ca":"en",no:"nb",nn:"nb",ms:"id"};function resolveAltchaLanguage(locale){const raw=(locale??"").trim().toLowerCase();if(!raw)return"en";if(ALIASES[raw])return ALIASES[raw];if(LOADERS[raw])return raw;const base=raw.split("-")[0];if(ALIASES[base])return ALIASES[base];if(LOADERS[base])return base;return"en"}async function loadAltchaLanguage(locale){const code=resolveAltchaLanguage(locale);await LOADERS[code]();return code}import{jsx as jsx2}from"react/jsx-runtime";function loadAltchaWidget(locale){return Promise.all([import("./altcha-NPBMCOEY.js"),loadAltchaLanguage(locale)]).then(([,language])=>{runAltchaLoadedHook();return language})}function preloadAltchaWidget(locale){loadAltchaWidget(locale).catch(()=>{})}var THEME_CLASS=cn("block w-full","[--altcha-max-width:100%] [--altcha-border-width:1px]","[--altcha-border-radius:0.5rem]","[--altcha-color-base:var(--site-field-bg,rgba(255,255,255,0.9))]","[--altcha-color-border:var(--site-field-border,rgba(0,0,0,0.15))]","[--altcha-color-border-focus:var(--site-field-accent,var(--brand-color,#FF5733))]","[--altcha-color-active:var(--site-field-accent,var(--brand-color,#FF5733))]","[--altcha-color-text:inherit]","text-[15px] text-[var(--site-field-fg,#18181b)]","[&_.altcha-checkbox_input]:accent-[var(--site-field-accent,var(--brand-color,#FF5733))] [&_.altcha-spinner]:text-[var(--site-field-fg-muted,#71717a)]","[&_.altcha-main]:min-h-11 [&_.altcha-main]:px-3.5 [&_.altcha-main]:py-2.5");function AltchaWidget({challengeUrl,onVerified,onInvalidated,expireMs=ALTCHA_WIDGET_EXPIRE_MS,locale,className,invisible=false,revealed=false,generation=0,onStateChange,labels}){const siteLabels=useOptionalSiteLabels();const text=labels??siteLabels?.ui;const containerRef=useRef(null);const scope=usePartScope(containerRef);const[language,setLanguage]=useState(null);useEffect(()=>{let cancelled=false;void loadAltchaWidget(locale).then(code=>{if(!cancelled)setLanguage(code)});return()=>{cancelled=true}},[locale]);useEffect(()=>{if(!onVerified)return;const widget=containerRef.current?.querySelector("altcha-widget");if(!widget)return;const handler=ev=>{const detail=ev.detail;const transition=resolveAltchaStateChange(detail);if(transition.kind==="verified")onVerified(transition.payload);else onInvalidated?.();onStateChange?.(transition.kind==="verified"?"verified":transition.state)};widget.addEventListener("statechange",handler);return()=>widget.removeEventListener("statechange",handler)},[onVerified,onInvalidated,onStateChange,language,generation]);if(!text)throw new Error("AltchaWidget: pass `labels` or render it inside a SiteLabelsProvider");const hidden=invisible&&!revealed;if(!language){if(hidden)return null;return jsx2("div",{ref:scope.ref,className:cn("h-11 w-full animate-pulse rounded-lg "+TONE_BG_TINT_STRONG,scope.className,className),"aria-label":text.botProtectionLoading})}return jsx2("div",{ref:scope.ref,className:cn(THEME_CLASS,scope.className,className,hidden&&"hidden"),"aria-label":text.botProtection,hidden:hidden||void 0,children:createElement("altcha-widget",{key:generation,challengeurl:challengeUrl,expire:expireMs,language,...invisible?{auto:"onload"}:{},hidefooter:true,hidelogo:true})})}import{useEffect as useEffect2,useRef as useRef2}from"react";import{jsx as jsx3}from"react/jsx-runtime";var captchaGlobals=()=>globalThis;var scriptPromises=new Map;function loadScript(src,ready){const existing=scriptPromises.get(src);if(existing)return existing;const promise=new Promise((resolve,reject)=>{if(ready()){resolve();return}const script=document.createElement("script");script.src=src;script.async=true;script.defer=true;script.onerror=()=>{scriptPromises.delete(src);reject(new Error(`Failed to load ${src}`))};script.onload=()=>{const started=Date.now();const poll=()=>{if(ready())resolve();else if(Date.now()-started>1e4)reject(new Error(`Timed out waiting for ${src}`));else setTimeout(poll,50)};poll()};document.head.appendChild(script)});scriptPromises.set(src,promise);return promise}function hlParam(locale){return locale?`&hl=${encodeURIComponent(locale)}`:""}function ThirdPartyCaptcha({provider,siteKey,action,cData,recaptchaVersion,locale,invisible=false,generation=0,onVerified,onInvalidated,onError,registerExecutor,className}){const containerRef=useRef2(null);const widgetRef=useRef2(null);const callbacks=useRef2({onVerified,onInvalidated,onError});callbacks.current={onVerified,onInvalidated,onError};const isV3=provider==="recaptcha"&&recaptchaVersion==="v3";useEffect2(()=>{let cancelled=false;const el=containerRef.current;const verified=token=>!cancelled&&callbacks.current.onVerified(token);const invalidated=()=>!cancelled&&callbacks.current.onInvalidated();const failed=()=>{if(cancelled)return;callbacks.current.onInvalidated();callbacks.current.onError?.()};if(provider==="turnstile"){loadScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",()=>Boolean(captchaGlobals().turnstile?.render)).then(()=>{const api=captchaGlobals().turnstile;if(cancelled||!el||!api)return;widgetRef.current=api.render(el,{sitekey:siteKey,action,...cData?{cData}:{},theme:"auto",size:"flexible",appearance:invisible?"interaction-only":"always","refresh-expired":"auto",callback:verified,"expired-callback":invalidated,"timeout-callback":invalidated,"error-callback":failed})}).catch(failed)}else if(provider==="hcaptcha"){loadScript(`https://js.hcaptcha.com/1/api.js?render=explicit&recaptchacompat=off${hlParam(locale)}`,()=>Boolean(captchaGlobals().hcaptcha?.render)).then(()=>{const api=captchaGlobals().hcaptcha;if(cancelled||!el||!api)return;widgetRef.current=api.render(el,{sitekey:siteKey,callback:verified,"expired-callback":invalidated,"chalexpired-callback":invalidated,"error-callback":failed})}).catch(failed)}else if(isV3){loadScript(`https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(siteKey)}${hlParam(locale)}`,()=>Boolean(captchaGlobals().grecaptcha?.execute)).then(()=>{if(cancelled)return;registerExecutor?.(()=>new Promise(resolve=>{const api=captchaGlobals().grecaptcha;if(!api)return resolve(null);api.ready(()=>{api.execute(siteKey,{action}).then(resolve,()=>resolve(null))})}))}).catch(failed)}else{loadScript(`https://www.google.com/recaptcha/api.js?render=explicit${hlParam(locale)}`,()=>Boolean(captchaGlobals().grecaptcha?.render)).then(()=>{const api=captchaGlobals().grecaptcha;if(cancelled||!el||!api)return;api.ready(()=>{if(cancelled||widgetRef.current!==null)return;widgetRef.current=api.render(el,{sitekey:siteKey,callback:verified,"expired-callback":invalidated,"error-callback":failed})})}).catch(failed)}return()=>{cancelled=true;registerExecutor?.(null);const id=widgetRef.current;widgetRef.current=null;if(id===null)return;try{if(provider==="turnstile")captchaGlobals().turnstile?.remove(id);else if(provider==="hcaptcha")captchaGlobals().hcaptcha?.remove(id)}catch{}}},[provider,siteKey,action,cData,isV3,invisible,locale]);useEffect2(()=>{if(generation===0)return;const id=widgetRef.current;if(id===null)return;try{if(provider==="turnstile")captchaGlobals().turnstile?.reset(id);else if(provider==="hcaptcha")captchaGlobals().hcaptcha?.reset(id);else if(!isV3)captchaGlobals().grecaptcha?.reset(id)}catch{}},[generation,provider,isV3]);if(isV3)return null;return jsx3("div",{ref:containerRef,className:cn("min-h-[65px] w-full",className),"data-captcha-provider":provider})}import{Fragment,jsx as jsx4,jsxs}from"react/jsx-runtime";var HONEYPOT_WRAPPER_STYLE={position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:0};function appendContext(url,context){if(!context)return url;const sep=url.includes("?")?"&":"?";return`${url}${sep}context=${encodeURIComponent(context)}`}function BotProtectionAltcha({variant,altchaChallengeUrl,context,onAltchaVerified,onAltchaInvalidated,locale,className,invisible,revealed,generation,onStateChange,labels}){if(variant!=="full"||!altchaChallengeUrl||!onAltchaVerified)return null;return jsx4(AltchaWidget,{challengeUrl:appendContext(altchaChallengeUrl,context),onVerified:onAltchaVerified,onInvalidated:onAltchaInvalidated,locale,className,invisible,revealed,generation,onStateChange,labels})}function BotProtectionChallenge({provider,fieldProps,captcha,locale,className,invisible,revealed,generation,onStateChange,onCaptchaError}){if(provider!=="kanorio"&&captcha){return jsx4(ThirdPartyCaptcha,{provider:captcha.provider,siteKey:captcha.siteKey,action:captcha.action,cData:captcha.cData,recaptchaVersion:captcha.recaptchaVersion,locale,invisible,generation:captcha.generation,onVerified:captcha.onVerified,onInvalidated:captcha.onInvalidated,onError:onCaptchaError,registerExecutor:captcha.registerExecutor,className})}return jsx4(BotProtectionAltcha,{...fieldProps,locale,className,invisible,revealed,generation,onStateChange})}function BotProtectionFields({variant,altchaChallengeUrl,context,onAltchaVerified,onAltchaInvalidated,onHoneypotChange,onHoneypotWpChange,onHoneypotCoChange,locale,renderAltcha=true}){const handleHpChange=useCallback(e=>{onHoneypotChange?.(e.target.value)},[onHoneypotChange]);const handleWpChange=useCallback(e=>{onHoneypotWpChange?.(e.target.value)},[onHoneypotWpChange]);const handleCoChange=useCallback(e=>{onHoneypotCoChange?.(e.target.value)},[onHoneypotCoChange]);const honeypots=[{name:HONEYPOT_FIELD_NAME,onChange:handleHpChange},{name:HONEYPOT_FIELD_WP,onChange:handleWpChange},{name:HONEYPOT_FIELD_CO,onChange:handleCoChange}];return jsxs(Fragment,{children:[renderAltcha&&jsx4(BotProtectionAltcha,{variant,altchaChallengeUrl,context,onAltchaVerified,onAltchaInvalidated,locale}),honeypots.map(({name,onChange})=>jsxs("div",{style:HONEYPOT_WRAPPER_STYLE,"aria-hidden":"true",children:[jsx4("label",{htmlFor:name,children:"Leave this field empty"}),jsx4("input",{type:"text",id:name,name,autoComplete:"one-time-code",tabIndex:-1,onChange})]},name))]})}import{useCallback as useCallback2,useEffect as useEffect3,useMemo,useRef as useRef3,useState as useState2}from"react";var SIGNED_TOKEN_REFRESH_MS=10*60*1e3;function useBotProtection(options={}){const{variant="standard",challengeUrl="/api/form-protection/challenge",altchaChallengeUrl="/api/form-protection/altcha",context="",entry,needsUploadToken=false}=options;const contextConfig=useBotProtectionConfig();const config=options.config!==void 0?options.config:contextConfig;const thirdPartyEntry=entry&&config&&config.provider!=="kanorio"?config.entries[entry]:void 0;const provider=thirdPartyEntry&&config?config.provider:"kanorio";const isThirdParty=provider!=="kanorio";const recaptchaVersion=isThirdParty?config?.recaptchaVersion??null:null;const isRecaptchaV3=provider==="recaptcha"&&recaptchaVersion==="v3";const wantsSignedToken=!isThirdParty&&variant==="standard"||isThirdParty&&needsUploadToken;const[isReady,setIsReady]=useState2(variant==="full"||isThirdParty);const[isSubmittable,setIsSubmittable]=useState2(false);const[isAltchaVerified,setIsAltchaVerified]=useState2(false);const[isCaptchaVerified,setIsCaptchaVerified]=useState2(false);const[hasSignedToken,setHasSignedToken]=useState2(false);const[captchaGeneration,setCaptchaGeneration]=useState2(0);const loadTimestampRef=useRef3(0);const tokenRef=useRef3("");const signedTokenRef=useRef3("");const captchaTokenRef=useRef3("");const captchaExecutorRef=useRef3(null);const honeypotRef=useRef3("");const honeypotWpRef=useRef3("");const honeypotCoRef=useRef3("");const firstFocusTimeRef=useRef3(0);const timerRef=useRef3(null);const registerAltchaPayload=useCallback2(payload=>{tokenRef.current=payload;setIsAltchaVerified(true)},[]);const invalidateAltchaPayload=useCallback2(()=>{tokenRef.current="";setIsAltchaVerified(false)},[]);const registerCaptchaToken=useCallback2(token=>{captchaTokenRef.current=token;setIsCaptchaVerified(true)},[]);const invalidateCaptchaToken=useCallback2(()=>{captchaTokenRef.current="";setIsCaptchaVerified(false)},[]);const registerCaptchaExecutor=useCallback2(executor=>{captchaExecutorRef.current=executor},[]);useEffect3(()=>{loadTimestampRef.current=Date.now();honeypotRef.current="";honeypotWpRef.current="";honeypotCoRef.current="";if(!wantsSignedToken){setIsReady(true);return}const url=`${challengeUrl}?context=${encodeURIComponent(context)}`;const fetchToken=()=>fetch(url).then(res=>res.ok?res.json():Promise.reject(new Error("Challenge fetch failed"))).then(data=>{const token=`${data.nonce}|${data.ts}|${data.sig}`;if(isThirdParty)signedTokenRef.current=token;else tokenRef.current=token;setHasSignedToken(true)}).catch(()=>{});void fetchToken().finally(()=>setIsReady(true));const refresh=setInterval(()=>void fetchToken(),SIGNED_TOKEN_REFRESH_MS);return()=>{clearInterval(refresh);if(timerRef.current)clearTimeout(timerRef.current)}},[wantsSignedToken,isThirdParty,challengeUrl,context]);const registerFocus=useCallback2(()=>{if(firstFocusTimeRef.current===0){firstFocusTimeRef.current=Date.now();if(timerRef.current)clearTimeout(timerRef.current);timerRef.current=setTimeout(()=>{setIsSubmittable(true);timerRef.current=null},BOT_PROTECTION_DEFAULTS.INTERACTION_DELAY_MS)}},[]);const effectiveSubmittable=isThirdParty?isSubmittable&&(isRecaptchaV3||isCaptchaVerified):variant==="full"?isSubmittable&&isAltchaVerified:isSubmittable;const baseData=useCallback2(()=>({_hp:honeypotRef.current,_wp:honeypotWpRef.current,_co:honeypotCoRef.current,_ts:loadTimestampRef.current,...context?{_ctx:context}:{}}),[context]);const getProtectionData=useCallback2(()=>{if(isThirdParty)return{...baseData(),_tk:"",captchaToken:captchaTokenRef.current};return{...baseData(),_tk:tokenRef.current}},[baseData,isThirdParty]);const getUploadProtectionData=useCallback2(()=>{if(isThirdParty)return{...baseData(),_tk:signedTokenRef.current};return{...baseData(),_tk:tokenRef.current}},[baseData,isThirdParty]);const prepare=useCallback2(async()=>{if(!isRecaptchaV3)return;const token=await captchaExecutorRef.current?.()??"";captchaTokenRef.current=token;setIsCaptchaVerified(Boolean(token))},[isRecaptchaV3]);const renewCaptcha=useCallback2(()=>{if(!isThirdParty)return;captchaTokenRef.current="";setIsCaptchaVerified(false);setCaptchaGeneration(generation=>generation+1)},[isThirdParty]);const reset=useCallback2(()=>{loadTimestampRef.current=Date.now();honeypotRef.current="";honeypotWpRef.current="";honeypotCoRef.current="";firstFocusTimeRef.current=0;setIsSubmittable(false);setIsAltchaVerified(false);if(timerRef.current){clearTimeout(timerRef.current);timerRef.current=null}if(isThirdParty){captchaTokenRef.current="";setIsCaptchaVerified(false);setCaptchaGeneration(generation=>generation+1);return}if(variant==="standard"){const url=`${challengeUrl}?context=${encodeURIComponent(context)}`;fetch(url).then(res=>res.ok?res.json():Promise.reject(new Error("Challenge fetch failed"))).then(data=>{tokenRef.current=`${data.nonce}|${data.ts}|${data.sig}`}).catch(()=>{tokenRef.current=""})}else{tokenRef.current=""}},[isThirdParty,variant,challengeUrl,context]);const setHoneypotValue=useCallback2(value=>{honeypotRef.current=value},[]);const setHoneypotWpValue=useCallback2(value=>{honeypotWpRef.current=value},[]);const setHoneypotCoValue=useCallback2(value=>{honeypotCoRef.current=value},[]);const fieldProps=useMemo(()=>({variant,context,altchaChallengeUrl,onAltchaVerified:variant==="full"?registerAltchaPayload:void 0,onAltchaInvalidated:variant==="full"?invalidateAltchaPayload:void 0,onHoneypotChange:setHoneypotValue,onHoneypotWpChange:setHoneypotWpValue,onHoneypotCoChange:setHoneypotCoValue}),[variant,context,altchaChallengeUrl,registerAltchaPayload,invalidateAltchaPayload,setHoneypotValue,setHoneypotWpValue,setHoneypotCoValue]);const captcha=useMemo(()=>isThirdParty&&thirdPartyEntry?{provider,siteKey:thirdPartyEntry.siteKey,action:thirdPartyEntry.action,cData:provider==="turnstile"?protectionCData(context):null,recaptchaVersion,generation:captchaGeneration,onVerified:registerCaptchaToken,onInvalidated:invalidateCaptchaToken,registerExecutor:registerCaptchaExecutor}:null,[isThirdParty,thirdPartyEntry,provider,context,recaptchaVersion,captchaGeneration,registerCaptchaToken,invalidateCaptchaToken,registerCaptchaExecutor]);return{getProtectionData,getUploadProtectionData,isReady,isSubmittable:effectiveSubmittable,isUploadReady:isThirdParty?hasSignedToken:effectiveSubmittable,registerFocus,registerAltchaPayload:variant==="full"&&!isThirdParty?registerAltchaPayload:void 0,reset,prepare,renewCaptcha,provider,fieldProps,challengeProps:{provider,fieldProps,captcha},_setHoneypotValue:setHoneypotValue,_setHoneypotWpValue:setHoneypotWpValue,_setHoneypotCoValue:setHoneypotCoValue}}export{BotProtectionConfigProvider,parsePublicBotProtectionConfig,preloadAltchaWidget,BotProtectionAltcha,BotProtectionChallenge,BotProtectionFields,useBotProtection};
2
- //# sourceMappingURL=chunk-IXDKZO42.js.map
@@ -1,2 +0,0 @@
1
- import{ELEMENTS_PDFJS_BASE_URL,setPdfjsAssetBase}from"./chunk-CU2JJTXI.js";var SERVER_KEY_HEADER="X-Kanorio-Server-Key";var SERVER_KEY_VISITOR_IP_HEADER="X-Kanorio-Visitor-IP";var SERVER_KEY_PREFIX="knr_sk_";var PROBE_FAKE_SERVER_KEY=`${SERVER_KEY_PREFIX}${"0".repeat(43)}`;function parseIpv4(value){const parts=value.split(".");if(parts.length!==4)return null;const out=[];for(const part of parts){if(!/^\d{1,3}$/.test(part))return null;const n=Number(part);if(n>255)return null;out.push(n)}return out}function parseIpv6(value){if(!value.includes(":")||value.includes("%"))return null;let head=value;let tailV4=null;const lastColon=value.lastIndexOf(":");const maybeV4=value.slice(lastColon+1);if(maybeV4.includes(".")){tailV4=parseIpv4(maybeV4);if(!tailV4)return null;head=`${value.slice(0,lastColon)}:0:0`}const doubleColon=head.indexOf("::");if(doubleColon!==head.lastIndexOf("::"))return null;let groups;if(doubleColon>=0){const left=head.slice(0,doubleColon).split(":").filter(Boolean);const right=head.slice(doubleColon+2).split(":").filter(Boolean);const missing=8-left.length-right.length;if(missing<1)return null;groups=[...left,...Array(missing).fill("0"),...right]}else{groups=head.split(":")}if(groups.length!==8)return null;const bytes=[];for(const group of groups){if(!/^[0-9a-fA-F]{1,4}$/.test(group))return null;const n=parseInt(group,16);bytes.push(n>>8,n&255)}if(tailV4)bytes.splice(12,4,...tailV4);return bytes}function parseIp(raw){const value=raw.trim();if(!value||value.length>45)return null;const v4=parseIpv4(value);if(v4)return{version:4,bytes:v4};const v6=parseIpv6(value);if(!v6)return null;const mapped=v6.slice(0,10).every(b=>b===0)&&v6[10]===255&&v6[11]===255;if(mapped)return{version:4,bytes:v6.slice(12)};return{version:6,bytes:v6}}function inPrefix(bytes,prefix,bits){const full=Math.floor(bits/8);for(let i=0;i<full;i++)if(bytes[i]!==prefix[i])return false;const rest=bits%8;if(rest===0)return true;const mask=255<<8-rest&255;return((bytes[full]??0)&mask)===((prefix[full]??0)&mask)}var NON_PUBLIC_V4=[[[0,0,0,0],8],[[10,0,0,0],8],[[100,64,0,0],10],[[127,0,0,0],8],[[169,254,0,0],16],[[172,16,0,0],12],[[192,0,0,0],24],[[192,0,2,0],24],[[192,168,0,0],16],[[198,18,0,0],15],[[198,51,100,0],24],[[203,0,113,0],24],[[224,0,0,0],3]];var NON_PUBLIC_V6=[[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],127],[[252,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],7],[[254,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0],10],[[255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],8],[[32,1,13,184,0,0,0,0,0,0,0,0,0,0,0,0],32]];function isPublicIp(ip){const table=ip.version===4?NON_PUBLIC_V4:NON_PUBLIC_V6;return!table.some(([prefix,bits])=>inPrefix(ip.bytes,prefix,bits))}function formatIp(ip){if(ip.version===4)return ip.bytes.join(".");const groups=[];for(let i=0;i<16;i+=2)groups.push(((ip.bytes[i]??0)<<8|(ip.bytes[i+1]??0)).toString(16));return groups.join(":")}function normalizeVisitorIp(raw){if(!raw)return null;const parsed=parseIp(raw);if(!parsed||!isPublicIp(parsed))return null;return formatIp(parsed)}var LOCAL_HOST_RE=/^(localhost|127\.0\.0\.1|\[::1\])$/i;function isBrowser(){return typeof window!=="undefined"&&typeof document!=="undefined"}async function serverKeyRequest(options,targetUrl){const key=options.serverKey?.trim();if(!key)return null;if(isBrowser()){throw new Error("@kanorio/sdk: `serverKey` must never be used in the browser. Call Kanorio from your server (route handler, server action, middleware) and keep the key in an environment variable.")}const url=new URL(targetUrl);if(url.protocol!=="https:"&&!LOCAL_HOST_RE.test(url.hostname)){throw new Error("@kanorio/sdk: `serverKey` requires an https site URL.")}const headers={[SERVER_KEY_HEADER]:key};const raw=typeof options.visitorIp==="function"?await options.visitorIp():options.visitorIp;const visitorIp=normalizeVisitorIp(raw);if(visitorIp)headers[SERVER_KEY_VISITOR_IP_HEADER]=visitorIp;return{headers,redirect:"error"}}function isEdgeChallenge(response){return response.headers.get("cf-mitigated")==="challenge"}var EDGE_CHALLENGE_CODE="EDGE_CHALLENGE";function edgeChallengeMessage(hasServerKey){if(isBrowser()){return"Kanorio's edge challenged this request. In a browser this usually clears after the visitor passes the check; retry the request."}return hasServerKey?`Kanorio's edge challenged this server-side request even though a server key was sent. Check that the key is a server key (starts with knr_sk_, purpose "Website server") and that it is sent to the site's own hostname.`:'Kanorio\'s edge challenged this server-side request. Server-side writes need a server key: create one under Site settings > Developer (purpose "Website server"), store it as KANORIO_SERVER_KEY, and pass `serverKey` to the client. Do not paste the key into chat or commit it.'}var KANORIO_SDK_VERSION="1.2.0";var SDK_VERSION_HEADER="x-kanorio-sdk-version";function isErrorEnvelope(value){if(typeof value!=="object"||value===null)return false;const error=value.error;if(typeof error!=="object"||error===null)return false;const{code,message}=error;return typeof code==="string"&&typeof message==="string"}var KanorioApiError=class extends Error{constructor(code,status,message,details,retryAfter,availableAt){super(message);this.code=code;this.status=status;this.details=details;this.retryAfter=retryAfter;this.availableAt=availableAt;this.name="KanorioApiError"}};var KanorioEdgeChallengeError=class extends KanorioApiError{constructor(message){super(EDGE_CHALLENGE_CODE,403,message);this.name="KanorioEdgeChallengeError"}};function toApiError(status,body,headers){const retryHeader=headers.get("retry-after");const retryAfter=retryHeader?Number.parseInt(retryHeader,10):void 0;if(isErrorEnvelope(body)){const details=body.error.details;const detailRetry=typeof details?.retryAfter==="number"?details.retryAfter:void 0;const availableAt=typeof details?.availableAt==="string"?details.availableAt:void 0;return new KanorioApiError(body.error.code,status,body.error.message,body.error.details,retryAfter??detailRetry,availableAt)}const code=status===401?"UNAUTHENTICATED":status===404?"NOT_FOUND":status===429?"RATE_LIMITED":status>=500?"UPSTREAM_ERROR":"HTTP_ERROR";const text=typeof body==="string"?body.slice(0,200):"";return new KanorioApiError(code,status,text||`Request failed with HTTP ${status}.`,void 0,retryAfter)}function parseDeprecation(headers,method,path){if(!headers.has("deprecation"))return null;const link=headers.get("link")??"";const rel=name=>{const match=link.match(new RegExp(`<([^>]+)>;\\s*rel="${name}"`));return match?.[1]??null};return{method,path,sunset:headers.get("sunset"),successor:rel("successor-version"),policy:rel("deprecation")}}function buildUrl(baseUrl,path,query){const url=new URL(path.replace(/^\//,""),baseUrl.endsWith("/")?baseUrl:`${baseUrl}/`);if(query){for(const[key,raw]of Object.entries(query)){const values=Array.isArray(raw)?raw:[raw];for(const v of values){if(v===void 0||v===null)continue;url.searchParams.append(key,String(v))}}}return url.toString()}function createHttpClient(options){const fetchImpl=options.fetch??globalThis.fetch;if(!fetchImpl)throw new Error("@kanorio/sdk: global fetch is not available; pass `fetch` in options.");const warned=new Set;const onDeprecation=options.onDeprecation??(notice=>{const key=`${notice.method} ${notice.path}`;if(warned.has(key))return;warned.add(key);console.warn(`[kanorio] ${key} is deprecated${notice.sunset?` (sunset ${notice.sunset})`:""}${notice.successor?`; use ${notice.successor}`:""}.`)});async function raw(method,path,req={}){const headers=new Headers(typeof options.headers==="function"?await options.headers():options.headers);new Headers(req.headers).forEach((v,k)=>headers.set(k,v));headers.set("accept","application/json");if(typeof document==="undefined"){headers.set(SDK_VERSION_HEADER,KANORIO_SDK_VERSION);if(options.userAgent)headers.set("user-agent",options.userAgent)}let body;if(req.body!==void 0){headers.set("content-type","application/json");body=JSON.stringify(req.body)}const url=buildUrl(options.baseUrl,path,req.query);const viaServerKey=await serverKeyRequest(options,url);if(viaServerKey)for(const[name,value]of Object.entries(viaServerKey.headers))headers.set(name,value);const controller=options.timeoutMs?new AbortController:null;const timer=controller?setTimeout(()=>controller.abort(),options.timeoutMs):null;if(controller&&req.signal)req.signal.addEventListener("abort",()=>controller.abort(),{once:true});try{return await fetchImpl(url,{method,headers,body,signal:controller?.signal??req.signal,...viaServerKey?{redirect:viaServerKey.redirect}:{}})}finally{if(timer)clearTimeout(timer)}}async function request(method,path,req={}){const res=await raw(method,path,req);if(isEdgeChallenge(res))throw new KanorioEdgeChallengeError(edgeChallengeMessage(Boolean(options.serverKey)));const notice=parseDeprecation(res.headers,method,path);if(notice)onDeprecation(notice);const text=await res.text();let parsed=text;if(text){try{parsed=JSON.parse(text)}catch{parsed=text}}else{parsed=void 0}if(!res.ok)throw toApiError(res.status,parsed,res.headers);return parsed}return{request,raw}}var SEO_REWRITE_PATHS=[{source:"/sitemap.xml",apiPath:"/seo/sitemap.xml"},{source:"/robots.txt",apiPath:"/seo/robots.txt"},{source:"/llms.txt",apiPath:"/seo/llms.txt"},{source:"/llms-full.txt",apiPath:"/seo/llms-full.txt"},{source:"/feed.xml",apiPath:"/feed"},{source:"/rss.xml",apiPath:"/feed"},{source:"/feed.atom",apiPath:"/feed.atom"}];function seoRewrites(options){const base=deliveryBaseUrl(options.siteUrl);const rules=SEO_REWRITE_PATHS.map(r=>({source:r.source,destination:`${base}${r.apiPath}`}));if(options.framework==="astro"){return Object.fromEntries(rules.map(r=>[r.source,r.destination]))}rules.push({source:"/:key([a-f0-9]{32}).txt",destination:`${base}/seo/indexnow-key.txt`});return rules}function escapeJsonForScript(json){return json.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}async function fetchDeliveryJsonLd(options){const fetchImpl=options.fetch??globalThis.fetch;const rawPath=(options.path??"/").trim();const normalizedPath=rawPath.startsWith("/")?rawPath:`/${rawPath}`;const url=`${deliveryBaseUrl(options.siteUrl)}/seo/jsonld?path=${encodeURIComponent(normalizedPath)}`;const res=await fetchImpl(url);if(!res.ok)return null;const jsonLd=await res.json();return{jsonLd,scriptJson:escapeJsonForScript(JSON.stringify(jsonLd)),cacheTags:parseDeliveryCacheTags(res.headers)}}async function fetchSitemapEntries(options){const fetchImpl=options.fetch??globalThis.fetch;try{const res=await fetchImpl(`${deliveryBaseUrl(options.siteUrl)}/seo/sitemap`);if(!res.ok)return null;const body=await res.json();if(typeof body.siteUrl!=="string"||!Array.isArray(body.urls))return null;return{siteUrl:body.siteUrl,urls:body.urls,cacheTags:parseDeliveryCacheTags(res.headers)}}catch{return null}}function createSeoHelpers(options){function rewrites(opts){return seoRewrites({siteUrl:options.siteUrl,framework:opts.framework})}return{rewrites,jsonLd:(path="/")=>fetchDeliveryJsonLd({siteUrl:options.siteUrl,path,fetch:options.fetch}),sitemapEntries:()=>fetchSitemapEntries({siteUrl:options.siteUrl,fetch:options.fetch})}}function fillPath(template,params){return template.replace(/\{([^}]+)\}/g,(_,name)=>{const value=params?.[name];if(value===void 0||value===null)throw new Error(`@kanorio/sdk: missing path parameter "${name}" for ${template}`);return encodeURIComponent(String(value))})}function createTypedClient(http){const call=method=>(path,req)=>{const r=req??{};const options={query:r.query,body:r.body,headers:r.headers,signal:r.signal};return http.request(method,fillPath(path,r.params),options)};return{get:call("GET"),post:call("POST"),put:call("PUT"),patch:call("PATCH"),delete:call("DELETE"),http}}var DELIVERY_CACHE_TAGS_HEADER="x-kanorio-cache-tags";function unique(tags){const out=[];const seen=new Set;for(const tag of tags){const trimmed=tag.trim();if(!trimmed||seen.has(trimmed))continue;seen.add(trimmed);out.push(trimmed)}return out}function parseCacheTagsHeader(raw){if(!raw)return[];return unique(raw.split(/\s+/))}var DELIVERY_PREVIEW_HEADER="x-kanorio-preview";function deliveryBaseUrl(siteUrl){return`${siteUrl.replace(/\/+$/,"")}/api/v1`}function createDeliveryClient(options){const{siteUrl,previewToken,headers:baseHeaders,...rest}=options;const headers=previewToken===void 0?baseHeaders:async()=>{const merged=new Headers(typeof baseHeaders==="function"?await baseHeaders():baseHeaders);const token=typeof previewToken==="function"?await previewToken():previewToken;if(token)merged.set(DELIVERY_PREVIEW_HEADER,token);return merged};const baseClient=createTypedClient(createHttpClient({...rest,headers,baseUrl:deliveryBaseUrl(siteUrl)}));const seoHelpers=createSeoHelpers({siteUrl,fetch:rest.fetch});return Object.assign(baseClient,{seo:seoHelpers})}var DELIVERY_CACHE_TAGS_HEADER2=DELIVERY_CACHE_TAGS_HEADER;function parseDeliveryCacheTags(headers){if(!headers)return[];const raw=typeof headers.get==="function"?headers.get(DELIVERY_CACHE_TAGS_HEADER2):headers[DELIVERY_CACHE_TAGS_HEADER2]??headers["X-Kanorio-Cache-Tags"];return parseCacheTagsHeader(raw)}function customerBaseUrl(siteUrl){return`${siteUrl.replace(/\/+$/,"")}/api/v1/customer`}async function resolveToken(source){const value=typeof source==="function"?await source():source;return value?value:null}function createCustomerClient(options){const{siteUrl,token,headers,...rest}=options;const http=createHttpClient({...rest,baseUrl:customerBaseUrl(siteUrl),headers:async()=>{const h=new Headers(headers);const value=await resolveToken(token);if(value)h.set("authorization",`Bearer ${value}`);return h}});return createTypedClient(http)}var CUSTOMER_TOKEN_STORAGE_KEY="kanorio.customer.token";function defaultStorage(){try{return typeof localStorage==="undefined"?void 0:localStorage}catch{return void 0}}function writeStoredCustomerToken(token,storage=defaultStorage()){try{if(token)storage?.setItem(CUSTOMER_TOKEN_STORAGE_KEY,token);else storage?.removeItem(CUSTOMER_TOKEN_STORAGE_KEY)}catch{}}function succeed(body){return{...body,ok:true}}function createCustomerContentClient(options){const client=createCustomerClient(options);const anonymous=createHttpClient({...options,baseUrl:`${options.siteUrl.replace(/\/+$/,"")}/api/v1`});const toFail=error=>{if(error instanceof KanorioApiError)return{ok:false,code:error.code,...error.availableAt?{availableAt:error.availableAt}:{}};return{ok:false,code:"NETWORK_ERROR"}};return{async openUnit(unitId,mode,openOptions){try{const token=await resolveToken(options.token);if(!token)return succeed(await anonymous.request("POST",`units/${encodeURIComponent(unitId)}/open`,{body:{mode}}));const body=openOptions?.attachmentId?{mode,attachmentId:openOptions.attachmentId}:{mode};return succeed(await client.post("/units/{id}/open",{params:{id:unitId},query:options.locale?{locale:options.locale}:{},body}))}catch(error){return toFail(error)}},async reportProgress(input){try{return succeed(await client.post("/progress",{body:input}))}catch(error){return toFail(error)}},async submitQuiz(input){try{return succeed(await client.post("/units/{id}/quiz",{params:{id:input.unitId},body:{answers:input.answers}}))}catch(error){return toFail(error)}},async getCertificate(deliverableId){try{return succeed(await client.get("/deliverables/{deliverableId}/certificate",{params:{deliverableId}}))}catch(error){return toFail(error)}},async getTranscript(unitId,locale){try{const wanted=locale??options.locale;return succeed(await client.get("/units/{id}/transcript",{params:{id:unitId},query:wanted?{locale:wanted}:{}}))}catch(error){return toFail(error)}}}}var PKCE_STORAGE_KEY="kanorio.customer.pkce";function toGrant(wire){return{accessToken:wire.access_token,tokenType:wire.token_type,expiresIn:wire.expires_in,expiresAt:wire.expires_at,refreshToken:wire.refresh_token,refreshTokenExpiresIn:wire.refresh_token_expires_in,contactId:wire.contactId}}function base64url(bytes){let binary="";for(const byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function randomString(bytes=32){const buffer=new Uint8Array(bytes);crypto.getRandomValues(buffer);return base64url(buffer)}async function createPkcePair(){const verifier=randomString(32);const digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier));return{verifier,challenge:base64url(new Uint8Array(digest)),method:"S256"}}function buildHostedLoginUrl(params){const base=params.siteUrl.replace(/\/+$/,"");const url=new URL(`${base}${params.localeRoot??""}/account/login`);url.searchParams.set("client_id",params.clientId);url.searchParams.set("redirect_uri",params.redirectUri);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method","S256");url.searchParams.set("state",params.state);return url.toString()}function currentRedirectUri(){const url=new URL(window.location.href);url.searchParams.delete("code");url.searchParams.delete("state");url.hash="";return url.toString()}async function startHostedCustomerLogin(options){const storage=options.storage??sessionStorage;const redirectUri=options.redirectUri??currentRedirectUri();const pkce=await createPkcePair();const state=randomString(16);storage.setItem(PKCE_STORAGE_KEY,JSON.stringify({verifier:pkce.verifier,state,redirectUri}));const url=buildHostedLoginUrl({siteUrl:options.siteUrl,clientId:options.clientId,redirectUri,codeChallenge:pkce.challenge,state,localeRoot:options.localeRoot});(options.navigate??(target=>window.location.assign(target)))(url)}async function completeHostedCustomerLogin(options){const url=new URL(window.location.href);const code=url.searchParams.get("code");const state=url.searchParams.get("state");if(!code)return null;const storage=options.storage??sessionStorage;const raw=storage.getItem(PKCE_STORAGE_KEY);storage.removeItem(PKCE_STORAGE_KEY);const saved=raw?JSON.parse(raw):null;if(!saved||saved.state!==state)throw new Error("Hosted sign-in state mismatch; start the sign-in again.");if(options.cleanUrl!==false){url.searchParams.delete("code");url.searchParams.delete("state");window.history.replaceState(window.history.state,"",url.toString())}const grant=await exchangeHostedLoginCode({siteUrl:options.siteUrl,clientId:options.clientId,code,codeVerifier:saved.verifier,redirectUri:saved.redirectUri});if(options.storeToken!==false)writeStoredCustomerToken(grant.accessToken);return grant}async function exchangeHostedLoginCode(params){const client=createCustomerClient({siteUrl:params.siteUrl,serverKey:params.serverKey,visitorIp:params.visitorIp});const wire=await client.post("/auth/oauth2/token",{body:{grant_type:"authorization_code",code:params.code,code_verifier:params.codeVerifier,redirect_uri:params.redirectUri,client_id:params.clientId}});return toGrant(wire)}import{createContext,useCallback,useContext,useEffect,useLayoutEffect,useMemo,useState,useSyncExternalStore}from"react";var FALLBACK_LOCALE="en-US";var LOADERS={ar:()=>import("./ar-3VA7IUCO.js"),bg:()=>import("./bg-IRGRVWOG.js"),bn:()=>import("./bn-DM5WNGJ5.js"),cs:()=>import("./cs-3IX2ZQKJ.js"),da:()=>import("./da-AFMLFM32.js"),de:()=>import("./de-5JPEK4HF.js"),el:()=>import("./el-SMBF7FG4.js"),"en-AU":()=>import("./en-AU-LB5UVGIW.js"),"en-CA":()=>import("./en-CA-AZDOY7PW.js"),"en-GB":()=>import("./en-GB-2N4WB6SL.js"),"en-US":()=>import("./en-US-74L4OI3J.js"),en:()=>import("./en-AIAENVLI.js"),"es-419":()=>import("./es-419-Q5IH6W5F.js"),"es-ES":()=>import("./es-ES-ETSYFLPQ.js"),fa:()=>import("./fa-WRJCKGS3.js"),fi:()=>import("./fi-44ST6B6Q.js"),"fr-CA":()=>import("./fr-CA-KXRNFZBP.js"),"fr-FR":()=>import("./fr-FR-MQAFE7IX.js"),gu:()=>import("./gu-RNCZTEOA.js"),he:()=>import("./he-GNC45OCB.js"),hi:()=>import("./hi-DKG5TPYX.js"),hu:()=>import("./hu-3Y5YEIFL.js"),id:()=>import("./id-7DWHYYFC.js"),it:()=>import("./it-7RASZ4SK.js"),ja:()=>import("./ja-4V7QJLTM.js"),km:()=>import("./km-HPCMYWAG.js"),kn:()=>import("./kn-QAWBGLHG.js"),ko:()=>import("./ko-55JV4VQK.js"),lo:()=>import("./lo-JNUKFIQV.js"),ml:()=>import("./ml-3LXSDTNF.js"),mr:()=>import("./mr-PLM72664.js"),ms:()=>import("./ms-N544Y63H.js"),my:()=>import("./my-6IKSM3XW.js"),nb:()=>import("./nb-345ACUTX.js"),ne:()=>import("./ne-ASFNHMO3.js"),"nl-BE":()=>import("./nl-BE-WK4C6XRZ.js"),"nl-NL":()=>import("./nl-NL-2YLHGJZL.js"),nn:()=>import("./nn-I5A2LCBH.js"),pa:()=>import("./pa-VX5TUNDP.js"),pl:()=>import("./pl-4Y4BWTLT.js"),"pt-BR":()=>import("./pt-BR-CW3MRSRP.js"),"pt-PT":()=>import("./pt-PT-ZTPCI2K6.js"),ro:()=>import("./ro-ANISGUFX.js"),ru:()=>import("./ru-PKSZKOLH.js"),si:()=>import("./si-5F7RWQIE.js"),sv:()=>import("./sv-HZVCM7LG.js"),sw:()=>import("./sw-5XU65KFC.js"),ta:()=>import("./ta-R73RBA23.js"),te:()=>import("./te-GVW56XDM.js"),th:()=>import("./th-G6SY3D2Q.js"),tl:()=>import("./tl-PZNXANIM.js"),tr:()=>import("./tr-2BDM6H5Q.js"),uk:()=>import("./uk-OQRACKKD.js"),ur:()=>import("./ur-J5HV4NTW.js"),vi:()=>import("./vi-MQSOSIUY.js"),"zh-CN":()=>import("./zh-CN-RNW2BEY7.js"),"zh-HK":()=>import("./zh-HK-RKREDSAO.js"),"zh-Hant":()=>import("./zh-Hant-T6KHSA5B.js")};var VISITOR_MESSAGE_LOCALES=Object.keys(LOADERS);function resolveVisitorLocale(locale){return locale&&locale in LOADERS?locale:FALLBACK_LOCALE}async function loadVisitorMessages(locale){const mod=await LOADERS[resolveVisitorLocale(locale)]();return mod.default}var ELEMENTS_ROOT_CLASS="kanorio-elements";var ELEMENTS_POPUP_CLASS="kanorio-popup";var ELEMENTS_PART_CLASS="kanorio-part";var BRAND_ATTRIBUTE="data-kanorio-brand";function markScope(element,theme,brandScope){if(theme)element.setAttribute("data-kanorio-theme",theme);else element.removeAttribute("data-kanorio-theme");if(brandScope)element.setAttribute(BRAND_ATTRIBUTE,brandScope);else element.removeAttribute(BRAND_ATTRIBUTE)}var SCOPE_SELECTOR=`:is(.${ELEMENTS_ROOT_CLASS}, .${ELEMENTS_POPUP_CLASS}, .${ELEMENTS_PART_CLASS})`;var HOST_DARK_MARKS=[".dark",'[data-theme="dark"]'];var HOST_DARK_MARK_SELECTOR=HOST_DARK_MARKS.join(", ");var HOST_DARK_DESCENDANT_SELECTOR=HOST_DARK_MARKS.map(mark=>`${mark} *`).join(", ");var DARK_SELECTOR=['[data-kanorio-theme="dark"]','[data-kanorio-theme="dark"] *',`[data-kanorio-theme="auto"]:where(${HOST_DARK_DESCENDANT_SELECTOR})`,`[data-kanorio-theme="auto"]:where(${HOST_DARK_DESCENDANT_SELECTOR}) *`].join(", ");var SYSTEM_DARK_SELECTOR='[data-kanorio-theme="auto"], [data-kanorio-theme="auto"] *';import{jsx}from"react/jsx-runtime";setPdfjsAssetBase(ELEMENTS_PDFJS_BASE_URL);var TOKEN_CHANGE_EVENT="kanorio:token-change";function resolveSiteUrl(siteUrl){const given=siteUrl?.replace(/\/+$/,"");if(given)return given;if(typeof window!=="undefined")return window.location.origin;if(siteUrl)return"";throw new Error("@kanorio/elements: siteUrl is required outside the browser.")}function optionalSiteUrl(siteUrl){const given=siteUrl?.replace(/\/+$/,"");if(given)return given;return typeof window!=="undefined"?window.location.origin:null}function resolveLocale(locale){if(locale)return locale;if(typeof document!=="undefined"&&document.documentElement.lang)return document.documentElement.lang;return"en"}var noSubscription=()=>()=>{};var NO_ENTRY=Object.freeze({value:null,failures:0,round:0});var serverEntry=()=>NO_ENTRY;function createLoadedStore(fetchValue){const entries=new Map;const pending=new Map;const listeners=new Set;let generation=0;const emit=()=>{for(const listener of[...listeners])listener()};return{entry:key=>entries.get(key)??NO_ENTRY,subscribe(listener){listeners.add(listener);return()=>{listeners.delete(listener)}},load(key){const current=entries.get(key);if(current&&current.value!==null)return Promise.resolve(current.value);const inFlight=pending.get(key);if(inFlight)return inFlight;const started=generation;const request=Promise.resolve().then(()=>fetchValue(key)).catch(()=>null).then(value=>{if(pending.get(key)===request)pending.delete(key);if(started!==generation)return value;const before=entries.get(key)??NO_ENTRY;entries.set(key,value===null?{...before,failures:before.failures+1}:{value,failures:before.failures,round:before.round});emit();return value});pending.set(key,request);return request},clear(){generation+=1;for(const[key,entry]of entries)entries.set(key,{value:null,failures:entry.failures,round:entry.round+1});for(const key of pending.keys())if(!entries.has(key))entries.set(key,{...NO_ENTRY,round:1});pending.clear();emit()},retryFailed(){let changed=false;for(const[key,entry]of entries){if(entry.value!==null||pending.has(key))continue;entries.set(key,{...entry,round:entry.round+1});changed=true}if(changed)emit()},reset(){generation+=1;entries.clear();pending.clear();emit()}}}function useLoaded(store,key){const entry=useSyncExternalStore(key===null?noSubscription:store.subscribe,()=>key===null?NO_ENTRY:store.entry(key),serverEntry);const[since,setSince]=useState(()=>({key,failures:key===null?0:store.entry(key).failures}));let baseline=since;if(since.key!==key){baseline={key,failures:key===null?0:store.entry(key).failures};setSince(baseline)}const wanted=key!==null&&entry.value===null;useEffect(()=>{if(wanted&&key!==null)void store.load(key)},[store,key,wanted,entry.round]);const error=key!==null&&entry.value===null&&entry.failures>baseline.failures;return useMemo(()=>({value:entry.value,error}),[entry.value,error])}var messagesStore=createLoadedStore(locale=>loadVisitorMessages(locale));var siteStore=createLoadedStore(siteUrl=>createDeliveryClient({siteUrl}).get("/site").then(site=>typeof site?.id==="string"?site:null));if(typeof window!=="undefined"){window.addEventListener("online",()=>{messagesStore.retryFailed();siteStore.retryFailed()})}function loadElementsMessages(locale){return messagesStore.load(locale).then(messages=>messages??Promise.reject(new Error(`@kanorio/elements: the visitor text for "${locale}" could not be loaded.`)))}function useElementsMessages(locale,enabled=true){const{value,error}=useLoaded(messagesStore,enabled?locale:null);const[shown,setShown]=useState(null);if(value!==null&&(shown===null||shown.messages!==value||shown.locale!==locale))setShown({messages:value,locale});const messages=value??shown?.messages??null;const shownLocale=value!==null?locale:shown?.locale??locale;return useMemo(()=>({messages,locale:shownLocale,error}),[messages,shownLocale,error])}function loadSiteMeta(siteUrl){return siteStore.load(siteUrl)}function clearSiteMetaCache(){siteStore.clear()}function useSiteMeta(siteUrl,enabled=true){const{value,error}=useLoaded(siteStore,enabled?siteUrl:null);const[shown,setShown]=useState(null);if(value!==null&&(shown===null||shown.site!==value||shown.siteUrl!==siteUrl))setShown({site:value,siteUrl});const site=value??(enabled&&shown?.siteUrl===siteUrl?shown.site:null);return useMemo(()=>({site,error}),[site,error])}function brandFontLocale(locale){const normalized=locale.toLowerCase();if(normalized.startsWith("zh-hans")||normalized.startsWith("zh-cn")||normalized.startsWith("zh-sg"))return"zh-Hans";if(normalized.startsWith("zh"))return"zh-Hant";if(normalized.startsWith("ja"))return"ja";if(normalized.startsWith("ko"))return"ko";return"en"}function brandRules(brand,locale,target){const light=brand.colors.primary.light;const dark=brand.colors.primary.dark;const radius=Object.entries(brand.radius).map(([key,value])=>`--site-radius-${key}: ${value};`).join(" ");const fontLocale=brandFontLocale(locale);const font=brand.fonts.find(entry=>entry.locales.includes(fontLocale))??brand.fonts[0];const fontVar=font?`--site-font-family: ${font.family};`:"";const darkVars=`--brand-color: ${dark.background}; --brand-foreground: ${dark.foreground};`;return[`:where(${target}) { --brand-color: ${light.background}; --brand-foreground: ${light.foreground}; ${radius} ${fontVar} font-family: var(--site-font-family, inherit); }`,`:where(${target}):where(${DARK_SELECTOR}) { ${darkVars} }`,`@media (prefers-color-scheme: dark) { :where(${target}):where(${SYSTEM_DARK_SELECTOR}) { ${darkVars} } }`].join("\n")}function brandCss(brand,locale){return brandRules(brand,locale,SCOPE_SELECTOR)}function brandScopeOf(siteId,locale){return`${siteId}-${brandFontLocale(locale)}`}var useBeforePaintEffect=typeof window==="undefined"?useEffect:useLayoutEffect;var writtenBrands=new Map;function useBrandStyle(site,locale,enabled){const scope=enabled&&site?.brand?brandScopeOf(site.id,locale):null;useBeforePaintEffect(()=>{if(!scope||!site?.brand||typeof document==="undefined")return;const written=writtenBrands.get(scope);if(written&&written.site===site&&written.style.isConnected)return;const id=`kanorio-brand-${scope}`;const css=brandRules(site.brand,locale,`[${BRAND_ATTRIBUTE}="${scope}"]`);let style=document.getElementById(id);if(!style){style=document.createElement("style");style.id=id;document.head.appendChild(style)}if(style.textContent!==css)style.textContent=css;for(const font of site.brand.fonts){if(!font.stylesheetUrl)continue;const selector=`link[data-kanorio-font="${CSS.escape(font.stylesheetUrl)}"]`;if(document.head.querySelector(selector))continue;const link=document.createElement("link");link.rel="stylesheet";link.href=font.stylesheetUrl;link.dataset.kanorioFont=font.stylesheetUrl;document.head.appendChild(link)}writtenBrands.set(scope,{site,style})},[scope,site,locale]);return scope}var tokenListeners=new Set;function emitToken(){for(const listener of[...tokenListeners])listener()}function subscribeToken(listener){tokenListeners.add(listener);if(tokenListeners.size===1){window.addEventListener("storage",emitToken);window.addEventListener(TOKEN_CHANGE_EVENT,emitToken)}return()=>{tokenListeners.delete(listener);if(tokenListeners.size===0){window.removeEventListener("storage",emitToken);window.removeEventListener(TOKEN_CHANGE_EVENT,emitToken)}}}var memoryToken=null;function readToken(){try{return localStorage.getItem(CUSTOMER_TOKEN_STORAGE_KEY)}catch{return memoryToken}}var noToken=()=>null;function writeToken(token){memoryToken=token;try{writeStoredCustomerToken(token)}catch{}if(typeof window!=="undefined")window.dispatchEvent(new CustomEvent(TOKEN_CHANGE_EVENT,{detail:{token}}))}function useExplicitToken(explicit){const[state,setState]=useState({given:explicit,written:null});let written=state.written;if(state.given!==explicit){written=null;setState({given:explicit,written:null})}const setToken=useCallback(token=>{setState(current=>({given:current.given,written:{token}}));writeToken(token)},[]);return useMemo(()=>{if(explicit===void 0)return null;return{token:written?written.token:explicit,setToken}},[explicit,written,setToken])}function useElementToken(own,inherited){const ownSource=useExplicitToken(own);const explicit=ownSource??inherited;const stored=useSyncExternalStore(explicit?noSubscription:subscribeToken,explicit?noToken:readToken,noToken);return useMemo(()=>explicit??{token:stored,setToken:writeToken},[explicit,stored])}var ProviderContext=createContext(null);function KanorioProvider({children,siteUrl,token,locale,theme,timeZone,brand}){const tokenSource=useExplicitToken(token);const config=useMemo(()=>({siteUrl,token,locale,theme,timeZone,brand}),[siteUrl,token,locale,theme,timeZone,brand]);const value=useMemo(()=>({config,token:tokenSource}),[config,tokenSource]);return jsx(ProviderContext.Provider,{value,children})}function useKanorioProviderConfig(){return useContext(ProviderContext)?.config??null}function useKanorioSiteUrl(siteUrl){const parent=useContext(ProviderContext);return resolveSiteUrl(siteUrl??parent?.config.siteUrl)}function useElementContext(overrides,options={}){const parent=useContext(ProviderContext);const config={...parent?.config,...stripUndefined(overrides)};const siteUrl=resolveSiteUrl(config.siteUrl);const theme=config.theme??"auto";const timeZone=config.timeZone??null;const brand=config.brand!==false;const{token,setToken}=useElementToken(overrides.token,parent?.token??null);const text=useElementsMessages(resolveLocale(config.locale));const locale=text.locale;const{site,error:siteError}=useSiteMeta(siteUrl,brand||options.needsSite===true);const brandScope=useBrandStyle(site,locale,brand);const client=useMemo(()=>createCustomerContentClient({siteUrl,token:()=>token,locale}),[siteUrl,token,locale]);const messages=text.messages;const messagesError=text.error;return useMemo(()=>({siteUrl,token,setToken,locale,theme,timeZone,messages,messagesError,client,brandScope,site,siteError}),[siteUrl,token,setToken,locale,theme,timeZone,messages,messagesError,client,brandScope,site,siteError])}function useKanorio(overrides={}){return useElementContext(overrides)}function stripUndefined(obj){return Object.fromEntries(Object.entries(obj).filter(([,v])=>v!==void 0))}export{KanorioApiError,createDeliveryClient,createCustomerClient,startHostedCustomerLogin,completeHostedCustomerLogin,resolveVisitorLocale,ELEMENTS_ROOT_CLASS,ELEMENTS_POPUP_CLASS,ELEMENTS_PART_CLASS,BRAND_ATTRIBUTE,markScope,HOST_DARK_MARK_SELECTOR,TOKEN_CHANGE_EVENT,optionalSiteUrl,resolveLocale,loadElementsMessages,useElementsMessages,loadSiteMeta,clearSiteMetaCache,useSiteMeta,brandCss,useBrandStyle,KanorioProvider,useKanorioProviderConfig,useKanorioSiteUrl,useElementContext,useKanorio};
2
- //# sourceMappingURL=chunk-MIQK3T3Y.js.map
@@ -1,3 +0,0 @@
1
- import{a as B,b as q}from"./chunk-BKNL7ZCI.js";import{a as V}from"./chunk-OU4IOHLN.js";import{a as _e}from"./chunk-6LGTFWQS.js";import{c as A}from"./chunk-CDG7S4P5.js";var W="X-Kanorio-Server-Key",j="X-Kanorio-Visitor-IP";var Oe="knr_sk_";var Rt=`${Oe}${"0".repeat(43)}`;function G(e){let t=e.split(".");if(t.length!==4)return null;let r=[];for(let n of t){if(!/^\d{1,3}$/.test(n))return null;let o=Number(n);if(o>255)return null;r.push(o)}return r}function Pe(e){if(!e.includes(":")||e.includes("%"))return null;let t=e,r=null,n=e.lastIndexOf(":"),o=e.slice(n+1);if(o.includes(".")){if(r=G(o),!r)return null;t=`${e.slice(0,n)}:0:0`}let i=t.indexOf("::");if(i!==t.lastIndexOf("::"))return null;let s;if(i>=0){let l=t.slice(0,i).split(":").filter(Boolean),c=t.slice(i+2).split(":").filter(Boolean),d=8-l.length-c.length;if(d<1)return null;s=[...l,...Array(d).fill("0"),...c]}else s=t.split(":");if(s.length!==8)return null;let a=[];for(let l of s){if(!/^[0-9a-fA-F]{1,4}$/.test(l))return null;let c=parseInt(l,16);a.push(c>>8,c&255)}return r&&a.splice(12,4,...r),a}function Ie(e){let t=e.trim();if(!t||t.length>45)return null;let r=G(t);if(r)return{version:4,bytes:r};let n=Pe(t);return n?n.slice(0,10).every(i=>i===0)&&n[10]===255&&n[11]===255?{version:4,bytes:n.slice(12)}:{version:6,bytes:n}:null}function Ae(e,t,r){let n=Math.floor(r/8);for(let s=0;s<n;s++)if(e[s]!==t[s])return!1;let o=r%8;if(o===0)return!0;let i=255<<8-o&255;return((e[n]??0)&i)===((t[n]??0)&i)}var Le=[[[0,0,0,0],8],[[10,0,0,0],8],[[100,64,0,0],10],[[127,0,0,0],8],[[169,254,0,0],16],[[172,16,0,0],12],[[192,0,0,0],24],[[192,0,2,0],24],[[192,168,0,0],16],[[198,18,0,0],15],[[198,51,100,0],24],[[203,0,113,0],24],[[224,0,0,0],3]],Ke=[[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],127],[[252,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],7],[[254,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0],10],[[255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],8],[[32,1,13,184,0,0,0,0,0,0,0,0,0,0,0,0],32]];function He(e){return!(e.version===4?Le:Ke).some(([r,n])=>Ae(e.bytes,r,n))}function Ue(e){if(e.version===4)return e.bytes.join(".");let t=[];for(let r=0;r<16;r+=2)t.push(((e.bytes[r]??0)<<8|(e.bytes[r+1]??0)).toString(16));return t.join(":")}function z(e){if(!e)return null;let t=Ie(e);return!t||!He(t)?null:Ue(t)}var De=/^(localhost|127\.0\.0\.1|\[::1\])$/i;function Y(){return typeof window<"u"&&typeof document<"u"}async function J(e,t){let r=e.serverKey?.trim();if(!r)return null;if(Y())throw new Error("@kanorio/sdk: `serverKey` must never be used in the browser. Call Kanorio from your server (route handler, server action, middleware) and keep the key in an environment variable.");let n=new URL(t);if(n.protocol!=="https:"&&!De.test(n.hostname))throw new Error("@kanorio/sdk: `serverKey` requires an https site URL.");let o={[W]:r},i=typeof e.visitorIp=="function"?await e.visitorIp():e.visitorIp,s=z(i);return s&&(o[j]=s),{headers:o,redirect:"error"}}function Q(e){return e.headers.get("cf-mitigated")==="challenge"}var X="EDGE_CHALLENGE";function Z(e){return Y()?"Kanorio's edge challenged this request. In a browser this usually clears after the visitor passes the check; retry the request.":e?`Kanorio's edge challenged this server-side request even though a server key was sent. Check that the key is a server key (starts with knr_sk_, purpose "Website server") and that it is sent to the site's own hostname.`:'Kanorio\'s edge challenged this server-side request. Server-side writes need a server key: create one under Site settings > Developer (purpose "Website server"), store it as KANORIO_SERVER_KEY, and pass `serverKey` to the client. Do not paste the key into chat or commit it.'}var ee="1.2.0",te="x-kanorio-sdk-version";function Me(e){if(typeof e!="object"||e===null)return!1;let t=e.error;if(typeof t!="object"||t===null)return!1;let{code:r,message:n}=t;return typeof r=="string"&&typeof n=="string"}var m=class extends Error{constructor(r,n,o,i,s,a){super(o);this.code=r;this.status=n;this.details=i;this.retryAfter=s;this.availableAt=a;this.name="KanorioApiError"}},v=class extends m{constructor(t){super(X,403,t),this.name="KanorioEdgeChallengeError"}};function Ne(e,t,r){let n=r.get("retry-after"),o=n?Number.parseInt(n,10):void 0;if(Me(t)){let a=t.error.details,l=typeof a?.retryAfter=="number"?a.retryAfter:void 0,c=typeof a?.availableAt=="string"?a.availableAt:void 0;return new m(t.error.code,e,t.error.message,t.error.details,o??l,c)}let i=e===401?"UNAUTHENTICATED":e===404?"NOT_FOUND":e===429?"RATE_LIMITED":e>=500?"UPSTREAM_ERROR":"HTTP_ERROR",s=typeof t=="string"?t.slice(0,200):"";return new m(i,e,s||`Request failed with HTTP ${e}.`,void 0,o)}function $e(e,t,r){if(!e.has("deprecation"))return null;let n=e.get("link")??"",o=i=>n.match(new RegExp(`<([^>]+)>;\\s*rel="${i}"`))?.[1]??null;return{method:t,path:r,sunset:e.get("sunset"),successor:o("successor-version"),policy:o("deprecation")}}function Fe(e,t,r){let n=new URL(t.replace(/^\//,""),e.endsWith("/")?e:`${e}/`);if(r)for(let[o,i]of Object.entries(r)){let s=Array.isArray(i)?i:[i];for(let a of s)a!=null&&n.searchParams.append(o,String(a))}return n.toString()}function R(e){let t=e.fetch??globalThis.fetch;if(!t)throw new Error("@kanorio/sdk: global fetch is not available; pass `fetch` in options.");let r=new Set,n=e.onDeprecation??(s=>{let a=`${s.method} ${s.path}`;r.has(a)||(r.add(a),console.warn(`[kanorio] ${a} is deprecated${s.sunset?` (sunset ${s.sunset})`:""}${s.successor?`; use ${s.successor}`:""}.`))});async function o(s,a,l={}){let c=new Headers(typeof e.headers=="function"?await e.headers():e.headers);new Headers(l.headers).forEach((y,h)=>c.set(h,y)),c.set("accept","application/json"),typeof document>"u"&&(c.set(te,ee),e.userAgent&&c.set("user-agent",e.userAgent));let d;l.body!==void 0&&(c.set("content-type","application/json"),d=JSON.stringify(l.body));let p=Fe(e.baseUrl,a,l.query),g=await J(e,p);if(g)for(let[y,h]of Object.entries(g.headers))c.set(y,h);let f=e.timeoutMs?new AbortController:null,x=f?setTimeout(()=>f.abort(),e.timeoutMs):null;f&&l.signal&&l.signal.addEventListener("abort",()=>f.abort(),{once:!0});try{return await t(p,{method:s,headers:c,body:d,signal:f?.signal??l.signal,...g?{redirect:g.redirect}:{}})}finally{x&&clearTimeout(x)}}async function i(s,a,l={}){let c=await o(s,a,l);if(Q(c))throw new v(Z(!!e.serverKey));let d=$e(c.headers,s,a);d&&n(d);let p=await c.text(),g=p;if(p)try{g=JSON.parse(p)}catch{g=p}else g=void 0;if(!c.ok)throw Ne(c.status,g,c.headers);return g}return{request:i,raw:o}}var Ve=[{source:"/sitemap.xml",apiPath:"/seo/sitemap.xml"},{source:"/robots.txt",apiPath:"/seo/robots.txt"},{source:"/llms.txt",apiPath:"/seo/llms.txt"},{source:"/llms-full.txt",apiPath:"/seo/llms-full.txt"},{source:"/feed.xml",apiPath:"/feed"},{source:"/rss.xml",apiPath:"/feed"},{source:"/feed.atom",apiPath:"/feed.atom"}];function Be(e){let t=E(e.siteUrl),r=Ve.map(n=>({source:n.source,destination:`${t}${n.apiPath}`}));return e.framework==="astro"?Object.fromEntries(r.map(n=>[n.source,n.destination])):(r.push({source:"/:key([a-f0-9]{32}).txt",destination:`${t}/seo/indexnow-key.txt`}),r)}function qe(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}async function We(e){let t=e.fetch??globalThis.fetch,r=(e.path??"/").trim(),n=r.startsWith("/")?r:`/${r}`,o=`${E(e.siteUrl)}/seo/jsonld?path=${encodeURIComponent(n)}`,i=await t(o);if(!i.ok)return null;let s=await i.json();return{jsonLd:s,scriptJson:qe(JSON.stringify(s)),cacheTags:T(i.headers)}}async function je(e){let t=e.fetch??globalThis.fetch;try{let r=await t(`${E(e.siteUrl)}/seo/sitemap`);if(!r.ok)return null;let n=await r.json();return typeof n.siteUrl!="string"||!Array.isArray(n.urls)?null:{siteUrl:n.siteUrl,urls:n.urls,cacheTags:T(r.headers)}}catch{return null}}function re(e){function t(r){return Be({siteUrl:e.siteUrl,framework:r.framework})}return{rewrites:t,jsonLd:(r="/")=>We({siteUrl:e.siteUrl,path:r,fetch:e.fetch}),sitemapEntries:()=>je({siteUrl:e.siteUrl,fetch:e.fetch})}}function Ge(e,t){return e.replace(/\{([^}]+)\}/g,(r,n)=>{let o=t?.[n];if(o==null)throw new Error(`@kanorio/sdk: missing path parameter "${n}" for ${e}`);return encodeURIComponent(String(o))})}function _(e){let t=r=>(n,o)=>{let i=o??{},s={query:i.query,body:i.body,headers:i.headers,signal:i.signal};return e.request(r,Ge(n,i.params),s)};return{get:t("GET"),post:t("POST"),put:t("PUT"),patch:t("PATCH"),delete:t("DELETE"),http:e}}var ne="x-kanorio-cache-tags";function ze(e){let t=[],r=new Set;for(let n of e){let o=n.trim();!o||r.has(o)||(r.add(o),t.push(o))}return t}function oe(e){return e?ze(e.split(/\s+/)):[]}var se="x-kanorio-preview";function E(e){return`${e.replace(/\/+$/,"")}/api/v1`}function K(e){let{siteUrl:t,previewToken:r,headers:n,...o}=e,s=_(R({...o,headers:r===void 0?n:async()=>{let l=new Headers(typeof n=="function"?await n():n),c=typeof r=="function"?await r():r;return c&&l.set(se,c),l},baseUrl:E(t)})),a=re({siteUrl:t,fetch:o.fetch});return Object.assign(s,{seo:a})}var L=ne;function T(e){if(!e)return[];let t=typeof e.get=="function"?e.get(L):e[L]??e["X-Kanorio-Cache-Tags"];return oe(t)}function ie(e){return`${e.replace(/\/+$/,"")}/api/v1/customer`}async function ae(e){let t=typeof e=="function"?await e():e;return t||null}function O(e){let{siteUrl:t,token:r,headers:n,...o}=e,i=R({...o,baseUrl:ie(t),headers:async()=>{let s=new Headers(n),a=await ae(r);return a&&s.set("authorization",`Bearer ${a}`),s}});return _(i)}var b="kanorio.customer.token";function Ye(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function C(e,t=Ye()){try{e?t?.setItem(b,e):t?.removeItem(b)}catch{}}function S(e){return{...e,ok:!0}}function H(e){let t=O(e),r=R({...e,baseUrl:`${e.siteUrl.replace(/\/+$/,"")}/api/v1`}),n=o=>o instanceof m?{ok:!1,code:o.code,...o.availableAt?{availableAt:o.availableAt}:{}}:{ok:!1,code:"NETWORK_ERROR"};return{async openUnit(o,i,s){try{if(!await ae(e.token))return S(await r.request("POST",`units/${encodeURIComponent(o)}/open`,{body:{mode:i}}));let l=s?.attachmentId?{mode:i,attachmentId:s.attachmentId}:{mode:i};return S(await t.post("/units/{id}/open",{params:{id:o},query:e.locale?{locale:e.locale}:{},body:l}))}catch(a){return n(a)}},async reportProgress(o){try{return S(await t.post("/progress",{body:o}))}catch(i){return n(i)}},async submitQuiz(o){try{return S(await t.post("/units/{id}/quiz",{params:{id:o.unitId},body:{answers:o.answers}}))}catch(i){return n(i)}},async getCertificate(o){try{return S(await t.get("/deliverables/{deliverableId}/certificate",{params:{deliverableId:o}}))}catch(i){return n(i)}},async getTranscript(o,i){try{let s=i??e.locale;return S(await t.get("/units/{id}/transcript",{params:{id:o},query:s?{locale:s}:{}}))}catch(s){return n(s)}}}}var U="kanorio.customer.pkce";function Je(e){return{accessToken:e.access_token,tokenType:e.token_type,expiresIn:e.expires_in,expiresAt:e.expires_at,refreshToken:e.refresh_token,refreshTokenExpiresIn:e.refresh_token_expires_in,contactId:e.contactId}}function le(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ce(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),le(t)}async function ue(){let e=ce(32),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return{verifier:e,challenge:le(new Uint8Array(t)),method:"S256"}}function de(e){let t=e.siteUrl.replace(/\/+$/,""),r=new URL(`${t}${e.localeRoot??""}/account/login`);return r.searchParams.set("client_id",e.clientId),r.searchParams.set("redirect_uri",e.redirectUri),r.searchParams.set("code_challenge",e.codeChallenge),r.searchParams.set("code_challenge_method","S256"),r.searchParams.set("state",e.state),r.toString()}function Qe(){let e=new URL(window.location.href);return e.searchParams.delete("code"),e.searchParams.delete("state"),e.hash="",e.toString()}async function Xe(e){let t=e.storage??sessionStorage,r=e.redirectUri??Qe(),n=await ue(),o=ce(16);t.setItem(U,JSON.stringify({verifier:n.verifier,state:o,redirectUri:r}));let i=de({siteUrl:e.siteUrl,clientId:e.clientId,redirectUri:r,codeChallenge:n.challenge,state:o,localeRoot:e.localeRoot});(e.navigate??(s=>window.location.assign(s)))(i)}async function Ze(e){let t=new URL(window.location.href),r=t.searchParams.get("code"),n=t.searchParams.get("state");if(!r)return null;let o=e.storage??sessionStorage,i=o.getItem(U);o.removeItem(U);let s=i?JSON.parse(i):null;if(!s||s.state!==n)throw new Error("Hosted sign-in state mismatch; start the sign-in again.");e.cleanUrl!==!1&&(t.searchParams.delete("code"),t.searchParams.delete("state"),window.history.replaceState(window.history.state,"",t.toString()));let a=await pe({siteUrl:e.siteUrl,clientId:e.clientId,code:r,codeVerifier:s.verifier,redirectUri:s.redirectUri});return e.storeToken!==!1&&C(a.accessToken),a}async function pe(e){let r=await O({siteUrl:e.siteUrl,serverKey:e.serverKey,visitorIp:e.visitorIp}).post("/auth/oauth2/token",{body:{grant_type:"authorization_code",code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri,client_id:e.clientId}});return Je(r)}var u=A(_e(),1);var et="en-US",D={ar:()=>import("./ar-AUQCHHZG.js"),bg:()=>import("./bg-QWC2KG3G.js"),bn:()=>import("./bn-BHRS66N3.js"),cs:()=>import("./cs-NZW6FBFY.js"),da:()=>import("./da-PZ32KKTE.js"),de:()=>import("./de-MVL4XGYR.js"),el:()=>import("./el-G2AWU43W.js"),"en-AU":()=>import("./en-AU-Q2O2HPJ2.js"),"en-CA":()=>import("./en-CA-PVKXM3WS.js"),"en-GB":()=>import("./en-GB-Y5QRPC7S.js"),"en-US":()=>import("./en-US-EKS52JBW.js"),en:()=>import("./en-SAXQF5YW.js"),"es-419":()=>import("./es-419-VSZWGONE.js"),"es-ES":()=>import("./es-ES-7L55KPLO.js"),fa:()=>import("./fa-OYP2Q5EV.js"),fi:()=>import("./fi-J6NJBPNK.js"),"fr-CA":()=>import("./fr-CA-PWWAPLBH.js"),"fr-FR":()=>import("./fr-FR-FMLQPLOD.js"),gu:()=>import("./gu-BREQK3GJ.js"),he:()=>import("./he-VXZCGAHY.js"),hi:()=>import("./hi-F7Y62LAZ.js"),hu:()=>import("./hu-L6W5O2G5.js"),id:()=>import("./id-DCV57AQB.js"),it:()=>import("./it-JICU5WVL.js"),ja:()=>import("./ja-52MBIM3T.js"),km:()=>import("./km-PHVYTPLT.js"),kn:()=>import("./kn-5DYCOYAN.js"),ko:()=>import("./ko-FZIJZG6K.js"),lo:()=>import("./lo-YRHYLRZC.js"),ml:()=>import("./ml-QO64O4H6.js"),mr:()=>import("./mr-5WLN37JQ.js"),ms:()=>import("./ms-PIAATVMD.js"),my:()=>import("./my-3J665CWK.js"),nb:()=>import("./nb-F33WYJ6T.js"),ne:()=>import("./ne-AAIECB2W.js"),"nl-BE":()=>import("./nl-BE-SHZLAL5T.js"),"nl-NL":()=>import("./nl-NL-PHRY43UB.js"),nn:()=>import("./nn-S3SNETRB.js"),pa:()=>import("./pa-P2GAYL5A.js"),pl:()=>import("./pl-SGPLZAER.js"),"pt-BR":()=>import("./pt-BR-WKEKB5CG.js"),"pt-PT":()=>import("./pt-PT-AJZQS2C6.js"),ro:()=>import("./ro-HRV64STT.js"),ru:()=>import("./ru-7U566HR4.js"),si:()=>import("./si-5VUM5FGR.js"),sv:()=>import("./sv-UOGO55PW.js"),sw:()=>import("./sw-KVAYRFED.js"),ta:()=>import("./ta-MNWTH3F5.js"),te:()=>import("./te-5SBVH4OF.js"),th:()=>import("./th-2GWK7DBB.js"),tl:()=>import("./tl-OCD2O6J3.js"),tr:()=>import("./tr-VFMHVRQX.js"),uk:()=>import("./uk-PGHXMWJR.js"),ur:()=>import("./ur-4CR64XUI.js"),vi:()=>import("./vi-U7OT2LM7.js"),"zh-CN":()=>import("./zh-CN-CCYHPSVA.js"),"zh-HK":()=>import("./zh-HK-HE2T63O2.js"),"zh-Hant":()=>import("./zh-Hant-GBQLGJDF.js")},Xt=Object.keys(D);function tt(e){return e&&e in D?e:et}async function ge(e){return(await D[tt(e)]()).default}var rt="kanorio-elements",nt="kanorio-popup",ot="kanorio-part",P="data-kanorio-brand";function er(e,t,r){t?e.setAttribute("data-kanorio-theme",t):e.removeAttribute("data-kanorio-theme"),r?e.setAttribute(P,r):e.removeAttribute(P)}var st=`:is(.${rt}, .${nt}, .${ot})`,me=[".dark",'[data-theme="dark"]'],tr=me.join(", "),fe=me.map(e=>`${e} *`).join(", "),ye=['[data-kanorio-theme="dark"]','[data-kanorio-theme="dark"] *',`[data-kanorio-theme="auto"]:where(${fe})`,`[data-kanorio-theme="auto"]:where(${fe}) *`].join(", "),he='[data-kanorio-theme="auto"], [data-kanorio-theme="auto"] *';var xt=A(V(),1);q(B);var M="kanorio:token-change";function xe(e){let t=e?.replace(/\/+$/,"");if(t)return t;if(typeof window<"u")return window.location.origin;if(e)return"";throw new Error("@kanorio/elements: siteUrl is required outside the browser.")}function ar(e){let t=e?.replace(/\/+$/,"");return t||(typeof window<"u"?window.location.origin:null)}function it(e){return e||(typeof document<"u"&&document.documentElement.lang?document.documentElement.lang:"en")}var Re=()=>()=>{},k=Object.freeze({value:null,failures:0,round:0}),at=()=>k;function be(e){let t=new Map,r=new Map,n=new Set,o=0,i=()=>{for(let s of[...n])s()};return{entry:s=>t.get(s)??k,subscribe(s){return n.add(s),()=>{n.delete(s)}},load(s){let a=t.get(s);if(a&&a.value!==null)return Promise.resolve(a.value);let l=r.get(s);if(l)return l;let c=o,d=Promise.resolve().then(()=>e(s)).catch(()=>null).then(p=>{if(r.get(s)===d&&r.delete(s),c!==o)return p;let g=t.get(s)??k;return t.set(s,p===null?{...g,failures:g.failures+1}:{value:p,failures:g.failures,round:g.round}),i(),p});return r.set(s,d),d},clear(){o+=1;for(let[s,a]of t)t.set(s,{value:null,failures:a.failures,round:a.round+1});for(let s of r.keys())t.has(s)||t.set(s,{...k,round:1});r.clear(),i()},retryFailed(){let s=!1;for(let[a,l]of t)l.value!==null||r.has(a)||(t.set(a,{...l,round:l.round+1}),s=!0);s&&i()},reset(){o+=1,t.clear(),r.clear(),i()}}}function Ce(e,t){let r=(0,u.useSyncExternalStore)(t===null?Re:e.subscribe,()=>t===null?k:e.entry(t),at),[n,o]=(0,u.useState)(()=>({key:t,failures:t===null?0:e.entry(t).failures})),i=n;n.key!==t&&(i={key:t,failures:t===null?0:e.entry(t).failures},o(i));let s=t!==null&&r.value===null;(0,u.useEffect)(()=>{s&&t!==null&&e.load(t)},[e,t,s,r.round]);let a=t!==null&&r.value===null&&r.failures>i.failures;return(0,u.useMemo)(()=>({value:r.value,error:a}),[r.value,a])}var we=be(e=>ge(e)),N=be(e=>K({siteUrl:e}).get("/site").then(t=>typeof t?.id=="string"?t:null));typeof window<"u"&&window.addEventListener("online",()=>{we.retryFailed(),N.retryFailed()});function lt(e,t=!0){let{value:r,error:n}=Ce(we,t?e:null),[o,i]=(0,u.useState)(null);r!==null&&(o===null||o.messages!==r||o.locale!==e)&&i({messages:r,locale:e});let s=r??o?.messages??null,a=r!==null?e:o?.locale??e;return(0,u.useMemo)(()=>({messages:s,locale:a,error:n}),[s,a,n])}function lr(e){return N.load(e)}function ct(e,t=!0){let{value:r,error:n}=Ce(N,t?e:null),[o,i]=(0,u.useState)(null);r!==null&&(o===null||o.site!==r||o.siteUrl!==e)&&i({site:r,siteUrl:e});let s=r??(t&&o?.siteUrl===e?o.site:null);return(0,u.useMemo)(()=>({site:s,error:n}),[s,n])}function ke(e){let t=e.toLowerCase();return t.startsWith("zh-hans")||t.startsWith("zh-cn")||t.startsWith("zh-sg")?"zh-Hans":t.startsWith("zh")?"zh-Hant":t.startsWith("ja")?"ja":t.startsWith("ko")?"ko":"en"}function ut(e,t,r){let n=e.colors.primary.light,o=e.colors.primary.dark,i=Object.entries(e.radius).map(([d,p])=>`--site-radius-${d}: ${p};`).join(" "),s=ke(t),a=e.fonts.find(d=>d.locales.includes(s))??e.fonts[0],l=a?`--site-font-family: ${a.family};`:"",c=`--brand-color: ${o.background}; --brand-foreground: ${o.foreground};`;return[`:where(${r}) { --brand-color: ${n.background}; --brand-foreground: ${n.foreground}; ${i} ${l} font-family: var(--site-font-family, inherit); }`,`:where(${r}):where(${ye}) { ${c} }`,`@media (prefers-color-scheme: dark) { :where(${r}):where(${he}) { ${c} } }`].join(`
2
- `)}function dt(e,t){return`${e}-${ke(t)}`}var pt=typeof window>"u"?u.useEffect:u.useLayoutEffect,Ee=new Map;function gt(e,t,r){let n=r&&e?.brand?dt(e.id,t):null;return pt(()=>{if(!n||!e?.brand||typeof document>"u")return;let o=Ee.get(n);if(o&&o.site===e&&o.style.isConnected)return;let i=`kanorio-brand-${n}`,s=ut(e.brand,t,`[${P}="${n}"]`),a=document.getElementById(i);a||(a=document.createElement("style"),a.id=i,document.head.appendChild(a)),a.textContent!==s&&(a.textContent=s);for(let l of e.brand.fonts){if(!l.stylesheetUrl)continue;let c=`link[data-kanorio-font="${CSS.escape(l.stylesheetUrl)}"]`;if(document.head.querySelector(c))continue;let d=document.createElement("link");d.rel="stylesheet",d.href=l.stylesheetUrl,d.dataset.kanorioFont=l.stylesheetUrl,document.head.appendChild(d)}Ee.set(n,{site:e,style:a})},[n,e,t]),n}var w=new Set;function I(){for(let e of[...w])e()}function ft(e){return w.add(e),w.size===1&&(window.addEventListener("storage",I),window.addEventListener(M,I)),()=>{w.delete(e),w.size===0&&(window.removeEventListener("storage",I),window.removeEventListener(M,I))}}var ve=null;function mt(){try{return localStorage.getItem(b)}catch{return ve}}var Se=()=>null;function Te(e){ve=e;try{C(e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(M,{detail:{token:e}}))}function yt(e){let[t,r]=(0,u.useState)({given:e,written:null}),n=t.written;t.given!==e&&(n=null,r({given:e,written:null}));let o=(0,u.useCallback)(i=>{r(s=>({given:s.given,written:{token:i}})),Te(i)},[]);return(0,u.useMemo)(()=>e===void 0?null:{token:n?n.token:e,setToken:o},[e,n,o])}function ht(e,t){let n=yt(e)??t,o=(0,u.useSyncExternalStore)(n?Re:ft,n?Se:mt,Se);return(0,u.useMemo)(()=>n??{token:o,setToken:Te},[n,o])}var $=(0,u.createContext)(null);function cr(){return(0,u.useContext)($)?.config??null}function ur(e){let t=(0,u.useContext)($);return xe(e??t?.config.siteUrl)}function Et(e,t={}){let r=(0,u.useContext)($),n={...r?.config,...St(e)},o=xe(n.siteUrl),i=n.theme??"auto",s=n.timeZone??null,a=n.brand!==!1,{token:l,setToken:c}=ht(e.token,r?.token??null),d=lt(it(n.locale)),p=d.locale,{site:g,error:f}=ct(o,a||t.needsSite===!0),x=gt(g,p,a),y=(0,u.useMemo)(()=>H({siteUrl:o,token:()=>l,locale:p}),[o,l,p]),h=d.messages,F=d.error;return(0,u.useMemo)(()=>({siteUrl:o,token:l,setToken:c,locale:p,theme:i,timeZone:s,messages:h,messagesError:F,client:y,brandScope:x,site:g,siteError:f}),[o,l,c,p,i,s,h,F,y,x,g,f])}function dr(e={}){return Et(e)}function St(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}export{m as a,K as b,O as c,Xe as d,Ze as e,tt as f,rt as g,nt as h,ot as i,P as j,er as k,tr as l,ar as m,it as n,lt as o,lr as p,ct as q,gt as r,cr as s,ur as t,Et as u,dr as v};
3
- //# sourceMappingURL=chunk-QGR3QAQB.js.map
@@ -1,2 +0,0 @@
1
- import{BotProtectionAltcha,BotProtectionFields,preloadAltchaWidget,useBotProtection}from"./chunk-IXDKZO42.js";import{useIsInsideElementsRoot}from"./chunk-4MOCTNN7.js";import{PartScopeProvider}from"./chunk-763LNERD.js";import{useOptionalSiteLabels}from"./chunk-U7H3W23Q.js";import{ELEMENTS_PART_CLASS,markScope,optionalSiteUrl,resolveLocale,resolveVisitorLocale,useBrandStyle,useElementsMessages,useKanorioProviderConfig,useKanorioSiteUrl,useSiteMeta}from"./chunk-MIQK3T3Y.js";import{useEffect,useMemo as useMemo2}from"react";import{createContext,useContext,useMemo}from"react";import{jsx}from"react/jsx-runtime";var BotProtectionContext=createContext(null);import{Fragment,jsx as jsx2,jsxs}from"react/jsx-runtime";function useKanorioBotProtection(options={}){const siteUrl=useKanorioSiteUrl(options.siteUrl);return useBotProtection({...options,variant:options.variant??"full",challengeUrl:`${siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`})}var ENGLISH_ALTCHA_LABELS={botProtection:"Human verification",botProtectionLoading:"Loading human verification"};function useBotProtectionPart(theme,localeProp,wantsAltcha){const parent=useKanorioProviderConfig();const insideRoot=useIsInsideElementsRoot();const locale=resolveLocale(localeProp??parent?.locale);const hostTheme=theme??(parent?.theme==="light"||parent?.theme==="dark"?parent.theme:null);const resolvedTheme=insideRoot?null:hostTheme;const brandSiteUrl=wantsAltcha&&!insideRoot&&parent!==null&&parent.brand!==false?optionalSiteUrl(parent.siteUrl):null;const{site}=useSiteMeta(brandSiteUrl??"",brandSiteUrl!==null);const brandScope=useBrandStyle(site,locale,brandSiteUrl!==null);const scope=useMemo2(()=>insideRoot?null:{className:ELEMENTS_PART_CLASS,mark:element=>markScope(element,resolvedTheme,brandScope)},[insideRoot,resolvedTheme,brandScope]);const rootLabels=useOptionalSiteLabels();const english=resolveVisitorLocale(locale).startsWith("en");const{messages}=useElementsMessages(locale,wantsAltcha&&rootLabels===null&&!english);const labels=useMemo2(()=>{if(rootLabels)return void 0;if(!messages||english)return ENGLISH_ALTCHA_LABELS;return{botProtection:messages.ui.botProtection,botProtectionLoading:messages.ui.botProtectionLoading}},[rootLabels,messages,english]);useEffect(()=>{if(wantsAltcha)preloadAltchaWidget(locale)},[wantsAltcha,locale]);return{scope,labels,locale}}function KanorioBotProtection({theme,...props}){return jsxs(Fragment,{children:[props.renderAltcha===false?null:jsx2(KanorioBotProtectionAltcha,{theme,...props}),jsx2(BotProtectionFields,{...props,renderAltcha:false})]})}function KanorioBotProtectionAltcha({theme,...props}){const{scope,labels,locale}=useBotProtectionPart(theme,props.locale,props.variant==="full");return jsx2(PartScopeProvider,{value:scope,children:jsx2(BotProtectionAltcha,{...props,locale,labels})})}export{useKanorioBotProtection,ENGLISH_ALTCHA_LABELS,KanorioBotProtection,KanorioBotProtectionAltcha};
2
- //# sourceMappingURL=chunk-SUXTLVTX.js.map
@@ -1,3 +0,0 @@
1
- import{CUSTOMER_SESSION_HINT_COOKIE_NAME,CustomerAccountPanel,createHostedCustomerAuthTransport,customerButtonClass,normalizeCustomerAuthMethods}from"./chunk-EE4S6NRV.js";import{composeRefs}from"./chunk-AQ6F6MIJ.js";import{useHydrated}from"./chunk-63XJWMJG.js";import{onDemand}from"./chunk-E77WGXYW.js";import{LOGIN_EVENT,LOGOUT_EVENT}from"./chunk-LWKCGUHS.js";import{BotProtectionConfigProvider,parsePublicBotProtectionConfig}from"./chunk-IXDKZO42.js";import{useSiteChrome}from"./chunk-Z4A5NQWJ.js";import{lockPageScroll}from"./chunk-HFYLTH5B.js";import{LoaderCircle,X}from"./chunk-33AQQY6T.js";import{clsx,cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-4MOCTNN7.js";import{fillLabel}from"./chunk-KNNN5V3T.js";import{useSiteLabels}from"./chunk-U7H3W23Q.js";import{KanorioApiError,completeHostedCustomerLogin,createCustomerClient,startHostedCustomerLogin,useElementContext}from"./chunk-MIQK3T3Y.js";import{useEffect as useEffect4,useMemo as useMemo2,useState as useState2}from"react";import{jsx,jsxs}from"react/jsx-runtime";import{jsx as jsx2}from"react/jsx-runtime";import{jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";import{useEffect,useRef}from"react";import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";import{createContext,useCallback as useCallback2,useContext,useEffect as useEffect3,useMemo,useRef as useRef3,useState}from"react";import{useCallback,useEffect as useEffect2,useRef as useRef2}from"react";import{createPortal}from"react-dom";import{jsx as jsx5,jsxs as jsxs4}from"react/jsx-runtime";var FOCUSABLE_SELECTOR='a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';function SiteResponsiveModal({open,onClose,title,closeLabel,children,footer,showHeader=true,dismissible=true,desktopZIndexClassName="z-[var(--z-dialog,200)]",drawerZIndexClassName="z-[var(--z-dialog,200)]",maxWidthClassName="max-w-lg",desktopVariant="dialog",surface="glass",headerSlot,subheader,bodyClassName,footerClassName,id}){const isSide=desktopVariant==="side";const chrome=useSiteChrome();const mounted=useHydrated();const onCloseRef=useRef2(onClose);const dismissibleRef=useRef2(dismissible);useEffect2(()=>{onCloseRef.current=onClose;dismissibleRef.current=dismissible});useEffect2(()=>{if(!open)return;const releaseScrollLock=lockPageScroll();const onKeyDown=e=>{if(e.key==="Escape"&&dismissibleRef.current)onCloseRef.current()};document.addEventListener("keydown",onKeyDown);return()=>{releaseScrollLock();document.removeEventListener("keydown",onKeyDown)}},[open]);const sheetRef=useRef2(null);const subheaderRef=useRef2(null);const bodyRef=useRef2(null);const dragZoneRef=useRef2(null);const dragStartY=useRef2(null);const dragDelta=useRef2(0);const portalTarget=chrome?chrome.slots.modal:mounted?document.body:null;const rendered=open&&!!portalTarget;useEffect2(()=>{if(!rendered)return;const sheet=sheetRef.current;if(!sheet)return;const previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null;const focusables=()=>Array.from(sheet.querySelectorAll(FOCUSABLE_SELECTOR)).filter(el=>!el.hasAttribute("disabled")&&el.getAttribute("aria-hidden")!=="true");const firstInSubheader=subheaderRef.current?.querySelector(FOCUSABLE_SELECTOR);const firstInBody=bodyRef.current?.querySelector(FOCUSABLE_SELECTOR);(firstInSubheader??firstInBody??focusables()[0]??sheet).focus({preventScroll:true});const onKeyDown=e=>{if(e.key!=="Tab")return;const list=focusables();if(list.length===0){e.preventDefault();sheet.focus();return}const first=list[0];const last=list[list.length-1];const active=document.activeElement;const inside=active instanceof Node&&sheet.contains(active);if(e.shiftKey){if(!inside||active===first||active===sheet){e.preventDefault();last.focus()}}else if(!inside||active===last){e.preventDefault();first.focus()}};document.addEventListener("keydown",onKeyDown);return()=>{document.removeEventListener("keydown",onKeyDown);if(previouslyFocused&&previouslyFocused.isConnected){previouslyFocused.focus({preventScroll:true})}}},[rendered]);const onTouchStart=useCallback(e=>{if(!dismissibleRef.current)return;const target=e.target instanceof Node?e.target:null;const fromDragZone=!!target&&!!dragZoneRef.current?.contains(target);const bodyAtTop=(bodyRef.current?.scrollTop??0)<=0;if(!fromDragZone&&!bodyAtTop)return;dragStartY.current=e.touches[0].clientY;dragDelta.current=0},[]);const onTouchMove=useCallback(e=>{if(dragStartY.current==null)return;const delta=e.touches[0].clientY-dragStartY.current;if(delta<0&&(bodyRef.current?.scrollTop??0)>0){dragStartY.current=null;if(sheetRef.current)sheetRef.current.style.transform="";return}dragDelta.current=delta;if(delta>0&&sheetRef.current){sheetRef.current.style.transform=`translateY(${delta}px)`}},[]);const onTouchEnd=useCallback(()=>{if(dragStartY.current==null)return;if(sheetRef.current){sheetRef.current.style.transform=""}if(dragDelta.current>100&&dismissibleRef.current){onCloseRef.current()}dragStartY.current=null;dragDelta.current=0},[]);if(!rendered)return null;const headerCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"relative h-10 w-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors before:absolute before:-inset-0.5 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});const floatingCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"absolute right-2 top-2 z-10 h-9 w-9 flex items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm hover:bg-black/60 transition-colors before:absolute before:-inset-1 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});return createPortal(jsxs4("div",{className:cn("pointer-events-auto fixed inset-0 flex items-end justify-center",isSide?"md:items-stretch md:justify-end":"md:items-center md:p-4",desktopZIndexClassName,drawerZIndexClassName),role:"dialog","aria-modal":"true","aria-label":title,children:[jsx5("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:dismissible?onClose:void 0,"aria-hidden":"true"}),jsxs4("div",{id,ref:sheetRef,tabIndex:-1,onTouchStart,onTouchMove,onTouchEnd,className:cn("relative flex w-full flex-col overflow-hidden outline-none transition-transform duration-150 ease-out","max-h-[90dvh] rounded-t-[var(--site-radius-card)]",isSide?"animate-site-side-panel md:h-full md:max-h-full md:rounded-none md:rounded-l-[var(--site-radius-card)] md:border-y-0 md:border-r-0":"animate-site-sheet-up md:max-h-[80vh] md:rounded-[var(--site-radius-card)]",surface==="glass"?"glass-card":"border border-zinc-200/50 bg-white shadow-2xl shadow-black/20 dark:border-zinc-700/50 dark:bg-zinc-900 dark:shadow-black/40","max-md:max-w-none",maxWidthClassName),children:[jsxs4("div",{ref:dragZoneRef,className:"flex shrink-0 flex-col",children:[dismissible&&jsx5("button",{type:"button",onClick:onClose,className:"mx-auto mt-1.5 mb-0.5 flex h-4 w-14 shrink-0 items-center justify-center md:hidden","aria-label":closeLabel,children:jsx5("span",{className:"h-1 w-full rounded-full bg-zinc-400 dark:bg-zinc-500"})}),showHeader?jsxs4("div",{className:"flex flex-shrink-0 items-center justify-between border-b border-zinc-200/50 px-4 py-2 dark:border-zinc-700/50",children:[headerSlot??jsx5("h2",{className:"text-lg font-semibold text-zinc-900 dark:text-zinc-50",children:title}),headerSlot&&jsx5("h2",{className:"sr-only",children:title}),dismissible&&headerCloseButton]}):dismissible&&floatingCloseButton]}),subheader&&jsx5("div",{ref:subheaderRef,className:"shrink-0",children:subheader}),jsx5("div",{ref:bodyRef,className:cn("min-h-0 flex-1 overflow-y-auto overscroll-contain kano-scrollbar",showHeader?"p-4":"p-0",bodyClassName),children}),footer&&jsx5("div",{className:cn("flex-shrink-0 border-t border-zinc-200/50 p-4 dark:border-zinc-700/50",footerClassName),children:footer})]})]}),portalTarget)}import*as React2 from"react";import*as React from"react";import{Fragment as Fragment2,jsx as jsx6}from"react/jsx-runtime";var REACT_LAZY_TYPE=Symbol.for("react.lazy");var use=React[" use ".trim().toString()];function isPromiseLike(value){return typeof value==="object"&&value!==null&&"then"in value}function isLazyComponent(element){return element!=null&&typeof element==="object"&&"$$typeof"in element&&element.$$typeof===REACT_LAZY_TYPE&&"_payload"in element&&isPromiseLike(element._payload)}function createSlot(ownerName){const SlotClone=createSlotClone(ownerName);const Slot2=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}const childrenArray=React.Children.toArray(children);const slottable=childrenArray.find(isSlottable);if(slottable){const newElement=slottable.props.children;const newChildren=childrenArray.map(child=>{if(child===slottable){if(React.Children.count(newElement)>1)return React.Children.only(null);return React.isValidElement(newElement)?newElement.props.children:null}else{return child}});return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children:React.isValidElement(newElement)?React.cloneElement(newElement,void 0,newChildren):null})}return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children})});Slot2.displayName=`${ownerName}.Slot`;return Slot2}var Slot=createSlot("Slot");function createSlotClone(ownerName){const SlotClone=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}if(React.isValidElement(children)){const childrenRef=getElementRef(children);const props2=mergeProps(slotProps,children.props);if(children.type!==React.Fragment){props2.ref=forwardedRef?composeRefs(forwardedRef,childrenRef):childrenRef}return React.cloneElement(children,props2)}return React.Children.count(children)>1?React.Children.only(null):null});SlotClone.displayName=`${ownerName}.SlotClone`;return SlotClone}var SLOTTABLE_IDENTIFIER=Symbol("radix.slottable");function isSlottable(child){return React.isValidElement(child)&&typeof child.type==="function"&&"__radixId"in child.type&&child.type.__radixId===SLOTTABLE_IDENTIFIER}function mergeProps(slotProps,childProps){const overrideProps={...childProps};for(const propName in childProps){const slotPropValue=slotProps[propName];const childPropValue=childProps[propName];const isHandler=/^on[A-Z]/.test(propName);if(isHandler){if(slotPropValue&&childPropValue){overrideProps[propName]=(...args)=>{const result=childPropValue(...args);slotPropValue(...args);return result}}else if(slotPropValue){overrideProps[propName]=slotPropValue}}else if(propName==="style"){overrideProps[propName]={...slotPropValue,...childPropValue}}else if(propName==="className"){overrideProps[propName]=[slotPropValue,childPropValue].filter(Boolean).join(" ")}}return{...slotProps,...overrideProps}}function getElementRef(element){let getter=Object.getOwnPropertyDescriptor(element.props,"ref")?.get;let mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.ref}getter=Object.getOwnPropertyDescriptor(element,"ref")?.get;mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.props.ref}return element.props.ref||element.ref}var falsyToString=value=>typeof value==="boolean"?`${value}`:value===0?"0":value;var cx=clsx;var cva=(base,config)=>props=>{var _config_compoundVariants;if((config===null||config===void 0?void 0:config.variants)==null)return cx(base,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className);const{variants,defaultVariants}=config;const getVariantClassNames=Object.keys(variants).map(variant=>{const variantProp=props===null||props===void 0?void 0:props[variant];const defaultVariantProp=defaultVariants===null||defaultVariants===void 0?void 0:defaultVariants[variant];if(variantProp===null)return null;const variantKey=falsyToString(variantProp)||falsyToString(defaultVariantProp);return variants[variant][variantKey]});const propsWithoutUndefined=props&&Object.entries(props).reduce((acc,param)=>{let[key,value]=param;if(value===void 0){return acc}acc[key]=value;return acc},{});const getCompoundVariantClassNames=config===null||config===void 0?void 0:(_config_compoundVariants=config.compoundVariants)===null||_config_compoundVariants===void 0?void 0:_config_compoundVariants.reduce((acc,param)=>{let{class:cvClass,className:cvClassName,...compoundVariantOptions}=param;return Object.entries(compoundVariantOptions).every(param2=>{let[key,value]=param2;return Array.isArray(value)?value.includes({...defaultVariants,...propsWithoutUndefined}[key]):{...defaultVariants,...propsWithoutUndefined}[key]===value})?[...acc,cvClass,cvClassName]:acc},[]);return cx(base,getVariantClassNames,getCompoundVariantClassNames,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className)};import{jsx as jsx7}from"react/jsx-runtime";var buttonVariants=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-200 hover:scale-[1.02] hover:shadow-md active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 disabled:hover:scale-100 disabled:hover:shadow-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-11 rounded-[var(--site-radius-button)] px-4 py-2",sm:"h-9 rounded-[var(--site-radius-button)] px-3",lg:"h-14 rounded-[var(--site-radius-button)] px-8",icon:"h-11 w-11 rounded-full"}},defaultVariants:{variant:"default",size:"default"}});var Button=React2.forwardRef(({className,variant,size,asChild=false,...props},ref)=>{const Comp=asChild?Slot:"button";return jsx7(Comp,{className:cn(buttonVariants({variant,size,className})),ref,...props})});Button.displayName="Button";import{jsx as jsx8,jsxs as jsxs5}from"react/jsx-runtime";var CustomerAccountPanel2=onDemand(()=>import("./CustomerAccountPanel-RWEHWBJY.js").then(m=>m.CustomerAccountPanel),()=>jsx8("div",{className:"flex min-h-40 items-center justify-center","aria-busy":"true",children:jsx8(LoaderCircle,{className:"h-5 w-5 animate-spin opacity-50"})}));function hasCustomerSessionHint(){if(typeof document==="undefined")return false;return document.cookie.split(";").some(part=>part.trim().startsWith(`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=`))}function clearCustomerSessionHint(){if(typeof document==="undefined")return;document.cookie=`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=; Max-Age=0; Path=/; SameSite=Lax`}var overviewCacheKey=siteId=>`knr_customer_overview:${siteId}`;function sessionFingerprint(sessionKey){if(sessionKey===null)return"";let hash=2166136261;for(let index=0;index<sessionKey.length;index+=1){hash^=sessionKey.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function readCachedOverview(siteId,sessionKey){try{const raw=typeof sessionStorage==="undefined"?null:sessionStorage.getItem(overviewCacheKey(siteId));if(!raw)return null;const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||!parsed.contact||parsed.session!==sessionFingerprint(sessionKey))return null;return parsed}catch{return null}}function writeCachedOverview(siteId,overview,sessionKey){try{if(typeof sessionStorage==="undefined")return;if(overview){const{id,email,name}=overview.contact;const cached={session:sessionFingerprint(sessionKey),contact:{id,email,name},sections:overview.sections,landing:overview.landing};sessionStorage.setItem(overviewCacheKey(siteId),JSON.stringify(cached))}else sessionStorage.removeItem(overviewCacheKey(siteId))}catch{}}var SESSION_RETRY_DELAYS_MS=[1e3,3e3,1e4];var CustomerAuthContext=createContext(null);function CustomerAuthProvider({config,children}){const[user,setUser]=useState(null);const[sections,setSections]=useState([]);const[landing,setLanding]=useState(null);const[check,setCheck]=useState("pending");const[hinted,setHinted]=useState(false);const[panelOpen,setPanelOpen]=useState(false);const[refreshTick,setRefreshTick]=useState(0);const transport=useMemo(()=>config?.transport??createHostedCustomerAuthTransport(),[config?.transport]);const sessionHint=config?.sessionHint??hasCustomerSessionHint;const siteId=config?.siteId??null;const sessionKey=config?.sessionKey??null;const lastCheckRef=useRef3(null);const sessionKeyRef=useRef3(sessionKey);sessionKeyRef.current=sessionKey;const applySession=useCallback2(overview=>{if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done");if(!overview)setRefreshTick(tick=>tick+1)},[siteId]);const retrySession=useCallback2(()=>{setCheck("pending");setRefreshTick(tick=>tick+1)},[]);useEffect3(()=>{if(siteId===null)return;const previous=lastCheckRef.current;lastCheckRef.current={siteId,sessionKey};if(!sessionHint()){writeCachedOverview(siteId,null,sessionKey);setHinted(false);setUser(null);setSections([]);setLanding(null);setCheck("done");return}setHinted(true);if(previous===null||previous.siteId!==siteId||previous.sessionKey!==sessionKey)setCheck("pending");const cached=readCachedOverview(siteId,sessionKey);if(cached){setUser(cached.contact);setSections(cached.sections??[]);setLanding(cached.landing??null)}else if(previous!==null&&(previous.siteId!==siteId||previous.sessionKey!==null&&previous.sessionKey!==sessionKey)){setUser(null);setSections([]);setLanding(null)}let cancelled=false;let retryTimer=null;const ask=attempt=>{transport.session().then(overview=>{if(cancelled)return;writeCachedOverview(siteId,overview,sessionKey);if(!overview)clearCustomerSessionHint();setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")}).catch(()=>{if(cancelled)return;const delay=SESSION_RETRY_DELAYS_MS[attempt];if(delay!==void 0){retryTimer=setTimeout(()=>ask(attempt+1),delay);return}setCheck(current=>current==="pending"?"failed":current)})};ask(0);return()=>{cancelled=true;if(retryTimer!==null)clearTimeout(retryTimer)}},[siteId,sessionKey,transport,refreshTick]);useEffect3(()=>{if(!config||typeof document==="undefined")return;const sync=()=>{if(document.visibilityState!=="visible")return;const hint=sessionHint();if(hint&&user===null)setRefreshTick(tick=>tick+1);if(!hint&&user!==null){writeCachedOverview(config.siteId,null,sessionKey);setUser(null);setSections([]);setLanding(null);setCheck("done")}};document.addEventListener("visibilitychange",sync);window.addEventListener("focus",sync);return()=>{document.removeEventListener("visibilitychange",sync);window.removeEventListener("focus",sync)}},[config,user]);const refresh=useCallback2(async()=>{let overview;try{overview=await transport.session()}catch{setCheck("done");return}if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")},[transport,siteId]);const signOut=useCallback2(async()=>{await transport.signOut();if(siteId)writeCachedOverview(siteId,null,sessionKeyRef.current);clearCustomerSessionHint();setUser(null);setSections([]);setLanding(null);setCheck("done")},[transport,siteId]);const openPanel=useCallback2(()=>setPanelOpen(true),[]);const closePanel=useCallback2(()=>setPanelOpen(false),[]);const value=useMemo(()=>config?{siteId:config.siteId,siteName:config.siteName,locale:config.locale,siteLocale:config.siteLocale,accountBaseUrl:config.accountBaseUrl,showNavEntry:config.showNavEntry,allowSignup:config.allowSignup,methods:config.methods,messages:config.messages,transport,user,sections,landing,checked:check!=="pending",pending:hinted&&check==="pending"&&user===null,sessionUnavailable:hinted&&check==="failed"&&user===null,retrySession,applySession,refresh,signOut,panelOpen,openPanel,closePanel}:null,[config,transport,user,sections,landing,check,hinted,applySession,retrySession,refresh,signOut,panelOpen,openPanel,closePanel]);return jsxs5(CustomerAuthContext.Provider,{value,children:[children,value?jsx8(CustomerAccountModal,{auth:value}):null]})}function useCustomerAuth(){return useContext(CustomerAuthContext)}function CustomerAccountModal({auth}){const{ui}=useSiteLabels();const title=auth.user||auth.pending?ui.myAccount:fillLabel(auth.messages.signInTitle,{siteName:auth.siteName});return jsx8(SiteResponsiveModal,{id:"customer-account-panel",open:auth.panelOpen,onClose:auth.closePanel,title,closeLabel:ui.close,maxWidthClassName:"max-w-md",surface:"solid",bodyClassName:"p-5 sm:p-6",children:jsx8(CustomerAccountPanel2,{variant:"panel",auth,onNavigate:auth.closePanel})})}import{Fragment as Fragment3,jsx as jsx9,jsxs as jsxs6}from"react/jsx-runtime";function loginReturnTo(returnTo){if(returnTo?.startsWith("/"))return returnTo;if(typeof window==="undefined")return void 0;const url=new URL(window.location.href);for(const key of["token","handoff","error","verify","email"])url.searchParams.delete(key);return`${url.pathname}${url.search}`}function failure(error){if(error instanceof KanorioApiError)return{ok:false,code:error.code??"SERVER_ERROR"};return{ok:false,code:"NETWORK_ERROR"}}var sessionRequests=new Map;function createBearerCustomerAuthTransport(params){return bearerTransport(params,false)}function bearerTransport(params,strictSession){const siteUrl=params.siteUrl.replace(/\/+$/,"");const client=createCustomerClient({siteUrl,token:params.token});const post=async(path,body)=>{try{const data=await client.post(path,{body});return{ok:true,...data}}catch(error){return failure(error)}};const get=async path=>{try{const data=await client.get(path,{});return{ok:true,...data}}catch(error){return failure(error)}};const grant=result=>{if(result.ok&&result.sessionToken)params.onToken(result.sessionToken);return result};return{altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,requestChallenge:({email,locale,returnTo,protection})=>post("/auth/challenge",{email,locale,returnTo,...protection}),verifyCode:async({email,code})=>grant(await post("/auth/verify",{method:"code",email,code,channel:"bearer"})),verifyToken:async({method,token})=>grant(await post("/auth/verify",{method,token,channel:"bearer"})),startOauth:({method,returnTo,locale})=>post("/auth/oauth/start",{method,returnTo,locale}),passkeyLoginOptions:()=>post("/auth/passkey/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyLoginVerify:async input=>grant(await post("/auth/passkey/verify",{...input,channel:"bearer"})),listPasskeys:()=>get("/passkeys"),passkeyRegisterOptions:()=>post("/passkeys/register/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyRegister:input=>post("/passkeys/register",input),session:()=>{const token=params.token();if(!token)return Promise.resolve(null);const key=`${siteUrl}
2
- ${token}`;const running=sessionRequests.get(key);const request=running??createCustomerClient({siteUrl,token}).get("/me").then(data=>{const overview=data;if(!overview.contact)return null;const{id,email,name}=overview.contact;return{contact:{id,email,name},sections:overview.sections??[],landing:overview.landing??"/account"}},error=>{if(error instanceof KanorioApiError&&error.status===401)return null;throw error});if(!running){sessionRequests.set(key,request);void request.then(()=>sessionRequests.delete(key),()=>sessionRequests.delete(key))}return strictSession?request:request.catch(()=>null)},signOut:async()=>{try{await client.delete("/session",{body:{mode:"current"}})}catch{}params.onToken(null)}}}var hostedExchanges=new Map;function hostedExchange(siteUrl,clientId){const key=`${siteUrl}|${clientId}`;const running=hostedExchanges.get(key);if(running)return running;if(!new URLSearchParams(window.location.search).has("code"))return null;const exchange={result:completeHostedCustomerLogin({siteUrl,clientId}),signedIn:false};hostedExchanges.set(key,exchange);void exchange.result.then(()=>hostedExchanges.delete(key),()=>hostedExchanges.delete(key));return exchange}function KanorioAccount({siteName,mode="direct",redirectUri,returnTo,onLogin,onLogout,renderSignedIn,className,...config}){const ctx=useElementContext(config,{needsSite:true});const site=ctx.site;const[redirectState,setRedirectState]=useState2({busy:false,error:null});const siteId=site?.id??"";const setToken=ctx.setToken;useEffect4(()=>{if(mode!=="redirect"||!siteId||typeof window==="undefined")return;const exchange=hostedExchange(ctx.siteUrl,siteId);if(!exchange)return;let cancelled=false;setRedirectState({busy:true,error:null});exchange.result.then(grant=>{if(cancelled)return;if(grant&&!exchange.signedIn){exchange.signedIn=true;setToken(grant.accessToken);const session={token:grant.accessToken,contactId:grant.contactId,expiresAt:grant.expiresAt};onLogin?.(session);window.dispatchEvent(new CustomEvent(LOGIN_EVENT,{detail:session}))}setRedirectState({busy:false,error:null})}).catch(error=>{if(cancelled)return;setRedirectState({busy:false,error:error instanceof KanorioApiError?error.code:"NETWORK_ERROR"})});return()=>{cancelled=true}},[mode,siteId,ctx.siteUrl,setToken]);const[initial]=useState2(()=>{if(typeof window==="undefined")return{};const params=new URLSearchParams(window.location.search);return{email:params.get("email")??void 0,token:params.get("token")??void 0,handoff:params.get("handoff")??void 0,verify:params.get("verify")==="1",error:params.get("error")??void 0}});const tokenRef=useLatest(ctx.token);const transport=useMemo2(()=>bearerTransport({siteUrl:ctx.siteUrl,token:()=>tokenRef.current,onToken:token=>{tokenRef.current=token;setToken(token)}},true),[ctx.siteUrl,setToken,tokenRef]);const resolvedSiteName=siteName??site?.brand?.displayName??site?.name??"";const authConfig=useMemo2(()=>site&&ctx.messages?{siteId:site.id,siteName:resolvedSiteName,locale:ctx.locale,siteLocale:site.locale??ctx.locale,accountBaseUrl:ctx.siteUrl,showNavEntry:site.customerAccess?.showNavEntry===true,allowSignup:site.customerAccess?.allowSignup===true,methods:normalizeCustomerAuthMethods(site.customerAccess?.methods),messages:ctx.messages.account,transport,sessionHint:()=>Boolean(tokenRef.current),sessionKey:ctx.token}:null,[site,ctx.messages,ctx.locale,ctx.siteUrl,ctx.token,resolvedSiteName,transport,tokenRef]);if(!ctx.messages)return jsx9(ElementsRoot,{context:ctx,className,loading:true});return jsx9(ElementsRoot,{context:ctx,className,children:jsx9(BotProtectionConfigProvider,{value:parsePublicBotProtectionConfig(site?.botProtection),children:jsx9(CustomerAuthProvider,{config:authConfig,children:mode==="redirect"?jsx9(RedirectBody,{siteUrl:ctx.siteUrl,siteId,siteName:resolvedSiteName,redirectUri,busy:redirectState.busy,error:redirectState.error,messages:ctx.messages.account,onLogout,renderSignedIn}):jsx9(AccountBody,{returnTo:loginReturnTo(returnTo),initial,onLogin,onLogout,renderSignedIn})})})})}function RedirectBody({siteUrl,siteId,siteName,redirectUri,busy,error,messages,onLogout,renderSignedIn}){const auth=useCustomerAuth();const[starting,setStarting]=useState2(false);if(!auth)return jsx9("div",{"aria-busy":"true"});if(auth.user){if(renderSignedIn)return jsx9(Fragment3,{children:renderSignedIn(()=>void auth.signOut().then(()=>emitLogout(onLogout)))});return jsx9("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:jsx9(CustomerAccountPanel,{variant:"panel",auth,onSignedOut:()=>emitLogout(onLogout)})})}const start=async()=>{if(!siteId)return;setStarting(true);try{await startHostedCustomerLogin({siteUrl,clientId:siteId,redirectUri})}catch{setStarting(false)}};if(auth.sessionUnavailable){return jsxs6("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[jsx9("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:messages.errorServiceUnavailable}),jsx9("button",{type:"button",className:customerButtonClass({block:true}),onClick:auth.retrySession,children:messages.contentRetry})]})}return jsxs6("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[error?jsx9("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:messages.errorGeneric}):null,jsx9("button",{type:"button",className:customerButtonClass({block:true}),onClick:()=>void start(),disabled:starting||busy||auth.pending||!siteId,"aria-busy":busy||auth.pending||void 0,children:busy||auth.pending?messages.sessionChecking:fillLabel(messages.signInTitle,{siteName})})]})}function AccountBody({returnTo,initial,onLogin,onLogout,renderSignedIn}){const auth=useCustomerAuth();if(!auth)return jsx9("div",{"aria-busy":"true"});if(auth.user&&renderSignedIn){return jsx9(Fragment3,{children:renderSignedIn(()=>void auth.signOut().then(()=>emitLogout(onLogout)))})}return jsx9("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:jsx9(CustomerAccountPanel,{variant:"panel",auth,initial,returnTo,onSignedIn:grant=>{if(!grant.sessionToken)return;const session={token:grant.sessionToken,contactId:grant.contactId??"",expiresAt:grant.expiresAt??""};onLogin?.(session);window.dispatchEvent(new CustomEvent(LOGIN_EVENT,{detail:session}))},onSignedOut:()=>emitLogout(onLogout)})})}function emitLogout(onLogout){onLogout?.();window.dispatchEvent(new CustomEvent(LOGOUT_EVENT))}function useLatest(value){const ref=useState2(()=>({current:value}))[0];useEffect4(()=>{ref.current=value},[ref,value]);ref.current=value;return ref}export{createBearerCustomerAuthTransport,KanorioAccount};
3
- //# sourceMappingURL=chunk-UIHBR4NU.js.map
@@ -1,2 +0,0 @@
1
- import{c as f,d as p,e as y,g as b,h as E,i as R}from"./chunk-GJY6AQIS.js";function m(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string")return null;let r=e.normalize("NFKC").replace(/[\s,]/g,"");if(!/^[+-]?(\d+\.?\d*|\.\d+)$/.test(r))return null;let n=Number(r);return Number.isFinite(n)?n:null}var k=/^[a-z0-9][a-z0-9_-]{0,39}$/;function v(e){return e==null||e===""||Array.isArray(e)&&e.length===0}var P=/^[^\s@]+@[^\s@]+\.[^\s@]+$/u,U=254;function I(e){return e.length<=U&&P.test(e)}var H=/^(\d{4})-(\d{2})-(\d{2})$/u,X=/^(\d{2}):(\d{2})$/u;function w(e){let r=H.exec(e);if(!r)return!1;let[,n,i,t]=r.map(Number),u=new Date(Date.UTC(n,i-1,t));return u.getUTCFullYear()===n&&u.getUTCMonth()===i-1&&u.getUTCDate()===t}function C(e){let r=X.exec(e);if(!r)return!1;let[,n,i]=r.map(Number);return n>=0&&n<=23&&i>=0&&i<=59}function O(e,r,n=1){if(typeof e!="string")return{ok:!1,code:"required"};let i=e.trim();return i?i.length>r?{ok:!1,code:"too_long"}:i.length<n?{ok:!1,code:"too_short"}:{ok:!0,value:i}:{ok:!1,code:"required"}}var z=2048;function T(e,r=z){if(typeof e!="string"||e.length>r)return null;try{let n=new URL(e.trim());return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password?null:n}catch{return null}}var B=200;function S(e,r=B){if(e.length===0||e.length>r||/\([^()]*[+*|][^()]*\)\s*[+*{]/.test(e)||/\\[1-9]/.test(e)||/\(\?[<=!]/.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function $(e){return e.filter(r=>f(r.type))}function x(e){return e==null?!1:typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:typeof e=="object"?Object.entries(e).some(([r,n])=>r!=="countryCode"&&typeof n=="string"&&n.trim()!==""):!0}function ye(e,r){return $(e).filter(n=>x(r[n.id])).length}var _=["answered","not_answered"],F=["answered","not_answered","equals","not_equals","contains"],j=["answered","not_answered","includes","not_includes"],N=["answered","not_answered","equals","not_equals","gt","gte","lt","lte"],W={short_text:F,long_text:F,url:F,email:_,phone:_,date:_,time:_,choice:j,number:N,rating:N,file:[],statement:[],address:[],tax_id:[],hidden:F};function Y(e){return W[e]??[]}function K(e,r){switch(r){case"answered":case"not_answered":return"none";case"includes":case"not_includes":return"option";case"contains":return"text";case"equals":case"not_equals":return e==="number"||e==="rating"?"number":"text";case"gt":case"gte":case"lt":case"lte":return"number"}}function G(e){return e==null?!1:typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:!0}function g(e){return typeof e=="string"?e.normalize("NFKC").trim().toLowerCase():typeof e=="number"?String(e):""}function Q(e,r,n){if(!Y(r).includes(e.op))return null;let i=G(n);switch(e.op){case"answered":return i;case"not_answered":return!i;case"includes":case"not_includes":{let u=(Array.isArray(n)?n:typeof n=="string"&&n?[n]:[]).includes(e.value);return e.op==="includes"?u:!u}case"contains":return i&&g(n).includes(g(e.value));case"equals":case"not_equals":{if(K(r,e.op)==="number"){let u=m(n),o=u!==null&&u===e.value;return e.op==="equals"?o:!o}let t=i&&g(n)===g(e.value);return e.op==="equals"?t:!t}case"gt":case"gte":case"lt":case"lte":{let t=m(n),u=typeof e.value=="number"?e.value:null;return t===null||u===null?!1:e.op==="gt"?t>u:e.op==="gte"?t>=u:e.op==="lt"?t<u:t<=u}}}function V(e,r){let n=new Set,i=new Map;for(let t of e){let u=t.visibleWhen,o=u&&Array.isArray(u.conditions)?u.conditions:[];if(o.length===0||t.type==="email"||t.type==="phone"){n.add(t.id),i.set(t.id,t.type);continue}let a=!1,l=o.map(c=>{let h=c.kind==="hidden"?"hidden":i.get(c.ref);if(!h)return a=!0,!1;let q=c.kind==="hidden"||n.has(c.ref)?r[c.ref]:null,A=Q(c,h,q);return A===null&&(a=!0),A===!0});(a||(u?.match==="any"?l.some(Boolean):l.every(Boolean)))&&n.add(t.id),i.set(t.id,t.type)}return n}function Ae(e){return e.some(r=>(r.visibleWhen?.conditions?.length??0)>0)}var J=["required","invalid_email","invalid_phone","invalid_date","invalid_time","too_long","too_short","invalid_format","invalid_option","other_required","too_few_options","too_many_options","invalid_number","not_integer","out_of_range","invalid_url","date_out_of_range","invalid_address","invalid_tax_id","invalid_postal_code","invalid"];function Z(e){return typeof e=="string"&&J.includes(e)}var ee=/^[a-z][a-z_]{0,39}$/;function re(e){return Z(e)?e:typeof e=="string"&&ee.test(e)?"invalid":null}function D(e){let r={};if(!e||typeof e!="object"||Array.isArray(e))return r;for(let[n,i]of Object.entries(e)){let t=k.test(n)?re(i):null;t&&(r[n]=t)}return r}var ne=["invalid_answers","duplicate","daily_limit","rate_limited","verification_expired","temporarily_unavailable","too_large","server_error"];function te(e){return typeof e=="string"&&ne.includes(e)}var oe=/^[a-z0-9]{20,30}$/;function Ie(e){if(!e||typeof e!="object")return{ok:!1,error:"server_error"};let r=e;if(r.ok===!0||r.ok===void 0&&r.error===void 0){let n=r.state;if(n==="closed"||n==="not_open"||n==="full")return{ok:!0,state:n};let i=typeof r.redirectUrl=="string"&&!b(r.redirectUrl)?E(r.redirectUrl):null;return{ok:!0,...typeof r.submissionId=="string"&&oe.test(r.submissionId)?{submissionId:r.submissionId}:{},...i?{redirectUrl:i.url}:{}}}if(r.ok===!1&&te(r.error))return r.error!=="invalid_answers"?{ok:!1,error:r.error}:{ok:!1,error:"invalid_answers",errors:D(r.errors)};if(r.error&&typeof r.error=="object"){let n=r.error,t=(n.details&&typeof n.details=="object"?n.details:{}).issues??n.issues;switch(n.code){case"VERIFICATION_EXPIRED":return{ok:!1,error:"verification_expired"};case"DUPLICATE_SUBMISSION":return{ok:!1,error:"duplicate"};case"RATE_LIMITED":return{ok:!1,error:"rate_limited"};case"INVALID_ANSWERS":return{ok:!1,error:"invalid_answers",errors:D(t)};case"PAYLOAD_TOO_LARGE":return{ok:!1,error:"too_large"}}}return{ok:!1,error:"server_error"}}function ie(e,r){return e.defaultCountry?.toUpperCase()||r?.toUpperCase()||null}var se="__other__";function ue(e){return typeof e!="string"?null:e.replace(/\p{Cc}/gu,"").trim().slice(0,p.HIDDEN_VALUE_MAX)||null}var d=e=>({ok:!0,value:e}),s=e=>({ok:!1,code:e}),we={phone:null,address:null,tax_id:null};function le(e,r){if(!S(e))return!0;try{return new RegExp(`^(?:${e})$`,"u").test(r)}catch{return!0}}function L(e,r,n){let i=O(e,r,n??1);return i.ok?d(i.value):s(i.code)}var ae=40;function de(e,r){if(typeof r=="string"&&r.length>ae)return s("invalid_number");let n=m(r);return n===null||Math.abs(n)>Number.MAX_SAFE_INTEGER?s("invalid_number"):e.integer&&!Number.isInteger(n)?s("not_integer"):e.min!==void 0&&n<e.min||e.max!==void 0&&n>e.max?s("out_of_range"):d(n)}function ce(e){if(typeof e!="string")return s("invalid_url");let r=e.trim(),n=T(r.includes("://")?r:`https://${r}`);return!n||!n.hostname.includes(".")?s("invalid_url"):d(n.toString())}function pe(e,r,n){if(typeof r!="string"||!w(r))return s("invalid_date");let i=y(e.range?.min,n),t=y(e.range?.max,n);return i&&r<i||t&&r>t?s("date_out_of_range"):d(r)}function me(e,r,n){let i=new Set(e.options.map(a=>a.id)),t=Array.isArray(r)?r:typeof r=="string"&&r?[r]:[];if(!e.allowMultiple&&t.length>1||t.length>p.MAX_OPTIONS+1)return s("invalid_option");let u=n?.trim()??"",o=[];for(let a of t){if(typeof a!="string")return s("invalid_option");if(i.has(a)){o.includes(a)||o.push(a);continue}if(!e.allowOther)return s("invalid_option");let l=a===se?u:a.trim();if(!l)return s("other_required");if(l.length>p.LABEL_MAX)return s("too_long");o.push(l)}return o.length===0?s("required"):e.allowMultiple?e.minSelections!==void 0&&o.length<e.minSelections?s("too_few_options"):e.maxSelections!==void 0&&o.length>e.maxSelections?s("too_many_options"):d(o):d(o[0])}function M(e,r,n,i,t){let u=v(typeof n=="string"?n.trim():n);if(r.type==="file"){let o=Array.isArray(n)?n:[];if(o.some(l=>typeof l!="string"||!l||l.length>64)||o.length>r.maxFiles)return s("invalid_option");let a=t.fileRequired!=="skip"&&!t.fileRequired.exempt.includes(r.id);return r.required&&o.length===0&&a?s("required"):d(o.length>0?o:null)}if(r.type==="address")return e.address?e.address(r,n):r.required&&!x(n)?s("required"):d(n??null);if(r.type==="tax_id"){if(e.tax_id)return e.tax_id(r,n);let o=R(n)&&n.value.trim()!=="";return r.required&&!o?s("required"):d(n??null)}if(u)return r.required?s("required"):d(null);switch(r.type){case"short_text":{let o=L(n,r.maxLength??p.SHORT_TEXT_MAX,r.minLength);return!o.ok||!r.pattern||typeof o.value!="string"||le(r.pattern,o.value)?o:s("invalid_format")}case"long_text":return L(n,r.maxLength??p.LONG_TEXT_MAX,r.minLength);case"email":{if(typeof n!="string")return s("invalid_email");let o=n.trim().toLowerCase();return I(o)?d(o):s("invalid_email")}case"phone":{if(typeof n!="string")return s("invalid_phone");if(!e.phone)return d(n);let o=e.phone(n,ie(r,t.defaultPhoneCountry));return o?d(o):s("invalid_phone")}case"choice":return me(r,n,i.otherText?.[r.id]);case"date":return pe(r,n,t.today);case"number":return de(r,n);case"url":return ce(n);case"statement":return d(null);case"time":return typeof n=="string"&&C(n)?d(n):s("invalid_time");case"rating":{let o=typeof n=="number"?n:Number(n);return Number.isInteger(o)&&o>=1&&o<=r.max?d(o):s("invalid_option")}}}function Ce(e,r,n,i){let t={},u={},o=n.answers&&typeof n.answers=="object"?n.answers:{},a=V(r,o);for(let l of r){if(!f(l.type))continue;if(!a.has(l.id)){t[l.id]=null;continue}let c=M(e,l,o[l.id],n,i);c.ok?t[l.id]=c.value:u[l.id]=c.code}for(let l of i.hiddenFields??[])t[l.id]=ue(o[l.id]);return Object.keys(u).length>0?{ok:!1,errors:u}:{ok:!0,answers:t}}function Oe(e,r,n,i){if(!f(r.type))return null;let t=M(e,r,n.answers[r.id],n,i);return t.ok?null:t.code}export{ye as a,V as b,Ae as c,Ie as d,ie as e,se as f,d as g,s as h,we as i,Ce as j,Oe as k};
2
- //# sourceMappingURL=chunk-WXIUWMFR.js.map