@cimplify/sdk 0.108.0 → 0.110.2

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 (608) hide show
  1. package/LICENSE +21 -0
  2. package/dist/advanced.d.mts +4 -3
  3. package/dist/advanced.d.ts +4 -3
  4. package/dist/advanced.js +24 -24
  5. package/dist/advanced.mjs +5 -5
  6. package/dist/animation-4EXBXRVX.js +27 -0
  7. package/dist/animation-6DICNWUP.mjs +6 -0
  8. package/dist/audio-DhvyjqdA.d.mts +249 -0
  9. package/dist/audio-m0w8cnxq.d.ts +249 -0
  10. package/dist/avatars.d.mts +110 -0
  11. package/dist/avatars.d.ts +110 -0
  12. package/dist/avatars.js +82 -0
  13. package/dist/avatars.mjs +5 -0
  14. package/dist/backend-gUCzs5Kg.d.mts +3866 -0
  15. package/dist/backend-gUCzs5Kg.d.ts +3866 -0
  16. package/dist/{catalogue-B4eLL8Mi.d.ts → catalogue-CPTMyBUz.d.mts} +109 -221
  17. package/dist/catalogue-DzrTXP3v.d.mts +541 -0
  18. package/dist/catalogue-DzrTXP3v.d.ts +541 -0
  19. package/dist/{catalogue-OT89_Ifs.d.mts → catalogue-OTuS5zp-.d.ts} +109 -221
  20. package/dist/chunk-22BD3RHN.mjs +1809 -0
  21. package/dist/chunk-25T4JHEA.mjs +21 -0
  22. package/dist/chunk-2AQ237Y4.js +508 -0
  23. package/dist/chunk-2IC4H6OV.mjs +48 -0
  24. package/dist/chunk-2LHLG4OB.mjs +71 -0
  25. package/dist/chunk-2O2CG465.js +1709 -0
  26. package/dist/chunk-2Q4DTHXK.js +316 -0
  27. package/dist/chunk-2QTQ6BUH.mjs +46 -0
  28. package/dist/chunk-2UN4SFLR.mjs +100 -0
  29. package/dist/chunk-2V75I7K3.js +454 -0
  30. package/dist/chunk-2V7IL4HC.js +10 -0
  31. package/dist/chunk-34XBXUMW.js +296 -0
  32. package/dist/chunk-3C4C654I.js +71 -0
  33. package/dist/chunk-3DAD2LDF.mjs +72 -0
  34. package/dist/chunk-3GXH2NFD.mjs +4 -0
  35. package/dist/chunk-3O47ZFW3.js +961 -0
  36. package/dist/chunk-3OY3VYNF.mjs +11 -0
  37. package/dist/chunk-3S6WPBZL.js +2936 -0
  38. package/dist/chunk-3TUOUP5T.js +399 -0
  39. package/dist/chunk-3VEH23I5.mjs +1380 -0
  40. package/dist/chunk-3ZYSAW2T.mjs +263 -0
  41. package/dist/chunk-4ANVF274.js +103 -0
  42. package/dist/chunk-4C7I3ELN.js +388 -0
  43. package/dist/chunk-4DYKAYFO.mjs +8 -0
  44. package/dist/chunk-4ZDR72SG.js +329 -0
  45. package/dist/chunk-52YS45RR.js +1066 -0
  46. package/dist/chunk-5325XSCH.js +107 -0
  47. package/dist/chunk-5AD5X6AV.js +13 -0
  48. package/dist/chunk-5BYDGGWO.mjs +197 -0
  49. package/dist/chunk-5C3C7VDM.mjs +55 -0
  50. package/dist/chunk-5HFMY3D7.js +660 -0
  51. package/dist/chunk-5LH2QN3T.js +1862 -0
  52. package/dist/chunk-5PJEXSOW.js +44 -0
  53. package/dist/chunk-5SXDH3Y7.js +90 -0
  54. package/dist/chunk-5YFBGGCK.mjs +502 -0
  55. package/dist/chunk-5YWN6H5Q.mjs +133 -0
  56. package/dist/chunk-66QP3SMN.js +402 -0
  57. package/dist/chunk-6DAEZKIG.mjs +385 -0
  58. package/dist/chunk-6DATW7TB.mjs +420 -0
  59. package/dist/{chunk-JRGK3NXR.mjs → chunk-6ETDAU62.mjs} +72 -212
  60. package/dist/chunk-6H254EVP.mjs +178 -0
  61. package/dist/chunk-6PFNJPBJ.mjs +820 -0
  62. package/dist/chunk-6PJWXIFX.mjs +357 -0
  63. package/dist/chunk-6SWKWCMS.js +80 -0
  64. package/dist/chunk-6VVXXX7S.js +808 -0
  65. package/dist/chunk-6WUBSMTX.js +1403 -0
  66. package/dist/chunk-73SGZLAQ.mjs +35 -0
  67. package/dist/chunk-76L2V6KD.mjs +4 -0
  68. package/dist/chunk-7AAIAVAA.js +1531 -0
  69. package/dist/chunk-7ARSJPV3.mjs +93 -0
  70. package/dist/chunk-7BHW5GTC.mjs +1234 -0
  71. package/dist/chunk-7DQSDKDU.js +6 -0
  72. package/dist/chunk-7IQQQENP.mjs +401 -0
  73. package/dist/chunk-7KFTYENS.js +11357 -0
  74. package/dist/chunk-7SM6XSPZ.js +3171 -0
  75. package/dist/chunk-7SXOHAIR.mjs +28 -0
  76. package/dist/chunk-A2MAX6S4.js +90 -0
  77. package/dist/chunk-A33OORT7.mjs +1530 -0
  78. package/dist/{chunk-U6ACF76H.mjs → chunk-A36JRXXH.mjs} +1075 -1845
  79. package/dist/chunk-A7BU3BK4.js +52 -0
  80. package/dist/chunk-A7MQSN2V.mjs +77 -0
  81. package/dist/chunk-A7V4L2IT.mjs +416 -0
  82. package/dist/chunk-AABEK6XU.js +226 -0
  83. package/dist/chunk-AGV33FWC.mjs +5005 -0
  84. package/dist/chunk-AHNR3BXI.js +108 -0
  85. package/dist/chunk-AQ5RLBU2.mjs +286 -0
  86. package/dist/chunk-AQOE6WCG.js +1270 -0
  87. package/dist/chunk-ATAWRACV.mjs +62 -0
  88. package/dist/chunk-ATCURNUV.js +14 -0
  89. package/dist/chunk-AWPV33OO.js +6 -0
  90. package/dist/chunk-AYJPHKYV.js +337 -0
  91. package/dist/chunk-AZ5BGWHB.js +162 -0
  92. package/dist/chunk-AZAXD44P.js +1373 -0
  93. package/dist/chunk-BBGKQIJJ.mjs +406 -0
  94. package/dist/chunk-BP4JLSUA.js +1453 -0
  95. package/dist/{chunk-SUCE7FWA.mjs → chunk-BTUSVHIE.mjs} +539 -978
  96. package/dist/chunk-BU6OK542.mjs +818 -0
  97. package/dist/chunk-CVSRWM6W.js +418 -0
  98. package/dist/chunk-CYBMFMJD.mjs +247 -0
  99. package/dist/chunk-DDJLDOUX.mjs +217 -0
  100. package/dist/{chunk-V32BCG7M.js → chunk-DFZWHNRG.js} +75 -215
  101. package/dist/chunk-DJ2C7AVG.js +644 -0
  102. package/dist/chunk-DS2VU4WW.mjs +102 -0
  103. package/dist/chunk-DSAG7T5P.js +7290 -0
  104. package/dist/chunk-E2QPPH7I.js +327 -0
  105. package/dist/chunk-E65WCTIG.mjs +1187 -0
  106. package/dist/{chunk-33VCYWVL.mjs → chunk-E6QQKDNE.mjs} +30 -42
  107. package/dist/chunk-ECDK6QBF.mjs +981 -0
  108. package/dist/chunk-EIB4OWVQ.mjs +620 -0
  109. package/dist/chunk-EQUZYCGO.js +250 -0
  110. package/dist/chunk-F3UJ6ZRM.mjs +313 -0
  111. package/dist/chunk-F63N2ZTQ.js +7023 -0
  112. package/dist/chunk-F6XRYEM3.mjs +26 -0
  113. package/dist/chunk-FE6VCE4K.js +5030 -0
  114. package/dist/chunk-FLWD6GRR.js +1372 -0
  115. package/dist/chunk-FQBFWJBS.mjs +110 -0
  116. package/dist/chunk-FXVJ2HFU.js +26 -0
  117. package/dist/chunk-FZMQMQBW.js +312 -0
  118. package/dist/chunk-G3EEC44R.js +53 -0
  119. package/dist/{chunk-KG3WT4PR.mjs → chunk-GCKWKLZF.mjs} +73 -104
  120. package/dist/chunk-GCX7TY4D.mjs +6826 -0
  121. package/dist/chunk-GDB6TCSD.js +450 -0
  122. package/dist/chunk-GDCV4IWO.mjs +21 -0
  123. package/dist/chunk-GDZT5LZ5.js +170 -0
  124. package/dist/chunk-GHPUYD4I.mjs +213 -0
  125. package/dist/chunk-GHS6MIL6.mjs +1432 -0
  126. package/dist/chunk-GPS2THCL.mjs +11 -0
  127. package/dist/{chunk-EV2EVOYS.js → chunk-GTJWQAGU.js} +31 -42
  128. package/dist/chunk-GVTI6UJQ.mjs +130 -0
  129. package/dist/chunk-GXKI64OT.mjs +1138 -0
  130. package/dist/chunk-GYDYF2WX.js +275 -0
  131. package/dist/chunk-GYLP6UG4.mjs +705 -0
  132. package/dist/chunk-H3OQKK6X.js +1158 -0
  133. package/dist/chunk-H5DFSCJ6.js +40 -0
  134. package/dist/chunk-HAGEIC2L.mjs +186 -0
  135. package/dist/chunk-HAJ4JRFO.js +293 -0
  136. package/dist/chunk-HDR72GB6.js +188 -0
  137. package/dist/chunk-HF5HPS4T.mjs +40 -0
  138. package/dist/chunk-HK6LOFDS.js +218 -0
  139. package/dist/chunk-HMWYTXCY.mjs +143 -0
  140. package/dist/chunk-HPCSRCMA.js +89 -0
  141. package/dist/chunk-HSEO6TPU.js +247 -0
  142. package/dist/chunk-I5FOHCLH.js +132 -0
  143. package/dist/chunk-IDLW4NWA.mjs +85 -0
  144. package/dist/chunk-IIDZ5WUX.js +61 -0
  145. package/dist/chunk-IR74FJHU.js +2332 -0
  146. package/dist/chunk-IRVFYAKP.mjs +100 -0
  147. package/dist/{chunk-XBL3TMPC.mjs → chunk-IZDWAL53.mjs} +1795 -3287
  148. package/dist/chunk-J2KZXIU3.js +51 -0
  149. package/dist/chunk-J2U6PJSO.js +91 -0
  150. package/dist/chunk-J5AJNY2N.js +283 -0
  151. package/dist/chunk-J6KQZ4FO.mjs +821 -0
  152. package/dist/{chunk-OWW5GUSB.js → chunk-JGBCIKJV.js} +7 -6
  153. package/dist/chunk-JKGTBMU7.mjs +25 -0
  154. package/dist/chunk-JR3TNEQC.js +422 -0
  155. package/dist/chunk-JURRXY2J.mjs +29 -0
  156. package/dist/chunk-K3HW5I2A.mjs +317 -0
  157. package/dist/chunk-K46SMZ66.mjs +103 -0
  158. package/dist/chunk-K4UDGE3Z.mjs +6 -0
  159. package/dist/chunk-KDQOR4QQ.mjs +350 -0
  160. package/dist/chunk-KDTVOLHI.mjs +288 -0
  161. package/dist/chunk-KGHJH5KJ.mjs +35 -0
  162. package/dist/chunk-KIZOA5LX.mjs +140 -0
  163. package/dist/chunk-KK6HYVBI.mjs +242 -0
  164. package/dist/chunk-KMKWGXMK.js +856 -0
  165. package/dist/chunk-KPA6K5IB.js +80 -0
  166. package/dist/chunk-KU7O4IXU.mjs +260 -0
  167. package/dist/chunk-KVFNRJOR.mjs +11142 -0
  168. package/dist/chunk-KZJRSXHK.js +2432 -0
  169. package/dist/chunk-LHWPRUJL.js +79 -0
  170. package/dist/chunk-LIV3KXJG.mjs +369 -0
  171. package/dist/chunk-LKV4LACG.js +21 -0
  172. package/dist/chunk-LUY45X3U.mjs +263 -0
  173. package/dist/chunk-LYEZZEEF.mjs +17 -0
  174. package/dist/chunk-M5EXQZYY.mjs +1519 -0
  175. package/dist/chunk-ME6HGG4I.mjs +1338 -0
  176. package/dist/chunk-MEXP6DA6.js +31 -0
  177. package/dist/chunk-MG52AW3H.js +902 -0
  178. package/dist/chunk-MIPO6F72.js +334 -0
  179. package/dist/{chunk-5QW7CQBA.js → chunk-MKIJQL5Q.js} +211 -321
  180. package/dist/chunk-MN3YETVN.mjs +17 -0
  181. package/dist/chunk-MOBSBXVE.mjs +2391 -0
  182. package/dist/chunk-MOMOZEUM.mjs +88 -0
  183. package/dist/chunk-MRFUNRAP.js +62 -0
  184. package/dist/chunk-MTIHEW2M.js +433 -0
  185. package/dist/chunk-N4RGGDEL.mjs +73 -0
  186. package/dist/chunk-NH654HAT.js +10 -0
  187. package/dist/chunk-NHJUGZUR.mjs +253 -0
  188. package/dist/chunk-NMQT4HG3.mjs +757 -0
  189. package/dist/chunk-NPSYB6DC.mjs +906 -0
  190. package/dist/chunk-NW2GPMSO.js +857 -0
  191. package/dist/chunk-NXKQOQ6L.js +76 -0
  192. package/dist/chunk-NXLAZIJZ.js +309 -0
  193. package/dist/chunk-NYWNA5CF.js +148 -0
  194. package/dist/chunk-NZTKLY2W.js +1442 -0
  195. package/dist/chunk-O2ICABUD.js +36 -0
  196. package/dist/chunk-OIVVQQ22.js +862 -0
  197. package/dist/chunk-OKC2B4O3.mjs +312 -0
  198. package/dist/chunk-OLWFPDBK.js +2220 -0
  199. package/dist/chunk-OMTVH334.js +3779 -0
  200. package/dist/chunk-OQRVEM56.mjs +362 -0
  201. package/dist/chunk-OXMIBOD4.js +337 -0
  202. package/dist/chunk-PBL6YL5L.mjs +288 -0
  203. package/dist/chunk-PDOELNNQ.js +97 -0
  204. package/dist/chunk-PDQJY2GZ.js +136 -0
  205. package/dist/chunk-PKOZXD2Q.js +1274 -0
  206. package/dist/chunk-PPF2BYFL.mjs +2191 -0
  207. package/dist/chunk-PQTQKNKD.js +539 -0
  208. package/dist/chunk-PRSR4FAV.mjs +81 -0
  209. package/dist/chunk-PTRNO5UD.js +95 -0
  210. package/dist/chunk-Q2Y3VMKH.js +2000 -0
  211. package/dist/chunk-QCZOE65N.js +96 -0
  212. package/dist/chunk-QDYFLATW.mjs +52 -0
  213. package/dist/chunk-QQABGCMM.js +22 -0
  214. package/dist/chunk-QS6TRHMR.js +345 -0
  215. package/dist/chunk-R56P64LB.mjs +208 -0
  216. package/dist/chunk-RCQ2MPBV.js +428 -0
  217. package/dist/chunk-RFVRPYR2.mjs +856 -0
  218. package/dist/chunk-RKBLPGPV.js +11521 -0
  219. package/dist/chunk-RM2V4IND.mjs +327 -0
  220. package/dist/chunk-RQXN5A34.mjs +613 -0
  221. package/dist/chunk-RUVGVNOF.mjs +2687 -0
  222. package/dist/chunk-SAFJIGYB.mjs +165 -0
  223. package/dist/chunk-SKQFLBDD.js +263 -0
  224. package/dist/chunk-SMK6JU2F.mjs +2092 -0
  225. package/dist/{chunk-UVRPC2P7.js → chunk-SNNEOS5Z.js} +1984 -3476
  226. package/dist/chunk-SPCRQ6NO.mjs +1246 -0
  227. package/dist/chunk-SWX4SALA.mjs +19 -0
  228. package/dist/{chunk-JVODCGFP.mjs → chunk-SYEO2WV4.mjs} +128 -238
  229. package/dist/chunk-T2QQMX2N.js +10 -0
  230. package/dist/chunk-T3AFF3L7.mjs +57 -0
  231. package/dist/chunk-T6Z2EXYL.js +712 -0
  232. package/dist/chunk-T7LOXGYX.js +118 -0
  233. package/dist/chunk-TJCAE7RC.mjs +1315 -0
  234. package/dist/chunk-TJI3K6RP.js +137 -0
  235. package/dist/chunk-TL2SVO4P.mjs +55 -0
  236. package/dist/chunk-TM63CYGN.mjs +399 -0
  237. package/dist/chunk-TU5RYTYU.mjs +13 -0
  238. package/dist/chunk-TVJZ4GPS.js +1553 -0
  239. package/dist/chunk-TWM6DLYF.js +371 -0
  240. package/dist/chunk-U63OC4TQ.js +30 -0
  241. package/dist/{chunk-L5GKVQVJ.js → chunk-U6BVSJZ6.js} +25 -57
  242. package/dist/chunk-U6UVWEAK.mjs +792 -0
  243. package/dist/chunk-UCEPNO6N.mjs +11048 -0
  244. package/dist/{chunk-ANT574FD.js → chunk-UCR5HRYM.js} +74 -105
  245. package/dist/chunk-UG5BTOTF.mjs +334 -0
  246. package/dist/chunk-UGH37BQW.mjs +157 -0
  247. package/dist/chunk-V7ZRH3PY.mjs +271 -0
  248. package/dist/chunk-VBGHBL3E.mjs +1394 -0
  249. package/dist/chunk-VRBDAS5I.js +920 -0
  250. package/dist/chunk-VVE3Y76O.js +230 -0
  251. package/dist/chunk-W65JIRI4.mjs +1182 -0
  252. package/dist/chunk-WHYKAT7G.js +62 -0
  253. package/dist/{chunk-YOIVZ6OA.mjs → chunk-WIZRUIZB.mjs} +25 -57
  254. package/dist/chunk-WKWTDZS7.js +385 -0
  255. package/dist/chunk-WLMINRC4.mjs +78 -0
  256. package/dist/chunk-WOF3AD3J.js +22 -0
  257. package/dist/chunk-WWKMOA76.js +1262 -0
  258. package/dist/chunk-X5A5FOWW.js +615 -0
  259. package/dist/chunk-X6CN6KQF.mjs +192 -0
  260. package/dist/chunk-XD2PMH46.mjs +517 -0
  261. package/dist/chunk-XJA2NGTI.mjs +88 -0
  262. package/dist/chunk-XJIHN3BY.mjs +8 -0
  263. package/dist/chunk-XK6UDWJS.js +203 -0
  264. package/dist/chunk-XPG3N5CF.mjs +415 -0
  265. package/dist/chunk-XVZ2NKSU.mjs +74 -0
  266. package/dist/chunk-XYP45OLE.js +117 -0
  267. package/dist/chunk-XZSDGZX6.mjs +301 -0
  268. package/dist/chunk-Y2EMGN4T.mjs +120 -0
  269. package/dist/chunk-Y3XWP5XW.mjs +298 -0
  270. package/dist/chunk-Y4K22JL6.js +228 -0
  271. package/dist/chunk-Y65LXQGA.mjs +3164 -0
  272. package/dist/chunk-Y66WVMO5.mjs +87 -0
  273. package/dist/chunk-Y7JWLB25.mjs +7280 -0
  274. package/dist/chunk-YCDXAJKU.js +175 -0
  275. package/dist/chunk-YRDQCCIS.js +152 -0
  276. package/dist/chunk-YV52DGSA.js +111 -0
  277. package/dist/chunk-YXGZQPUD.js +94 -0
  278. package/dist/chunk-Z3A3AFVU.mjs +102 -0
  279. package/dist/chunk-ZCY6YKKP.mjs +475 -0
  280. package/dist/chunk-ZEQHXVU5.js +215 -0
  281. package/dist/chunk-ZF7JCXCI.js +284 -0
  282. package/dist/chunk-ZJBRUH6V.js +29 -0
  283. package/dist/chunk-ZMIL4ZOA.js +365 -0
  284. package/dist/chunk-ZR5ULMN2.mjs +337 -0
  285. package/dist/chunk-ZXREOYOW.js +87 -0
  286. package/dist/{client-BSP9U1O1.d.mts → client-CX_WR0-J.d.mts} +2 -2
  287. package/dist/client-Dytx_ZTC.d.ts +230 -0
  288. package/dist/{client-B878xeAP.d.ts → client-dqOhP9Nc.d.ts} +2 -2
  289. package/dist/client-hTKbCuhG.d.mts +230 -0
  290. package/dist/clock-B-UAjkKa.d.mts +5 -0
  291. package/dist/clock-B-UAjkKa.d.ts +5 -0
  292. package/dist/config-BlXQluJR.d.mts +36 -0
  293. package/dist/config-BlXQluJR.d.ts +36 -0
  294. package/dist/courier-Cnn-edJ4.d.ts +95 -0
  295. package/dist/courier-FmGfkvIN.d.mts +95 -0
  296. package/dist/crowd-DdHFbqKK.d.ts +186 -0
  297. package/dist/crowd-hOVSAmA3.d.mts +186 -0
  298. package/dist/danfo-BEBapFlX.d.mts +146 -0
  299. package/dist/danfo-UQ_PTIIx.d.ts +146 -0
  300. package/dist/{elements-Bty6Qs_N.d.mts → elements-DdsRig-2.d.mts} +1548 -257
  301. package/dist/{elements-Bty6Qs_N.d.ts → elements-DdsRig-2.d.ts} +1548 -257
  302. package/dist/engines/godot.d.mts +56 -0
  303. package/dist/engines/godot.d.ts +56 -0
  304. package/dist/engines/godot.js +28 -0
  305. package/dist/engines/godot.mjs +3 -0
  306. package/dist/engines/wasm.d.mts +11 -0
  307. package/dist/engines/wasm.d.ts +11 -0
  308. package/dist/engines/wasm.js +178 -0
  309. package/dist/engines/wasm.mjs +176 -0
  310. package/dist/fallback-CrG_lTFk.d.mts +270 -0
  311. package/dist/fallback-CrG_lTFk.d.ts +270 -0
  312. package/dist/fallback-KDB4Y2CE.mjs +6 -0
  313. package/dist/fallback-Y26TQENE.js +19 -0
  314. package/dist/features-CZB4rmcD.d.mts +118 -0
  315. package/dist/features-CZB4rmcD.d.ts +118 -0
  316. package/dist/fit-BWiE7rgA.d.mts +44 -0
  317. package/dist/fit-DK0oT7zO.d.ts +44 -0
  318. package/dist/five-a-side-Bv1AOUy3.d.mts +115 -0
  319. package/dist/five-a-side-EC51SJY1.d.ts +115 -0
  320. package/dist/fluid-ARr0qUIL.d.ts +939 -0
  321. package/dist/fluid-DLlEj2cs.d.mts +939 -0
  322. package/dist/game/conformance.d.mts +84 -0
  323. package/dist/game/conformance.d.ts +84 -0
  324. package/dist/game/conformance.js +1025 -0
  325. package/dist/game/conformance.mjs +994 -0
  326. package/dist/game/heap.d.mts +40 -0
  327. package/dist/game/heap.d.ts +40 -0
  328. package/dist/game/heap.js +48 -0
  329. package/dist/game/heap.mjs +7 -0
  330. package/dist/game/kit/canvas.d.mts +240 -0
  331. package/dist/game/kit/canvas.d.ts +240 -0
  332. package/dist/game/kit/canvas.js +3566 -0
  333. package/dist/game/kit/canvas.mjs +1039 -0
  334. package/dist/game/kit/courier.d.mts +17 -0
  335. package/dist/game/kit/courier.d.ts +17 -0
  336. package/dist/game/kit/courier.js +66 -0
  337. package/dist/game/kit/courier.mjs +49 -0
  338. package/dist/game/kit/danfo.d.mts +11 -0
  339. package/dist/game/kit/danfo.d.ts +11 -0
  340. package/dist/game/kit/danfo.js +109 -0
  341. package/dist/game/kit/danfo.mjs +44 -0
  342. package/dist/game/kit/engine.d.mts +29 -0
  343. package/dist/game/kit/engine.d.ts +29 -0
  344. package/dist/game/kit/engine.js +183 -0
  345. package/dist/game/kit/engine.mjs +30 -0
  346. package/dist/game/kit/five-a-side.d.mts +11 -0
  347. package/dist/game/kit/five-a-side.d.ts +11 -0
  348. package/dist/game/kit/five-a-side.js +86 -0
  349. package/dist/game/kit/five-a-side.mjs +41 -0
  350. package/dist/game/kit/frontier.d.mts +344 -0
  351. package/dist/game/kit/frontier.d.ts +344 -0
  352. package/dist/game/kit/frontier.js +435 -0
  353. package/dist/game/kit/frontier.mjs +14 -0
  354. package/dist/game/kit/genesis.d.mts +752 -0
  355. package/dist/game/kit/genesis.d.ts +752 -0
  356. package/dist/game/kit/genesis.js +380 -0
  357. package/dist/game/kit/genesis.mjs +15 -0
  358. package/dist/game/kit/ludo.d.mts +15 -0
  359. package/dist/game/kit/ludo.d.ts +15 -0
  360. package/dist/game/kit/ludo.js +87 -0
  361. package/dist/game/kit/ludo.mjs +42 -0
  362. package/dist/game/kit/runner.d.mts +12 -0
  363. package/dist/game/kit/runner.d.ts +12 -0
  364. package/dist/game/kit/runner.js +83 -0
  365. package/dist/game/kit/runner.mjs +46 -0
  366. package/dist/game/kit/shootout.d.mts +13 -0
  367. package/dist/game/kit/shootout.d.ts +13 -0
  368. package/dist/game/kit/shootout.js +122 -0
  369. package/dist/game/kit/shootout.mjs +57 -0
  370. package/dist/game/kit/slots.d.mts +392 -0
  371. package/dist/game/kit/slots.d.ts +392 -0
  372. package/dist/game/kit/slots.js +215 -0
  373. package/dist/game/kit/slots.mjs +6 -0
  374. package/dist/game/kit/tycoon.d.mts +16 -0
  375. package/dist/game/kit/tycoon.d.ts +16 -0
  376. package/dist/game/kit/tycoon.js +145 -0
  377. package/dist/game/kit/tycoon.mjs +44 -0
  378. package/dist/game/kit/word.d.mts +11 -0
  379. package/dist/game/kit/word.d.ts +11 -0
  380. package/dist/game/kit/word.js +78 -0
  381. package/dist/game/kit/word.mjs +41 -0
  382. package/dist/game/kit/worlds.d.mts +18 -0
  383. package/dist/game/kit/worlds.d.ts +18 -0
  384. package/dist/game/kit/worlds.js +74 -0
  385. package/dist/game/kit/worlds.mjs +49 -0
  386. package/dist/game/kit.d.mts +53 -0
  387. package/dist/game/kit.d.ts +53 -0
  388. package/dist/game/kit.js +2610 -0
  389. package/dist/game/kit.mjs +101 -0
  390. package/dist/game/prepared.d.mts +14 -0
  391. package/dist/game/prepared.d.ts +14 -0
  392. package/dist/game/prepared.js +81 -0
  393. package/dist/game/prepared.mjs +32 -0
  394. package/dist/game-Bx8onkhX.d.mts +1451 -0
  395. package/dist/game-fgQy2YIm.d.ts +1451 -0
  396. package/dist/game-theme-CBTw1b_d.d.mts +35 -0
  397. package/dist/game-theme-Dg-ict5A.d.ts +35 -0
  398. package/dist/game.d.mts +3546 -0
  399. package/dist/game.d.ts +3546 -0
  400. package/dist/game.js +4455 -0
  401. package/dist/game.mjs +50 -0
  402. package/dist/graphics-C6YjWYvP.d.ts +5 -0
  403. package/dist/graphics-Dk2yQnYN.d.mts +5 -0
  404. package/dist/guest-DrsA00XD.d.mts +732 -0
  405. package/dist/guest-wIdfoT05.d.ts +732 -0
  406. package/dist/hit-stop-BKkVwTq7.d.mts +43 -0
  407. package/dist/hit-stop-D-8pPYnM.d.ts +43 -0
  408. package/dist/hot-Crn9XpHJ.d.ts +29 -0
  409. package/dist/hot-DH3nOhQD.d.mts +29 -0
  410. package/dist/{index-CQStGb3B.d.mts → index-6gkHMGAq.d.mts} +2 -2
  411. package/dist/index-B8ybCKJI.d.ts +41 -0
  412. package/dist/{index-DJwXmoaP.d.ts → index-B98Xac8e.d.ts} +2 -2
  413. package/dist/{index-B7oA_1XI.d.ts → index-B_ByTtIT.d.ts} +2 -2
  414. package/dist/index-DHjNHb1c.d.mts +41 -0
  415. package/dist/{index-DhUSTAhT.d.mts → index-DbAN_VQE.d.mts} +2 -2
  416. package/dist/index.d.mts +134 -24
  417. package/dist/index.d.ts +134 -24
  418. package/dist/index.js +407 -248
  419. package/dist/index.mjs +184 -58
  420. package/dist/interactives-authoring.d.mts +231 -0
  421. package/dist/interactives-authoring.d.ts +231 -0
  422. package/dist/interactives-authoring.js +1743 -0
  423. package/dist/interactives-authoring.mjs +1704 -0
  424. package/dist/interactives-canvas.global.js +148 -0
  425. package/dist/interactives-guest.d.mts +20 -0
  426. package/dist/interactives-guest.d.ts +20 -0
  427. package/dist/interactives-guest.js +63 -0
  428. package/dist/interactives-guest.json +1 -0
  429. package/dist/interactives-guest.mjs +61 -0
  430. package/dist/interactives-jsc.global.js +9357 -0
  431. package/dist/interactives-meters.d.mts +93 -0
  432. package/dist/interactives-meters.d.ts +93 -0
  433. package/dist/interactives-meters.js +252 -0
  434. package/dist/interactives-meters.mjs +68 -0
  435. package/dist/interactives-production.d.mts +430 -0
  436. package/dist/interactives-production.d.ts +430 -0
  437. package/dist/interactives-production.js +1231 -0
  438. package/dist/interactives-production.mjs +1170 -0
  439. package/dist/interactives-record.d.mts +112 -0
  440. package/dist/interactives-record.d.ts +112 -0
  441. package/dist/interactives-record.js +302 -0
  442. package/dist/interactives-record.mjs +295 -0
  443. package/dist/interactives-runtime.d.mts +61 -0
  444. package/dist/interactives-runtime.d.ts +61 -0
  445. package/dist/interactives-runtime.js +442 -0
  446. package/dist/interactives-runtime.mjs +25 -0
  447. package/dist/interactives-studio-kernel.global.js +1 -0
  448. package/dist/interactives-studio.d.mts +806 -0
  449. package/dist/interactives-studio.d.ts +806 -0
  450. package/dist/interactives-studio.js +5741 -0
  451. package/dist/interactives-studio.mjs +5651 -0
  452. package/dist/interactives-tick.d.mts +90 -0
  453. package/dist/interactives-tick.d.ts +90 -0
  454. package/dist/interactives-tick.js +203 -0
  455. package/dist/interactives-tick.mjs +6 -0
  456. package/dist/interactives-web.d.mts +762 -0
  457. package/dist/interactives-web.d.ts +762 -0
  458. package/dist/interactives-web.js +5000 -0
  459. package/dist/interactives-web.mjs +4628 -0
  460. package/dist/interactives.d.mts +2430 -0
  461. package/dist/interactives.d.ts +2430 -0
  462. package/dist/interactives.js +5723 -0
  463. package/dist/interactives.mjs +4333 -0
  464. package/dist/juice-CoHxlpKA.d.ts +42 -0
  465. package/dist/juice-DQztFS43.d.mts +42 -0
  466. package/dist/launch-T2f4_Di4.d.mts +151 -0
  467. package/dist/launch-d6oreMzR.d.ts +151 -0
  468. package/dist/library-DXYaMFhi.d.mts +69 -0
  469. package/dist/library-DXYaMFhi.d.ts +69 -0
  470. package/dist/link-BUTqGmyi.d.mts +38 -0
  471. package/dist/link-BUTqGmyi.d.ts +38 -0
  472. package/dist/lint.js +104 -204
  473. package/dist/lint.mjs +103 -203
  474. package/dist/local-D8_I6UeL.d.mts +6967 -0
  475. package/dist/local-VZkqsCzR.d.ts +6967 -0
  476. package/dist/lockstep-BLf6dglI.d.mts +321 -0
  477. package/dist/lockstep-D50Ia0JW.d.ts +321 -0
  478. package/dist/ludo-B8ClkDqr.d.ts +205 -0
  479. package/dist/ludo-BOuohQ-M.d.mts +205 -0
  480. package/dist/mock/cli.mjs +200 -56
  481. package/dist/mock/library.js +200 -56
  482. package/dist/mock/library.mjs +200 -56
  483. package/dist/mock/msw.js +200 -56
  484. package/dist/mock/msw.mjs +200 -56
  485. package/dist/native-BodxSh03.d.mts +16 -0
  486. package/dist/native-DUHMT8gA.d.ts +16 -0
  487. package/dist/network-ZXLD7l1b.d.mts +19 -0
  488. package/dist/network-ZXLD7l1b.d.ts +19 -0
  489. package/dist/online-XeymeM9s.d.ts +381 -0
  490. package/dist/online-d7W_Al9a.d.mts +381 -0
  491. package/dist/params-DxFb5G_U.d.mts +155 -0
  492. package/dist/params-DxFb5G_U.d.ts +155 -0
  493. package/dist/play-BRRlfLhX.d.ts +940 -0
  494. package/dist/play-ClrMd_e8.d.mts +940 -0
  495. package/dist/policy-CCw8tXLm.d.mts +3078 -0
  496. package/dist/policy-CMqOSQIu.d.ts +3078 -0
  497. package/dist/ports-B_0v_P3A.d.mts +13 -0
  498. package/dist/ports-CGU_3e_0.d.ts +13 -0
  499. package/dist/prefetch-BHnicOQj.d.ts +117 -0
  500. package/dist/prefetch-CBXgYacv.d.mts +117 -0
  501. package/dist/{price-CSztR02F.d.mts → price-BOzexBww.d.mts} +1 -1
  502. package/dist/{price-C_vasx9A.d.ts → price-C1h9sPxE.d.ts} +1 -1
  503. package/dist/protocol-C8qbpUbT.d.mts +242 -0
  504. package/dist/protocol-C8qbpUbT.d.ts +242 -0
  505. package/dist/rapier-AZHT4YI7.js +7886 -0
  506. package/dist/rapier-ODEPCQA6.mjs +7792 -0
  507. package/dist/react.d.mts +157 -15
  508. package/dist/react.d.ts +157 -15
  509. package/dist/react.js +5564 -5904
  510. package/dist/react.mjs +5451 -5808
  511. package/dist/runner-CQcLL7By.d.ts +189 -0
  512. package/dist/runner-D46Yj-wE.d.mts +189 -0
  513. package/dist/runtime-BRWfkf_q.d.mts +51 -0
  514. package/dist/runtime-DyuBMkKM.d.ts +51 -0
  515. package/dist/scheduling-D2ajXpMC.d.ts +224 -0
  516. package/dist/scheduling-DSRbbaZb.d.mts +224 -0
  517. package/dist/schema-BrWxzKp6.d.mts +63 -0
  518. package/dist/schema-BrWxzKp6.d.ts +63 -0
  519. package/dist/server/evict.js +34 -37
  520. package/dist/server/evict.mjs +34 -37
  521. package/dist/server/tanstack.d.mts +49 -3
  522. package/dist/server/tanstack.d.ts +49 -3
  523. package/dist/server/tanstack.js +169 -117
  524. package/dist/server/tanstack.mjs +166 -118
  525. package/dist/{server-Dckg4Vdr.d.ts → server-D29IIuDV.d.ts} +136 -130
  526. package/dist/{server-B6dW7-Lj.d.mts → server-DQMWPnc8.d.mts} +136 -130
  527. package/dist/server.d.mts +45 -5
  528. package/dist/server.d.ts +45 -5
  529. package/dist/server.js +171 -227
  530. package/dist/server.mjs +165 -225
  531. package/dist/session-grant-CJ27DwrT.d.mts +19 -0
  532. package/dist/session-grant-CJ27DwrT.d.ts +19 -0
  533. package/dist/shootout-BJZeX6FG.d.ts +140 -0
  534. package/dist/shootout-tcZd1Rxt.d.mts +140 -0
  535. package/dist/state-replica-stMtdkVD.d.mts +42 -0
  536. package/dist/state-replica-stMtdkVD.d.ts +42 -0
  537. package/dist/studio-CowqWqez.d.mts +14 -0
  538. package/dist/studio-CowqWqez.d.ts +14 -0
  539. package/dist/styles.css +1 -1
  540. package/dist/template-AhCdB1kW.d.mts +190 -0
  541. package/dist/template-BkEGVTQj.d.ts +190 -0
  542. package/dist/terrain-BMxEc6Oc.d.ts +429 -0
  543. package/dist/terrain-C-XC1Oui.d.mts +429 -0
  544. package/dist/testing/msw.d.mts +28 -4
  545. package/dist/testing/msw.d.ts +28 -4
  546. package/dist/testing/msw.js +15 -21
  547. package/dist/testing/msw.mjs +15 -21
  548. package/dist/testing/suite.d.mts +6 -5
  549. package/dist/testing/suite.d.ts +6 -5
  550. package/dist/testing/suite.js +89 -124
  551. package/dist/testing/suite.mjs +81 -116
  552. package/dist/testing.d.mts +27 -1227
  553. package/dist/testing.d.ts +27 -1227
  554. package/dist/testing.js +127 -131
  555. package/dist/testing.mjs +19 -23
  556. package/dist/tick-transport-C8QEh8Uw.d.mts +50 -0
  557. package/dist/tick-transport-UjHY3xK1.d.ts +50 -0
  558. package/dist/timeline-protocol-hp6e8zFB.d.mts +47 -0
  559. package/dist/timeline-protocol-hp6e8zFB.d.ts +47 -0
  560. package/dist/tokens-DhanQRQS.d.mts +21 -0
  561. package/dist/tokens-K8yxwd6G.d.ts +21 -0
  562. package/dist/tree-C-Io2Hbx.d.mts +35 -0
  563. package/dist/tree-CP_qSW4H.d.ts +35 -0
  564. package/dist/tycoon-B5KHk2Xx.d.mts +255 -0
  565. package/dist/tycoon-hmHo-3HX.d.ts +255 -0
  566. package/dist/types-BQkxPwZP.d.mts +219 -0
  567. package/dist/types-D_f6UUxM.d.ts +219 -0
  568. package/dist/ui-DwHicuFv.d.mts +563 -0
  569. package/dist/ui-hi7S2YcH.d.ts +563 -0
  570. package/dist/{sign-in-DQlIdqsi.d.mts → url-52ndUruG.d.mts} +15 -1
  571. package/dist/{sign-in-DQlIdqsi.d.ts → url-52ndUruG.d.ts} +15 -1
  572. package/dist/utils.d.mts +3 -3
  573. package/dist/utils.d.ts +3 -3
  574. package/dist/utils.js +37 -37
  575. package/dist/utils.mjs +4 -4
  576. package/dist/vars-Dc_PrhBK.d.mts +511 -0
  577. package/dist/vars-Dc_PrhBK.d.ts +511 -0
  578. package/dist/vm-IUARFFAI.mjs +63 -0
  579. package/dist/vm-N7L6MGGH.js +65 -0
  580. package/dist/weave-delivery-CW-Kstut.d.mts +360 -0
  581. package/dist/weave-delivery-CW-Kstut.d.ts +360 -0
  582. package/dist/web-Dss74a7v.d.ts +883 -0
  583. package/dist/web-f9ZQPoyw.d.mts +883 -0
  584. package/dist/web-transport-C7MkBL0a.d.ts +19 -0
  585. package/dist/web-transport-aYEqXMd9.d.mts +19 -0
  586. package/dist/weight-CPGjsgjV.d.ts +92 -0
  587. package/dist/weight-tF1ODR1p.d.mts +92 -0
  588. package/dist/word-BcX9Jcmv.d.mts +70 -0
  589. package/dist/word-C7sVPLHm.d.ts +70 -0
  590. package/dist/world-PvILHDR1.d.ts +2285 -0
  591. package/dist/world-qekkXjJv.d.mts +2285 -0
  592. package/dist/worlds-Br2Pb0Cs.d.ts +109 -0
  593. package/dist/worlds-D5ydYr7d.d.mts +109 -0
  594. package/engines/c/cimplify.h +108 -0
  595. package/engines/c/cimplify.lib.js +11 -0
  596. package/engines/godot/addons/cimplify/cimplify.gd +97 -0
  597. package/engines/rust/interactives-ctx/Cargo.toml +9 -0
  598. package/engines/rust/interactives-ctx/src/lib.rs +189 -0
  599. package/package.json +189 -3
  600. package/vendor/rapier3d-compat/LICENSE +201 -0
  601. package/vendor/rapier3d-compat/PATCHES.md +61 -0
  602. package/dist/chunk-2P4KXFB6.js +0 -274
  603. package/dist/chunk-3G6RQLXK.mjs +0 -21
  604. package/dist/chunk-3V4DVXV3.mjs +0 -254
  605. package/dist/chunk-EDK3LNM6.js +0 -2436
  606. package/dist/chunk-F7J3HK27.js +0 -4549
  607. package/dist/chunk-U4MW6PYU.mjs +0 -23
  608. package/dist/chunk-XREIZ56K.js +0 -26
