@everfur/sdk 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/README.md +2 -1
  3. package/dist/{Chat-BOG0SXKV.d.cts → Chat.d-DUNTfzqC.d.ts} +170 -8
  4. package/dist/{Chat-CIolBgjJ.d.ts → Chat.d-Dts8u_1a.d.cts} +170 -8
  5. package/dist/{DepthViews-BR6VQ3Ta.d.cts → DepthViews.d-BIp599lz.d.cts} +1 -1
  6. package/dist/{DepthViews-280t3BcQ.d.ts → DepthViews.d-BMU2jFPw.d.cts} +1 -1
  7. package/dist/{DepthViews-DlBuFsgN.d.ts → DepthViews.d-Ce2Zhnrb.d.ts} +1 -1
  8. package/dist/{DepthViews-BTbF_DJY.d.cts → DepthViews.d-CubkMPbU.d.ts} +1 -1
  9. package/dist/{ErrorPolicyPort-10s3HJCt.d.cts → ErrorPolicyPort.d-68yrE3BE.d.ts} +1 -1
  10. package/dist/{ErrorPolicyPort-C3nNSS_j.d.ts → ErrorPolicyPort.d-DirW9hgO.d.cts} +1 -1
  11. package/dist/{EverfurError-DeBqRpQV.d.cts → EverfurError.d-8NHtlgzA.d.cts} +11 -1
  12. package/dist/{EverfurError-DeBqRpQV.d.ts → EverfurError.d-8NHtlgzA.d.ts} +11 -1
  13. package/dist/{EverfurResult-ClPTS0P2.d.ts → EverfurResult.d-BFH-3s6E.d.cts} +1 -1
  14. package/dist/{EverfurResult-COlXj1wq.d.cts → EverfurResult.d-D_-254ZY.d.ts} +1 -1
  15. package/dist/{IntakeMedia-BH0fYDT2.d.cts → IntakeMedia.d-4a89XrP7.d.ts} +1 -1
  16. package/dist/{IntakeMedia-B-_vA9ZB.d.cts → IntakeMedia.d-DGxrhgIW.d.ts} +1 -1
  17. package/dist/{IntakeMedia-CIoTXAWs.d.ts → IntakeMedia.d-DUPR4lVM.d.cts} +1 -1
  18. package/dist/{IntakeMedia-Bavl7E4Z.d.ts → IntakeMedia.d-JJCUvQu7.d.cts} +1 -1
  19. package/dist/LifecyclePort.d-Cr1p33a7.d.cts +23 -0
  20. package/dist/LifecyclePort.d-Cr1p33a7.d.ts +23 -0
  21. package/dist/{PhotoController-vzY5bfY_.d.ts → PhotoController.d-BzCJOE7e.d.cts} +2 -2
  22. package/dist/{PhotoController-3l7MT9jA.d.cts → PhotoController.d-D0XiUUOl.d.ts} +2 -2
  23. package/dist/animations/index.cjs +5 -1
  24. package/dist/animations/index.d.cts +24 -24
  25. package/dist/animations/index.d.ts +24 -24
  26. package/dist/animations/index.js +5 -1
  27. package/dist/{attachments-CGxvnYu4.d.ts → attachments.d-Bp2qbHxn.d.cts} +22 -26
  28. package/dist/{attachments-CWNj1ZkM.d.ts → attachments.d-D1yhJjcZ.d.ts} +4 -4
  29. package/dist/{attachments-waXcJWCp.d.cts → attachments.d-DisnvB9R.d.cts} +4 -4
  30. package/dist/{attachments-B6h4cJU-.d.cts → attachments.d-Djy9z_0Z.d.ts} +22 -26
  31. package/dist/{bookingCopy-CjPKeg75.d.ts → bookingCopy.d-BJF6gd1A.d.ts} +24 -9
  32. package/dist/{bookingCopy-8aEU6ZmR.d.cts → bookingCopy.d-BlBmhAJc.d.cts} +24 -9
  33. package/dist/{branding-DJf4h12Q.d.ts → branding.d-DI8S400y.d.cts} +9 -2
  34. package/dist/{branding-BCfwLj0h.d.cts → branding.d-OIGLbQeM.d.ts} +9 -2
  35. package/dist/{callRoom-BhIdadyV.d.cts → callRoom.d-B1DoYdJe.d.cts} +1 -1
  36. package/dist/{callRoom-B92eH_ij.d.ts → callRoom.d-Dqm1rUqT.d.ts} +1 -1
  37. package/dist/{casesRepository-CGdhvzTu.d.cts → casesRepository.d-CT2LTicS.d.cts} +3 -3
  38. package/dist/{casesRepository-ZG9Sg0e4.d.ts → casesRepository.d-UsWOz9bv.d.ts} +3 -3
  39. package/dist/chat/index.cjs +132 -57
  40. package/dist/chat/index.d.cts +18 -16
  41. package/dist/chat/index.d.ts +18 -16
  42. package/dist/chat/index.js +133 -58
  43. package/dist/client/index.cjs +15 -10
  44. package/dist/client/index.d.cts +19 -18
  45. package/dist/client/index.d.ts +19 -18
  46. package/dist/client/index.js +15 -10
  47. package/dist/{config-B0p6Lygh.d.cts → config.d-BR3DT9ho.d.cts} +3 -3
  48. package/dist/{config-DmFAZJOx.d.ts → config.d-Dy6igYlH.d.ts} +3 -3
  49. package/dist/consent/index.cjs +5 -1
  50. package/dist/consent/index.d.cts +10 -10
  51. package/dist/consent/index.d.ts +10 -10
  52. package/dist/consent/index.js +5 -1
  53. package/dist/{context-BNreNLtL.d.ts → context.d-Cwks0p3C.d.cts} +15 -15
  54. package/dist/{context-BgS2a57J.d.cts → context.d-QcCgguzA.d.ts} +15 -15
  55. package/dist/{copy-DLJriGQS.d.ts → copy.d-CiMn2IIt.d.ts} +6 -6
  56. package/dist/{copy-lWp-Lkv5.d.cts → copy.d-DLJTyRfT.d.cts} +6 -6
  57. package/dist/core/index.cjs +17 -13
  58. package/dist/core/index.d.cts +33 -29
  59. package/dist/core/index.d.ts +33 -29
  60. package/dist/core/index.js +17 -13
  61. package/dist/{depth-BYb3RXoA.d.cts → depth.d-CjPGVPDL.d.cts} +9 -115
  62. package/dist/{depth-COz-sSG5.d.ts → depth.d-OSALbYM7.d.ts} +9 -115
  63. package/dist/{entitlementRepository-D-Lse67w.d.cts → entitlementRepository.d-CVQa1DA1.d.cts} +10 -5
  64. package/dist/{entitlementRepository-CrTOP_-o.d.ts → entitlementRepository.d-Cf3LbTwD.d.ts} +10 -5
  65. package/dist/features.d-fNsGcg0R.d.cts +108 -0
  66. package/dist/features.d-fNsGcg0R.d.ts +108 -0
  67. package/dist/focus.d-DMg2ngHI.d.ts +1178 -0
  68. package/dist/focus.d-az9cqUz3.d.cts +1178 -0
  69. package/dist/health-plan/index.cjs +370 -0
  70. package/dist/health-plan/index.d.cts +251 -0
  71. package/dist/health-plan/index.d.ts +251 -0
  72. package/dist/health-plan/index.js +370 -0
  73. package/dist/idempotency.d-D461_DPD.d.cts +910 -0
  74. package/dist/idempotency.d-WpXx9zQo.d.ts +910 -0
  75. package/dist/{identity-Cw07BKZp.d.ts → identity.d-60LeJt_s.d.cts} +3 -3
  76. package/dist/{identity-DFVGYn1o.d.cts → identity.d-DzTijonw.d.ts} +3 -3
  77. package/dist/index.cjs +141 -66
  78. package/dist/index.d.cts +31 -29
  79. package/dist/index.d.ts +31 -29
  80. package/dist/index.js +142 -67
  81. package/dist/{models-A4A5S7AG.d.cts → models.d-BagXhafD.d.ts} +8 -3
  82. package/dist/{models-CnXY5LuO.d.ts → models.d-BnLm3VAA.d.cts} +8 -3
  83. package/dist/notifications/index.cjs +5 -1
  84. package/dist/notifications/index.d.cts +9 -9
  85. package/dist/notifications/index.d.ts +9 -9
  86. package/dist/notifications/index.js +5 -1
  87. package/dist/optInView.d-CEyHR6PK.d.cts +325 -0
  88. package/dist/optInView.d-acKpV8V2.d.ts +325 -0
  89. package/dist/parse.d-C8CXyS58.d.ts +210 -0
  90. package/dist/parse.d-tEzufgJX.d.cts +210 -0
  91. package/dist/{pets-BYALZTSu.d.ts → pets.d-C_53_fzo.d.ts} +3 -3
  92. package/dist/{pets-CcyPQS-H.d.cts → pets.d-NbJvP_kh.d.cts} +3 -3
  93. package/dist/{petsRepository-B_Q1gFkE.d.cts → petsRepository.d-BuGHymNx.d.ts} +4 -4
  94. package/dist/{petsRepository-518QkPxH.d.ts → petsRepository.d-lp1BHRqM.d.cts} +4 -4
  95. package/dist/photo/index.cjs +6 -2
  96. package/dist/photo/index.d.cts +9 -9
  97. package/dist/photo/index.d.ts +9 -9
  98. package/dist/photo/index.js +6 -2
  99. package/dist/{ports-BN6RHF9W.d.ts → ports.d-BX4f4UsB.d.cts} +14 -1
  100. package/dist/{ports-BN6RHF9W.d.cts → ports.d-BX4f4UsB.d.ts} +14 -1
  101. package/dist/{ports-RuNJmBA-.d.cts → ports.d-CEROoqnA.d.cts} +16 -10
  102. package/dist/{ports-DmQeMArX.d.ts → ports.d-COIyN624.d.ts} +16 -10
  103. package/dist/presentation.d-DMbdad7G.d.cts +90 -0
  104. package/dist/presentation.d-DMbdad7G.d.ts +90 -0
  105. package/dist/records/depth/index.cjs +11 -7
  106. package/dist/records/depth/index.d.cts +14 -12
  107. package/dist/records/depth/index.d.ts +14 -12
  108. package/dist/records/depth/index.js +11 -7
  109. package/dist/records/index.cjs +225 -62
  110. package/dist/records/index.d.cts +159 -20
  111. package/dist/records/index.d.ts +159 -20
  112. package/dist/records/index.js +225 -62
  113. package/dist/recordsAsk.d-C5CGSi3j.d.cts +14 -0
  114. package/dist/recordsAsk.d-C5CGSi3j.d.ts +14 -0
  115. package/dist/{requestFunnel-B9fdXMi5.d.ts → requestFunnel.d-CXUMPw1K.d.ts} +5 -5
  116. package/dist/{requestFunnel-BBjNNwc9.d.cts → requestFunnel.d-DWQQpjFR.d.cts} +5 -5
  117. package/dist/{resolve-D4Ywz5OS.d.ts → resolve.d-jI8FmBj3.d.cts} +3 -3
  118. package/dist/{resolve-D4Ywz5OS.d.cts → resolve.d-jI8FmBj3.d.ts} +3 -3
  119. package/dist/{runtimeTypes-CstDBX8w.d.cts → runtimeTypes.d-4yFNNuYR.d.ts} +20 -13
  120. package/dist/{runtimeTypes-N_K4BVZB.d.ts → runtimeTypes.d-D6N_fhxx.d.cts} +20 -13
  121. package/dist/server/events/index.cjs +7 -3
  122. package/dist/server/events/index.d.cts +51 -9
  123. package/dist/server/events/index.d.ts +51 -9
  124. package/dist/server/events/index.js +7 -3
  125. package/dist/server/index.cjs +12 -6
  126. package/dist/server/index.d.cts +152 -8
  127. package/dist/server/index.d.ts +152 -8
  128. package/dist/server/index.js +12 -6
  129. package/dist/sheetCopy.d-CAhLOxjc.d.cts +4 -0
  130. package/dist/sheetCopy.d-CAhLOxjc.d.ts +4 -0
  131. package/dist/sheetSeam.d-Cviqk89n.d.ts +45 -0
  132. package/dist/sheetSeam.d-DCS3LW8g.d.cts +45 -0
  133. package/dist/shop/index.cjs +262 -0
  134. package/dist/shop/index.d.cts +193 -0
  135. package/dist/shop/index.d.ts +193 -0
  136. package/dist/shop/index.js +262 -0
  137. package/dist/televet/booking/index.cjs +16 -12
  138. package/dist/televet/booking/index.d.cts +36 -22
  139. package/dist/televet/booking/index.d.ts +36 -22
  140. package/dist/televet/booking/index.js +16 -12
  141. package/dist/televet/call/index.d.cts +5 -5
  142. package/dist/televet/call/index.d.ts +5 -5
  143. package/dist/televet/index.cjs +7 -3
  144. package/dist/televet/index.d.cts +12 -12
  145. package/dist/televet/index.d.ts +12 -12
  146. package/dist/televet/index.js +7 -3
  147. package/dist/{televetGlobal-C5dTUACe.d.cts → televetGlobal.d-CC-DrqkQ.d.ts} +7 -2
  148. package/dist/{televetGlobal-CnjrfhT4.d.ts → televetGlobal.d-CKwDCbmN.d.cts} +7 -2
  149. package/dist/testing/index.cjs +7 -3
  150. package/dist/testing/index.d.cts +3 -3
  151. package/dist/testing/index.d.ts +3 -3
  152. package/dist/testing/index.js +7 -3
  153. package/dist/testing/rn/index.cjs +5 -1
  154. package/dist/testing/rn/index.d.cts +23 -22
  155. package/dist/testing/rn/index.d.ts +23 -22
  156. package/dist/testing/rn/index.js +5 -1
  157. package/dist/testing/web/index.cjs +5 -1
  158. package/dist/testing/web/index.d.cts +23 -22
  159. package/dist/testing/web/index.d.ts +23 -22
  160. package/dist/testing/web/index.js +5 -1
  161. package/dist/texting/index.cjs +158 -0
  162. package/dist/texting/index.d.cts +36 -0
  163. package/dist/texting/index.d.ts +36 -0
  164. package/dist/texting/index.js +158 -0
  165. package/dist/threadOptions.d-B1pTMmDF.d.cts +260 -0
  166. package/dist/threadOptions.d-B1pTMmDF.d.ts +260 -0
  167. package/dist/{timelineRows-7yjHyh8i.d.ts → timelineRows.d-BNxgzYRW.d.cts} +1 -1
  168. package/dist/{timelineRows-WvnL-Lds.d.cts → timelineRows.d-CU5GvvLk.d.ts} +1 -1
  169. package/dist/{tokens-DLj8OnLH.d.cts → tokens.d-DarDaV39.d.cts} +10 -2
  170. package/dist/{tokens-DLj8OnLH.d.ts → tokens.d-DarDaV39.d.ts} +10 -2
  171. package/dist/{typeStyle-BxVyF71R.d.ts → typeStyle.d-Bl8pzbBy.d.cts} +2 -2
  172. package/dist/{typeStyle-DJedEu14.d.cts → typeStyle.d-C1HBRAI3.d.ts} +2 -2
  173. package/dist/{uploadTransport-BM_pnEWj.d.cts → uploadTransport.d-CWL7CdWP.d.cts} +1 -1
  174. package/dist/{uploadTransport-C6kGP1Kd.d.ts → uploadTransport.d-EGoUl7gX.d.ts} +1 -1
  175. package/dist/usePresentation.d-D6qsFzBz.d.cts +9 -0
  176. package/dist/usePresentation.d-DuGQe_Do.d.ts +9 -0
  177. package/dist/useRecords.d-Cb-36SF5.d.cts +121 -0
  178. package/dist/useRecords.d-aQTzQZoV.d.ts +121 -0
  179. package/dist/{useRecordsDepth-Bp6L4M5P.d.ts → useRecordsDepth.d-DFcCfiXm.d.ts} +8 -20
  180. package/dist/{useRecordsDepth-DPdAK_81.d.cts → useRecordsDepth.d-sAq2Qkhr.d.cts} +8 -20
  181. package/dist/{useVetVisit-DmWa7lt1.d.ts → useVetVisit.d-BtdwhmgD.d.cts} +15 -4
  182. package/dist/{useVetVisit-PtBjNwZr.d.cts → useVetVisit.d-DoYQimyt.d.ts} +15 -4
  183. package/dist/video/index.cjs +6 -2
  184. package/dist/video/index.d.cts +7 -7
  185. package/dist/video/index.d.ts +7 -7
  186. package/dist/video/index.js +6 -2
  187. package/dist/{view-C6go2uUt.d.ts → view.d-C-SNpDJX.d.ts} +10 -122
  188. package/dist/{view-CiF_HVFQ.d.cts → view.d-Dps5C8-s.d.cts} +10 -122
  189. package/dist/web/consent/index.cjs +5 -1
  190. package/dist/web/consent/index.d.cts +10 -10
  191. package/dist/web/consent/index.d.ts +10 -10
  192. package/dist/web/consent/index.js +5 -1
  193. package/dist/web/health-plan/index.cjs +414 -0
  194. package/dist/web/health-plan/index.d.cts +335 -0
  195. package/dist/web/health-plan/index.d.ts +335 -0
  196. package/dist/web/health-plan/index.js +414 -0
  197. package/dist/web/index.cjs +150 -82
  198. package/dist/web/index.d.cts +152 -38
  199. package/dist/web/index.d.ts +152 -38
  200. package/dist/web/index.js +150 -82
  201. package/dist/web/notifications/index.cjs +16 -3
  202. package/dist/web/notifications/index.d.cts +39 -209
  203. package/dist/web/notifications/index.d.ts +39 -209
  204. package/dist/web/notifications/index.js +16 -3
  205. package/dist/web/records/depth/index.cjs +11 -7
  206. package/dist/web/records/depth/index.d.cts +14 -12
  207. package/dist/web/records/depth/index.d.ts +14 -12
  208. package/dist/web/records/depth/index.js +11 -7
  209. package/dist/web/records/index.cjs +95 -68
  210. package/dist/web/records/index.d.cts +66 -21
  211. package/dist/web/records/index.d.ts +66 -21
  212. package/dist/web/records/index.js +95 -68
  213. package/dist/web/records/upload/index.d.cts +2 -2
  214. package/dist/web/records/upload/index.d.ts +2 -2
  215. package/dist/web/records-sheet/index.cjs +278 -0
  216. package/dist/web/records-sheet/index.d.cts +102 -0
  217. package/dist/web/records-sheet/index.d.ts +102 -0
  218. package/dist/web/records-sheet/index.js +278 -0
  219. package/dist/web/shop/index.cjs +301 -0
  220. package/dist/web/shop/index.d.cts +42 -0
  221. package/dist/web/shop/index.d.ts +42 -0
  222. package/dist/web/shop/index.js +301 -0
  223. package/dist/web/televet/booking/index.cjs +16 -12
  224. package/dist/web/televet/booking/index.d.cts +37 -23
  225. package/dist/web/televet/booking/index.d.ts +37 -23
  226. package/dist/web/televet/booking/index.js +16 -12
  227. package/dist/web/televet/call/index.d.cts +4 -4
  228. package/dist/web/televet/call/index.d.ts +4 -4
  229. package/dist/web/televet/index.cjs +7 -3
  230. package/dist/web/televet/index.d.cts +12 -12
  231. package/dist/web/televet/index.d.ts +12 -12
  232. package/dist/web/televet/index.js +7 -3
  233. package/dist/web/texting/index.cjs +157 -0
  234. package/dist/web/texting/index.d.cts +36 -0
  235. package/dist/web/texting/index.d.ts +36 -0
  236. package/dist/web/texting/index.js +157 -0
  237. package/health-plan/package.json +8 -0
  238. package/package.json +106 -4
  239. package/shop/package.json +8 -0
  240. package/texting/package.json +8 -0
  241. package/web/health-plan/native-blocked.cjs +12 -0
  242. package/web/health-plan/package.json +8 -0
  243. package/web/records-sheet/native-blocked.cjs +12 -0
  244. package/web/records-sheet/package.json +8 -0
  245. package/web/shop/native-blocked.cjs +12 -0
  246. package/web/shop/package.json +8 -0
  247. package/web/texting/native-blocked.cjs +12 -0
  248. package/web/texting/package.json +8 -0
  249. /package/dist/{CameraPort-Cv31Pz7g.d.cts → CameraPort.d-Cv31Pz7g.d.cts} +0 -0
  250. /package/dist/{CameraPort-Cv31Pz7g.d.ts → CameraPort.d-Cv31Pz7g.d.ts} +0 -0
  251. /package/dist/{TelemetryPort-BDNr00hu.d.cts → TelemetryPort.d-BDNr00hu.d.cts} +0 -0
  252. /package/dist/{TelemetryPort-BDNr00hu.d.ts → TelemetryPort.d-BDNr00hu.d.ts} +0 -0
  253. /package/dist/{cacheEpoch-DknKn3S0.d.cts → cacheEpoch.d-DknKn3S0.d.cts} +0 -0
  254. /package/dist/{cacheEpoch-DknKn3S0.d.ts → cacheEpoch.d-DknKn3S0.d.ts} +0 -0
  255. /package/dist/{callCopy-Bw6oZT54.d.cts → callCopy.d-Bw6oZT54.d.cts} +0 -0
  256. /package/dist/{callCopy-Bw6oZT54.d.ts → callCopy.d-Bw6oZT54.d.ts} +0 -0
  257. /package/dist/{ids-B2GAAifq.d.cts → ids.d-B2GAAifq.d.cts} +0 -0
  258. /package/dist/{ids-B2GAAifq.d.ts → ids.d-B2GAAifq.d.ts} +0 -0
  259. /package/dist/{optionalModule-DbJmsq5f.d.cts → optionalModule.d-DbJmsq5f.d.cts} +0 -0
  260. /package/dist/{optionalModule-DbJmsq5f.d.ts → optionalModule.d-DbJmsq5f.d.ts} +0 -0
  261. /package/dist/{profile-CSs1wlXT.d.cts → profile.d-CSs1wlXT.d.cts} +0 -0
  262. /package/dist/{profile-CSs1wlXT.d.ts → profile.d-CSs1wlXT.d.ts} +0 -0
  263. /package/dist/{projection-CeIUsbSk.d.cts → projection.d-CeIUsbSk.d.cts} +0 -0
  264. /package/dist/{projection-CeIUsbSk.d.ts → projection.d-CeIUsbSk.d.ts} +0 -0
  265. /package/dist/{species-BXAIMh7I.d.cts → species.d-BXAIMh7I.d.cts} +0 -0
  266. /package/dist/{species-BXAIMh7I.d.ts → species.d-BXAIMh7I.d.ts} +0 -0
  267. /package/dist/{visitIntent-D7_yVp1I.d.cts → visitIntent.d-D7_yVp1I.d.cts} +0 -0
  268. /package/dist/{visitIntent-D7_yVp1I.d.ts → visitIntent.d-D7_yVp1I.d.ts} +0 -0