@@ -1,6 +1,7 @@
1
- import { messagePreview } from './chunk-U4MW6PYU.mjs';
2
- import { ok, err, safe, generateIdempotencyKey, SESSION_CLEARED, SESSION_CLAIMED, createClientEvents, createDefaultPaymentAuthorizationAdapterRegistry, AUTH_TOKEN_CHANGED, CatalogueQueries, CartOperations, CheckoutService, OrderQueries, LinkService, AuthService, BusinessService, InventoryService, SchedulingService, LiteService, FxService, createElements } from './chunk-U6ACF76H.mjs';
3
- import { PURCHASE_INTENT_RESOLVE_STATUS, PURCHASE_INTENT_CONFIRM_STATUS, PURCHASE_INTENT_RESOLUTION_KIND, PURCHASE_INTENT_ACTION_DECISION, CimplifyError, PURCHASE_INTENT_ERROR_CODE, ErrorCode, IdempotencyMismatchError, enrichError } from './chunk-KG3WT4PR.mjs';
1
+ import { messagePreview } from './chunk-SWX4SALA.mjs';
2
+ import { ok, err, safe, generateIdempotencyKey, SESSION_CLEARED, SESSION_CLAIMED, createClientEvents, createDefaultPaymentAuthorizationAdapterRegistry, AUTH_TOKEN_CHANGED, CatalogueQueries, CartOperations, CheckoutService, OrderQueries, LinkService, AuthService, BusinessService, InventoryService, SchedulingService, LiteService, FxService, createElements } from './chunk-A36JRXXH.mjs';
3
+ import { ErrorCode, PURCHASE_INTENT_CONFIRM_STATUS, PURCHASE_INTENT_RESOLVE_STATUS, PURCHASE_INTENT_RESOLUTION_KIND, CimplifyError, PURCHASE_INTENT_ERROR_CODE, PURCHASE_INTENT_ACTION_DECISION, enrichError, IdempotencyMismatchError } from './chunk-GCKWKLZF.mjs';
4
+ import { sha256 } from '@noble/hashes/sha2.js';
4
5
 
5
6
  // src/types/observability.ts
6
7
  var SESSION_CHANGE_SOURCE = {
@@ -10,97 +11,96 @@ var SESSION_CHANGE_SOURCE = {
10
11
  };
11
12
 
12
13
  // src/utils/purchase-intent-resolver.ts
13
- var DEFAULT_POLL_INTERVAL_MS = 3e3;
14
- var DEFAULT_MAX_POLL_ATTEMPTS = 60;
15
- var DEFAULT_MAX_ACTION_STEPS = 4;
16
- var DEFAULT_MAX_TERMS_REVIEW_STEPS = 4;
14
+ var DEFAULT_POLL_INTERVAL_MS = 3e3, DEFAULT_MAX_POLL_ATTEMPTS = 60, DEFAULT_MAX_ACTION_STEPS = 4, DEFAULT_MAX_TERMS_REVIEW_STEPS = 4, DEFAULT_DEADLINE_MS = (3e3) * (60), TRANSIENT_RETRY_BASE_MS = 1e3, TRANSIENT_RETRY_MAX_MS = 8e3, HTTP_SERVER_ERROR_PREFIX = "HTTP_5", TRANSIENT_ERROR_CODES = /* @__PURE__ */ new Set([
15
+ ErrorCode.NETWORK_ERROR,
16
+ ErrorCode.TIMEOUT,
17
+ ErrorCode.SERVER_ERROR
18
+ ]), PROVIDER_OWNED_ACTIONS = /* @__PURE__ */ new Set([
19
+ PURCHASE_INTENT_CONFIRM_STATUS.REDIRECT_REQUIRED,
20
+ PURCHASE_INTENT_CONFIRM_STATUS.CARD_POPUP_REQUIRED
21
+ ]);
17
22
  function nonnegativeInteger(value, fallback) {
18
- if (value === void 0 || !Number.isFinite(value)) return fallback;
19
- return Math.max(0, Math.floor(value));
23
+ return value === void 0 || !Number.isFinite(value) ? fallback : Math.max(0, Math.floor(value));
24
+ }
25
+ function isTransientPurchaseIntentError(error) {
26
+ return error.retryable || TRANSIENT_ERROR_CODES.has(error.code) || error.code.startsWith(HTTP_SERVER_ERROR_PREFIX);
27
+ }
28
+ function transientRetryDelay(attempt) {
29
+ return Math.min((1e3) * 2 ** Math.max(0, attempt - 1), (8e3));
20
30
  }
21
31
  function abortError() {
22
- const error = new Error("Purchase-intent resolution was cancelled.");
23
- error.name = "AbortError";
24
- return error;
32
+ let error = new Error("Purchase-intent resolution was cancelled.");
33
+ return error.name = "AbortError", error;
25
34
  }
26
35
  async function abortableWait(milliseconds, signal) {
27
36
  if (signal?.aborted) throw abortError();
28
- if (milliseconds <= 0) return;
29
- await new Promise((resolve, reject) => {
30
- const timer = setTimeout(() => {
31
- signal?.removeEventListener("abort", onAbort);
32
- resolve();
33
- }, milliseconds);
34
- const onAbort = () => {
35
- clearTimeout(timer);
36
- reject(abortError());
37
+ milliseconds <= 0 || await new Promise((resolve, reject) => {
38
+ let timer = setTimeout(() => {
39
+ signal?.removeEventListener("abort", onAbort), resolve();
40
+ }, milliseconds), onAbort = () => {
41
+ clearTimeout(timer), reject(abortError());
37
42
  };
38
43
  signal?.addEventListener("abort", onAbort, { once: true });
39
44
  });
40
45
  }
41
46
  var PurchaseIntentResolver = class {
42
47
  constructor(dependencies) {
43
- this.confirmation = dependencies.confirmation;
44
- this.wait = dependencies.wait ?? abortableWait;
48
+ this.confirmation = dependencies.confirmation, this.wait = dependencies.wait ?? abortableWait, this.now = dependencies.now ?? Date.now;
45
49
  }
46
50
  async resolve(intentId, options) {
47
- const pollIntervalMs = nonnegativeInteger(
51
+ let pollIntervalMs = nonnegativeInteger(
48
52
  options.pollIntervalMs,
49
- DEFAULT_POLL_INTERVAL_MS
50
- );
51
- const maxPollAttempts = nonnegativeInteger(
53
+ (3e3)
54
+ ), maxPollAttempts = nonnegativeInteger(
52
55
  options.maxPollAttempts,
53
- DEFAULT_MAX_POLL_ATTEMPTS
54
- );
55
- const maxActionSteps = nonnegativeInteger(options.maxActionSteps, DEFAULT_MAX_ACTION_STEPS);
56
- const maxTermsReviewSteps = nonnegativeInteger(
56
+ (60)
57
+ ), maxActionSteps = nonnegativeInteger(options.maxActionSteps, (4)), maxTermsReviewSteps = nonnegativeInteger(
57
58
  options.maxTermsReviewSteps,
58
- DEFAULT_MAX_TERMS_REVIEW_STEPS
59
- );
60
- let request = options.confirmation;
61
- let pollAttempts = 0;
62
- let actionSteps = 0;
63
- let termsReviewSteps = 0;
64
- const requestOptions = { signal: options.signal, timeoutMs: options.requestTimeoutMs };
65
- this.ensureActive(options.signal);
66
- this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.CONFIRMING);
59
+ (4)
60
+ ), deadline = this.now() + nonnegativeInteger(options.deadlineMs, DEFAULT_DEADLINE_MS), request = options.confirmation, pollAttempts = 0, actionSteps = 0, termsReviewSteps = 0, transientAttempts = 0, lastResponse = null, handedOverAction = null, requestOptions = { signal: options.signal, timeoutMs: options.requestTimeoutMs };
61
+ this.ensureActive(options.signal), this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.CONFIRMING);
67
62
  let responseResult = options.initialResponse ? ok(options.initialResponse) : await this.confirmation.confirm(intentId, request, requestOptions);
68
- while (responseResult.ok) {
69
- this.ensureActive(options.signal);
70
- const response = responseResult.value;
71
- switch (response.status) {
63
+ for (; ; ) {
64
+ if (this.ensureActive(options.signal), !responseResult.ok) {
65
+ let remaining = deadline - this.now();
66
+ if (!isTransientPurchaseIntentError(responseResult.error) || remaining <= 0)
67
+ return remaining <= 0 && lastResponse?.status === PURCHASE_INTENT_CONFIRM_STATUS.COLLECTION_PROCESSING ? ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.TIMED_OUT, response: lastResponse }) : responseResult;
68
+ transientAttempts += 1, this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.RECONNECTING, lastResponse ?? void 0), await this.wait(Math.min(transientRetryDelay(transientAttempts), remaining), options.signal), responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
69
+ continue;
70
+ }
71
+ transientAttempts = 0;
72
+ let response = responseResult.value;
73
+ switch (lastResponse = response, response.status) {
72
74
  case PURCHASE_INTENT_CONFIRM_STATUS.ORDER_CREATED:
73
- this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.COMPLETED, response);
74
- return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.COMPLETED, response });
75
+ return this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.COMPLETED, response), ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.COMPLETED, response });
75
76
  case PURCHASE_INTENT_CONFIRM_STATUS.PAYMENT_FAILED:
76
- this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.FAILED, response);
77
- return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.FAILED, response });
77
+ return this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.FAILED, response), ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.FAILED, response });
78
78
  case PURCHASE_INTENT_CONFIRM_STATUS.PAYMENT_OUTCOME_UNKNOWN:
79
- this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.OUTCOME_UNKNOWN, response);
80
- return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.OUTCOME_UNKNOWN, response });
79
+ return this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.OUTCOME_UNKNOWN, response), ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.OUTCOME_UNKNOWN, response });
81
80
  case PURCHASE_INTENT_CONFIRM_STATUS.COLLECTION_PROCESSING:
82
- if (pollAttempts >= maxPollAttempts) {
81
+ if (pollAttempts >= maxPollAttempts)
83
82
  return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.TIMED_OUT, response });
84
- }
85
- pollAttempts += 1;
86
- this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.POLLING, response);
87
- await this.wait(pollIntervalMs, options.signal);
88
- responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
83
+ pollAttempts += 1, this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.POLLING, response), await this.wait(pollIntervalMs, options.signal), responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
89
84
  continue;
90
85
  case PURCHASE_INTENT_CONFIRM_STATUS.REDIRECT_REQUIRED:
91
86
  case PURCHASE_INTENT_CONFIRM_STATUS.CARD_POPUP_REQUIRED:
92
87
  case PURCHASE_INTENT_CONFIRM_STATUS.AUTHORIZATION_REQUIRED: {
93
88
  this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.AWAITING_ACTION, response);
94
- if (!options.onActionRequired || actionSteps >= maxActionSteps) {
95
- return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.ACTION_REQUIRED, response });
89
+ let actionKey = `${response.attempt_id}:${response.status}`;
90
+ if (actionKey === handedOverAction) {
91
+ if (pollAttempts >= maxPollAttempts)
92
+ return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.ACTION_REQUIRED, response });
93
+ pollAttempts += 1, await this.wait(pollIntervalMs, options.signal), responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
94
+ continue;
96
95
  }
96
+ if (!options.onActionRequired || actionSteps >= maxActionSteps)
97
+ return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.ACTION_REQUIRED, response });
97
98
  actionSteps += 1;
98
- const decision = await options.onActionRequired(response);
99
- if (decision === PURCHASE_INTENT_ACTION_DECISION.STOP) {
99
+ let decision = await options.onActionRequired(response);
100
+ if (decision === PURCHASE_INTENT_ACTION_DECISION.STOP)
100
101
  return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.ACTION_REQUIRED, response });
101
- }
102
- if (typeof decision === "object" && decision.kind === PURCHASE_INTENT_ACTION_DECISION.SUBMIT) {
103
- if (!this.confirmation.submitAction) {
102
+ if (typeof decision == "object" && decision.kind === PURCHASE_INTENT_ACTION_DECISION.SUBMIT) {
103
+ if (!this.confirmation.submitAction)
104
104
  return err(
105
105
  new CimplifyError(
106
106
  PURCHASE_INTENT_ERROR_CODE.ACTION_UNSUPPORTED,
@@ -108,7 +108,6 @@ var PurchaseIntentResolver = class {
108
108
  false
109
109
  )
110
110
  );
111
- }
112
111
  responseResult = await this.confirmation.submitAction(
113
112
  intentId,
114
113
  response.attempt_id,
@@ -117,7 +116,7 @@ var PurchaseIntentResolver = class {
117
116
  );
118
117
  continue;
119
118
  }
120
- if (decision !== PURCHASE_INTENT_ACTION_DECISION.CONTINUE) {
119
+ if (decision !== PURCHASE_INTENT_ACTION_DECISION.CONTINUE)
121
120
  return err(
122
121
  new CimplifyError(
123
122
  PURCHASE_INTENT_ERROR_CODE.ACTION_UNSUPPORTED,
@@ -125,32 +124,33 @@ var PurchaseIntentResolver = class {
125
124
  false
126
125
  )
127
126
  );
128
- }
129
- await this.wait(pollIntervalMs, options.signal);
130
- responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
127
+ PROVIDER_OWNED_ACTIONS.has(response.status) && (handedOverAction = actionKey), await this.wait(pollIntervalMs, options.signal), responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
131
128
  continue;
132
129
  }
133
130
  case PURCHASE_INTENT_CONFIRM_STATUS.TERMS_CHANGED: {
134
- this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.REVIEWING_TERMS, response);
135
- if (!options.onTermsChanged || termsReviewSteps >= maxTermsReviewSteps) {
131
+ if (this.notify(options, PURCHASE_INTENT_RESOLVE_STATUS.REVIEWING_TERMS, response), !options.onTermsChanged || termsReviewSteps >= maxTermsReviewSteps)
136
132
  return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.REVIEW_REQUIRED, response });
137
- }
138
133
  termsReviewSteps += 1;
139
- const replacementRequest = await options.onTermsChanged(response);
140
- if (!replacementRequest) {
134
+ let replacementRequest = await options.onTermsChanged(response);
135
+ if (!replacementRequest)
141
136
  return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.REVIEW_REQUIRED, response });
142
- }
143
- request = replacementRequest;
144
- responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
137
+ request = replacementRequest, responseResult = await this.confirmation.confirm(intentId, request, requestOptions);
145
138
  continue;
146
139
  }
147
140
  case PURCHASE_INTENT_CONFIRM_STATUS.SELECTION_UNAVAILABLE:
148
141
  case PURCHASE_INTENT_CONFIRM_STATUS.OFFER_ENDED:
149
142
  case PURCHASE_INTENT_CONFIRM_STATUS.SOURCE_UNAVAILABLE:
150
143
  return ok({ kind: PURCHASE_INTENT_RESOLUTION_KIND.REVIEW_REQUIRED, response });
144
+ default:
145
+ return err(
146
+ new CimplifyError(
147
+ PURCHASE_INTENT_ERROR_CODE.ACTION_UNSUPPORTED,
148
+ "The payment returned a status this checkout does not understand.",
149
+ false
150
+ )
151
+ );
151
152
  }
152
153
  }
153
- return responseResult;
154
154
  }
155
155
  ensureActive(signal) {
156
156
  if (signal?.aborted) throw abortError();
@@ -175,12 +175,12 @@ var PURCHASE_INTENT_ROUTE = {
175
175
  ACTIONS: "actions"
176
176
  };
177
177
  function directIntentPath(intentId) {
178
- const normalized = intentId.trim();
178
+ let normalized = intentId.trim();
179
179
  if (!normalized) throw new TypeError("intentId must not be empty");
180
180
  return `${PURCHASE_INTENT_ROUTE.DIRECT_COLLECTION}/${encodeURIComponent(normalized)}`;
181
181
  }
182
182
  function hostedSessionPath(sessionId) {
183
- const normalized = sessionId.trim();
183
+ let normalized = sessionId.trim();
184
184
  if (!normalized) throw new TypeError("sessionId must not be empty");
185
185
  return `${PURCHASE_INTENT_ROUTE.HOSTED_SESSION_COLLECTION}/${encodeURIComponent(normalized)}`;
186
186
  }
@@ -207,7 +207,7 @@ var PurchaseIntentService = class {
207
207
  );
208
208
  }