@@ -1,5 +1,14 @@
1
1
  "use client";
2
- "use strict";var react=require("react");function ok(value,warning){/* @__PURE__ */
2
+ "use strict";var react=require("react"),jsxRuntime=require("react/jsx-runtime");function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"};deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function EverfurNotificationStack(props){let guarded=guardHostProps(props,["onOpen"]),theme=useEverfurTheme(),S=react.useMemo(()=>styles(theme),[theme]),cls=guarded.classNames,part=name=>{let c=cls?.[name];return c!==void 0&&c!==""?{className:c}:{style:S[name]}},root=part("root");/* @__PURE__ */
3
+ return jsxRuntime.jsxs("section",{...root,style:root.style===void 0?guarded.style:{...root.style,...guarded.style},"aria-label":guarded.label,children:[guarded.date!==void 0?/* @__PURE__ */jsxRuntime.jsx("p",{...part("date"),children:guarded.date}):null,guarded.time!==void 0?/* @__PURE__ */jsxRuntime.jsx("p",{...part("time"),children:guarded.time}):null,
4
+ /* @__PURE__ */jsxRuntime.jsx("div",{...part("stack"),children:guarded.notes.map((note,i)=>{let n=part("note");/* @__PURE__ */
5
+ return jsxRuntime.jsxs("button",{type:"button",...n,style:{...n.style,"--i":i},onClick:()=>guarded.onOpen(note),children:[
6
+ /* @__PURE__ */jsxRuntime.jsx("span",{...part("app"),children:guarded.appIcon}),
7
+ /* @__PURE__ */jsxRuntime.jsxs("span",{...part("text"),children:[
8
+ /* @__PURE__ */jsxRuntime.jsxs("span",{...part("meta"),children:[
9
+ /* @__PURE__ */jsxRuntime.jsx("strong",{children:note.app}),
10
+ /* @__PURE__ */jsxRuntime.jsx("small",{children:note.when})]}),
11
+ /* @__PURE__ */jsxRuntime.jsx("strong",{children:note.title}),note.body!==void 0?/* @__PURE__ */jsxRuntime.jsx("span",{children:note.body}):null]}),note.thumbUrl!==void 0?/* @__PURE__ */jsxRuntime.jsx("img",{...part("thumb"),alt:"",src:note.thumbUrl}):null]},note.id)})}),guarded.hint!==void 0?/* @__PURE__ */jsxRuntime.jsx("p",{...part("hint"),children:guarded.hint}):null]})}function styles(theme){let{color:color,radius:radius,space:space,type:type}=theme,text=(size,ink,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,color:ink});return{root:{display:"flex",flexDirection:"column",alignItems:"center",padding:space.lg,gap:space.xs,backgroundColor:color.brandInk,color:color.surface},date:text(type.size.body,color.surface,"bold"),time:{...text(64,color.surface,"bold"),lineHeight:1},stack:{width:"100%",marginTop:space.lg,display:"grid",gap:space.xs},note:{width:"100%",display:"grid",gridTemplateColumns:"38px minmax(0, 1fr) auto",gap:space.sm,alignItems:"start",padding:space.sm,border:"none",borderRadius:radius.lg,backgroundColor:color.surface,color:color.text.primary,textAlign:"left",cursor:"pointer"},app:{width:38,height:38,borderRadius:radius.sm,display:"grid",placeItems:"center",backgroundColor:color.brandSofter},text:{...text(type.size.caption,color.text.primary),display:"grid",gap:1},meta:{display:"flex",justifyContent:"space-between",color:color.text.muted},thumb:{width:40,height:40,borderRadius:radius.sm,objectFit:"cover",alignSelf:"center"},hint:{...text(type.size.caption,color.surface),marginTop:space.lg}}}function ok(value,warning){/* @__PURE__ */
3
12
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
4
13
  return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
5
14
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
@@ -24,6 +33,8 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
24
33
  /* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
25
34
  /* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
26
35
  /* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
36
+ /* @__PURE__ */Object.freeze({wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
37
+ /* @__PURE__ */Object.freeze({wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
27
38
  /* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
28
39
  /* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
29
40
  /* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
@@ -48,6 +59,7 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
48
59
  /* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
49
60
  /* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
50
61
  /* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
62
+ /* @__PURE__ */Object.freeze({wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false}),
51
63
  /* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
52
64
  /* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
53
65
  /* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
@@ -84,14 +96,15 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
84
96
  /* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
85
97
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
86
98
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
99
+ /* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
87
100
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
88
101
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
89
102
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
90
103
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
91
104
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
92
105
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
93
- /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function errorFrame(fields){/* @__PURE__ */
106
+ /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function errorFrame(fields){/* @__PURE__ */
94
107
  return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
95
108
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
96
109
  return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at2=findResetsAt(error.raw);if(at2!==null){let delta=at2-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function wireCodeOf2(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}function foldWireReason(error,table){let wire=wireCodeOf2(error);if(wire===null)return error;let fold=table[wire];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:wire,reasonCode:wire,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}var NOTIFICATIONS_REASON_MESSAGES=/* @__PURE__ */Object.freeze({provider_unsupported:"Everfur does not send through this push provider yet. Register an Expo push token (provider expo) or an FCM registration token (provider fcm); APNs direct is not available in this version.",token_invalid:"The token is not a push token of the given provider. Expo tokens look like ExponentPushToken[...]; FCM registration tokens are long opaque strings. Pass the token exactly as your notification library printed it.",device_cipher_unavailable:"Everfur could not seal the token at rest, so nothing was stored. Retry the registration later; the SDK retries it on the next launch and login.",credentials_missing:"Everfur holds no push credential for this provider on your tenant, so deliveries to it are skipped. Expo needs nothing unless you enabled push security (then your Expo access token). A bare app using FCM supplies its Firebase service-account JSON to Everfur; push credentials are set by Everfur on your tenant, never through the SDK."}),REASONS=/* @__PURE__ */new Set(["provider_unsupported","token_invalid","device_cipher_unavailable","credentials_missing"]);function explainNotificationsReason(error){let reason=error.reasonCode;return reason!==void 0&&REASONS.has(reason)?NOTIFICATIONS_REASON_MESSAGES[reason]:null}var PROVIDERS=/* @__PURE__ */new Set(["expo","fcm","apns"]),PLATFORMS=/* @__PURE__ */new Set(["ios","android"]),TOKEN_MAX=4096,INSTALLATION_ID_MAX=128,DEVICE_ID_MAX=64,CONTROL_OR_SPACE=/[\0- ]/;function invalid(wireMessage,reasonCode){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage,...reasonCode?{reasonCode:reasonCode}:{}})}function validateRegister(input){if(typeof input!="object"||input===null)return invalid("registerDevice needs an input object");let{token:token,provider:provider,platform:platform,installationId:installationId}=input;return typeof provider!="string"||!PROVIDERS.has(provider)?invalid("provider must be expo, fcm or apns"):typeof platform!="string"||!PLATFORMS.has(platform)?invalid("platform must be ios or android"):typeof token!="string"||token.trim().length===0||token.length>TOKEN_MAX||CONTROL_OR_SPACE.test(token)?invalid(`token must be a push token of 1..${TOKEN_MAX} characters with no whitespace`,"token_invalid"):installationId!==void 0&&(typeof installationId!="string"||installationId.length===0||installationId.length>INSTALLATION_ID_MAX)?invalid(`installationId must be 1..${INSTALLATION_ID_MAX} characters`):null}function validateDeviceId(deviceId){return typeof deviceId!="string"||deviceId.length===0||deviceId.length>DEVICE_ID_MAX?invalid(`deviceId must be 1..${DEVICE_ID_MAX} characters`):CONTROL_OR_SPACE.test(deviceId)||deviceId.includes("/")||deviceId==="."||deviceId===".."?invalid("deviceId is not a device id"):null}function validatePreferences(input){if(typeof input!="object"||input===null)return invalid("setPreferences needs an input object");let{pushEnabled:pushEnabled,emailEnabled:emailEnabled}=input;return typeof pushEnabled!="boolean"||typeof emailEnabled!="boolean"?invalid("pushEnabled and emailEnabled must both be booleans: the route replaces both switches"):null}function str(value){return typeof value=="string"&&value.length>0?value:null}function parseDevice(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,deviceId=str(o.device_id),provider=str(o.provider),platform=str(o.platform),registeredAt=str(o.registered_at),lastSeenAt=str(o.last_seen_at);if(deviceId===null||provider===null||platform===null||registeredAt===null||lastSeenAt===null||!PROVIDERS.has(provider)||!PLATFORMS.has(platform))return null;let installation=o.installation_id;/* @__PURE__ */
97
- return Object.freeze({deviceId:deviceId,provider:provider,platform:platform,installationId:typeof installation=="string"&&installation.length>0?installation:null,registeredAt:registeredAt,lastSeenAt:lastSeenAt})}function parsePreferences(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,updatedAt=str(o.updated_at);return typeof o.push_enabled!="boolean"||typeof o.email_enabled!="boolean"||updatedAt===null?null:/* @__PURE__ */Object.freeze({pushEnabled:o.push_enabled,emailEnabled:o.email_enabled,updatedAt:updatedAt})}function malformed(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}var ROUTE_REASONS=/* @__PURE__ */Object.freeze({provider_unsupported:{code:"validationFailed",retryable:false},token_invalid:{code:"validationFailed",retryable:false},device_cipher_unavailable:{code:"serviceUnavailable",retryable:true}});function refine(error){return foldWireReason(error,ROUTE_REASONS)}function disposed(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function createNotificationsClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createNotificationsClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{registerDevice:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("registerDevice"))):over().registerDevice(input,opts),unregisterDevice:(deviceId,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("unregisterDevice"))):over().unregisterDevice(deviceId,opts),setPreferences:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("setPreferences"))):over().setPreferences(input,opts)}}function createNotificationsClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),withSignal=(req,signal)=>signal?{...req,signal:signal}:req;return{async registerDevice(input,opts){let bad=validateRegister(input);if(bad!==null)return err(bad);let body={token:input.token,provider:input.provider,platform:input.platform};input.installationId!==void 0&&(body.installation_id=input.installationId);let res=await funnel.send("notifications.registerDevice",withSignal({method:"POST",path:"/widget/v1/me/devices",body:body},opts?.signal));if(!res.ok)return err(refine(res.error));let device=parseDevice(res.value);return device===null?err(malformed("registerDevice")):ok(device)},async unregisterDevice(deviceId,opts){let bad=validateDeviceId(deviceId);if(bad!==null)return err(bad);let res=await funnel.send("notifications.unregisterDevice",withSignal({method:"DELETE",path:`/widget/v1/me/devices/${encodeURIComponent(deviceId)}`},opts?.signal));return res.ok?ok(void 0):err(refine(res.error))},async setPreferences(input,opts){let bad=validatePreferences(input);if(bad!==null)return err(bad);let res=await funnel.send("notifications.setPreferences",withSignal({method:"PUT",path:"/widget/v1/me/notification-preferences",body:{push_enabled:input.pushEnabled,email_enabled:input.emailEnabled}},opts?.signal));if(!res.ok)return err(refine(res.error));let preferences=parsePreferences(res.value);return preferences===null?err(malformed("setPreferences")):ok(preferences)}}}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3;var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var STORED_VERSION=1;async function readStored(kv){try{let raw=await kv.getItem(NOTIFICATIONS_DEVICE_KV_KEY);if(raw===null)return null;let parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null)return null;let{v:v,userRef:userRef,deviceId:deviceId}=parsed;return v!==STORED_VERSION||typeof userRef!="string"||typeof deviceId!="string"||deviceId.length===0?null:{userRef:userRef,deviceId:deviceId}}catch{return null}}async function writeStored(kv,entry){try{await kv.setItem(NOTIFICATIONS_DEVICE_KV_KEY,JSON.stringify({v:STORED_VERSION,...entry}))}catch{}}async function clearStored(kv){try{await kv.removeItem(NOTIFICATIONS_DEVICE_KV_KEY)}catch{}}var SIGNED_OUT=/* @__PURE__ */Object.freeze({status:"signed_out",device:null,error:null}),NO_TOKEN=/* @__PURE__ */Object.freeze({status:"no_token",device:null,error:null});function noUser(){return makeEverfurError("sessionRequired",{retryable:false,wireMessage:"notifications need a signed-in user on the provider"})}function useEverfurNotificationsClient(){let{runtime:runtime}=useEverfurContext();return react.useMemo(()=>createNotificationsClient(runtime),[runtime])}function useEverfurNotifications(options){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{token:token,provider:provider,platform:platform,installationId:installationId}=options,kv=runtime.registry.services.kv,client=useEverfurNotificationsClient(),[settled,setSettled]=react.useState(userRef===null?SIGNED_OUT:NO_TOKEN),knownRef=react.useRef(null),generation=react.useRef(0);react.useEffect(()=>{if(generation.current+=1,knownRef.current=null,setSettled(userRef===null?SIGNED_OUT:NO_TOKEN),userRef===null)return;let live=true;return readStored(kv).then(stored=>{if(!live||stored===null||stored.userRef!==userRef)return;let known=knownRef.current;if(known===null){knownRef.current=stored;return}known.deviceId!==stored.deviceId&&client.unregisterDevice(stored.deviceId)}),()=>{live=false}},[client,kv,userRef]);let registerFor=react.useCallback(async(user,current)=>{let gen=generation.current+=1;setSettled({status:"registering",device:null,error:null});let result=await client.registerDevice({token:current,provider:provider,platform:platform,...installationId===void 0?{}:{installationId:installationId}});if(gen!==generation.current)return result;if(!result.ok)return setSettled({status:result.error.httpStatus===404?"unavailable":"failed",device:null,error:result.error}),result;let previous=knownRef.current;return knownRef.current={userRef:user,deviceId:result.value.deviceId},setSettled({status:"registered",device:result.value,error:null}),await writeStored(kv,knownRef.current),previous!==null&&previous.userRef===user&&previous.deviceId!==result.value.deviceId&&client.unregisterDevice(previous.deviceId),result},[client,kv,provider,platform,installationId]);react.useEffect(()=>{userRef===null||token===null||registerFor(userRef,token)},[registerFor,userRef,token]),react.useEffect(()=>runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==leaving)return;knownRef.current=null;let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}}),result=await createNotificationsClientOver({auth:auth,funnel:funnel}).unregisterDevice(known.deviceId);(result.ok||result.error.httpStatus===404)&&await clearStored(kv)}),[runtime,kv]);let register=react.useCallback(async()=>userRef===null?err(noUser()):token===null?err(makeEverfurError("validationFailed",{retryable:false,reasonCode:"token_invalid",wireMessage:"no push token was given"})):registerFor(userRef,token),[registerFor,userRef,token]),unregister=react.useCallback(async()=>{if(userRef===null)return err(noUser());let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==userRef)return ok(void 0);let gen=generation.current+=1,result=await client.unregisterDevice(known.deviceId);return result.ok||result.error.httpStatus===404?(knownRef.current=null,await clearStored(kv),gen===generation.current&&setSettled({status:"unregistered",device:null,error:null}),result.ok?result:ok(void 0)):result},[client,kv,userRef]),setPreferences=react.useCallback(input=>userRef===null?Promise.resolve(err(noUser())):client.setPreferences(input),[client,userRef]);return react.useMemo(()=>({status:settled.status,device:settled.device,error:settled.error,register:register,unregister:unregister,setPreferences:setPreferences}),[settled,register,unregister,setPreferences])}var INTENT_BY_VISIT_EVENT=/* @__PURE__ */Object.freeze({"visit.booked":"visit","visit.reminder":"join","visit.rescheduled":"visit","visit.followup_sent":"messages","visit.message_received":"messages","visit.completed":"summary","visit.ended":"visit","visit.cancelled":null,"visit.no_show":null});function vetVisitIntentForEvent(eventType){return Object.prototype.hasOwnProperty.call(INTENT_BY_VISIT_EVENT,eventType)?INTENT_BY_VISIT_EVENT[eventType]:"visit"}var EVERFUR_NOTIFICATION_VERSION=1,EVERFUR_NOTIFICATION_TARGET_KINDS=/* @__PURE__ */Object.freeze(["record_request","pet","visit","case"]),EVERFUR_NOTIFICATION_EVENT_TYPES=/* @__PURE__ */Object.freeze(["record_request.updated","record.ready","pet.vaccination.due","visit.booked","visit.cancelled","visit.completed","visit.no_show","visit.rescheduled","visit.reminder","visit.followup_sent","visit.message_received","visit.ended","chat.follow_up_due","chat.reminder_due","record.activation"]),TOP_KEYS=["v","event_id","event_type","target"],TARGET_KEYS=/* @__PURE__ */new Set(["kind","conversation_id","request_id","visit_ref","case_ref","pet_ref"]),EVENT_TYPES=new Set(EVERFUR_NOTIFICATION_EVENT_TYPES),KINDS=new Set(EVERFUR_NOTIFICATION_TARGET_KINDS),MAX_VALUE_LENGTH=128,MAX_ENCODED_LENGTH=4096,EVENT_ID=/^evt_[A-Za-z0-9]{1,64}$/,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,CONTROL_CHAR=/[\0-]/;function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function keysOf(value){return Object.keys(value)}function decodeBlock(raw){if(isRecord2(raw))return raw;if(typeof raw!="string"||raw.length===0||raw.length>MAX_ENCODED_LENGTH)return null;let decoded=JSON.parse(raw);return isRecord2(decoded)?decoded:null}function at(root,path){let current=root;for(let key of path){if(!isRecord2(current))return;current=current[key]}return current}var DATA_PATHS=[[],["data"],["request","content","data"],["notification","request","content","data"]];function locateBlock(payload){if(!isRecord2(payload))return null;for(let path of DATA_PATHS){let map=at(payload,path);if(isRecord2(map)&&"everfur"in map)return map.everfur}return TOP_KEYS.every(key=>key in payload)?payload:null}function opaqueString(value){return typeof value!="string"||value.length===0||value.length>MAX_VALUE_LENGTH||CONTROL_CHAR.test(value)||value.includes("://")||value.toLowerCase().startsWith("everfur")?null:value}function optional(target,key){if(!(key in target))return{ok:true,value:null};let value=opaqueString(target[key]);return value===null?{ok:false}:{ok:true,value:value}}function required(target,key){return key in target?opaqueString(target[key]):null}function parseTarget(raw,eventType){if(!isRecord2(raw))return null;let keys=keysOf(raw);if(!keys.includes("kind")||keys.some(key=>!TARGET_KEYS.has(key)))return null;let kind=raw.kind;if(typeof kind!="string"||!KINDS.has(kind))return null;for(let key of keys)if(key!=="kind"&&opaqueString(raw[key])===null)return null;let pet=optional(raw,"pet_ref");if(!pet.ok)return null;let petRef=pet.value;switch(kind){case"record_request":{let requestId=required(raw,"request_id");return requestId===null?null:/* @__PURE__ */Object.freeze({kind:"record_request",requestId:requestId,petRef:petRef})}case"pet":return petRef===null?null:/* @__PURE__ */Object.freeze({kind:"pet",petRef:petRef});case"visit":{let visitRef=required(raw,"visit_ref");return visitRef===null?null:/* @__PURE__ */Object.freeze({kind:"visit",visitRef:visitRef,petRef:petRef,intent:vetVisitIntentForEvent(eventType)})}case"case":{let caseRef=required(raw,"case_ref");if(caseRef===null)return null;let conversation=optional(raw,"conversation_id");return!conversation.ok||conversation.value!==null&&!UUID.test(conversation.value)?null:/* @__PURE__ */Object.freeze({kind:"case",caseRef:caseRef,conversationId:conversation.value,petRef:petRef})}default:return null}}function parseBlock(block){let keys=keysOf(block);if(keys.length!==TOP_KEYS.length||TOP_KEYS.some(key=>!keys.includes(key))||block.v!==EVERFUR_NOTIFICATION_VERSION)return null;let eventId=block.event_id;if(typeof eventId!="string"||!EVENT_ID.test(eventId))return null;let eventType=block.event_type;if(typeof eventType!="string"||!EVENT_TYPES.has(eventType))return null;let target=parseTarget(block.target,eventType);return target===null?null:/* @__PURE__ */Object.freeze({eventId:eventId,eventType:eventType,target:target})}function parseEverfurNotification(payload){try{let block=decodeBlock(locateBlock(payload));return block===null?null:parseBlock(block)}catch{return null}}exports.EVERFUR_NOTIFICATION_EVENT_TYPES=EVERFUR_NOTIFICATION_EVENT_TYPES;exports.EVERFUR_NOTIFICATION_TARGET_KINDS=EVERFUR_NOTIFICATION_TARGET_KINDS;exports.EVERFUR_NOTIFICATION_VERSION=EVERFUR_NOTIFICATION_VERSION;exports.NOTIFICATIONS_REASON_MESSAGES=NOTIFICATIONS_REASON_MESSAGES;exports.createNotificationsClient=createNotificationsClient;exports.explainNotificationsReason=explainNotificationsReason;exports.parseEverfurNotification=parseEverfurNotification;exports.useEverfurNotifications=useEverfurNotifications;exports.useEverfurNotificationsClient=useEverfurNotificationsClient;
110
+ return Object.freeze({deviceId:deviceId,provider:provider,platform:platform,installationId:typeof installation=="string"&&installation.length>0?installation:null,registeredAt:registeredAt,lastSeenAt:lastSeenAt})}function parsePreferences(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,updatedAt=str(o.updated_at);return typeof o.push_enabled!="boolean"||typeof o.email_enabled!="boolean"||updatedAt===null?null:/* @__PURE__ */Object.freeze({pushEnabled:o.push_enabled,emailEnabled:o.email_enabled,updatedAt:updatedAt})}function malformed(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}var ROUTE_REASONS=/* @__PURE__ */Object.freeze({provider_unsupported:{code:"validationFailed",retryable:false},token_invalid:{code:"validationFailed",retryable:false},device_cipher_unavailable:{code:"serviceUnavailable",retryable:true}});function refine(error){return foldWireReason(error,ROUTE_REASONS)}function disposed(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function createNotificationsClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createNotificationsClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{registerDevice:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("registerDevice"))):over().registerDevice(input,opts),unregisterDevice:(deviceId,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("unregisterDevice"))):over().unregisterDevice(deviceId,opts),setPreferences:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("setPreferences"))):over().setPreferences(input,opts)}}function createNotificationsClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),withSignal=(req,signal)=>signal?{...req,signal:signal}:req;return{async registerDevice(input,opts){let bad=validateRegister(input);if(bad!==null)return err(bad);let body={token:input.token,provider:input.provider,platform:input.platform};input.installationId!==void 0&&(body.installation_id=input.installationId);let res=await funnel.send("notifications.registerDevice",withSignal({method:"POST",path:"/widget/v1/me/devices",body:body},opts?.signal));if(!res.ok)return err(refine(res.error));let device=parseDevice(res.value);return device===null?err(malformed("registerDevice")):ok(device)},async unregisterDevice(deviceId,opts){let bad=validateDeviceId(deviceId);if(bad!==null)return err(bad);let res=await funnel.send("notifications.unregisterDevice",withSignal({method:"DELETE",path:`/widget/v1/me/devices/${encodeURIComponent(deviceId)}`},opts?.signal));return res.ok?ok(void 0):err(refine(res.error))},async setPreferences(input,opts){let bad=validatePreferences(input);if(bad!==null)return err(bad);let res=await funnel.send("notifications.setPreferences",withSignal({method:"PUT",path:"/widget/v1/me/notification-preferences",body:{push_enabled:input.pushEnabled,email_enabled:input.emailEnabled}},opts?.signal));if(!res.ok)return err(refine(res.error));let preferences=parsePreferences(res.value);return preferences===null?err(malformed("setPreferences")):ok(preferences)}}}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3;var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var STORED_VERSION=1;async function readStored(kv){try{let raw=await kv.getItem(NOTIFICATIONS_DEVICE_KV_KEY);if(raw===null)return null;let parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null)return null;let{v:v,userRef:userRef,deviceId:deviceId}=parsed;return v!==STORED_VERSION||typeof userRef!="string"||typeof deviceId!="string"||deviceId.length===0?null:{userRef:userRef,deviceId:deviceId}}catch{return null}}async function writeStored(kv,entry){try{await kv.setItem(NOTIFICATIONS_DEVICE_KV_KEY,JSON.stringify({v:STORED_VERSION,...entry}))}catch{}}async function clearStored(kv){try{await kv.removeItem(NOTIFICATIONS_DEVICE_KV_KEY)}catch{}}var SIGNED_OUT=/* @__PURE__ */Object.freeze({status:"signed_out",device:null,error:null}),NO_TOKEN=/* @__PURE__ */Object.freeze({status:"no_token",device:null,error:null});function noUser(){return makeEverfurError("sessionRequired",{retryable:false,wireMessage:"notifications need a signed-in user on the provider"})}function useEverfurNotificationsClient(){let{runtime:runtime}=useEverfurContext();return react.useMemo(()=>createNotificationsClient(runtime),[runtime])}function useEverfurNotifications(options){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{token:token,provider:provider,platform:platform,installationId:installationId}=options,kv=runtime.registry.services.kv,client=useEverfurNotificationsClient(),[settled,setSettled]=react.useState(userRef===null?SIGNED_OUT:NO_TOKEN),knownRef=react.useRef(null),generation=react.useRef(0);react.useEffect(()=>{if(generation.current+=1,knownRef.current=null,setSettled(userRef===null?SIGNED_OUT:NO_TOKEN),userRef===null)return;let live=true;return readStored(kv).then(stored=>{if(!live||stored===null||stored.userRef!==userRef)return;let known=knownRef.current;if(known===null){knownRef.current=stored;return}known.deviceId!==stored.deviceId&&client.unregisterDevice(stored.deviceId)}),()=>{live=false}},[client,kv,userRef]);let registerFor=react.useCallback(async(user,current)=>{let gen=generation.current+=1;setSettled({status:"registering",device:null,error:null});let result=await client.registerDevice({token:current,provider:provider,platform:platform,...installationId===void 0?{}:{installationId:installationId}});if(gen!==generation.current)return result;if(!result.ok)return setSettled({status:result.error.httpStatus===404?"unavailable":"failed",device:null,error:result.error}),result;let previous=knownRef.current;return knownRef.current={userRef:user,deviceId:result.value.deviceId},setSettled({status:"registered",device:result.value,error:null}),await writeStored(kv,knownRef.current),previous!==null&&previous.userRef===user&&previous.deviceId!==result.value.deviceId&&client.unregisterDevice(previous.deviceId),result},[client,kv,provider,platform,installationId]);react.useEffect(()=>{userRef===null||token===null||registerFor(userRef,token)},[registerFor,userRef,token]),react.useEffect(()=>runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==leaving)return;knownRef.current=null;let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}}),result=await createNotificationsClientOver({auth:auth,funnel:funnel}).unregisterDevice(known.deviceId);(result.ok||result.error.httpStatus===404)&&await clearStored(kv)}),[runtime,kv]);let register=react.useCallback(async()=>userRef===null?err(noUser()):token===null?err(makeEverfurError("validationFailed",{retryable:false,reasonCode:"token_invalid",wireMessage:"no push token was given"})):registerFor(userRef,token),[registerFor,userRef,token]),unregister=react.useCallback(async()=>{if(userRef===null)return err(noUser());let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==userRef)return ok(void 0);let gen=generation.current+=1,result=await client.unregisterDevice(known.deviceId);return result.ok||result.error.httpStatus===404?(knownRef.current=null,await clearStored(kv),gen===generation.current&&setSettled({status:"unregistered",device:null,error:null}),result.ok?result:ok(void 0)):result},[client,kv,userRef]),setPreferences=react.useCallback(input=>userRef===null?Promise.resolve(err(noUser())):client.setPreferences(input),[client,userRef]);return react.useMemo(()=>({status:settled.status,device:settled.device,error:settled.error,register:register,unregister:unregister,setPreferences:setPreferences}),[settled,register,unregister,setPreferences])}var INTENT_BY_VISIT_EVENT=/* @__PURE__ */Object.freeze({"visit.booked":"visit","visit.reminder":"join","visit.rescheduled":"visit","visit.followup_sent":"messages","visit.message_received":"messages","visit.completed":"summary","visit.ended":"visit","visit.cancelled":null,"visit.no_show":null});function vetVisitIntentForEvent(eventType){return Object.prototype.hasOwnProperty.call(INTENT_BY_VISIT_EVENT,eventType)?INTENT_BY_VISIT_EVENT[eventType]:"visit"}var EVERFUR_NOTIFICATION_VERSION=1,EVERFUR_NOTIFICATION_TARGET_KINDS=/* @__PURE__ */Object.freeze(["record_request","pet","visit","case"]),EVERFUR_NOTIFICATION_EVENT_TYPES=/* @__PURE__ */Object.freeze(["record_request.updated","record.ready","pet.vaccination.due","visit.booked","visit.cancelled","visit.completed","visit.no_show","visit.rescheduled","visit.reminder","visit.followup_sent","visit.message_received","visit.ended","chat.follow_up_due","chat.reminder_due","record.activation"]),TOP_KEYS=["v","event_id","event_type","target"],TARGET_KEYS=/* @__PURE__ */new Set(["kind","conversation_id","request_id","visit_ref","case_ref","pet_ref"]),EVENT_TYPES=new Set(EVERFUR_NOTIFICATION_EVENT_TYPES),KINDS=new Set(EVERFUR_NOTIFICATION_TARGET_KINDS),MAX_VALUE_LENGTH=128,MAX_ENCODED_LENGTH=4096,EVENT_ID=/^evt_[A-Za-z0-9]{1,64}$/,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,CONTROL_CHAR=/[\0-]/;function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function keysOf(value){return Object.keys(value)}function decodeBlock(raw){if(isRecord2(raw))return raw;if(typeof raw!="string"||raw.length===0||raw.length>MAX_ENCODED_LENGTH)return null;let decoded=JSON.parse(raw);return isRecord2(decoded)?decoded:null}function at(root,path){let current=root;for(let key of path){if(!isRecord2(current))return;current=current[key]}return current}var DATA_PATHS=[[],["data"],["request","content","data"],["notification","request","content","data"]];function locateBlock(payload){if(!isRecord2(payload))return null;for(let path of DATA_PATHS){let map=at(payload,path);if(isRecord2(map)&&"everfur"in map)return map.everfur}return TOP_KEYS.every(key=>key in payload)?payload:null}function opaqueString(value){return typeof value!="string"||value.length===0||value.length>MAX_VALUE_LENGTH||CONTROL_CHAR.test(value)||value.includes("://")||value.toLowerCase().startsWith("everfur")?null:value}function optional(target,key){if(!(key in target))return{ok:true,value:null};let value=opaqueString(target[key]);return value===null?{ok:false}:{ok:true,value:value}}function required(target,key){return key in target?opaqueString(target[key]):null}function parseTarget(raw,eventType){if(!isRecord2(raw))return null;let keys=keysOf(raw);if(!keys.includes("kind")||keys.some(key=>!TARGET_KEYS.has(key)))return null;let kind=raw.kind;if(typeof kind!="string"||!KINDS.has(kind))return null;for(let key of keys)if(key!=="kind"&&opaqueString(raw[key])===null)return null;let pet=optional(raw,"pet_ref");if(!pet.ok)return null;let petRef=pet.value;switch(kind){case"record_request":{let requestId=required(raw,"request_id");return requestId===null?null:/* @__PURE__ */Object.freeze({kind:"record_request",requestId:requestId,petRef:petRef})}case"pet":return petRef===null?null:/* @__PURE__ */Object.freeze({kind:"pet",petRef:petRef});case"visit":{let visitRef=required(raw,"visit_ref");return visitRef===null?null:/* @__PURE__ */Object.freeze({kind:"visit",visitRef:visitRef,petRef:petRef,intent:vetVisitIntentForEvent(eventType)})}case"case":{let caseRef=required(raw,"case_ref");if(caseRef===null)return null;let conversation=optional(raw,"conversation_id");return!conversation.ok||conversation.value!==null&&!UUID.test(conversation.value)?null:/* @__PURE__ */Object.freeze({kind:"case",caseRef:caseRef,conversationId:conversation.value,petRef:petRef})}default:return null}}function parseBlock(block){let keys=keysOf(block);if(keys.length!==TOP_KEYS.length||TOP_KEYS.some(key=>!keys.includes(key))||block.v!==EVERFUR_NOTIFICATION_VERSION)return null;let eventId=block.event_id;if(typeof eventId!="string"||!EVENT_ID.test(eventId))return null;let eventType=block.event_type;if(typeof eventType!="string"||!EVENT_TYPES.has(eventType))return null;let target=parseTarget(block.target,eventType);return target===null?null:/* @__PURE__ */Object.freeze({eventId:eventId,eventType:eventType,target:target})}function parseEverfurNotification(payload){try{let block=decodeBlock(locateBlock(payload));return block===null?null:parseBlock(block)}catch{return null}}exports.EVERFUR_NOTIFICATION_EVENT_TYPES=EVERFUR_NOTIFICATION_EVENT_TYPES;exports.EVERFUR_NOTIFICATION_TARGET_KINDS=EVERFUR_NOTIFICATION_TARGET_KINDS;exports.EVERFUR_NOTIFICATION_VERSION=EVERFUR_NOTIFICATION_VERSION;exports.EverfurNotificationStack=EverfurNotificationStack;exports.NOTIFICATIONS_REASON_MESSAGES=NOTIFICATIONS_REASON_MESSAGES;exports.createNotificationsClient=createNotificationsClient;exports.explainNotificationsReason=explainNotificationsReason;exports.parseEverfurNotification=parseEverfurNotification;exports.useEverfurNotifications=useEverfurNotifications;exports.useEverfurNotificationsClient=useEverfurNotificationsClient;
@@ -1,214 +1,44 @@
1
- import { E as EverfurError } from '../../EverfurError-DeBqRpQV.cjs';
2
- export { a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError-DeBqRpQV.cjs';
3
- import { E as EverfurResult } from '../../EverfurResult-COlXj1wq.cjs';
4
- import { E as ErrorPolicyPort } from '../../ErrorPolicyPort-10s3HJCt.cjs';
5
- import { A as AuthContext } from '../../identity-DFVGYn1o.cjs';
6
- export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity-DFVGYn1o.cjs';
7
- import { U as UserRef, R as RecordsRequestId, P as PetRef, C as ConversationId } from '../../ids-B2GAAifq.cjs';
8
- export { B as Brand, _ as __brand } from '../../ids-B2GAAifq.cjs';
9
- import { V as VetVisitIntent } from '../../visitIntent-D7_yVp1I.cjs';
10
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config-B0p6Lygh.cjs';
1
+ import { ReactNode, CSSProperties } from 'react';
2
+ export { D as DevicePlatform, b as EVERFUR_NOTIFICATION_EVENT_TYPES, c as EVERFUR_NOTIFICATION_TARGET_KINDS, d as EVERFUR_NOTIFICATION_VERSION, e as EverfurNotification, f as EverfurNotificationEventType, g as EverfurNotificationTarget, h as EverfurNotificationTargetKind, E as EverfurNotificationsOptions, a as EverfurNotificationsState, i as EverfurNotificationsStatus, N as NOTIFICATIONS_REASON_MESSAGES, j as NotificationPreferences, k as NotificationPreferencesInput, l as NotificationsClient, m as NotificationsReasonCode, n as NotificationsRuntime, P as PushProvider, R as RegisterDeviceInput, o as RegisteredDevice, p as createNotificationsClient, q as explainNotificationsReason, r as parseEverfurNotification, s as useEverfurNotifications, u as useEverfurNotificationsClient } from '../../parse.d-tEzufgJX.cjs';
3
+ export { V as VetVisitIntent } from '../../visitIntent.d-D7_yVp1I.cjs';
4
+ export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-60LeJt_s.cjs';
5
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-BR3DT9ho.cjs';
6
+ export { B as Brand, C as ConversationId, P as PetRef, R as RecordsRequestId, U as UserRef, _ as __brand } from '../../ids.d-B2GAAifq.cjs';
7
+ export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError.d-8NHtlgzA.cjs';
8
+ export { E as EverfurResult } from '../../EverfurResult.d-BFH-3s6E.cjs';
9
+ export { E as ErrorPolicyPort } from '../../ErrorPolicyPort.d-DirW9hgO.cjs';
11
10
 
12
- /** The push providers the registration route accepts. `apns` is refused with `provider_unsupported` until APNs direct lands. */
13
- type PushProvider = 'expo' | 'fcm' | 'apns';
14
- /** The device platforms the registration route accepts. There is no web push in this version. */
15
- type DevicePlatform = 'ios' | 'android';
16
- /** What to register: the token your notification library obtained, which provider minted it, and which OS it is for. */
17
- interface RegisterDeviceInput {
11
+ interface EverfurNotificationCard {
12
+ readonly id: string;
13
+ /** The app name over the title ("<your brand>"). */
14
+ readonly app: string;
15
+ /** When it arrived, as the member reads it ("now", "2h ago"). */
16
+ readonly when: string;
17
+ readonly title: string;
18
+ readonly body?: string;
19
+ /** A thumbnail on the right (the pet's photo). https or a same-origin path. */
20
+ readonly thumbUrl?: string;
21
+ }
22
+ interface EverfurNotificationStackProps {
23
+ readonly notes: readonly EverfurNotificationCard[];
24
+ readonly onOpen: (note: EverfurNotificationCard) => void;
25
+ /** The app icon in each card's corner (your mark). */
26
+ readonly appIcon?: ReactNode;
27
+ /** The lock screen's date and time over the stack ("Friday, October 16", "9:41"). Absent, none is drawn. */
28
+ readonly date?: string;
29
+ readonly time?: string;
30
+ /** A hint under the stack ("Tap a notification"). */
31
+ readonly hint?: string;
32
+ /** Accessible name of the surface ("Lock screen"). */
33
+ readonly label?: string;
18
34
  /**
19
- * The push token as your library printed it: `ExponentPushToken[...]` from expo-notifications, or the FCM
20
- * registration token from Firebase Messaging. Never an APNs device token in this version.
35
+ * Classes per element (`root`, `date`, `time`, `stack`, `note`, `app`, `text`, `meta`, `thumb`, `hint`); a class
36
+ * drops that element's inline default. Each note also gets `--i` (its index) for a staggered entrance.
21
37
  */
22
- readonly token: string;
23
- readonly provider: PushProvider;
24
- readonly platform: DevicePlatform;
25
- /** Your own stable id for this install, if you keep one (1 to 128 characters). Echoed back, never interpreted. */
26
- readonly installationId?: string;
38
+ readonly classNames?: Readonly<Record<string, string | undefined>>;
39
+ readonly style?: CSSProperties;
27
40
  }
28
- /** The device row as Everfur stored it. The token itself is never echoed. */
29
- interface RegisteredDevice {
30
- /** Everfur's id for this device: pass it to `unregisterDevice` on sign-out. */
31
- readonly deviceId: string;
32
- readonly provider: PushProvider;
33
- readonly platform: DevicePlatform;
34
- readonly installationId: string | null;
35
- /** ISO 8601. */
36
- readonly registeredAt: string;
37
- /** ISO 8601; refreshed by every registration of the same token. */
38
- readonly lastSeenAt: string;
39
- }
40
- /** Both switches, always: the route is a replacement, not a patch. */
41
- interface NotificationPreferencesInput {
42
- readonly pushEnabled: boolean;
43
- readonly emailEnabled: boolean;
44
- }
45
- /** The member's switches as Everfur stored them. */
46
- interface NotificationPreferences {
47
- readonly pushEnabled: boolean;
48
- readonly emailEnabled: boolean;
49
- /** ISO 8601. */
50
- readonly updatedAt: string;
51
- }
52
- interface NotificationsClient {
53
- /**
54
- * `POST /widget/v1/me/devices`. Idempotent: the same token is the same device (its `lastSeenAt` moves), and a token
55
- * another member of your tenant registered rebinds to the calling member. Settles `ok(RegisteredDevice)`;
56
- * `validationFailed` with `reasonCode` `provider_unsupported` or `token_invalid`; `serviceUnavailable` with
57
- * `reasonCode` `device_cipher_unavailable` (retry later); `rateLimited` above ten registrations a minute; the
58
- * not-found error while notifications are not enabled for your tenant; `sessionRequired` for a publishable-key caller.
59
- */
60
- registerDevice(input: RegisterDeviceInput, opts?: {
61
- readonly signal?: AbortSignal;
62
- }): Promise<EverfurResult<RegisteredDevice>>;
63
- /**
64
- * `DELETE /widget/v1/me/devices/{device_id}`. Settles `ok(undefined)` on 204; an unknown id and another member's
65
- * device are the same not-found error.
66
- */
67
- unregisterDevice(deviceId: string, opts?: {
68
- readonly signal?: AbortSignal;
69
- }): Promise<EverfurResult<void>>;
70
- /** `PUT /widget/v1/me/notification-preferences`. Settles `ok(NotificationPreferences)`. */
71
- setPreferences(input: NotificationPreferencesInput, opts?: {
72
- readonly signal?: AbortSignal;
73
- }): Promise<EverfurResult<NotificationPreferences>>;
74
- }
75
- /**
76
- * The part of the runtime this client needs: the current auth at call time, the partner's error policy, and whether
77
- * the runtime is gone. `useEverfurContext().runtime` (any `EverfurRuntime`) satisfies it; the narrow shape keeps this
78
- * subpath's public types to what it reads.
79
- */
80
- interface NotificationsRuntime {
81
- readonly isDisposed: boolean;
82
- readonly registry: {
83
- readonly services: {
84
- authFor(userRef: UserRef | null): AuthContext;
85
- readonly errorPolicy: ErrorPolicyPort | undefined;
86
- };
87
- };
88
- }
89
- /** The sub-reasons a notifications call, or a delivery, can carry as `EverfurError.reasonCode`. */
90
- type NotificationsReasonCode = 'provider_unsupported' | 'token_invalid' | 'device_cipher_unavailable' | 'credentials_missing';
91
- /**
92
- * DEVELOPER-FACING explanations, one per reason. Log them, show them on a developer screen, never render them to a
93
- * member: `displayMessage` is the copy a person sees. `credentials_missing` is not a route answer but the reason a
94
- * delivery is skipped on Everfur's side (visible on the events API and in the partner console); it is here so one
95
- * table explains every reason this surface can name.
96
- */
97
- declare const NOTIFICATIONS_REASON_MESSAGES: Readonly<Record<NotificationsReasonCode, string>>;
98
- /** The developer-facing sentence for an error's `reasonCode`, or null when it carries none this surface knows. */
99
- declare function explainNotificationsReason(error: EverfurError): string | null;
100
- /**
101
- * The client over the runtime under your provider (`useEverfurContext().runtime`). Auth is read at call time, so the
102
- * client can be built once and reused across sign-ins; a disposed runtime settles every verb without a request.
103
- */
104
- declare function createNotificationsClient(runtime: NotificationsRuntime): NotificationsClient;
105
-
106
- /** What the hook needs from you: the token your notification library obtained, or null until you have one. */
107
- interface EverfurNotificationsOptions {
108
- /**
109
- * The push token as your library printed it (`ExponentPushToken[...]`, or an FCM registration token), or null
110
- * while you do not have one (permission not asked, not granted, or the token not yet fetched). Nothing is
111
- * registered without it; pass it as soon as you have it and the hook registers.
112
- */
113
- readonly token: string | null;
114
- /** `expo` for a token from expo-notifications, `fcm` for a Firebase registration token. */
115
- readonly provider: PushProvider;
116
- readonly platform: DevicePlatform;
117
- /** Your own stable id for this install, if you keep one. */
118
- readonly installationId?: string;
119
- }
120
- /**
121
- * `signed_out`: no signed-in user on the provider (nothing to register). `no_token`: a user, no token yet.
122
- * `registering` / `registered` / `failed` / `unavailable`: the registration of the current token.
123
- * `unavailable` is the dark tenant: notifications are not enabled for your client (the routes answer 404).
124
- * `unregistered`: `unregister()` was called; `register()` registers again.
125
- */
126
- type EverfurNotificationsStatus = 'signed_out' | 'no_token' | 'registering' | 'registered' | 'unavailable' | 'failed' | 'unregistered';
127
- interface EverfurNotificationsState {
128
- readonly status: EverfurNotificationsStatus;
129
- /** The device Everfur registered for this install and user, or null. */
130
- readonly device: RegisteredDevice | null;
131
- /** The settled failure of the last registration, or null. `error.displayMessage` is safe to show. */
132
- readonly error: EverfurError | null;
133
- /** Register the current token now (a retry after `failed`, or after `unregister()`). Settles, never throws. */
134
- register(): Promise<EverfurResult<RegisteredDevice>>;
135
- /** Unregister this install's device for the signed-in user. Settles, never throws. */
136
- unregister(): Promise<EverfurResult<void>>;
137
- /** The member's push and email switches, both at once (`PUT /widget/v1/me/notification-preferences`). */
138
- setPreferences(input: NotificationPreferencesInput): Promise<EverfurResult<NotificationPreferences>>;
139
- }
140
- /**
141
- * The notifications client bound to the runtime under your provider, for the imperative calls (`setPreferences`
142
- * from a settings screen, say). Auth is read at call time, so one client serves every sign-in.
143
- */
144
- declare function useEverfurNotificationsClient(): NotificationsClient;
145
- /**
146
- * Register this install's push token for the signed-in member, keep it registered as the token and the user
147
- * change, and unregister it before sign-out. Call it once, high in the tree under `EverfurProvider`.
148
- */
149
- declare function useEverfurNotifications(options: EverfurNotificationsOptions): EverfurNotificationsState;
150
-
151
- /** The version of the routing block this release reads. */
152
- declare const EVERFUR_NOTIFICATION_VERSION = 1;
153
- /** The closed target kinds, in the backend's order (`partner_target.py` TARGET_KINDS). */
154
- declare const EVERFUR_NOTIFICATION_TARGET_KINDS: readonly ["record_request", "pet", "visit", "case"];
155
- /** One target kind. */
156
- type EverfurNotificationTargetKind = (typeof EVERFUR_NOTIFICATION_TARGET_KINDS)[number];
157
- /**
158
- * The event types Everfur builds a push target for (`partner_target.py` TARGET_BUILDERS), in its order. The member
159
- * events, the urgency verdict and the endpoint test event reach the partner's webhook only and never a device, and
160
- * `visit.completed`, `visit.rescheduled` and `visit.ended` carry no consumer copy, so they are never pushed either;
161
- * they are listed because the platform builds their target.
162
- */
163
- declare const EVERFUR_NOTIFICATION_EVENT_TYPES: readonly ["record_request.updated", "record.ready", "pet.vaccination.due", "visit.booked", "visit.cancelled", "visit.completed", "visit.no_show", "visit.rescheduled", "visit.reminder", "visit.followup_sent", "visit.message_received", "visit.ended", "chat.follow_up_due", "chat.reminder_due", "record.activation"];
164
- /** One pushed event type. */
165
- type EverfurNotificationEventType = (typeof EVERFUR_NOTIFICATION_EVENT_TYPES)[number];
166
- /** What a tapped notification is about, keyed on `kind`. The optional references are null when the push carried none. */
167
- type EverfurNotificationTarget = {
168
- /**
169
- * A records request (`record_request.updated`, `record.ready`, and `record.activation`, which says what the
170
- * request's parse found): open that request.
171
- */
172
- readonly kind: 'record_request';
173
- readonly requestId: RecordsRequestId;
174
- readonly petRef: PetRef | null;
175
- } | {
176
- /** A pet: `pet.vaccination.due` opens that pet's records, `chat.reminder_due` that pet's chat. */
177
- readonly kind: 'pet';
178
- readonly petRef: PetRef;
179
- } | {
180
- /**
181
- * A vet visit (`visit.*`): open that visit. `visitRef` is the partner visit reference the visit events carry.
182
- * `intent` is what to open for it, derived from the event type with the consumer app's routing (the push
183
- * itself carries none): `visit` for a booking or a change to it, `join` for a reminder, `messages` for the
184
- * vet's reply or the follow-up, `summary` for a completed visit. Pass both to `useVetVisit().openVisit`.
185
- * `null` for a cancelled or missed visit: there is nothing left to open, so route to a new booking.
186
- */
187
- readonly kind: 'visit';
188
- readonly visitRef: string;
189
- readonly petRef: PetRef | null;
190
- readonly intent: VetVisitIntent | null;
191
- } | {
192
- /** A follow-up case (`chat.follow_up_due`): open the conversation the check-in landed in. */
193
- readonly kind: 'case';
194
- readonly caseRef: string;
195
- readonly conversationId: ConversationId | null;
196
- readonly petRef: PetRef | null;
197
- };
198
- /** A parsed push: the event it announces and the thing to open. Frozen. */
199
- interface EverfurNotification {
200
- /** `evt_` plus the public event id, the same id the webhook envelope for this event carries. */
201
- readonly eventId: string;
202
- readonly eventType: EverfurNotificationEventType;
203
- readonly target: EverfurNotificationTarget;
204
- }
205
- /**
206
- * Read the Everfur routing block out of a received push, or null when there is none or it is not one Everfur would
207
- * send. Pure and total: it never throws, whatever it is handed.
208
- *
209
- * Pass the object your notification library gave you: an expo-notifications `Notification` or `NotificationResponse`,
210
- * an FCM `RemoteMessage`, or its `data` map. Route on `target.kind`; `eventType` says why the push was sent.
211
- */
212
- declare function parseEverfurNotification(payload: unknown): EverfurNotification | null;
41
+ /** Tappable notification cards, stacked as a lock screen shows them. */
42
+ declare function EverfurNotificationStack(props: EverfurNotificationStackProps): ReactNode;
213
43
 
214
- export { AuthContext, ConversationId, type DevicePlatform, EVERFUR_NOTIFICATION_EVENT_TYPES, EVERFUR_NOTIFICATION_TARGET_KINDS, EVERFUR_NOTIFICATION_VERSION, ErrorPolicyPort, EverfurError, type EverfurNotification, type EverfurNotificationEventType, type EverfurNotificationTarget, type EverfurNotificationTargetKind, type EverfurNotificationsOptions, type EverfurNotificationsState, type EverfurNotificationsStatus, EverfurResult, NOTIFICATIONS_REASON_MESSAGES, type NotificationPreferences, type NotificationPreferencesInput, type NotificationsClient, type NotificationsReasonCode, type NotificationsRuntime, PetRef, type PushProvider, RecordsRequestId, type RegisterDeviceInput, type RegisteredDevice, UserRef, VetVisitIntent, createNotificationsClient, explainNotificationsReason, parseEverfurNotification, useEverfurNotifications, useEverfurNotificationsClient };
44
+ export { type EverfurNotificationCard, EverfurNotificationStack, type EverfurNotificationStackProps };