209
209
  refresh(intentId, expectedRevision, options) {
210
- const request = {
210
+ let request = {
211
211
  expected_intent_revision: expectedRevision
212
212
  };
213
213
  return safe(
@@ -235,7 +235,7 @@ var PurchaseIntentService = class {
235
235
  );
236
236
  }
237
237
  submitAction(intentId, attemptId, request, options) {
238
- const normalizedAttemptId = attemptId.trim();
238
+ let normalizedAttemptId = attemptId.trim();
239
239
  if (!normalizedAttemptId) throw new TypeError("attemptId must not be empty");
240
240
  return safe(
241
241
  this.transport.post(
@@ -261,12 +261,10 @@ var PurchaseIntentService = class {
261
261
  intentPath(intentId) {
262
262
  return directIntentPath(intentId);
263
263
  }
264
- };
265
- var HostedPurchaseIntentService = class {
264
+ }, HostedPurchaseIntentService = class {
266
265
  constructor(transport, sessionId) {
267
266
  this.transport = transport;
268
- this.sessionPath = hostedSessionPath(sessionId);
269
- this.resolver = new PurchaseIntentResolver({ confirmation: this });
267
+ this.sessionPath = hostedSessionPath(sessionId), this.resolver = new PurchaseIntentResolver({ confirmation: this });
270
268
  }
271
269
  prepare(request, options) {
272
270
  return safe(
@@ -306,7 +304,7 @@ var HostedPurchaseIntentService = class {
306
304
  );
307
305
  }
308
306
  submitAction(_intentId, attemptId, request, options) {
309
- const normalized = attemptId.trim();
307
+ let normalized = attemptId.trim();
310
308
  if (!normalized) throw new TypeError("attemptId must not be empty");
311
309
  return safe(
312
310
  this.transport.post(
@@ -339,47 +337,34 @@ var StoreCreditQueries = class {
339
337
  };
340
338
 
341
339
  // src/internal/analytics-session.ts
342
- var ANALYTICS_SESSION_IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
343
340
  var ANALYTICS_SESSION_STORAGE_KEY_PREFIX = "cimplify_analytics_session:v2:";
344
- var ANALYTICS_SESSION_STATE_VERSION = 2;
345
- var MICROSECONDS_PER_MILLISECOND = 1e3;
346
- var MICROSECONDS_PER_SECOND = 1e6;
347
341
  var AnalyticsSessionCoordinator = class {
348
342
  constructor(identity) {
349
343
  this.identity = identity;
350
344
  this.fallbackState = null;
351
345
  }
352
346
  beginEvent(nowMs = Date.now()) {
353
- const state = this.resolveActiveState(nowMs);
347
+ let state = this.resolveActiveState(nowMs);
354
348
  state.lastActivityAtMs = nowMs;
355
- const occurredAt = reserveOccurredAt(state, nowMs, 1);
356
- this.write(state);
357
- return toEventContext(state, occurredAt);
349
+ let occurredAt = reserveOccurredAt(state, nowMs, 1);
350
+ return this.write(state), toEventContext(state, occurredAt);
358
351
  }
359
352
  beginPage(path, nowMs = Date.now()) {
360
- const existing = this.read();
361
- const expired = !existing || isExpired(existing, nowMs);
362
- const state = expired ? newSession(nowMs) : existing;
363
- const previousPage = expired ? void 0 : durationFor(state.activePage, nowMs);
364
- state.lastActivityAtMs = nowMs;
365
- state.activePage = { path, enteredAtMs: nowMs };
366
- const occurredAt = reserveOccurredAt(state, nowMs, previousPage ? 2 : 1);
367
- this.write(state);
368
- return {
353
+ let existing = this.read(), expired = !existing || isExpired(existing, nowMs), state = expired ? newSession(nowMs) : existing, previousPage = expired ? void 0 : durationFor(state.activePage, nowMs);
354
+ state.lastActivityAtMs = nowMs, state.activePage = { path, enteredAtMs: nowMs };
355
+ let occurredAt = reserveOccurredAt(state, nowMs, previousPage ? 2 : 1);
356
+ return this.write(state), {
369
357
  session: toEventContext(state, occurredAt),
370
358
  previousPage
371
359
  };
372
360
  }
373
361
  current() {
374
- const state = this.read();
375
- if (!state || isExpired(state, Date.now())) return null;
376
- return toContext(state);
362
+ let state = this.read();
363
+ return !state || isExpired(state, Date.now()) ? null : toContext(state);
377
364
  }
378
365
  markBootstrapped(sessionId) {
379
- const state = this.read();
380
- if (!state || state.id !== sessionId) return;
381
- state.bootstrapped = true;
382
- this.write(state);
366
+ let state = this.read();
367
+ !state || state.id !== sessionId || (state.bootstrapped = true, this.write(state));
383
368
  }
384
369
  reset() {
385
370
  this.fallbackState = null;
@@ -389,20 +374,15 @@ var AnalyticsSessionCoordinator = class {
389
374
  }
390
375
  }
391
376
  resolveActiveState(nowMs) {
392
- const state = this.read();
377
+ let state = this.read();
393
378
  return !state || isExpired(state, nowMs) ? newSession(nowMs) : state;
394
379
  }
395
380
  read() {
396
381
  try {
397
- const serialized = sessionStorage.getItem(this.storageKey());
382
+ let serialized = sessionStorage.getItem(this.storageKey());
398
383
  if (!serialized) return this.fallbackState;
399
- const state = JSON.parse(serialized);
400
- if (!isPersistedSession(state)) {
401
- sessionStorage.removeItem(this.storageKey());
402
- return this.fallbackState;
403
- }
404
- this.fallbackState = state;
405
- return state;
384
+ let state = JSON.parse(serialized);
385
+ return isPersistedSession(state) ? (this.fallbackState = state, state) : (sessionStorage.removeItem(this.storageKey()), this.fallbackState);
406
386
  } catch {
407
387
  return this.fallbackState;
408
388
  }
@@ -420,7 +400,7 @@ var AnalyticsSessionCoordinator = class {
420
400
  };
421
401
  function newSession(nowMs) {
422
402
  return {
423
- version: ANALYTICS_SESSION_STATE_VERSION,
403
+ version: 2,
424
404
  id: generateSessionId(),
425
405
  startedAtMs: nowMs,
426
406
  lastActivityAtMs: nowMs,
@@ -441,161 +421,99 @@ function toEventContext(state, occurredAtMicros) {
441
421
  };
442
422
  }
443
423
  function reserveOccurredAt(state, nowMs, eventCount) {
444
- const wallClockMicros = Math.trunc(nowMs) * MICROSECONDS_PER_MILLISECOND;
445
- const occurredAtMicros = Math.max(
424
+ let wallClockMicros = Math.trunc(nowMs) * 1e3, occurredAtMicros = Math.max(
446
425
  wallClockMicros,
447
426
  (state.lastOccurredAtMicros ?? wallClockMicros - 1) + 1
448
427
  );
449
- state.lastOccurredAtMicros = occurredAtMicros + eventCount - 1;
450
- return occurredAtMicros;
428
+ return state.lastOccurredAtMicros = occurredAtMicros + eventCount - 1, occurredAtMicros;
451
429
  }
452
430
  function formatEpochMicros(epochMicros) {
453
- const epochMillis = Math.floor(epochMicros / MICROSECONDS_PER_MILLISECOND);
454
- const microsWithinSecond = epochMicros % MICROSECONDS_PER_SECOND;
455
- const millisecondIso = new Date(epochMillis).toISOString();
456
- return `${millisecondIso.slice(0, -5)}.${String(microsWithinSecond).padStart(6, "0")}Z`;
431
+ let epochMillis = Math.floor(epochMicros / 1e3), microsWithinSecond = epochMicros % 1e6;
432
+ return `${new Date(epochMillis).toISOString().slice(0, -5)}.${String(microsWithinSecond).padStart(6, "0")}Z`;
457
433
  }
458
434
  function durationFor(activePage, nowMs) {
459
- if (!activePage || nowMs < activePage.enteredAtMs) return void 0;
460
- return {
461
- path: activePage.path,
462
- timeOnPageSeconds: Math.floor((nowMs - activePage.enteredAtMs) / 1e3)
463
- };
435
+ if (!(!activePage || nowMs < activePage.enteredAtMs))
436
+ return {
437
+ path: activePage.path,
438
+ timeOnPageSeconds: Math.floor((nowMs - activePage.enteredAtMs) / 1e3)
439
+ };
464
440
  }
465
441
  function isExpired(state, nowMs) {
466
- return nowMs - state.lastActivityAtMs >= ANALYTICS_SESSION_IDLE_TIMEOUT_MS;
442
+ return nowMs - state.lastActivityAtMs >= 18e5;
467
443
  }
468
444
  function isPersistedSession(value) {
469
- if (!value || typeof value !== "object") return false;
470
- const state = value;
471
- return state.version === ANALYTICS_SESSION_STATE_VERSION && typeof state.id === "string" && state.id.length > 0 && typeof state.startedAtMs === "number" && Number.isFinite(state.startedAtMs) && typeof state.lastActivityAtMs === "number" && Number.isFinite(state.lastActivityAtMs) && (state.lastOccurredAtMicros === void 0 || typeof state.lastOccurredAtMicros === "number" && Number.isSafeInteger(state.lastOccurredAtMicros)) && typeof state.bootstrapped === "boolean" && (!state.activePage || typeof state.activePage.path === "string" && typeof state.activePage.enteredAtMs === "number" && Number.isFinite(state.activePage.enteredAtMs));
445
+ if (!value || typeof value != "object") return false;
446
+ let state = value;
447
+ return state.version === 2 && typeof state.id == "string" && state.id.length > 0 && typeof state.startedAtMs == "number" && Number.isFinite(state.startedAtMs) && typeof state.lastActivityAtMs == "number" && Number.isFinite(state.lastActivityAtMs) && (state.lastOccurredAtMicros === void 0 || typeof state.lastOccurredAtMicros == "number" && Number.isSafeInteger(state.lastOccurredAtMicros)) && typeof state.bootstrapped == "boolean" && (!state.activePage || typeof state.activePage.path == "string" && typeof state.activePage.enteredAtMs == "number" && Number.isFinite(state.activePage.enteredAtMs));
472
448
  }
473
449
  function generateSessionId() {
474
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
475
- return crypto.randomUUID();
476
- }
477
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (character) => {
478
- const random = Math.random() * 16 | 0;
479
- const value = character === "x" ? random : random & 3 | 8;
480
- return value.toString(16);
450
+ return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (character) => {
451
+ let random = Math.random() * 16 | 0;
452
+ return (character === "x" ? random : random & 3 | 8).toString(16);
481
453
  });
482
454
  }
483
455
 
484
456
  // src/activity.ts
485
- var VISITOR_ID_STORAGE_KEY = "cimplify_visitor_id";
486
- var ACTIVITY_RETRY_POLICY = {
457
+ var VISITOR_ID_STORAGE_KEY = "cimplify_visitor_id", ACTIVITY_RETRY_POLICY = {
487
458
  maxRetries: 1,
488
459
  jitterRatio: 0.2
489
- };
490
- var PAGE_VIEW_TRACKER_KEY = /* @__PURE__ */ Symbol.for("@cimplify/sdk.page-view-tracker-hub");
491
- var PAGE_VIEW_TRACKER_VERSION = 2;
460
+ }, PAGE_VIEW_TRACKER_KEY = /* @__PURE__ */ Symbol.for("@cimplify/sdk.page-view-tracker-hub"), PAGE_VIEW_TRACKER_VERSION = 2;
492
461
  function trackerHost() {
493
462
  return window;
494
463
  }
495
464
  function currentWindowTrackerHub() {
496
- const candidate = trackerHost()[PAGE_VIEW_TRACKER_KEY];
497
- return candidate?.version === PAGE_VIEW_TRACKER_VERSION && candidate.registrations instanceof Map && typeof candidate.recordAll === "function" ? candidate : null;
465
+ let candidate = trackerHost()[PAGE_VIEW_TRACKER_KEY];
466
+ return candidate?.version === (2) && candidate.registrations instanceof Map && typeof candidate.recordAll == "function" ? candidate : null;
498
467
  }
499
468
  function weakReference(target) {
500
- const WeakReference = globalThis.WeakRef;
501
- if (WeakReference) return new WeakReference(target);
502
- return { deref: () => target };
469
+ let WeakReference = globalThis.WeakRef;
470
+ return WeakReference ? new WeakReference(target) : { deref: () => target };
503
471
  }
504
472
  function latestLiveOwner(registration) {
505
473
  let latest = null;
506
- for (const [token, reference] of registration.owners) {
507
- const owner = reference.deref();
508
- if (!owner || owner.released) {
509
- registration.owners.delete(token);
510
- } else {
511
- latest = owner;
512
- }
474
+ for (let [token, reference] of registration.owners) {
475
+ let owner = reference.deref();
476
+ !owner || owner.released ? registration.owners.delete(token) : latest = owner;
513
477
  }
514
478
  return latest;
515
479
  }
516
480
  function recordRegistration(registration, path) {
517
481
  if (path === registration.lastPath) return;
518
- const owner = registration.activeOwner && !registration.activeOwner.released ? registration.activeOwner : latestLiveOwner(registration);
519
- if (!owner) return;
520
- registration.activeOwner = owner;
521
- registration.lastPath = path;
522
- owner.recorder(path);
482
+ let owner = registration.activeOwner && !registration.activeOwner.released ? registration.activeOwner : latestLiveOwner(registration);
483
+ owner && (registration.activeOwner = owner, registration.lastPath = path, owner.recorder(path));
523
484
  }
524
485
  function createWindowTrackerHub() {
525
- const originalPushState = window.history.pushState;
526
- const originalReplaceState = window.history.replaceState;
527
- const hub = {
528
- version: PAGE_VIEW_TRACKER_VERSION,
486
+ let originalPushState = window.history.pushState, originalReplaceState = window.history.replaceState, hub = {
487
+ version: (2),
529
488
  registrations: /* @__PURE__ */ new Map(),
530
489
  originalPushState,
531
490
  originalReplaceState
532
491
  };
533
- hub.recordAll = () => {
534
- const path = window.location.pathname;
535
- for (const registration of hub.registrations.values()) {
492
+ return hub.recordAll = () => {
493
+ let path = window.location.pathname;
494
+ for (let registration of hub.registrations.values())
536
495
  recordRegistration(registration, path);
537
- }
538
- };
539
- hub.patchedPushState = function(...args) {
540
- originalPushState.apply(this, args);
541
- hub.recordAll();
542
- };
543
- hub.patchedReplaceState = function(...args) {
544
- originalReplaceState.apply(this, args);
545
- hub.recordAll();
546
- };
547
- hub.popstateListener = () => hub.recordAll();
548
- window.history.pushState = hub.patchedPushState;
549
- window.history.replaceState = hub.patchedReplaceState;
550
- window.addEventListener("popstate", hub.popstateListener);
551
- trackerHost()[PAGE_VIEW_TRACKER_KEY] = hub;
552
- return hub;
496
+ }, hub.patchedPushState = function(...args) {
497
+ originalPushState.apply(this, args), hub.recordAll();
498
+ }, hub.patchedReplaceState = function(...args) {
499
+ originalReplaceState.apply(this, args), hub.recordAll();
500
+ }, hub.popstateListener = () => hub.recordAll(), window.history.pushState = hub.patchedPushState, window.history.replaceState = hub.patchedReplaceState, window.addEventListener("popstate", hub.popstateListener), trackerHost()[PAGE_VIEW_TRACKER_KEY] = hub, hub;
553
501
  }
554
502
  function pageViewTrackerIdentity(client) {
555
503
  return JSON.stringify([client.getBaseUrl(), client.getPublicKey().trim()]);
556
504
  }
557
505
  function acquireWindowPageViewTracker(identity, recorder) {
558
- const hub = currentWindowTrackerHub() ?? createWindowTrackerHub();
559
- let registration = hub.registrations.get(identity);
560
- const isNewIdentity = !registration;
561
- if (!registration) {
562
- registration = { owners: /* @__PURE__ */ new Map(), activeOwner: null, lastPath: null };
563
- hub.registrations.set(identity, registration);
564
- }
565
- const owner = {
506
+ let hub = currentWindowTrackerHub() ?? createWindowTrackerHub(), registration = hub.registrations.get(identity), isNewIdentity = !registration;
507
+ registration || (registration = { owners: /* @__PURE__ */ new Map(), activeOwner: null, lastPath: null }, hub.registrations.set(identity, registration));
508
+ let owner = {
566
509
  token: Symbol(identity),
567
510
  recorder,
568
511
  released: false
569
512
  };
570
- registration.owners.set(owner.token, weakReference(owner));
571
- registration.activeOwner = owner;
572
- if (isNewIdentity) {
573
- recordRegistration(registration, window.location.pathname);
574
- }
513
+ registration.owners.set(owner.token, weakReference(owner)), registration.activeOwner = owner, isNewIdentity && recordRegistration(registration, window.location.pathname);
575
514
  let released = false;
576
515
  return () => {
577
- if (released) return;
578
- released = true;
579
- owner.released = true;
580
- registration.owners.delete(owner.token);
581
- if (registration.activeOwner === owner) {
582
- registration.activeOwner = latestLiveOwner(registration);
583
- }
584
- if (registration.activeOwner) return;
585
- if (hub.registrations.get(identity) === registration) {
586
- hub.registrations.delete(identity);
587
- }
588
- if (hub.registrations.size !== 0) return;
589
- window.removeEventListener("popstate", hub.popstateListener);
590
- if (window.history.pushState === hub.patchedPushState) {
591
- window.history.pushState = hub.originalPushState;
592
- }
593
- if (window.history.replaceState === hub.patchedReplaceState) {
594
- window.history.replaceState = hub.originalReplaceState;
595
- }
596
- if (currentWindowTrackerHub() === hub) {
597
- delete trackerHost()[PAGE_VIEW_TRACKER_KEY];
598
- }
516
+ released || (released = true, owner.released = true, registration.owners.delete(owner.token), registration.activeOwner === owner && (registration.activeOwner = latestLiveOwner(registration)), !registration.activeOwner && (hub.registrations.get(identity) === registration && hub.registrations.delete(identity), hub.registrations.size === 0 && (window.removeEventListener("popstate", hub.popstateListener), window.history.pushState === hub.patchedPushState && (window.history.pushState = hub.originalPushState), window.history.replaceState === hub.patchedReplaceState && (window.history.replaceState = hub.originalReplaceState), currentWindowTrackerHub() === hub && delete trackerHost()[PAGE_VIEW_TRACKER_KEY])));
599
517
  };
600
518
  }
601
519
  var ActivityService = class {
@@ -611,35 +529,28 @@ var ActivityService = class {
611
529
  * by the track* methods.
612
530
  */
613
531
  startSession() {
614
- if (typeof window === "undefined") return;
615
- const session = this.sessions.beginEvent();
616
- void this.bootstrapSession(session, false, this.captureGeneration()).catch(() => {
532
+ if (typeof window > "u") return;
533
+ let session = this.sessions.beginEvent();
534
+ this.bootstrapSession(session, false, this.captureGeneration()).catch(() => {
617
535
  });
618
536
  }
619
537
  /** Rebind an existing analytics session after the server authenticates a customer. */
620
538
  refreshIdentity() {
621
- if (typeof window === "undefined") return;
622
- const session = this.sessions.current();
623
- if (!session) return;
624
- void this.bootstrapSession(session, true, this.captureGeneration()).catch(() => {
539
+ if (typeof window > "u") return;
540
+ let session = this.sessions.current();
541
+ session && this.bootstrapSession(session, true, this.captureGeneration()).catch(() => {
625
542
  });
626
543
  }
627
544
  /** A signed-out browser starts a fresh anonymous analytics session. */
628
545
  resetSession() {
629
- this.invalidatePendingActivity();
630
- this.sessions.reset();
546
+ this.invalidatePendingActivity(), this.sessions.reset();
631
547
  }
632
548
  /** Drop the old storefront's analytics state before binding this service to the new one. */
633
549
  resetForStorefrontIdentityChange() {
634
- this.invalidatePendingActivity();
635
- this.sessions.reset();
636
- this.sessions = this.createSessionCoordinator();
550
+ this.invalidatePendingActivity(), this.sessions.reset(), this.sessions = this.createSessionCoordinator();
637
551
  }
638
552
  buildSessionPayload(session) {
639
- const params = new URLSearchParams(window.location.search);
640
- const utm = (key) => params.get(`utm_${key}`) || void 0;
641
- const { visitorId, isNewVisitor } = resolveVisitor();
642
- let timezone;
553
+ let params = new URLSearchParams(window.location.search), utm = (key) => params.get(`utm_${key}`) || void 0, { visitorId, isNewVisitor } = resolveVisitor(), timezone;
643
554
  try {
644
555
  timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
645
556
  } catch {
@@ -669,27 +580,21 @@ var ActivityService = class {
669
580
  }
670
581
  /** Route-level page view. Product/category interactions are tracked separately. */
671
582
  trackPageView(options = {}) {
672
- if (typeof window === "undefined") return;
673
- const pagePath = options.pagePath ?? currentPath() ?? "";
674
- const transition = this.sessions.beginPage(pagePath);
675
- const events = [];
676
- if (transition.previousPage) {
677
- events.push({
678
- type: "page_duration",
679
- page_path: transition.previousPage.path,
680
- time_on_page: transition.previousPage.timeOnPageSeconds
681
- });
682
- }
683
- events.push({
583
+ if (typeof window > "u") return;
584
+ let pagePath = options.pagePath ?? currentPath() ?? "", transition = this.sessions.beginPage(pagePath), events = [];
585
+ transition.previousPage && events.push({
586
+ type: "page_duration",
587
+ page_path: transition.previousPage.path,
588
+ time_on_page: transition.previousPage.timeOnPageSeconds
589
+ }), events.push({
684
590
  type: "page_view",
685
591
  page_path: pagePath,
686
592
  page_title: options.pageTitle ?? currentTitle()
687
- });
688
- this.sendEvents(events, transition.session);
593
+ }), this.sendEvents(events, transition.session);
689
594
  }
690
595
  trackProductView(productId, options = {}) {
691
- if (typeof window === "undefined") return;
692
- const event = {
596
+ if (typeof window > "u") return;
597
+ let event = {
693
598
  type: "product_view",
694
599
  product_id: productId,
695
600
  product_name: options.productName,
@@ -700,8 +605,8 @@ var ActivityService = class {
700
605
  this.sendEvents([event]);
701
606
  }
702
607
  trackCategoryView(categoryId, options = {}) {
703
- if (typeof window === "undefined") return;
704
- const event = {
608
+ if (typeof window > "u") return;
609
+ let event = {
705
610
  type: "category_view",
706
611
  category_id: categoryId,
707
612
  category_name: options.categoryName,
@@ -713,11 +618,9 @@ var ActivityService = class {
713
618
  return safe(this.client.get("/api/v1/activity/state"));
714
619
  }
715
620
  async getRecommendations(options) {
716
- const params = new URLSearchParams();
717
- if (options?.location_id) params.set("location_id", options.location_id);
718
- if (options?.limit) params.set("limit", String(options.limit));
719
- const query = params.toString();
720
- const path = query ? `/api/v1/activity/recommendations?${query}` : "/api/v1/activity/recommendations";
621
+ let params = new URLSearchParams();
622
+ options?.location_id && params.set("location_id", options.location_id), options?.limit && params.set("limit", String(options.limit));
623
+ let query = params.toString(), path = query ? `/api/v1/activity/recommendations?${query}` : "/api/v1/activity/recommendations";
721
624
  return safe(this.client.get(path));
722
625
  }
723
626
  async dismissMessage(code) {
@@ -727,9 +630,8 @@ var ActivityService = class {
727
630
  }
728
631
  /** Records a page view now and on every route change; returns a stop fn. */
729
632
  autoTrackPageViews() {
730
- if (typeof window === "undefined") return () => {
731
- };
732
- return acquireWindowPageViewTracker(pageViewTrackerIdentity(this.client), (path) => {
633
+ return typeof window > "u" ? () => {
634
+ } : acquireWindowPageViewTracker(pageViewTrackerIdentity(this.client), (path) => {
733
635
  try {
734
636
  this.trackPageView({ pagePath: path });
735
637
  } catch {
@@ -737,8 +639,7 @@ var ActivityService = class {
737
639
  });
738
640
  }
739
641
  sendEvents(events, session) {
740
- if (typeof window === "undefined") return;
741
- void this.postEvents(events, session ?? this.sessions.beginEvent()).catch(() => {
642
+ typeof window > "u" || this.postEvents(events, session ?? this.sessions.beginEvent()).catch(() => {
742
643
  });
743
644
  }
744
645
  hasStorefrontIdentity() {
@@ -746,10 +647,8 @@ var ActivityService = class {
746
647
  }
747
648
  async postEvents(events, session) {
748
649
  if (!this.hasStorefrontIdentity()) return;
749
- const generation = this.captureGeneration();
750
- await this.bootstrapSession(session, false, generation);
751
- if (!this.isCurrentGeneration(generation)) return;
752
- await this.client.post(
650
+ let generation = this.captureGeneration();
651
+ await this.bootstrapSession(session, false, generation), this.isCurrentGeneration(generation) && await this.client.post(
753
652
  "/api/v1/activity/events",
754
653
  {
755
654
  analytics_session_id: session.id,
@@ -760,24 +659,17 @@ var ActivityService = class {
760
659
  );
761
660
  }
762
661
  bootstrapSession(session, force = false, generation = this.captureGeneration()) {
763
- if (!this.hasStorefrontIdentity()) return Promise.resolve();
764
- if (!force && !session.requiresBootstrap) return Promise.resolve();
765
- if (!force && this.bootstrapRequest?.sessionId === session.id && sameActivityGeneration(this.bootstrapRequest.generation, generation)) {
662
+ if (!this.hasStorefrontIdentity() || !force && !session.requiresBootstrap) return Promise.resolve();
663
+ if (!force && this.bootstrapRequest?.sessionId === session.id && sameActivityGeneration(this.bootstrapRequest.generation, generation))
766
664
  return this.bootstrapRequest.promise;
767
- }
768
- const promise = this.client.post("/api/v1/activity/session", this.buildSessionPayload(session), {
665
+ let promise = this.client.post("/api/v1/activity/session", this.buildSessionPayload(session), {
769
666
  retryPolicy: ACTIVITY_RETRY_POLICY
770
667
  }).then(() => {
771
- if (this.isCurrentGeneration(generation)) {
772
- this.sessions.markBootstrapped(session.id);
773
- }
668
+ this.isCurrentGeneration(generation) && this.sessions.markBootstrapped(session.id);
774
669
  }).finally(() => {
775
- if (this.bootstrapRequest?.promise === promise) {
776
- this.bootstrapRequest = null;
777
- }
670
+ this.bootstrapRequest?.promise === promise && (this.bootstrapRequest = null);
778
671
  });
779
- this.bootstrapRequest = { sessionId: session.id, generation, promise };
780
- return promise;
672
+ return this.bootstrapRequest = { sessionId: session.id, generation, promise }, promise;
781
673
  }
782
674
  captureGeneration() {
783
675
  return {
@@ -790,8 +682,7 @@ var ActivityService = class {
790
682
  return sameActivityGeneration(generation, this.captureGeneration());
791
683
  }
792
684
  invalidatePendingActivity() {
793
- this.localGeneration += 1;
794
- this.bootstrapRequest = null;
685
+ this.localGeneration += 1, this.bootstrapRequest = null;
795
686
  }
796
687
  createSessionCoordinator() {
797
688
  return new AnalyticsSessionCoordinator(pageViewTrackerIdentity(this.client));
@@ -801,26 +692,20 @@ function sameActivityGeneration(left, right) {
801
692
  return left.local === right.local && left.publicKey === right.publicKey && left.session === right.session;
802
693
  }
803
694
  function currentPath() {
804
- if (typeof window !== "undefined") {
695
+ if (typeof window < "u")
805
696
  return window.location.pathname;
806
- }
807
- return void 0;
808
697
  }
809
698
  function currentTitle() {
810
- if (typeof document !== "undefined" && document.title) {
699
+ if (typeof document < "u" && document.title)
811
700
  return document.title;
812
- }
813
- return void 0;
814
701
  }
815
702
  function resolveVisitor() {
816
703
  try {
817
- const existing = localStorage.getItem(VISITOR_ID_STORAGE_KEY);
818
- if (existing) {
819
- return { visitorId: existing, isNewVisitor: false };
820
- }
821
- const visitorId = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `v_${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
822
- localStorage.setItem(VISITOR_ID_STORAGE_KEY, visitorId);
823
- return { visitorId, isNewVisitor: true };
704
+ let existing = localStorage.getItem(VISITOR_ID_STORAGE_KEY);
705
+ if (existing)
706
+ return { visitorId: existing, isNewVisitor: !1 };
707
+ let visitorId = typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `v_${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
708
+ return localStorage.setItem(VISITOR_ID_STORAGE_KEY, visitorId), { visitorId, isNewVisitor: !0 };
824
709
  } catch {
825
710
  return {};
826
711
  }
@@ -835,12 +720,11 @@ var SubscriptionService = class {
835
720
  return safe(this.client.get("/api/v1/subscriptions"));
836
721
  }
837
722
  async get(id) {
838
- const encodedId = encodeURIComponent(id);
723
+ let encodedId = encodeURIComponent(id);
839
724
  return safe(this.client.get(`/api/v1/subscriptions/${encodedId}`));
840
725
  }
841
726
  async cancel(id, reason, opts) {
842
- const encodedId = encodeURIComponent(id);
843
- const idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
727
+ let encodedId = encodeURIComponent(id), idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
844
728
  return safe(
845
729
  this.client.post(
846
730
  `/api/v1/subscriptions/${encodedId}/cancel`,
@@ -850,20 +734,19 @@ var SubscriptionService = class {
850
734
  );
851
735
  }
852
736
  async pause(id) {
853
- const encodedId = encodeURIComponent(id);
737
+ let encodedId = encodeURIComponent(id);
854
738
  return safe(
855
739
  this.client.post(`/api/v1/subscriptions/${encodedId}/pause`)
856
740
  );
857
741
  }
858
742
  async resume(id) {
859
- const encodedId = encodeURIComponent(id);
743
+ let encodedId = encodeURIComponent(id);
860
744
  return safe(
861
745
  this.client.post(`/api/v1/subscriptions/${encodedId}/resume`)
862
746
  );
863
747
  }
864
748
  async skipNextRenewal(id, opts) {
865
- const encodedId = encodeURIComponent(id);
866
- const idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
749
+ let encodedId = encodeURIComponent(id), idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
867
750
  return safe(
868
751
  this.client.post(
869
752
  `/api/v1/subscriptions/${encodedId}/skip`,
@@ -873,21 +756,34 @@ var SubscriptionService = class {
873
756
  );
874
757
  }
875
758
  };
876
-
877
- // src/uploads.ts
759
+ var CONTENT_SHA256_HEADER = "x-amz-checksum-sha256", HASH_CHUNK_BYTES = 4 * 1024 * 1024, HEX_RADIX = 16, HEX_BYTE_WIDTH = 2;
760
+ async function contentSha256(blob) {
761
+ let hasher = sha256.create();
762
+ for (let offset = 0; offset < blob.size; offset += HASH_CHUNK_BYTES)
763
+ hasher.update(new Uint8Array(await blob.slice(offset, offset + HASH_CHUNK_BYTES).arrayBuffer()));
764
+ let digest = hasher.digest(), hex = "", binary = "";
765
+ for (let byte of digest)
766
+ hex += byte.toString((16)).padStart((2), "0"), binary += String.fromCharCode(byte);
767
+ return { hex, base64: btoa(binary) };
768
+ }
878
769
  var UploadService = class {
879
770
  constructor(client) {
880
771
  this.client = client;
881
772
  }
773
+ /**
774
+ * With `opts.digest` the PUT to `upload_url` must send `digest.base64` as
775
+ * `CONTENT_SHA256_HEADER`; without it the server hashes the stored bytes.
776
+ */
882
777
  async init(filename, contentType2, sizeBytes, opts) {
883
- const idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
778
+ let idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
884
779
  return safe(
885
780
  this.client.post(
886
781
  "/api/v1/uploads/init",
887
782
  {
888
783
  filename,
889
784
  content_type: contentType2,
890
- size_bytes: sizeBytes
785
+ size_bytes: sizeBytes,
786
+ content_sha256: opts?.digest?.hex
891
787
  },
892
788
  { idempotencyKey }
893
789
  )
@@ -901,25 +797,24 @@ var UploadService = class {
901
797
  );
902
798
  }
903
799
  async upload(file) {
904
- const initResult = await this.init(file.name, file.type, file.size);
800
+ let digest = await contentSha256(file), initResult = await this.init(file.name, file.type, file.size, { digest });
905
801
  if (!initResult.ok) return initResult;
906
- const { upload_id, upload_url } = initResult.value;
802
+ let { upload_id, upload_url } = initResult.value;
907
803
  try {
908
- const uploadResponse = await fetch(upload_url, {
804
+ let uploadResponse = await fetch(upload_url, {
909
805
  method: "PUT",
910
806
  body: file,
911
- headers: { "Content-Type": file.type }
807
+ headers: { "Content-Type": file.type, [CONTENT_SHA256_HEADER]: digest.base64 }
912
808
  });
913
- if (!uploadResponse.ok) {
809
+ if (!uploadResponse.ok)
914
810
  return {
915
- ok: false,
811
+ ok: !1,
916
812
  error: new CimplifyError(
917
813
  "UPLOAD_FAILED",
918
814
  `Upload failed with status ${uploadResponse.status}`,
919
- true
815
+ !0
920
816
  )
921
817
  };
922
- }
923
818
  } catch (error) {
924
819
  return {
925
820
  ok: false,
@@ -939,19 +834,26 @@ var PlacesService = class {
939
834
  constructor(client) {
940
835
  this.client = client;
941
836
  }
942
- async autocomplete(input, sessionToken) {
837
+ /** `country` (ISO alpha-2) biases results; absent, the store's own country. */
838
+ async autocomplete(input, sessionToken, country) {
943
839
  return safe(
944
840
  this.client.post("/api/v1/places/autocomplete", {
945
841
  input,
946
- sessionToken
842
+ sessionToken,
843
+ ...country ? { country } : {}
947
844
  })
948
845
  );
949
846
  }
950
- async details(placeId, sessionToken) {
847
+ /**
848
+ * `country` (ISO alpha-2) is the country the place must lie in; pass the one
849
+ * the autocomplete used. Absent, the store's own country.
850
+ */
851
+ async details(placeId, sessionToken, country) {
951
852
  return safe(
952
853
  this.client.post("/api/v1/places/details", {
953
854
  place_id: placeId,
954
- sessionToken
855
+ sessionToken,
856
+ ...country ? { country } : {}
955
857
  })
956
858
  );
957
859
  }
@@ -963,25 +865,16 @@ var DeliveryService = class {
963
865
  this.client = client;
964
866
  }
965
867
  async getFee(dropoffLat, dropoffLng, country) {
966
- const params = new URLSearchParams();
967
- params.set("dropoff_lat", String(dropoffLat));
968
- params.set("dropoff_lng", String(dropoffLng));
969
- if (country) params.set("country", country);
970
- return safe(this.client.get(`/api/v1/delivery/fee?${params.toString()}`));
868
+ let params = new URLSearchParams();
869
+ return params.set("dropoff_lat", String(dropoffLat)), params.set("dropoff_lng", String(dropoffLng)), country && params.set("country", country), safe(this.client.get(`/api/v1/delivery/fee?${params.toString()}`));
971
870
  }
972
871
  async getOptions(queryOrLatitude, longitude, legacyOptions) {
973
- const query = typeof queryOrLatitude === "number" ? {
872
+ let query = typeof queryOrLatitude == "number" ? {
974
873
  ...legacyOptions,
975
874
  dropoffLat: queryOrLatitude,
976
875
  dropoffLng: longitude
977
- } : queryOrLatitude ?? {};
978
- const params = new URLSearchParams();
979
- if (query.dropoffLat != null) params.set("dropoff_lat", String(query.dropoffLat));
980
- if (query.dropoffLng != null) params.set("dropoff_lng", String(query.dropoffLng));
981
- if (query.country) params.set("country", query.country);
982
- if (query.currency) params.set("currency", query.currency);
983
- if (query.orderValue != null) params.set("order_value", String(query.orderValue));
984
- return safe(
876
+ } : queryOrLatitude ?? {}, params = new URLSearchParams();
877
+ return query.dropoffLat != null && params.set("dropoff_lat", String(query.dropoffLat)), query.dropoffLng != null && params.set("dropoff_lng", String(query.dropoffLng)), query.country && params.set("country", query.country), query.currency && params.set("currency", query.currency), query.orderValue != null && params.set("order_value", String(query.orderValue)), safe(
985
878
  this.client.get(`/api/v1/delivery/options?${params.toString()}`)
986
879
  );
987
880
  }
@@ -989,20 +882,14 @@ var DeliveryService = class {
989
882
 
990
883
  // src/chat-wire.ts
991
884
  function senderType(message) {
992
- if (message.sender_side === "account") return "customer";
993
- if (message.sender_side === "system") return "system";
994
- return message.authorship === "ai" ? "bot" : "agent";
885
+ return message.sender_side === "account" ? "customer" : message.sender_side === "system" ? "system" : message.authorship === "ai" ? "bot" : "agent";
995
886
  }
996
887
  function contentType(message) {
997
- if (message.content_type === "rich") {
998
- return message.structured_content?.["kind"] === "reaction" ? "reaction" : "interactive";
999
- }
888
+ if (message.content_type === "rich")
889
+ return message.structured_content?.kind === "reaction" ? "reaction" : "interactive";
1000
890
  if (message.content_type === "media") {
1001
- const mime = message.media[0]?.mime_type ?? "";
1002
- if (mime.startsWith("image/")) return "image";
1003
- if (mime.startsWith("video/")) return "video";
1004
- if (mime.startsWith("audio/")) return "audio";
1005
- return "document";
891
+ let mime = message.media[0]?.mime_type ?? "";
892
+ return mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : mime.startsWith("audio/") ? "audio" : "document";
1006
893
  }
1007
894
  return "text";
1008
895
  }
@@ -1010,7 +897,7 @@ function unresolvedReply(id) {
1010
897
  return { id, sender_type: "system", preview: "Earlier message" };
1011
898
  }
1012
899
  function chatMessagesFromWire(messages) {
1013
- const converted = messages.map((message) => ({
900
+ let converted = messages.map((message) => ({
1014
901
  id: message.id,
1015
902
  sequence: message.sequence,
1016
903
  sender_type: senderType(message),
@@ -1022,13 +909,10 @@ function chatMessagesFromWire(messages) {
1022
909
  edited_at: message.edited_at,
1023
910
  deleted_at: message.deleted_at,
1024
911
  created_at: message.created_at
1025
- }));
1026
- const byId = new Map(converted.map((message) => [message.id, message]));
912
+ })), byId = new Map(converted.map((message) => [message.id, message]));
1027
913
  return converted.map((message) => {
1028
- const targetId = message.reply_to?.id;
1029
- const target = targetId ? byId.get(targetId) : void 0;
1030
- if (!targetId || !target) return message;
1031
- return {
914
+ let targetId = message.reply_to?.id, target = targetId ? byId.get(targetId) : void 0;
915
+ return !targetId || !target ? message : {
1032
916
  ...message,
1033
917
  reply_to: {
1034
918
  id: targetId,
@@ -1042,42 +926,27 @@ function chatMessageFromWire(message) {
1042
926
  return chatMessagesFromWire([message])[0];
1043
927
  }
1044
928
  function chatRealtimeUpdateFromWire(envelope) {
1045
- if (envelope.type === "message_created" && envelope.data) {
929
+ if (envelope.type === "message_created" && envelope.data)
1046
930
  return {
1047
931
  kind: "message",
1048
932
  message: chatMessageFromWire(envelope.data)
1049
933
  };
1050
- }
1051
- if (envelope.type === "message_updated" && envelope.data) {
934
+ if (envelope.type === "message_updated" && envelope.data)
1052
935
  return {
1053
936
  kind: "message_updated",
1054
937
  message: chatMessageFromWire(envelope.data)
1055
938
  };
1056
- }
1057
939
  if (envelope.type === "read" && envelope.data) {
1058
- const read = envelope.data;
1059
- if (read.reader_side === "business" && typeof read.occurred_at === "string") {
1060
- return { kind: "business_read", occurredAt: read.occurred_at };
1061
- }
1062
- return { kind: "none" };
940
+ let read = envelope.data;
941
+ return read.reader_side === "business" && typeof read.occurred_at == "string" ? { kind: "business_read", occurredAt: read.occurred_at } : { kind: "none" };
1063
942
  }
1064
- if (envelope.type === "history_imported") {
943
+ if (envelope.type === "history_imported")
1065
944
  return { kind: "reload" };
1066
- }
1067
945
  if (envelope.type === "ai_mode_changed" && envelope.data) {
1068
- const mode = envelope.data.mode;
1069
- if (mode === "auto" || mode === "assist" || mode === "off") {
1070
- return { kind: "ai_mode", mode };
1071
- }
1072
- return { kind: "none" };
1073
- }
1074
- if (envelope.type === "handoff_requested") {
1075
- return { kind: "handoff" };
946
+ let mode = envelope.data.mode;
947
+ return mode === "auto" || mode === "assist" || mode === "off" ? { kind: "ai_mode", mode } : { kind: "none" };
1076
948
  }
1077
- if (envelope.type === "resync") {
1078
- return { kind: "resync", latestSequence: envelope.latest_sequence };
1079
- }
1080
- return { kind: "none" };
949
+ return envelope.type === "handoff_requested" ? { kind: "handoff" } : envelope.type === "resync" ? { kind: "resync", latestSequence: envelope.latest_sequence } : { kind: "none" };
1081
950
  }
1082
951
 
1083
952
  // src/support.ts
@@ -1092,17 +961,14 @@ var SupportService = class {
1092
961
  * contact values, account ids, and message bodies.
1093
962
  */
1094
963
  async claimExternalChats() {
1095
- if (!this.client.getAccessToken()) {
1096
- return err(new CimplifyError("not_authenticated", "No access token to claim with"));
1097
- }
1098
- return safe(
964
+ return this.client.getAccessToken() ? safe(
1099
965
  (async () => {
1100
- const businessId = await this.client.resolveBusinessId();
966
+ let businessId = await this.client.resolveBusinessId();
1101
967
  return this.client.post("/v1/me/chats/external-claims", {
1102
968
  business_id: businessId
1103
969
  });
1104
970
  })()
1105
- );
971
+ ) : err(new CimplifyError("not_authenticated", "No access token to claim with"));
1106
972
  }
1107
973
  /**
1108
974
  * Peek at the conversation without creating one: resolves the existing
@@ -1110,29 +976,25 @@ var SupportService = class {
1110
976
  * the inbox with empty threads.
1111
977
  */
1112
978
  async peekConversation() {
1113
- const result = await safe(
979
+ let result = await safe(
1114
980
  this.client.get("/api/v1/support/conversation")
1115
981
  );
1116
- if (!result.ok) return result;
1117
- if (!result.value.conversation) return ok(null);
1118
- return ok({
982
+ return result.ok ? result.value.conversation ? ok({
1119
983
  conversation: result.value.conversation,
1120
984
  messages: chatMessagesFromWire(result.value.messages)
1121
- });
985
+ }) : ok(null) : result;
1122
986
  }
1123
987
  /** Open (or resume) the customer's widget conversation. */
1124
988
  async openConversation(opts) {
1125
- const idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
1126
- const result = await safe(
989
+ let idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey(), result = await safe(
1127
990
  this.client.post("/api/v1/support/conversation", void 0, {
1128
991
  idempotencyKey
1129
992
  })
1130
993
  );
1131
- if (!result.ok) return result;
1132
- return ok({
994
+ return result.ok ? ok({
1133
995
  conversation: result.value.conversation,
1134
996
  messages: chatMessagesFromWire(result.value.messages)
1135
- });
997
+ }) : result;
1136
998
  }
1137
999
  /**
1138
1000
  * Send a message in the active conversation.
@@ -1143,8 +1005,7 @@ var SupportService = class {
1143
1005
  * server resolves it thread-scoped and echoes the quote as `reply_to`.
1144
1006
  */
1145
1007
  async sendMessage(content, opts) {
1146
- const idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
1147
- const result = await safe(
1008
+ let idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey(), result = await safe(
1148
1009
  this.client.post(
1149
1010
  "/api/v1/support/conversation/messages",
1150
1011
  {
@@ -1163,21 +1024,14 @@ var SupportService = class {
1163
1024
  * backward for scrollback into older history.
1164
1025
  */
1165
1026
  async getMessages(options = {}) {
1166
- const params = new URLSearchParams();
1167
- if (options.afterSequence !== void 0)
1168
- params.set("after_sequence", String(options.afterSequence));
1169
- if (options.beforeSequence !== void 0)
1170
- params.set("before_sequence", String(options.beforeSequence));
1171
- if (options.limit) params.set("limit", String(options.limit));
1172
- const query = params.toString();
1173
- const path = query ? `/api/v1/support/conversation/messages?${query}` : "/api/v1/support/conversation/messages";
1174
- const result = await safe(this.client.get(path));
1027
+ let params = new URLSearchParams();
1028
+ options.afterSequence !== void 0 && params.set("after_sequence", String(options.afterSequence)), options.beforeSequence !== void 0 && params.set("before_sequence", String(options.beforeSequence)), options.limit && params.set("limit", String(options.limit));
1029
+ let query = params.toString(), path = query ? `/api/v1/support/conversation/messages?${query}` : "/api/v1/support/conversation/messages", result = await safe(this.client.get(path));
1175
1030
  return result.ok ? ok(chatMessagesFromWire(result.value)) : result;
1176
1031
  }
1177
1032
  /** React to a message in the active conversation by its `ChatMessage.id`. */
1178
1033
  async reactToMessage(messageId, emoji) {
1179
- const clientId = generateIdempotencyKey();
1180
- const result = await safe(
1034
+ let clientId = generateIdempotencyKey(), result = await safe(
1181
1035
  this.client.post(
1182
1036
  `/api/v1/support/conversation/messages/${messageId}/reactions`,
1183
1037
  { emoji, client_id: clientId },
@@ -1188,7 +1042,7 @@ var SupportService = class {
1188
1042
  }
1189
1043
  /** Ask for a person: flags the thread for the merchant's inbox. */
1190
1044
  async requestHuman(opts) {
1191
- const idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
1045
+ let idempotencyKey = opts?.idempotencyKey ?? generateIdempotencyKey();
1192
1046
  return safe(
1193
1047
  this.client.post(
1194
1048
  "/api/v1/support/conversation/handoff",
@@ -1200,9 +1054,7 @@ var SupportService = class {
1200
1054
  };
1201
1055
 
1202
1056
  // src/session.ts
1203
- var CLAIM_TIMEOUT_MS = 15e3;
1204
- var CLAIM_PATH = "/api/v1/auth/session/claim";
1205
- var SessionService = class {
1057
+ var CLAIM_TIMEOUT_MS = 15e3, CLAIM_PATH = "/api/v1/auth/session/claim", SessionService = class {
1206
1058
  constructor(client) {
1207
1059
  this.client = client;
1208
1060
  this.claimInFlight = null;
@@ -1210,24 +1062,19 @@ var SessionService = class {
1210
1062
  this.lastClaimedAccessToken = null;
1211
1063
  this.claimedName = null;
1212
1064
  this.client.events.on(SESSION_CLEARED, () => {
1213
- this.lastClaimedAccessToken = null;
1214
- this.claimedName = null;
1215
- });
1216
- this.client.events.on(SESSION_CLAIMED, (event) => {
1217
- if (event.customerName) this.claimedName = event.customerName;
1065
+ this.lastClaimedAccessToken = null, this.claimedName = null;
1066
+ }), this.client.events.on(SESSION_CLAIMED, (event) => {
1067
+ event.customerName && (this.claimedName = event.customerName);
1218
1068
  });
1219
1069
  }
1220
1070
  /** The verified customer this session is bound to, null while anonymous. */
1221
1071
  get claimedCustomerName() {
1222
1072
  return this.claimedName;
1223
1073
  }
1224
- /** Adopt a session another holder already bound for this bearer. */
1074
+ /** Adopt a session another holder already bound, for this bearer or, with
1075
+ * `null`, for a bearer this client never holds (the checkout element). */
1225
1076
  adopt(accessToken, session) {
1226
- this.lastClaimedAccessToken = accessToken;
1227
- this.claimedName = session.customerName || null;
1228
- this.client.adoptSessionToken(session.sessionToken);
1229
- this.client.publishSessionClaimed(this.claimedName);
1230
- this.client.events.emit(SESSION_CLAIMED, session);
1077
+ this.lastClaimedAccessToken = accessToken, this.claimedName = session.customerName || null, this.client.adoptSessionToken(session.sessionToken), this.client.publishSessionClaimed(this.claimedName), this.client.events.emit(SESSION_CLAIMED, session);
1231
1078
  }
1232
1079
  /**
1233
1080
  * Bind the anonymous session to the verified Link identity in one server
@@ -1242,34 +1089,27 @@ var SessionService = class {
1242
1089
  * the client's event channel.
1243
1090
  */
1244
1091
  async claim() {
1245
- const accessToken = this.client.getAccessToken();
1246
- if (!accessToken) {
1092
+ let accessToken = this.client.getAccessToken();
1093
+ if (!accessToken)
1247
1094
  return err(new CimplifyError("not_authenticated", "No access token to claim with"));
1248
- }
1249
- if (this.claimInFlight) {
1250
- if (this.claimInFlightToken === accessToken) return this.claimInFlight;
1251
- await this.claimInFlight;
1252
- return this.claim();
1253
- }
1254
- if (this.lastClaimedAccessToken === accessToken) {
1095
+ if (this.claimInFlight)
1096
+ return this.claimInFlightToken === accessToken ? this.claimInFlight : (await this.claimInFlight, this.claim());
1097
+ if (this.lastClaimedAccessToken === accessToken)
1255
1098
  return err(new CimplifyError("already_claimed", "Session already claimed for this token"));
1256
- }
1257
- const epoch = this.client.getSessionEpoch();
1258
- this.claimInFlightToken = accessToken;
1259
- this.claimInFlight = (async () => {
1260
- const result = await safe(
1099
+ let epoch = this.client.getSessionEpoch();
1100
+ this.claimInFlightToken = accessToken, this.claimInFlight = (async () => {
1101
+ let result = await safe(
1261
1102
  this.client.post(
1262
1103
  CLAIM_PATH,
1263
1104
  { access_token: accessToken },
1264
- { timeoutMs: CLAIM_TIMEOUT_MS }
1105
+ { timeoutMs: (15e3) }
1265
1106
  )
1266
1107
  );
1267
1108
  if (result.ok) {
1268
- if (this.client.getSessionEpoch() !== epoch) {
1109
+ if (this.client.getSessionEpoch() !== epoch)
1269
1110
  return err(
1270
1111
  new CimplifyError("session_cleared", "Session was cleared during the claim")
1271
1112
  );
1272
- }
1273
1113
  this.adopt(accessToken, {
1274
1114
  sessionToken: result.value.session_token,
1275
1115
  customerName: result.value.customer.name,
@@ -1282,221 +1122,159 @@ var SessionService = class {
1282
1122
  try {
1283
1123
  return await this.claimInFlight;
1284
1124
  } finally {
1285
- this.claimInFlight = null;
1286
- this.claimInFlightToken = null;
1125
+ this.claimInFlight = null, this.claimInFlightToken = null;
1287
1126
  }
1288
1127
  }
1289
1128
  };
1290
1129
 
1291
1130
  // src/internal/cross-tab-session.ts
1292
- var CROSS_TAB_SESSION_HUB_KEY = /* @__PURE__ */ Symbol.for("@cimplify/sdk.cross-tab-session-hub");
1293
- var SESSION_SYNC_STORAGE_KEY = "cimplify_session_sync";
1294
- var MAX_RECENT_ENVELOPES = 64;
1131
+ var CROSS_TAB_SESSION_HUB_KEY = /* @__PURE__ */ Symbol.for("@cimplify/sdk.cross-tab-session-hub"), SESSION_SYNC_STORAGE_KEY = "cimplify_session_sync", MAX_RECENT_ENVELOPES = 64;
1295
1132
  function hubHost() {
1296
1133
  return window;
1297
1134
  }
1298
1135
  function currentHub() {
1299
- const candidate = hubHost()[CROSS_TAB_SESSION_HUB_KEY];
1300
- return candidate?.subscribers instanceof Map && candidate.recentEnvelopes instanceof Set && typeof candidate.storageListener === "function" && typeof candidate.dispatch === "function" ? candidate : null;
1136
+ let candidate = hubHost()[CROSS_TAB_SESSION_HUB_KEY];
1137
+ return candidate?.subscribers instanceof Map && candidate.recentEnvelopes instanceof Set && typeof candidate.storageListener == "function" && typeof candidate.dispatch == "function" ? candidate : null;
1301
1138
  }
1302
1139
  function subscriberReference(target) {
1303
- const WeakReference = globalThis.WeakRef;
1304
- if (WeakReference) return new WeakReference(target);
1305
- return { deref: () => target };
1140
+ let WeakReference = globalThis.WeakRef;
1141
+ return WeakReference ? new WeakReference(target) : { deref: () => target };
1306
1142
  }
1307
1143
  function pruneSubscribers(hub) {
1308
- for (const [token, reference] of hub.subscribers) {
1309
- if (!reference.deref()) hub.subscribers.delete(token);
1310
- }
1144
+ for (let [token, reference] of hub.subscribers)
1145
+ reference.deref() || hub.subscribers.delete(token);
1311
1146
  }
1312
1147
  function parseSessionSyncPayload(serialized) {
1313
1148
  if (!serialized) return null;
1314
1149
  try {
1315
- const payload = JSON.parse(serialized);
1316
- return (payload.type === "claimed" || payload.type === "cleared") && typeof payload.token === "string" && payload.token.length > 0 && typeof payload.at === "number" && Number.isFinite(payload.at) && (payload.name === void 0 || payload.name === null || typeof payload.name === "string") ? payload : null;
1150
+ let payload = JSON.parse(serialized);
1151
+ return (payload.type === "claimed" || payload.type === "cleared") && typeof payload.token == "string" && payload.token.length > 0 && typeof payload.at == "number" && Number.isFinite(payload.at) && (payload.name === void 0 || payload.name === null || typeof payload.name == "string") ? payload : null;
1317
1152
  } catch {
1318
1153
  return null;
1319
1154
  }
1320
1155
  }
1321
1156
  function sessionSyncEnvelopeKey(payload) {
1322
- const name = payload.name === void 0 ? ["missing"] : ["present", payload.name];
1157
+ let name = payload.name === void 0 ? ["missing"] : ["present", payload.name];
1323
1158
  return JSON.stringify([payload.type, payload.token, name, payload.at]);
1324
1159
  }
1325
1160
  function rememberEnvelope(hub, envelope) {
1326
1161
  if (hub.recentEnvelopes.has(envelope)) return false;
1327
- hub.recentEnvelopes.add(envelope);
1328
- if (hub.recentEnvelopes.size > MAX_RECENT_ENVELOPES) {
1329
- const oldest = hub.recentEnvelopes.values().next().value;
1330
- if (oldest) hub.recentEnvelopes.delete(oldest);
1162
+ if (hub.recentEnvelopes.add(envelope), hub.recentEnvelopes.size > (64)) {
1163
+ let oldest = hub.recentEnvelopes.values().next().value;
1164
+ oldest && hub.recentEnvelopes.delete(oldest);
1331
1165
  }
1332
1166
  return true;
1333
1167
  }
1334
1168
  function createHub() {
1335
- const hub = {
1169
+ let hub = {
1336
1170
  subscribers: /* @__PURE__ */ new Map(),
1337
1171
  recentEnvelopes: /* @__PURE__ */ new Set()
1338
1172
  };
1339
- hub.dispatch = (payload) => {
1340
- if (!rememberEnvelope(hub, sessionSyncEnvelopeKey(payload))) return;
1341
- for (const [token, reference] of hub.subscribers) {
1342
- const subscriber = reference.deref();
1343
- if (!subscriber) {
1344
- hub.subscribers.delete(token);
1345
- continue;
1346
- }
1347
- try {
1348
- subscriber.notify(payload);
1349
- } catch {
1173
+ return hub.dispatch = (payload) => {
1174
+ if (rememberEnvelope(hub, sessionSyncEnvelopeKey(payload)))
1175
+ for (let [token, reference] of hub.subscribers) {
1176
+ let subscriber = reference.deref();
1177
+ if (!subscriber) {
1178
+ hub.subscribers.delete(token);
1179
+ continue;
1180
+ }
1181
+ try {
1182
+ subscriber.notify(payload);
1183
+ } catch {
1184
+ }
1350
1185
  }
1351
- }
1352
- };
1353
- hub.storageListener = (event) => {
1354
- const storageEvent = event;
1186
+ }, hub.storageListener = (event) => {
1187
+ let storageEvent = event;
1355
1188
  if (storageEvent.key !== SESSION_SYNC_STORAGE_KEY) return;
1356
- const payload = parseSessionSyncPayload(storageEvent.newValue);
1357
- if (payload) hub.dispatch(payload);
1358
- };
1359
- window.addEventListener("storage", hub.storageListener);
1360
- hubHost()[CROSS_TAB_SESSION_HUB_KEY] = hub;
1361
- return hub;
1189
+ let payload = parseSessionSyncPayload(storageEvent.newValue);
1190
+ payload && hub.dispatch(payload);
1191
+ }, window.addEventListener("storage", hub.storageListener), hubHost()[CROSS_TAB_SESSION_HUB_KEY] = hub, hub;
1362
1192
  }
1363
1193
  function publishLocalSessionSync(payload) {
1364
- if (typeof window === "undefined" || typeof window.addEventListener !== "function") return;
1365
- (currentHub() ?? createHub()).dispatch(payload);
1194
+ typeof window > "u" || typeof window.addEventListener != "function" || (currentHub() ?? createHub()).dispatch(payload);
1366
1195
  }
1367
1196
  function subscribeCrossTabSession(notify) {
1368
- if (typeof window === "undefined" || typeof window.addEventListener !== "function") {
1197
+ if (typeof window > "u" || typeof window.addEventListener != "function")
1369
1198
  return () => {
1370
1199
  };
1371
- }
1372
- const hub = currentHub() ?? createHub();
1200
+ let hub = currentHub() ?? createHub();
1373
1201
  pruneSubscribers(hub);
1374
- const token = /* @__PURE__ */ Symbol("cross-tab-session-subscriber");
1375
- const subscriber = { notify };
1202
+ let token = /* @__PURE__ */ Symbol("cross-tab-session-subscriber"), subscriber = { notify };
1376
1203
  hub.subscribers.set(token, subscriberReference(subscriber));
1377
1204
  let unsubscribed = false;
1378
1205
  return () => {
1379
- if (unsubscribed) return;
1380
- unsubscribed = true;
1381
- subscriber.notify = () => {
1382
- };
1383
- hub.subscribers.delete(token);
1384
- pruneSubscribers(hub);
1385
- if (hub.subscribers.size !== 0) return;
1386
- window.removeEventListener("storage", hub.storageListener);
1387
- if (currentHub() === hub) delete hubHost()[CROSS_TAB_SESSION_HUB_KEY];
1206
+ unsubscribed || (unsubscribed = true, subscriber.notify = () => {
1207
+ }, hub.subscribers.delete(token), pruneSubscribers(hub), hub.subscribers.size === 0 && (window.removeEventListener("storage", hub.storageListener), currentHub() === hub && delete hubHost()[CROSS_TAB_SESSION_HUB_KEY]));
1388
1208
  };
1389
1209
  }
1390
1210
 
1391
1211
  // src/client.ts
1392
- var SESSION_TOKEN_STORAGE_KEY = "cimplify_session_token";
1393
- var ORDER_TOKEN_PREFIX = "cimplify_ot_";
1394
- var SESSION_TOKEN_HEADER = "x-session-token";
1395
- var LOCATION_ID_QUERY_PARAMETER = "location_id";
1396
- var ORDER_TOKEN_TTL_MS = 24 * 60 * 60 * 1e3;
1397
- var DEFAULT_TIMEOUT_MS = 5e3;
1398
- var DEFAULT_MAX_RETRIES = 3;
1399
- var DEFAULT_RETRY_DELAY_MS = 1e3;
1400
- var MAX_RETRY_AFTER_MS = 3e4;
1212
+ var SESSION_TOKEN_STORAGE_KEY = "cimplify_session_token", ORDER_TOKEN_PREFIX = "cimplify_ot_", SESSION_TOKEN_HEADER = "x-session-token", LOCATION_ID_QUERY_PARAMETER = "location_id", ORDER_TOKEN_TTL_MS = 1440 * 60 * 1e3, DEFAULT_TIMEOUT_MS = 5e3, HTTP_SERVER_ERROR_STATUS = 500, HTTP_TOO_MANY_REQUESTS = 429, HTTP_SERVICE_UNAVAILABLE = 503, RETRY_AFTER_HEADER = "Retry-After", DEFAULT_MAX_RETRIES = 3, DEFAULT_RETRY_DELAY_MS = 1e3, MAX_RETRY_AFTER_MS = 3e4;
1401
1213
  function sleep(ms, signal) {
1402
- if (signal?.aborted) {
1403
- return Promise.reject(new CimplifyError(ErrorCode.CANCELLED, "Request was cancelled.", true));
1404
- }
1405
- return new Promise((resolve, reject) => {
1406
- const timer = setTimeout(() => {
1407
- signal?.removeEventListener("abort", onAbort);
1408
- resolve();
1409
- }, ms);
1410
- const onAbort = () => {
1411
- clearTimeout(timer);
1412
- reject(new CimplifyError(ErrorCode.CANCELLED, "Request was cancelled.", true));
1214
+ return signal?.aborted ? Promise.reject(new CimplifyError(ErrorCode.CANCELLED, "Request was cancelled.", true)) : new Promise((resolve, reject) => {
1215
+ let timer = setTimeout(() => {
1216
+ signal?.removeEventListener("abort", onAbort), resolve();
1217
+ }, ms), onAbort = () => {
1218
+ clearTimeout(timer), reject(new CimplifyError(ErrorCode.CANCELLED, "Request was cancelled.", true));
1413
1219
  };
1414
1220
  signal?.addEventListener("abort", onAbort, { once: true });
1415
1221
  });
1416
1222
  }
1417
- function parseRetryAfterMs(value) {
1223
+ var MS_PER_SECOND = 1e3;
1224
+ function retryAfterDelayMs(value) {
1418
1225
  if (!value) return null;
1419
- const seconds = Number(value);
1420
- if (Number.isFinite(seconds) && seconds >= 0) {
1421
- return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS);
1422
- }
1423
- const retryAt = Date.parse(value);
1424
- if (!Number.isFinite(retryAt)) return null;
1425
- return Math.min(Math.max(0, retryAt - Date.now()), MAX_RETRY_AFTER_MS);
1226
+ let seconds = Number(value);
1227
+ if (Number.isFinite(seconds) && seconds >= 0)
1228
+ return seconds * (1e3);
1229
+ let retryAt = Date.parse(value);
1230
+ return Number.isFinite(retryAt) ? Math.max(0, retryAt - Date.now()) : null;
1231
+ }
1232
+ function parseRetryAfterMs(value) {
1233
+ let delayMs = retryAfterDelayMs(value);
1234
+ return delayMs === null ? null : Math.min(delayMs, (3e4));
1426
1235
  }
1427
1236
  function withPositiveJitter(delayMs, jitterRatio = 0) {
1428
- const boundedRatio = Math.min(Math.max(jitterRatio, 0), 1);
1429
- if (boundedRatio === 0 || delayMs === 0) return delayMs;
1430
- return Math.round(delayMs + delayMs * boundedRatio * Math.random());
1237
+ let boundedRatio = Math.min(Math.max(jitterRatio, 0), 1);
1238
+ return boundedRatio === 0 || delayMs === 0 ? delayMs : Math.round(delayMs + delayMs * boundedRatio * Math.random());
1431
1239
  }
1432
1240
  function nextInit(cacheOptions) {
1433
1241
  if (!cacheOptions) return {};
1434
- const next = {};
1435
- if (cacheOptions.revalidate !== void 0) next.revalidate = cacheOptions.revalidate;
1436
- if (cacheOptions.tags && cacheOptions.tags.length > 0) next.tags = [...cacheOptions.tags];
1437
- if (next.revalidate === void 0 && !next.tags) return {};
1438
- return { next };
1242
+ let next = {};
1243
+ return cacheOptions.revalidate !== void 0 && (next.revalidate = cacheOptions.revalidate), cacheOptions.tags && cacheOptions.tags.length > 0 && (next.tags = [...cacheOptions.tags]), next.revalidate === void 0 && !next.tags ? {} : { next };
1439
1244
  }
1440
1245
  function mergeOptionHeaders(base, opts) {
1441
1246
  if (!opts) return base;
1442
- const merged = { ...base };
1443
- if (opts.headers) {
1444
- for (const [k, v] of Object.entries(opts.headers)) {
1247
+ let merged = { ...base };
1248
+ if (opts.headers)
1249
+ for (let [k, v] of Object.entries(opts.headers))
1445
1250
  merged[k] = v;
1446
- }
1447
- }
1448
- if (opts.idempotencyKey) {
1449
- merged["Idempotency-Key"] = opts.idempotencyKey;
1450
- }
1451
- return merged;
1251
+ return opts.idempotencyKey && (merged["Idempotency-Key"] = opts.idempotencyKey), merged;
1452
1252
  }
1453
1253
  function generateSessionToken() {
1454
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
1455
- return crypto.randomUUID();
1456
- }
1457
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1458
- const r = Math.random() * 16 | 0;
1459
- const v = c === "x" ? r : r & 3 | 8;
1460
- return v.toString(16);
1254
+ return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1255
+ let r = Math.random() * 16 | 0;
1256
+ return (c === "x" ? r : r & 3 | 8).toString(16);
1461
1257
  });
1462
1258
  }
1463
1259
  function isRetryable(error) {
1464
- if (error instanceof TypeError && error.message.includes("fetch")) {
1465
- return true;
1466
- }
1467
- if (error instanceof DOMException && error.name === "AbortError") {
1468
- return true;
1469
- }
1470
- if (error instanceof CimplifyError) {
1471
- return error.retryable;
1472
- }
1473
- return false;
1260
+ return error instanceof TypeError && error.message.includes("fetch") || error instanceof DOMException && error.name === "AbortError" ? true : error instanceof CimplifyError ? error.retryable : false;
1474
1261
  }
1475
1262
  function toNetworkError(error, isTestMode) {
1476
- if (error instanceof DOMException && error.name === "AbortError") {
1477
- return enrichError(
1478
- new CimplifyError(
1479
- ErrorCode.TIMEOUT,
1480
- "Request timed out. Please check your connection and try again.",
1481
- true
1482
- ),
1483
- { isTestMode }
1484
- );
1485
- }
1486
- if (error instanceof TypeError && error.message.includes("fetch")) {
1487
- return enrichError(
1488
- new CimplifyError(
1489
- ErrorCode.NETWORK_ERROR,
1490
- "Network error. Please check your internet connection.",
1491
- true
1492
- ),
1493
- { isTestMode }
1494
- );
1495
- }
1496
- if (error instanceof CimplifyError) {
1497
- return enrichError(error, { isTestMode });
1498
- }
1499
- return enrichError(
1263
+ return error instanceof DOMException && error.name === "AbortError" ? enrichError(
1264
+ new CimplifyError(
1265
+ ErrorCode.TIMEOUT,
1266
+ "Request timed out. Please check your connection and try again.",
1267
+ true
1268
+ ),
1269
+ { isTestMode }
1270
+ ) : error instanceof TypeError && error.message.includes("fetch") ? enrichError(
1271
+ new CimplifyError(
1272
+ ErrorCode.NETWORK_ERROR,
1273
+ "Network error. Please check your internet connection.",
1274
+ true
1275
+ ),
1276
+ { isTestMode }
1277
+ ) : error instanceof CimplifyError ? enrichError(error, { isTestMode }) : enrichError(
1500
1278
  new CimplifyError(
1501
1279
  ErrorCode.UNKNOWN_ERROR,
1502
1280
  error instanceof Error ? error.message : "An unknown error occurred",
@@ -1506,9 +1284,9 @@ function toNetworkError(error, isTestMode) {
1506
1284
  );
1507
1285
  }
1508
1286
  function deriveUrls() {
1509
- const hostname = typeof window !== "undefined" ? window.location.hostname : "";
1287
+ let hostname = typeof window < "u" ? window.location.hostname : "";
1510
1288
  if (hostname === "localhost" || hostname === "127.0.0.1") {
1511
- const protocol = window.location.protocol;
1289
+ let protocol = window.location.protocol;
1512
1290
  return {
1513
1291
  baseUrl: `${protocol}//${hostname}:8082`,
1514
1292
  linkApiUrl: `${protocol}//${hostname}:8080`
@@ -1520,16 +1298,14 @@ function deriveUrls() {
1520
1298
  };
1521
1299
  }
1522
1300
  function normalizeUrl(url) {
1523
- const trimmed = url.trim();
1524
- if (!trimmed) return trimmed;
1525
- return trimmed.replace(/\/+$/, "");
1301
+ let trimmed = url.trim();
1302
+ return trimmed && trimmed.replace(/\/+$/, "");
1526
1303
  }
1527
1304
  function getEnvPublicKey() {
1528
1305
  try {
1529
- const env = globalThis.process;
1530
- return env?.env.NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY || void 0;
1306
+ return globalThis.process?.env.NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY || void 0;
1531
1307
  } catch {
1532
- return void 0;
1308
+ return;
1533
1309
  }
1534
1310
  }
1535
1311
  var CimplifyClient = class {
@@ -1554,53 +1330,27 @@ var CimplifyClient = class {
1554
1330
  this.events = createClientEvents();
1555
1331
  this.stopPageViewTracking = null;
1556
1332
  this.publicKey = config.publicKey || getEnvPublicKey() || "";
1557
- const urls = deriveUrls();
1558
- this.baseUrl = config.baseUrl ? normalizeUrl(config.baseUrl) : urls.baseUrl;
1559
- this.linkApiUrl = config.linkApiUrl ? normalizeUrl(config.linkApiUrl) : urls.linkApiUrl;
1560
- this.credentials = config.credentials || "include";
1561
- this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
1562
- this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
1563
- this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
1564
- this.hooks = config.hooks ?? {};
1565
- this.authorizationAdapters = config.authorizationAdapterRegistry ?? createDefaultPaymentAuthorizationAdapterRegistry();
1566
- this.fetchImpl = (config.fetch ?? globalThis.fetch).bind(globalThis);
1567
- this.sessionToken = this.loadSessionToken() ?? this.mintSessionToken();
1568
- const persistedSessionSync = this.loadSessionSyncPayload();
1569
- if (persistedSessionSync) this.observeSessionSync(persistedSessionSync);
1570
- this.stopCrossTabSessionWatch = subscribeCrossTabSession((payload) => {
1333
+ let urls = deriveUrls();
1334
+ this.baseUrl = config.baseUrl ? normalizeUrl(config.baseUrl) : urls.baseUrl, this.linkApiUrl = config.linkApiUrl ? normalizeUrl(config.linkApiUrl) : urls.linkApiUrl, this.credentials = config.credentials || "include", this.timeout = config.timeout ?? (5e3), this.maxRetries = config.maxRetries ?? (3), this.retryDelay = config.retryDelay ?? (1e3), this.hooks = config.hooks ?? {}, this.authorizationAdapters = config.authorizationAdapterRegistry ?? createDefaultPaymentAuthorizationAdapterRegistry(), this.fetchImpl = (config.fetch ?? globalThis.fetch).bind(globalThis), this.sessionToken = this.loadSessionToken() ?? this.mintSessionToken();
1335
+ let persistedSessionSync = this.loadSessionSyncPayload();
1336
+ persistedSessionSync && this.observeSessionSync(persistedSessionSync), this.stopCrossTabSessionWatch = subscribeCrossTabSession((payload) => {
1571
1337
  this.applyCrossTabSession(payload);
1572
- });
1573
- if (!this.publicKey && !config.suppressPublicKeyWarning) {
1574
- console.warn(
1575
- '[Cimplify] No public key found. Set NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY in your environment, or pass { publicKey: "cpk_..." } to createCimplifyClient().'
1576
- );
1577
- }
1578
- if (config.trackPageViews !== false) {
1579
- this.stopPageViewTracking = this.activity.autoTrackPageViews();
1580
- }
1338
+ }), !this.publicKey && !config.suppressPublicKeyWarning && console.warn(
1339
+ '[Cimplify] No public key found. Set NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY in your environment, or pass { publicKey: "cpk_..." } to createCimplifyClient().'
1340
+ ), config.trackPageViews !== false && (this.stopPageViewTracking = this.activity.autoTrackPageViews());
1581
1341
  }
1582
1342
  buildUrl(base, path) {
1583
- const url = `${base}${path}`;
1584
- const locationId = this.context.location_id;
1343
+ let url = `${base}${path}`, locationId = this.context.location_id;
1585
1344
  if (!locationId) return url;
1586
- const fragmentIndex = url.indexOf("#");
1587
- const urlWithoutFragment = fragmentIndex === -1 ? url : url.slice(0, fragmentIndex);
1588
- const fragment = fragmentIndex === -1 ? "" : url.slice(fragmentIndex);
1589
- const queryIndex = urlWithoutFragment.indexOf("?");
1590
- const query = queryIndex === -1 ? "" : urlWithoutFragment.slice(queryIndex + 1);
1591
- if (new URLSearchParams(query).has(LOCATION_ID_QUERY_PARAMETER)) return url;
1592
- const separator = queryIndex === -1 ? "?" : "&";
1593
- return `${urlWithoutFragment}${separator}${LOCATION_ID_QUERY_PARAMETER}=${encodeURIComponent(locationId)}${fragment}`;
1345
+ let fragmentIndex = url.indexOf("#"), urlWithoutFragment = fragmentIndex === -1 ? url : url.slice(0, fragmentIndex), fragment = fragmentIndex === -1 ? "" : url.slice(fragmentIndex), queryIndex = urlWithoutFragment.indexOf("?"), query = queryIndex === -1 ? "" : urlWithoutFragment.slice(queryIndex + 1);
1346
+ return new URLSearchParams(query).has(LOCATION_ID_QUERY_PARAMETER) ? url : `${urlWithoutFragment}${queryIndex === -1 ? "?" : "&"}${LOCATION_ID_QUERY_PARAMETER}=${encodeURIComponent(locationId)}${fragment}`;
1594
1347
  }
1595
1348
  stopTrackingPageViews() {
1596
- this.stopPageViewTracking?.();
1597
- this.stopPageViewTracking = null;
1349
+ this.stopPageViewTracking?.(), this.stopPageViewTracking = null;
1598
1350
  }
1599
1351
  /** Release window-level subscriptions and automatic tracking owned by this client. */
1600
1352
  destroy() {
1601
- this.stopTrackingPageViews();
1602
- this.stopCrossTabSessionWatch?.();
1603
- this.stopCrossTabSessionWatch = null;
1353
+ this.stopTrackingPageViews(), this.stopCrossTabSessionWatch?.(), this.stopCrossTabSessionWatch = null;
1604
1354
  }
1605
1355
  getAccessToken() {
1606
1356
  return this.accessToken;
@@ -1621,17 +1371,12 @@ var CimplifyClient = class {
1621
1371
  return this.publicKey.trim().startsWith("cpk_test_");
1622
1372
  }
1623
1373
  setAccessToken(token) {
1624
- const previous = this.accessToken;
1625
- this.accessToken = token;
1626
- if (previous !== token) {
1627
- this.sessionEpoch++;
1628
- }
1629
- this.hooks.onSessionChange?.({
1374
+ let previous = this.accessToken;
1375
+ this.accessToken = token, previous !== token && this.sessionEpoch++, this.hooks.onSessionChange?.({
1630
1376
  previousToken: previous,
1631
1377
  newToken: token,
1632
1378
  source: SESSION_CHANGE_SOURCE.MANUAL
1633
- });
1634
- this.events.emit(AUTH_TOKEN_CHANGED, { token });
1379
+ }), this.events.emit(AUTH_TOKEN_CHANGED, { token });
1635
1380
  }
1636
1381
  /**
1637
1382
  * Zero-UI claim: a freshly verified customer identity (OTP verify, silent
@@ -1642,8 +1387,7 @@ var CimplifyClient = class {
1642
1387
  * have no storefront tenant and therefore activate without this step.
1643
1388
  */
1644
1389
  autoClaimSession() {
1645
- if (typeof window === "undefined" || !this.sessionToken || !this.accessToken) return;
1646
- void this.session.claim();
1390
+ typeof window > "u" || !this.sessionToken || !this.accessToken || this.session.claim();
1647
1391
  }
1648
1392
  /**
1649
1393
  * Adopt a server-rotated session token (claim flow). The old token stays
@@ -1651,32 +1395,20 @@ var CimplifyClient = class {
1651
1395
  * rotation durable across reloads.
1652
1396
  */
1653
1397
  adoptSessionToken(token) {
1654
- if (!token || token === this.sessionToken) return;
1655
- this.sessionToken = token;
1656
- this.sessionEpoch++;
1657
- this.saveSessionToken(token);
1398
+ !token || token === this.sessionToken || (this.sessionToken = token, this.sessionEpoch++, this.saveSessionToken(token));
1658
1399
  }
1659
1400
  clearSession() {
1660
- const previous = this.accessToken;
1661
- this.accessToken = null;
1662
- this._activity?.resetSession();
1663
- this.sessionToken = null;
1664
- this.sessionEpoch++;
1401
+ let previous = this.accessToken;
1402
+ this.accessToken = null, this._activity?.resetSession(), this.sessionToken = null, this.sessionEpoch++;
1665
1403
  try {
1666
1404
  this.safeStorage()?.removeItem(SESSION_TOKEN_STORAGE_KEY);
1667
1405
  } catch {
1668
1406
  }
1669
- this.sessionToken = this.mintSessionToken();
1670
- if (this.sessionToken) {
1671
- this.broadcastSessionSync({ type: "cleared", token: this.sessionToken });
1672
- }
1673
- this.hooks.onSessionChange?.({
1407
+ this.sessionToken = this.mintSessionToken(), this.sessionToken && this.broadcastSessionSync({ type: "cleared", token: this.sessionToken }), this.hooks.onSessionChange?.({
1674
1408
  previousToken: previous,
1675
1409
  newToken: null,
1676
1410
  source: SESSION_CHANGE_SOURCE.CLEAR
1677
- });
1678
- this.events.emit(AUTH_TOKEN_CHANGED, { token: null });
1679
- this.events.emit(SESSION_CLEARED, {});
1411
+ }), this.events.emit(AUTH_TOKEN_CHANGED, { token: null }), this.events.emit(SESSION_CLEARED, {});
1680
1412
  }
1681
1413
  getSessionEpoch() {
1682
1414
  return this.sessionEpoch;
@@ -1695,25 +1427,23 @@ var CimplifyClient = class {
1695
1427
  hasClaimedSessionAuthority() {
1696
1428
  if (!this.sessionToken) return false;
1697
1429
  try {
1698
- const payload = parseSessionSyncPayload(
1430
+ let payload = parseSessionSyncPayload(
1699
1431
  this.safeStorage()?.getItem(SESSION_SYNC_STORAGE_KEY) ?? null
1700
1432
  );
1701
- if (!payload) return false;
1702
- return payload.type === "claimed" && payload.token === this.sessionToken;
1433
+ return payload ? payload.type === "claimed" && payload.token === this.sessionToken : !1;
1703
1434
  } catch {
1704
1435
  return false;
1705
1436
  }
1706
1437
  }
1707
1438
  publishSessionClaimed(customerName) {
1708
- if (!this.sessionToken) return;
1709
- this.broadcastSessionSync({
1439
+ this.sessionToken && this.broadcastSessionSync({
1710
1440
  type: "claimed",
1711
1441
  token: this.sessionToken,
1712
1442
  name: customerName
1713
1443
  });
1714
1444
  }
1715
1445
  broadcastSessionSync(payload) {
1716
- const envelope = {
1446
+ let envelope = {
1717
1447
  ...payload,
1718
1448
  at: this.nextSessionSyncTimestamp()
1719
1449
  };
@@ -1724,158 +1454,103 @@ var CimplifyClient = class {
1724
1454
  publishLocalSessionSync(envelope);
1725
1455
  }
1726
1456
  applyCrossTabSession(payload) {
1727
- if (!this.observeSessionSync(payload)) return;
1728
- if (payload.token === this.sessionToken) return;
1729
- if (payload.type === "claimed") {
1730
- this.sessionToken = payload.token;
1731
- this.sessionEpoch++;
1732
- this.events.emit(SESSION_CLAIMED, {
1733
- sessionToken: payload.token,
1734
- customerName: payload.name ?? "",
1735
- customer: null,
1736
- cart: null
1737
- });
1738
- } else {
1739
- this.accessToken = null;
1740
- this._activity?.resetSession();
1741
- this.sessionToken = payload.token;
1742
- this.sessionEpoch++;
1743
- this.events.emit(AUTH_TOKEN_CHANGED, { token: null });
1744
- this.events.emit(SESSION_CLEARED, {});
1745
- }
1457
+ this.observeSessionSync(payload) && payload.token !== this.sessionToken && (payload.type === "claimed" ? (this.sessionToken = payload.token, this.sessionEpoch++, this.events.emit(SESSION_CLAIMED, {
1458
+ sessionToken: payload.token,
1459
+ customerName: payload.name ?? "",
1460
+ customer: null,
1461
+ cart: null
1462
+ })) : (this.accessToken = null, this._activity?.resetSession(), this.sessionToken = payload.token, this.sessionEpoch++, this.events.emit(AUTH_TOKEN_CHANGED, { token: null }), this.events.emit(SESSION_CLEARED, {})));
1746
1463
  }
1747
1464
  observeSessionSync(payload) {
1748
1465
  if (payload.at < this.latestSessionSyncAt) return false;
1749
- const envelope = sessionSyncEnvelopeKey(payload);
1750
- if (payload.at === this.latestSessionSyncAt && this.latestSessionSyncOrderKey !== null && envelope <= this.latestSessionSyncOrderKey) {
1751
- return false;
1752
- }
1753
- this.latestSessionSyncAt = payload.at;
1754
- this.latestSessionSyncOrderKey = envelope;
1755
- return true;
1466
+ let envelope = sessionSyncEnvelopeKey(payload);
1467
+ return payload.at === this.latestSessionSyncAt && this.latestSessionSyncOrderKey !== null && envelope <= this.latestSessionSyncOrderKey ? false : (this.latestSessionSyncAt = payload.at, this.latestSessionSyncOrderKey = envelope, true);
1756
1468
  }
1757
1469
  nextSessionSyncTimestamp() {
1758
- const now = Date.now();
1470
+ let now = Date.now();
1759
1471
  return Number.isFinite(this.latestSessionSyncAt) ? Math.max(now, this.latestSessionSyncAt + 1) : now;
1760
1472
  }
1761
1473
  setOrderToken(orderId, token) {
1762
1474
  try {
1763
- const entry = JSON.stringify({ token, storedAt: Date.now() });
1475
+ let entry = JSON.stringify({ token, storedAt: Date.now() });
1764
1476
  this.safeStorage()?.setItem(`${ORDER_TOKEN_PREFIX}${orderId}`, entry);
1765
1477
  } catch {
1766
1478
  }
1767
1479
  }
1768
1480
  getOrderToken(orderId) {
1769
1481
  try {
1770
- const storage = this.safeStorage();
1482
+ let storage = this.safeStorage();
1771
1483
  if (!storage) return null;
1772
- const raw = storage.getItem(`${ORDER_TOKEN_PREFIX}${orderId}`);
1484
+ let raw = storage.getItem(`${ORDER_TOKEN_PREFIX}${orderId}`);
1773
1485
  if (!raw) return null;
1774
- const entry = JSON.parse(raw);
1775
- if (Date.now() - entry.storedAt > ORDER_TOKEN_TTL_MS) {
1776
- storage.removeItem(`${ORDER_TOKEN_PREFIX}${orderId}`);
1777
- return null;
1778
- }
1779
- return entry.token;
1486
+ let entry = JSON.parse(raw);
1487
+ return Date.now() - entry.storedAt > ORDER_TOKEN_TTL_MS ? (storage.removeItem(`${ORDER_TOKEN_PREFIX}${orderId}`), null) : entry.token;
1780
1488
  } catch {
1781
1489
  return null;
1782
1490
  }
1783
1491
  }
1784
1492
  clearOrderTokens() {
1785
1493
  try {
1786
- const storage = this.safeStorage();
1494
+ let storage = this.safeStorage();
1787
1495
  if (!storage) return;
1788
- const keysToRemove = [];
1496
+ let keysToRemove = [];
1789
1497
  for (let i = 0; i < storage.length; i++) {
1790
- const key = storage.key(i);
1791
- if (key?.startsWith(ORDER_TOKEN_PREFIX)) {
1792
- keysToRemove.push(key);
1793
- }
1498
+ let key = storage.key(i);
1499
+ key?.startsWith(ORDER_TOKEN_PREFIX) && keysToRemove.push(key);
1794
1500
  }
1795
1501
  keysToRemove.forEach((k) => storage.removeItem(k));
1796
1502
  } catch {
1797
1503
  }
1798
1504
  }
1799
1505
  setLocationId(locationId) {
1800
- if (locationId) {
1801
- this.context.location_id = locationId;
1802
- } else {
1803
- delete this.context.location_id;
1804
- }
1506
+ locationId ? this.context.location_id = locationId : delete this.context.location_id;
1805
1507
  }
1806
1508
  getLocationId() {
1807
1509
  return this.context.location_id ?? null;
1808
1510
  }
1809
1511
  setBusinessId(businessId) {
1810
- const normalized = businessId.trim();
1811
- if (!normalized) {
1812
- return;
1813
- }
1814
- this.businessId = normalized;
1512
+ let normalized = businessId.trim();
1513
+ normalized && (this.businessId = normalized);
1815
1514
  }
1816
1515
  // Set the storefront public key after construction. Needed by hosts that
1817
1516
  // create the client before they know the key (e.g. the Link element, which
1818
1517
  // receives it in its INIT message) — without it, storefront calls carry no
1819
1518
  // X-API-Key and the business can't be resolved.
1820
1519
  setPublicKey(publicKey) {
1821
- const normalized = publicKey.trim();
1520
+ let normalized = publicKey.trim();
1822
1521
  if (normalized === this.publicKey) return;
1823
- const restartPageViewTracking = this.stopPageViewTracking !== null;
1824
- if (restartPageViewTracking) {
1825
- this.stopTrackingPageViews();
1826
- }
1827
- this.publicKey = normalized;
1828
- this.publicKeyEpoch += 1;
1829
- this.businessId = null;
1830
- this.businessIdResolvePromise = null;
1831
- this.inflightRequests.clear();
1832
- this._activity?.resetForStorefrontIdentityChange();
1833
- delete this.context.location_id;
1834
- if (this.accessToken !== null) {
1835
- this.setAccessToken(null);
1836
- }
1837
- this.events.emit(SESSION_CLEARED, {});
1838
- if (restartPageViewTracking) {
1839
- this.stopPageViewTracking = this.activity.autoTrackPageViews();
1840
- }
1522
+ let restartPageViewTracking = this.stopPageViewTracking !== null;
1523
+ restartPageViewTracking && this.stopTrackingPageViews(), this.publicKey = normalized, this.publicKeyEpoch += 1, this.businessId = null, this.businessIdResolvePromise = null, this.inflightRequests.clear(), this._activity?.resetForStorefrontIdentityChange(), delete this.context.location_id, this.accessToken !== null && this.setAccessToken(null), this.events.emit(SESSION_CLEARED, {}), restartPageViewTracking && (this.stopPageViewTracking = this.activity.autoTrackPageViews());
1841
1524
  }
1842
1525
  getBusinessId() {
1843
1526
  return this.businessId;
1844
1527
  }
1845
1528
  async resolveBusinessId() {
1846
- if (this.businessId) {
1529
+ if (this.businessId)
1847
1530
  return this.businessId;
1848
- }
1849
- if (this.businessIdResolvePromise) {
1531
+ if (this.businessIdResolvePromise)
1850
1532
  return this.businessIdResolvePromise;
1851
- }
1852
- const publicKeyEpoch = this.publicKeyEpoch;
1853
- const resolution = (async () => {
1854
- const result = await this.business.getInfo();
1855
- if (!result.ok || !result.value?.id) {
1533
+ let publicKeyEpoch = this.publicKeyEpoch, resolution = (async () => {
1534
+ let result = await this.business.getInfo();
1535
+ if (!result.ok || !result.value?.id)
1856
1536
  throw new CimplifyError(
1857
1537
  ErrorCode.NOT_FOUND,
1858
1538
  "Unable to resolve business ID from the current public key.",
1859
1539
  true
1860
1540
  );
1861
- }
1862
- if (this.publicKeyEpoch !== publicKeyEpoch) {
1541
+ if (this.publicKeyEpoch !== publicKeyEpoch)
1863
1542
  throw new CimplifyError(
1864
1543
  ErrorCode.TENANT_CONTEXT_CHANGED,
1865
1544
  "The storefront tenant changed while resolving its business identity.",
1866
1545
  true
1867
1546
  );
1868
- }
1869
- this.businessId = result.value.id;
1870
- return result.value.id;
1547
+ return this.businessId = result.value.id, result.value.id;
1871
1548
  })();
1872
1549
  this.businessIdResolvePromise = resolution;
1873
1550
  try {
1874
1551
  return await resolution;
1875
1552
  } finally {
1876
- if (this.businessIdResolvePromise === resolution) {
1877
- this.businessIdResolvePromise = null;
1878
- }
1553
+ this.businessIdResolvePromise === resolution && (this.businessIdResolvePromise = null);
1879
1554
  }
1880
1555
  }
1881
1556
  async authedFetch(url, options, timeoutMs, retryPolicy, signal) {
@@ -1887,9 +1562,8 @@ var CimplifyClient = class {
1887
1562
  // fall back to an in-memory session token instead.
1888
1563
  safeStorage() {
1889
1564
  try {
1890
- if (typeof window !== "undefined" && window.localStorage) {
1565
+ if (typeof window < "u" && window.localStorage)
1891
1566
  return window.localStorage;
1892
- }
1893
1567
  } catch {
1894
1568
  }
1895
1569
  return null;
@@ -1918,12 +1592,10 @@ var CimplifyClient = class {
1918
1592
  * every visitor to one session, so SSR keeps the lazy server-minted flow.
1919
1593
  */
1920
1594
  mintSessionToken() {
1921
- if (typeof window === "undefined") {
1595
+ if (typeof window > "u")
1922
1596
  return null;
1923
- }
1924
- const token = generateSessionToken();
1925
- this.saveSessionToken(token);
1926
- return token;
1597
+ let token = generateSessionToken();
1598
+ return this.saveSessionToken(token), token;
1927
1599
  }
1928
1600
  saveSessionToken(token) {
1929
1601
  try {
@@ -1932,43 +1604,23 @@ var CimplifyClient = class {
1932
1604
  }
1933
1605
  }
1934
1606
  captureSessionToken(response) {
1935
- if (typeof window === "undefined") return;
1936
- if (this.sessionToken) return;
1937
- const token = response.headers.get(SESSION_TOKEN_HEADER);
1938
- if (token) {
1939
- this.sessionToken = token;
1940
- this.saveSessionToken(token);
1941
- }
1607
+ if (typeof window > "u" || this.sessionToken) return;
1608
+ let token = response.headers.get(SESSION_TOKEN_HEADER);
1609
+ token && (this.sessionToken = token, this.saveSessionToken(token));
1942
1610
  }
1943
1611
  getHeaders() {
1944
- const headers = {
1612
+ let headers = {
1945
1613
  "Content-Type": "application/json"
1946
- };
1947
- const trimmedPublicKey = this.publicKey.trim();
1948
- if (trimmedPublicKey) {
1949
- headers["X-API-Key"] = trimmedPublicKey;
1950
- }
1951
- if (this.accessToken) {
1952
- headers["Authorization"] = `Bearer ${this.accessToken}`;
1953
- }
1954
- if (this.sessionToken) {
1955
- headers[SESSION_TOKEN_HEADER] = this.sessionToken;
1956
- }
1957
- if (typeof window !== "undefined") {
1614
+ }, trimmedPublicKey = this.publicKey.trim();
1615
+ if (trimmedPublicKey && (headers["X-API-Key"] = trimmedPublicKey), this.accessToken && (headers.Authorization = `Bearer ${this.accessToken}`), this.sessionToken && (headers[SESSION_TOKEN_HEADER] = this.sessionToken), typeof window < "u") {
1958
1616
  headers["X-Storefront-Host"] = window.location.host;
1959
- const preview = new URLSearchParams(window.location.search).get("preview");
1960
- if (preview) {
1961
- headers["X-Storefront-Preview"] = preview;
1962
- }
1617
+ let preview = new URLSearchParams(window.location.search).get("preview");
1618
+ preview && (headers["X-Storefront-Preview"] = preview);
1963
1619
  }
1964
1620
  return headers;
1965
1621
  }
1966
1622
  async resilientFetch(url, options, timeoutMs, retryPolicy, signal) {
1967
- const method = options.method || "GET";
1968
- const path = url.replace(this.baseUrl, "").replace(this.linkApiUrl, "");
1969
- const startTime = Date.now();
1970
- let retryCount = 0;
1971
- const context = {
1623
+ let method = options.method || "GET", path = url.replace(this.baseUrl, "").replace(this.linkApiUrl, ""), startTime = Date.now(), retryCount = 0, context = {
1972
1624
  method,
1973
1625
  path,
1974
1626
  url,
@@ -1976,22 +1628,16 @@ var CimplifyClient = class {
1976
1628
  startTime
1977
1629
  };
1978
1630
  this.hooks.onRequestStart?.(context);
1979
- let lastError;
1980
- const configuredMaxRetries = Math.max(0, Math.floor(this.maxRetries));
1981
- const maxRetries = Math.min(
1631
+ let lastError, configuredMaxRetries = Math.max(0, Math.floor(this.maxRetries)), maxRetries = Math.min(
1982
1632
  configuredMaxRetries,
1983
1633
  Math.max(0, Math.floor(retryPolicy?.maxRetries ?? configuredMaxRetries))
1984
- );
1985
- const jitterRatio = retryPolicy?.jitterRatio ?? 0;
1986
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1634
+ ), jitterRatio = retryPolicy?.jitterRatio ?? 0;
1635
+ for (let attempt = 0; attempt <= maxRetries; attempt++)
1987
1636
  try {
1988
- if (signal?.aborted) {
1989
- throw new CimplifyError(ErrorCode.CANCELLED, "Request was cancelled.", true);
1990
- }
1991
- const controller = new AbortController();
1992
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs ?? this.timeout);
1993
- const onAbort = () => controller.abort();
1994
- signal?.addEventListener("abort", onAbort, { once: true });
1637
+ if (signal?.aborted)
1638
+ throw new CimplifyError(ErrorCode.CANCELLED, "Request was cancelled.", !0);
1639
+ let controller = new AbortController(), timeoutId = setTimeout(() => controller.abort(), timeoutMs ?? this.timeout), onAbort = () => controller.abort();
1640
+ signal?.addEventListener("abort", onAbort, { once: !0 });
1995
1641
  let response;
1996
1642
  try {
1997
1643
  response = await this.fetchImpl(url, {
@@ -1999,114 +1645,93 @@ var CimplifyClient = class {
1999
1645
  signal: controller.signal
2000
1646
  });
2001
1647
  } finally {
2002
- clearTimeout(timeoutId);
2003
- signal?.removeEventListener("abort", onAbort);
1648
+ clearTimeout(timeoutId), signal?.removeEventListener("abort", onAbort);
2004
1649
  }
2005
- this.captureSessionToken(response);
2006
- if (response.ok) {
2007
- this.hooks.onRequestSuccess?.({
1650
+ if (this.captureSessionToken(response), response.ok)
1651
+ return this.hooks.onRequestSuccess?.({
2008
1652
  ...context,
2009
1653
  status: response.status,
2010
1654
  durationMs: Date.now() - startTime
2011
- });
2012
- return response;
2013
- }
2014
- if ((response.status === 429 || response.status === 503) && attempt < maxRetries) {
1655
+ }), response;
1656
+ if (response.status === (503) && attempt < maxRetries) {
2015
1657
  retryCount++;
2016
- const retryAfterMs = parseRetryAfterMs(response.headers.get("Retry-After"));
2017
- const retryBaseMs = retryAfterMs ?? this.retryDelay * Math.pow(2, attempt);
2018
- const jitteredDelayMs = withPositiveJitter(retryBaseMs, jitterRatio);
2019
- const delay = retryAfterMs === null ? jitteredDelayMs : Math.min(jitteredDelayMs, MAX_RETRY_AFTER_MS);
1658
+ let retryAfterMs = parseRetryAfterMs(response.headers.get(RETRY_AFTER_HEADER)), retryBaseMs = retryAfterMs ?? this.retryDelay * Math.pow(2, attempt), jitteredDelayMs = withPositiveJitter(retryBaseMs, jitterRatio), delay = retryAfterMs === null ? jitteredDelayMs : Math.min(jitteredDelayMs, (3e4));
2020
1659
  this.hooks.onRetry?.({
2021
1660
  ...context,
2022
1661
  attempt: retryCount,
2023
1662
  delayMs: delay,
2024
1663
  error: new Error(`Retryable: ${response.status}`)
2025
- });
2026
- await sleep(delay, signal);
1664
+ }), await sleep(delay, signal);
2027
1665
  continue;
2028
1666
  }
2029
- if (response.status >= 400 && response.status < 500) {
2030
- this.hooks.onRequestError?.({
1667
+ if (response.status >= 400 && response.status < 500)
1668
+ return this.hooks.onRequestError?.({
2031
1669
  ...context,
2032
1670
  error: new CimplifyError(
2033
1671
  `HTTP_${response.status}`,
2034
1672
  `Request failed with status ${response.status}`,
2035
- false
1673
+ !1
2036
1674
  ),
2037
1675
  status: response.status,
2038
1676
  durationMs: Date.now() - startTime,
2039
1677
  retryCount,
2040
- retryable: false
2041
- });
2042
- return response;
2043
- }
1678
+ retryable: !1
1679
+ }), response;
2044
1680
  if (response.status >= 500 && attempt < maxRetries) {
2045
1681
  retryCount++;
2046
- const delay = withPositiveJitter(this.retryDelay * Math.pow(2, attempt), jitterRatio);
1682
+ let delay = withPositiveJitter(this.retryDelay * Math.pow(2, attempt), jitterRatio);
2047
1683
  this.hooks.onRetry?.({
2048
1684
  ...context,
2049
1685
  attempt: retryCount,
2050
1686
  delayMs: delay,
2051
1687
  error: new Error(`Server error: ${response.status}`)
2052
- });
2053
- await sleep(delay, signal);
1688
+ }), await sleep(delay, signal);
2054
1689
  continue;
2055
1690
  }
2056
- this.hooks.onRequestError?.({
1691
+ return this.hooks.onRequestError?.({
2057
1692
  ...context,
2058
1693
  error: new CimplifyError(
2059
1694
  ErrorCode.SERVER_ERROR,
2060
1695
  `Server error ${response.status} after ${retryCount} retries`,
2061
- false
1696
+ !1
2062
1697
  ),
2063
1698
  status: response.status,
2064
1699
  durationMs: Date.now() - startTime,
2065
1700
  retryCount,
2066
- retryable: false
2067
- });
2068
- return response;
1701
+ retryable: !1
1702
+ }), response;
2069
1703
  } catch (error) {
2070
- lastError = error;
2071
- if (signal?.aborted) {
1704
+ if (lastError = error, signal?.aborted)
2072
1705
  throw new CimplifyError(ErrorCode.CANCELLED, "Request was cancelled.", true);
2073
- }
2074
- const networkError = toNetworkError(error, this.isTestMode());
2075
- const errorRetryable = isRetryable(error);
2076
- if (!errorRetryable || attempt >= maxRetries) {
2077
- this.hooks.onRequestError?.({
1706
+ let networkError = toNetworkError(error, this.isTestMode()), errorRetryable = isRetryable(error);
1707
+ if (!errorRetryable || attempt >= maxRetries)
1708
+ throw this.hooks.onRequestError?.({
2078
1709
  ...context,
2079
1710
  error: networkError,
2080
1711
  durationMs: Date.now() - startTime,
2081
1712
  retryCount,
2082
1713
  retryable: errorRetryable
2083
- });
2084
- throw networkError;
2085
- }
1714
+ }), networkError;
2086
1715
  retryCount++;
2087
- const delay = withPositiveJitter(this.retryDelay * Math.pow(2, attempt), jitterRatio);
1716
+ let delay = withPositiveJitter(this.retryDelay * Math.pow(2, attempt), jitterRatio);
2088
1717
  this.hooks.onRetry?.({
2089
1718
  ...context,
2090
1719
  attempt: retryCount,
2091
1720
  delayMs: delay,
2092
1721
  error: networkError
2093
- });
2094
- await sleep(delay, signal);
1722
+ }), await sleep(delay, signal);
2095
1723
  }
2096
- }
2097
- const finalError = toNetworkError(lastError, this.isTestMode());
2098
- this.hooks.onRequestError?.({
1724
+ let finalError = toNetworkError(lastError, this.isTestMode());
1725
+ throw this.hooks.onRequestError?.({
2099
1726
  ...context,
2100
1727
  error: finalError,
2101
1728
  durationMs: Date.now() - startTime,
2102
1729
  retryCount,
2103
1730
  retryable: false
2104
- });
2105
- throw finalError;
1731
+ }), finalError;
2106
1732
  }
2107
1733
  getDedupeKey(type, payload, cacheOptions) {
2108
- const cacheKey = cacheOptions ? `|${JSON.stringify(cacheOptions)}` : "";
2109
- const identityKey = JSON.stringify([
1734
+ let cacheKey = cacheOptions ? `|${JSON.stringify(cacheOptions)}` : "", identityKey = JSON.stringify([
2110
1735
  this.publicKey.trim(),
2111
1736
  this.publicKeyEpoch,
2112
1737
  this.sessionEpoch,
@@ -2115,21 +1740,17 @@ var CimplifyClient = class {
2115
1740
  return `${type}:${identityKey}:${JSON.stringify(payload)}${cacheKey}`;
2116
1741
  }
2117
1742
  async deduplicatedRequest(key, requestFn) {
2118
- const existing = this.inflightRequests.get(key);
2119
- if (existing) {
1743
+ let existing = this.inflightRequests.get(key);
1744
+ if (existing)
2120
1745
  return existing;
2121
- }
2122
- const request = requestFn().finally(() => {
2123
- if (this.inflightRequests.get(key) === request) {
2124
- this.inflightRequests.delete(key);
2125
- }
1746
+ let request = requestFn().finally(() => {
1747
+ this.inflightRequests.get(key) === request && this.inflightRequests.delete(key);
2126
1748
  });
2127
- this.inflightRequests.set(key, request);
2128
- return request;
1749
+ return this.inflightRequests.set(key, request), request;
2129
1750
  }
2130
1751
  async get(path, opts) {
2131
- const request = async () => {
2132
- const response = await this.authedFetch(
1752
+ let request = async () => {
1753
+ let response = await this.authedFetch(
2133
1754
  this.buildUrl(this.baseUrl, path),
2134
1755
  {
2135
1756
  method: "GET",
@@ -2144,11 +1765,11 @@ var CimplifyClient = class {
2144
1765
  return this.handleRestResponse(response);
2145
1766
  };
2146
1767
  if (opts?.signal) return request();
2147
- const key = this.getDedupeKey("get", path, opts?.cacheOptions);
1768
+ let key = this.getDedupeKey("get", path, opts?.cacheOptions);
2148
1769
  return this.deduplicatedRequest(key, request);
2149
1770
  }
2150
1771
  async post(path, body, opts) {
2151
- const response = await this.authedFetch(
1772
+ let response = await this.authedFetch(
2152
1773
  this.buildUrl(this.baseUrl, path),
2153
1774
  {
2154
1775
  method: "POST",
@@ -2163,7 +1784,7 @@ var CimplifyClient = class {
2163
1784
  return this.handleRestResponse(response);
2164
1785
  }
2165
1786
  async patch(path, body, opts) {
2166
- const response = await this.authedFetch(
1787
+ let response = await this.authedFetch(
2167
1788
  this.buildUrl(this.baseUrl, path),
2168
1789
  {
2169
1790
  method: "PATCH",
@@ -2178,7 +1799,7 @@ var CimplifyClient = class {
2178
1799
  return this.handleRestResponse(response);
2179
1800
  }
2180
1801
  async delete(path, opts) {
2181
- const response = await this.authedFetch(
1802
+ let response = await this.authedFetch(
2182
1803
  this.buildUrl(this.baseUrl, path),
2183
1804
  {
2184
1805
  method: "DELETE",
@@ -2192,8 +1813,8 @@ var CimplifyClient = class {
2192
1813
  return this.handleRestResponse(response);
2193
1814
  }
2194
1815
  async linkGet(path, opts) {
2195
- const request = async () => {
2196
- const response = await this.authedFetch(
1816
+ let request = async () => {
1817
+ let response = await this.authedFetch(
2197
1818
  `${this.linkApiUrl}${path}`,
2198
1819
  {
2199
1820
  method: "GET",
@@ -2208,11 +1829,11 @@ var CimplifyClient = class {
2208
1829
  return this.handleRestResponse(response);
2209
1830
  };
2210
1831
  if (opts?.signal) return request();
2211
- const key = this.getDedupeKey("linkGet", path, opts?.cacheOptions);
1832
+ let key = this.getDedupeKey("linkGet", path, opts?.cacheOptions);
2212
1833
  return this.deduplicatedRequest(key, request);
2213
1834
  }
2214
1835
  async linkPost(path, body, opts) {
2215
- const response = await this.authedFetch(
1836
+ let response = await this.authedFetch(
2216
1837
  `${this.linkApiUrl}${path}`,
2217
1838
  {
2218
1839
  method: "POST",
@@ -2227,7 +1848,7 @@ var CimplifyClient = class {
2227
1848
  return this.handleRestResponse(response);
2228
1849
  }
2229
1850
  async linkDelete(path, opts) {
2230
- const response = await this.authedFetch(
1851
+ let response = await this.authedFetch(
2231
1852
  `${this.linkApiUrl}${path}`,
2232
1853
  {
2233
1854
  method: "DELETE",
@@ -2241,27 +1862,38 @@ var CimplifyClient = class {
2241
1862
  return this.handleRestResponse(response);
2242
1863
  }
2243
1864
  async handleRestResponse(response) {
2244
- const json = await response.json();
1865
+ let serverFailure = response.status >= (500), json;
1866
+ try {
1867
+ json = await response.json();
1868
+ } catch {
1869
+ throw enrichError(
1870
+ new CimplifyError(
1871
+ serverFailure ? ErrorCode.SERVER_ERROR : ErrorCode.API_ERROR,
1872
+ serverFailure ? "The service is temporarily unavailable." : "The service returned an unreadable response.",
1873
+ serverFailure
1874
+ ),
1875
+ { isTestMode: this.isTestMode() }
1876
+ );
1877
+ }
2245
1878
  if (!response.ok) {
2246
- const errorCode = typeof json.error === "object" && json.error?.error_code || typeof json.error === "object" && json.error?.code || ErrorCode.API_ERROR;
2247
- const errorMessage = typeof json.error === "object" && json.error?.error_message || typeof json.error === "object" && json.error?.message || typeof json.error === "string" && json.error || typeof json.message === "string" && json.message || "An error occurred";
2248
- const retryable = typeof json.error === "object" && typeof json.error?.retryable === "boolean" ? json.error.retryable : false;
1879
+ let errorCode = typeof json.error == "object" && json.error?.error_code || typeof json.error == "object" && json.error?.code || ErrorCode.API_ERROR, errorMessage = typeof json.error == "object" && json.error?.error_message || typeof json.error == "object" && json.error?.message || typeof json.error == "string" && json.error || typeof json.message == "string" && json.message || "An error occurred", retryable = typeof json.error == "object" && typeof json.error?.retryable == "boolean" ? json.error.retryable : serverFailure;
2249
1880
  if (errorCode === ErrorCode.IDEMPOTENCY_MISMATCH) {
2250
- const originalCreatedAt = typeof json.error === "object" && json.error?.original_created_at || "";
1881
+ let originalCreatedAt = typeof json.error == "object" && json.error?.original_created_at || "";
2251
1882
  throw new IdempotencyMismatchError(errorMessage, originalCreatedAt);
2252
1883
  }
2253
- const error = enrichError(new CimplifyError(errorCode, errorMessage, retryable), {
1884
+ let error = enrichError(new CimplifyError(errorCode, errorMessage, retryable), {
2254
1885
  isTestMode: this.isTestMode()
2255
1886
  });
2256
- if ((response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) && this.accessToken) {
2257
- console.warn(
2258
- "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
2259
- );
1887
+ if (response.status === (429)) {
1888
+ let retryAfterMs = retryAfterDelayMs(response.headers.get(RETRY_AFTER_HEADER));
1889
+ retryAfterMs !== null && (error.retryAfterMs = retryAfterMs);
2260
1890
  }
2261
- throw error;
1891
+ throw (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) && this.accessToken && console.warn(
1892
+ "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
1893
+ ), error;
2262
1894
  }
2263
- if (json?.success === false || json?.error?.code || json?.error?.message) {
2264
- const error = enrichError(
1895
+ if (json?.success === false || json?.error?.code || json?.error?.message)
1896
+ throw enrichError(
2265
1897
  new CimplifyError(
2266
1898
  json.error?.code || ErrorCode.API_ERROR,
2267
1899
  json.error?.message || "An error occurred",
@@ -2269,151 +1901,80 @@ var CimplifyClient = class {
2269
1901
  ),
2270
1902
  { isTestMode: this.isTestMode() }
2271
1903
  );
2272
- throw error;
2273
- }
2274
- if (json?.data !== void 0) {
2275
- return json.data;
2276
- }
2277
- return json;
1904
+ return json?.data !== void 0 ? json.data : json;
2278
1905
  }
2279
1906
  get catalogue() {
2280
- if (!this._catalogue) {
2281
- this._catalogue = new CatalogueQueries(this);
2282
- }
2283
- return this._catalogue;
1907
+ return this._catalogue || (this._catalogue = new CatalogueQueries(this)), this._catalogue;
2284
1908
  }
2285
1909
  get cart() {
2286
- if (!this._cart) {
2287
- this._cart = new CartOperations(this);
2288
- }
2289
- return this._cart;
1910
+ return this._cart || (this._cart = new CartOperations(this)), this._cart;
2290
1911
  }
2291
1912
  get checkout() {
2292
- if (!this._checkout) {
2293
- this._checkout = new CheckoutService(this);
2294
- }
2295
- return this._checkout;
1913
+ return this._checkout || (this._checkout = new CheckoutService(this)), this._checkout;
2296
1914
  }
2297
1915
  get purchaseIntents() {
2298
- if (!this._purchaseIntents) {
2299
- this._purchaseIntents = new PurchaseIntentService(this);
2300
- }
2301
- return this._purchaseIntents;
1916
+ return this._purchaseIntents || (this._purchaseIntents = new PurchaseIntentService(this)), this._purchaseIntents;
2302
1917
  }
2303
1918
  get orders() {
2304
- if (!this._orders) {
2305
- this._orders = new OrderQueries(this);
2306
- }
2307
- return this._orders;
1919
+ return this._orders || (this._orders = new OrderQueries(this)), this._orders;
2308
1920
  }
2309
1921
  get storeCredit() {
2310
- if (!this._storeCredit) {
2311
- this._storeCredit = new StoreCreditQueries(this);
2312
- }
2313
- return this._storeCredit;
1922
+ return this._storeCredit || (this._storeCredit = new StoreCreditQueries(this)), this._storeCredit;
2314
1923
  }
2315
1924
  get subscriptions() {
2316
- if (!this._subscriptions) {
2317
- this._subscriptions = new SubscriptionService(this);
2318
- }
2319
- return this._subscriptions;
1925
+ return this._subscriptions || (this._subscriptions = new SubscriptionService(this)), this._subscriptions;
2320
1926
  }
2321
1927
  get uploads() {
2322
- if (!this._uploads) {
2323
- this._uploads = new UploadService(this);
2324
- }
2325
- return this._uploads;
1928
+ return this._uploads || (this._uploads = new UploadService(this)), this._uploads;
2326
1929
  }
2327
1930
  get places() {
2328
- if (!this._places) {
2329
- this._places = new PlacesService(this);
2330
- }
2331
- return this._places;
1931
+ return this._places || (this._places = new PlacesService(this)), this._places;
2332
1932
  }
2333
1933
  get link() {
2334
- if (!this._link) {
2335
- this._link = new LinkService(this);
2336
- }
2337
- return this._link;
1934
+ return this._link || (this._link = new LinkService(this)), this._link;
2338
1935
  }
2339
1936
  get auth() {
2340
- if (!this._auth) {
2341
- this._auth = new AuthService(this);
2342
- }
2343
- return this._auth;
1937
+ return this._auth || (this._auth = new AuthService(this)), this._auth;
2344
1938
  }
2345
1939
  get business() {
2346
- if (!this._business) {
2347
- this._business = new BusinessService(this);
2348
- }
2349
- return this._business;
1940
+ return this._business || (this._business = new BusinessService(this)), this._business;
2350
1941
  }
2351
1942
  get inventory() {
2352
- if (!this._inventory) {
2353
- this._inventory = new InventoryService(this);
2354
- }
2355
- return this._inventory;
1943
+ return this._inventory || (this._inventory = new InventoryService(this)), this._inventory;
2356
1944
  }
2357
1945
  get scheduling() {
2358
- if (!this._scheduling) {
2359
- this._scheduling = new SchedulingService(this);
2360
- }
2361
- return this._scheduling;
1946
+ return this._scheduling || (this._scheduling = new SchedulingService(this)), this._scheduling;
2362
1947
  }
2363
1948
  get lite() {
2364
- if (!this._lite) {
2365
- this._lite = new LiteService(this);
2366
- }
2367
- return this._lite;
1949
+ return this._lite || (this._lite = new LiteService(this)), this._lite;
2368
1950
  }
2369
1951
  get fx() {
2370
- if (!this._fx) {
2371
- this._fx = new FxService(this);
2372
- }
2373
- return this._fx;
1952
+ return this._fx || (this._fx = new FxService(this)), this._fx;
2374
1953
  }
2375
1954
  get activity() {
2376
- if (!this._activity) {
2377
- this._activity = new ActivityService(this);
2378
- }
2379
- return this._activity;
1955
+ return this._activity || (this._activity = new ActivityService(this)), this._activity;
2380
1956
  }
2381
1957
  get delivery() {
2382
- if (!this._delivery) {
2383
- this._delivery = new DeliveryService(this);
2384
- }
2385
- return this._delivery;
1958
+ return this._delivery || (this._delivery = new DeliveryService(this)), this._delivery;
2386
1959
  }
2387
1960
  get support() {
2388
- if (!this._support) {
2389
- this._support = new SupportService(this);
2390
- }
2391
- return this._support;
1961
+ return this._support || (this._support = new SupportService(this)), this._support;
2392
1962
  }
2393
1963
  get session() {
2394
- if (!this._session) {
2395
- this._session = new SessionService(this);
2396
- }
2397
- return this._session;
1964
+ return this._session || (this._session = new SessionService(this)), this._session;
2398
1965
  }
2399
1966
  buildWsUrl(path) {
2400
- const protocol = this.baseUrl.startsWith("https") ? "wss:" : "ws:";
2401
- const host = this.baseUrl.replace(/^https?:\/\//, "");
2402
- const params = new URLSearchParams();
2403
- if (this.publicKey) params.set("api_key", this.publicKey);
2404
- if (this.sessionToken) params.set("session_token", this.sessionToken);
2405
- const query = params.toString();
1967
+ let protocol = this.baseUrl.startsWith("https") ? "wss:" : "ws:", host = this.baseUrl.replace(/^https?:\/\//, ""), params = new URLSearchParams();
1968
+ this.publicKey && params.set("api_key", this.publicKey), this.sessionToken && params.set("session_token", this.sessionToken);
1969
+ let query = params.toString();
2406
1970
  return `${protocol}//${host}${path}${query ? `?${query}` : ""}`;
2407
1971
  }
2408
1972
  elements(businessId, options) {
2409
- if (businessId) {
2410
- this.setBusinessId(businessId);
2411
- }
2412
- return createElements(this, businessId ?? this.businessId ?? void 0, options);
1973
+ return businessId && this.setBusinessId(businessId), createElements(this, businessId ?? this.businessId ?? void 0, options);
2413
1974
  }
2414
1975
  };
2415
1976
  function createCimplifyClient(config = {}) {
2416
1977
  return new CimplifyClient(config);
2417
1978
  }
2418
1979
 
2419
- export { ActivityService, CimplifyClient, DeliveryService, HostedPurchaseIntentService, PURCHASE_INTENT_ROUTE, PlacesService, PurchaseIntentResolver, PurchaseIntentService, SESSION_CHANGE_SOURCE, SessionService, StoreCreditQueries, SubscriptionService, SupportService, UploadService, chatRealtimeUpdateFromWire, createCimplifyClient };
1980
+ export { ActivityService, CONTENT_SHA256_HEADER, CimplifyClient, DeliveryService, HostedPurchaseIntentService, PURCHASE_INTENT_ROUTE, PlacesService, PurchaseIntentResolver, PurchaseIntentService, SESSION_CHANGE_SOURCE, SessionService, StoreCreditQueries, SubscriptionService, SupportService, UploadService, chatRealtimeUpdateFromWire, contentSha256, createCimplifyClient, isTransientPurchaseIntentError };