@everfur/sdk 0.18.3 → 0.20.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 (221) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/dist/{Chat.d-CKKuXVw5.d.ts → Chat.d-D61LLPJh.d.ts} +1 -1
  3. package/dist/{Chat.d-BEbRI8FZ.d.cts → Chat.d-IpxKa9gS.d.cts} +1 -1
  4. package/dist/{DepthViews.d-CiU4f98J.d.ts → DepthViews.d-C8EsR8Gq.d.ts} +1 -1
  5. package/dist/{DepthViews.d-BiePRa3Z.d.cts → DepthViews.d-CDIL4mPa.d.cts} +1 -1
  6. package/dist/{DepthViews.d-Chn2xwZu.d.cts → DepthViews.d-Q1nqdH8n.d.cts} +1 -1
  7. package/dist/{DepthViews.d-_WMIpymE.d.ts → DepthViews.d-w2o4Nf7r.d.ts} +1 -1
  8. package/dist/{RecordsPage.d-CtNzoxre.d.cts → RecordsPage.d-BSjZOHu8.d.cts} +11 -5
  9. package/dist/{RecordsPage.d-CRRJM35Q.d.ts → RecordsPage.d-DqhM_rCr.d.ts} +11 -5
  10. package/dist/animations/index.cjs +1 -94
  11. package/dist/animations/index.d.cts +3 -3
  12. package/dist/animations/index.d.ts +3 -3
  13. package/dist/animations/index.js +1 -94
  14. package/dist/{attachments.d-BLEOCUU7.d.cts → attachments.d-BviU_Tja.d.cts} +2 -2
  15. package/dist/{attachments.d-DRkqNR-o.d.ts → attachments.d-DZVfHHnY.d.ts} +2 -2
  16. package/dist/{bookingCopy.d-CrUufdoE.d.ts → bookingCopy.d-5V3erfXD.d.ts} +2 -2
  17. package/dist/{bookingCopy.d-CoiNXrY8.d.cts → bookingCopy.d-DlzUPsFE.d.cts} +2 -2
  18. package/dist/{casesRepository.d-OyZOSNNv.d.cts → casesRepository.d-7Us2O-z8.d.cts} +1 -1
  19. package/dist/{casesRepository.d-DhI69yuj.d.ts → casesRepository.d-Dqg-KbpA.d.ts} +1 -1
  20. package/dist/chat/index.cjs +29 -119
  21. package/dist/chat/index.d.cts +11 -10
  22. package/dist/chat/index.d.ts +11 -10
  23. package/dist/chat/index.js +30 -120
  24. package/dist/chat/lite/index.cjs +29 -119
  25. package/dist/chat/lite/index.d.cts +11 -10
  26. package/dist/chat/lite/index.d.ts +11 -10
  27. package/dist/chat/lite/index.js +30 -120
  28. package/dist/{attachments.d-CeXw6R7_.d.cts → chatHandoffToken.d-B9pjkEfl.d.cts} +33 -9
  29. package/dist/{attachments.d-d1rWAw9K.d.ts → chatHandoffToken.d-TYcD8NIi.d.ts} +33 -9
  30. package/dist/{ports.d-CIfa_XF6.d.ts → chatTypes.d-DPALEQoW.d.ts} +41 -52
  31. package/dist/{ports.d--OjPUqPb.d.cts → chatTypes.d-RnQ5R4zP.d.cts} +41 -52
  32. package/dist/client/index.cjs +2 -95
  33. package/dist/client/index.d.cts +7 -7
  34. package/dist/client/index.d.ts +7 -7
  35. package/dist/client/index.js +2 -95
  36. package/dist/{clinicBatch.d-DVahpaN3.d.cts → clinicBatch.d-C6MzLj3X.d.cts} +3 -3
  37. package/dist/{clinicBatch.d-CcqnQ7-d.d.ts → clinicBatch.d-t9hkown2.d.ts} +3 -3
  38. package/dist/{clinicRequestProps.d-CjsMg_OD.d.ts → clinicRequestProps.d-BuMuGoVZ.d.ts} +1 -1
  39. package/dist/{clinicRequestProps.d-1dCtouGA.d.cts → clinicRequestProps.d-DjzUdDFx.d.cts} +1 -1
  40. package/dist/{config.d-KX-EkQ9j.d.ts → config.d-BnZkxI5a.d.ts} +1 -1
  41. package/dist/{config.d-Z_fyOZke.d.cts → config.d-DoC-XaJ0.d.cts} +1 -1
  42. package/dist/consent/index.cjs +2 -95
  43. package/dist/consent/index.d.cts +5 -5
  44. package/dist/consent/index.d.ts +5 -5
  45. package/dist/consent/index.js +2 -95
  46. package/dist/{context.d-DV5E_2Fs.d.cts → context.d-BAh7C7T4.d.cts} +7 -6
  47. package/dist/{context.d-DY6d4qXG.d.ts → context.d-z2zIjKEb.d.ts} +7 -6
  48. package/dist/{copy.d-CMY9OoCC.d.cts → copy.d-BkX6G-Ws.d.cts} +2 -2
  49. package/dist/{copy.d-BPzpKGGc.d.ts → copy.d-DLxgHsZZ.d.ts} +2 -2
  50. package/dist/core/index.cjs +6 -99
  51. package/dist/core/index.d.cts +15 -14
  52. package/dist/core/index.d.ts +15 -14
  53. package/dist/core/index.js +6 -99
  54. package/dist/{depth.d-qVYPByPb.d.cts → depth.d-aXddCjyh.d.cts} +3 -3
  55. package/dist/{depth.d-B_qNSgXr.d.ts → depth.d-z2FlzY3x.d.ts} +3 -3
  56. package/dist/{entitlementRepository.d-CwTVi7he.d.cts → entitlementRepository.d-CDCF8eFx.d.cts} +2 -2
  57. package/dist/{entitlementRepository.d-BXDWPyP8.d.ts → entitlementRepository.d-Cgmy4Opa.d.ts} +2 -2
  58. package/dist/{focus.d-BPofD7ow.d.ts → focus.d-C2fd_5MW.d.ts} +2 -2
  59. package/dist/{focus.d-DJD4lWFB.d.cts → focus.d-q_sXGhLn.d.cts} +2 -2
  60. package/dist/health-plan/index.cjs +1 -94
  61. package/dist/health-plan/index.d.cts +10 -10
  62. package/dist/health-plan/index.d.ts +10 -10
  63. package/dist/health-plan/index.js +1 -94
  64. package/dist/{idempotency.d-BmYuCb-n.d.cts → idempotency.d-Bqdyv_yn.d.cts} +1 -1
  65. package/dist/{idempotency.d-BVO0mU2R.d.ts → idempotency.d-DlAPAxD5.d.ts} +1 -1
  66. package/dist/{identity.d-CRVNfZzQ.d.ts → identity.d-BWZiaByn.d.ts} +1 -1
  67. package/dist/{identity.d-3ROlHbnP.d.cts → identity.d-CooKscNj.d.cts} +1 -1
  68. package/dist/index.cjs +30 -120
  69. package/dist/index.d.cts +14 -13
  70. package/dist/index.d.ts +14 -13
  71. package/dist/index.js +31 -121
  72. package/dist/{introEvents.d-DGQDEPJi.d.cts → introEvents.d-C8bDDiK6.d.cts} +1 -1
  73. package/dist/{introEvents.d-cvMxJfYd.d.ts → introEvents.d-baVM016i.d.ts} +1 -1
  74. package/dist/{models.d-BSqvbTE1.d.cts → models.d-BN53M9sU.d.cts} +52 -1
  75. package/dist/{models.d-DOwnr8fi.d.ts → models.d-Bhq9p6Wa.d.ts} +52 -1
  76. package/dist/notifications/inbox/index.cjs +44 -0
  77. package/dist/notifications/inbox/index.d.cts +50 -0
  78. package/dist/notifications/inbox/index.d.ts +50 -0
  79. package/dist/notifications/inbox/index.js +44 -0
  80. package/dist/notifications/index.cjs +18 -98
  81. package/dist/notifications/index.d.cts +12 -6
  82. package/dist/notifications/index.d.ts +12 -6
  83. package/dist/notifications/index.js +18 -98
  84. package/dist/{optInView.d-DIGu47Lz.d.ts → optInView.d-C04aX0Hs.d.ts} +2 -2
  85. package/dist/{optInView.d-CU1U_K-B.d.cts → optInView.d-D_D7fs6C.d.cts} +2 -2
  86. package/dist/parse.d-DYsx1Q2V.d.cts +168 -0
  87. package/dist/parse.d-Do0sdAgm.d.ts +168 -0
  88. package/dist/{pets.d-BRsbR8QU.d.ts → pets.d-CkFNO-x-.d.ts} +1 -1
  89. package/dist/{pets.d-5SMtOAwB.d.cts → pets.d-oJ2OIY22.d.cts} +1 -1
  90. package/dist/{petsRepository.d-DWsChqAS.d.ts → petsRepository.d-CKCi6rtp.d.ts} +1 -1
  91. package/dist/{petsRepository.d-DEnoZn92.d.cts → petsRepository.d-VWMyIeIJ.d.cts} +1 -1
  92. package/dist/photo/index.cjs +1 -94
  93. package/dist/photo/index.js +1 -94
  94. package/dist/records/depth/index.cjs +2 -95
  95. package/dist/records/depth/index.d.cts +11 -11
  96. package/dist/records/depth/index.d.ts +11 -11
  97. package/dist/records/depth/index.js +2 -95
  98. package/dist/records/index.cjs +17 -108
  99. package/dist/records/index.d.cts +47 -17
  100. package/dist/records/index.d.ts +47 -17
  101. package/dist/records/index.js +17 -108
  102. package/dist/{requestFunnel.d-CQX_Z1Hi.d.cts → requestFunnel.d-By0-I8Cp.d.cts} +2 -2
  103. package/dist/{requestFunnel.d-DSvCGf4J.d.ts → requestFunnel.d-DVCytzTE.d.ts} +2 -2
  104. package/dist/{parse.d-icynBIS-.d.ts → route.d-Ay-lRct1.d.ts} +90 -53
  105. package/dist/{parse.d-GzZJYu__.d.cts → route.d-DQDX6QFn.d.cts} +90 -53
  106. package/dist/{runtimeTypes.d-Be_vhOER.d.ts → runtimeTypes.d-C49Cgb9c.d.ts} +39 -5
  107. package/dist/{runtimeTypes.d-sXpNYnJp.d.cts → runtimeTypes.d-DUVNpR6g.d.cts} +39 -5
  108. package/dist/{screenProps.d-DpMK2_gi.d.ts → screenProps.d-B_arD3Lh.d.ts} +2 -2
  109. package/dist/{screenProps.d-BW6PZh5k.d.cts → screenProps.d-BgxlmfG5.d.cts} +2 -2
  110. package/dist/server/events/index.cjs +2 -95
  111. package/dist/server/events/index.d.cts +92 -5
  112. package/dist/server/events/index.d.ts +92 -5
  113. package/dist/server/events/index.js +2 -95
  114. package/dist/server/index.cjs +2 -95
  115. package/dist/server/index.d.cts +3 -3
  116. package/dist/server/index.d.ts +3 -3
  117. package/dist/server/index.js +2 -95
  118. package/dist/{sheetSeam.d-BBuEIVsa.d.cts → sheetSeam.d-B9iQqG_I.d.cts} +2 -2
  119. package/dist/{sheetSeam.d-B09jf4YC.d.ts → sheetSeam.d-CtuKILqp.d.ts} +2 -2
  120. package/dist/shop/index.d.cts +3 -3
  121. package/dist/shop/index.d.ts +3 -3
  122. package/dist/tabs/index.cjs +3 -96
  123. package/dist/tabs/index.d.cts +8 -8
  124. package/dist/tabs/index.d.ts +8 -8
  125. package/dist/tabs/index.js +3 -96
  126. package/dist/televet/booking/index.cjs +1 -94
  127. package/dist/televet/booking/index.d.cts +6 -6
  128. package/dist/televet/booking/index.d.ts +6 -6
  129. package/dist/televet/booking/index.js +1 -94
  130. package/dist/televet/index.cjs +1 -94
  131. package/dist/televet/index.js +1 -94
  132. package/dist/testing/index.cjs +1 -94
  133. package/dist/testing/index.d.cts +1 -1
  134. package/dist/testing/index.d.ts +1 -1
  135. package/dist/testing/index.js +1 -94
  136. package/dist/testing/rn/index.cjs +1 -94
  137. package/dist/testing/rn/index.d.cts +9 -8
  138. package/dist/testing/rn/index.d.ts +9 -8
  139. package/dist/testing/rn/index.js +1 -94
  140. package/dist/testing/web/index.cjs +1 -94
  141. package/dist/testing/web/index.d.cts +10 -9
  142. package/dist/testing/web/index.d.ts +10 -9
  143. package/dist/testing/web/index.js +1 -94
  144. package/dist/texting/index.cjs +1 -94
  145. package/dist/texting/index.d.cts +5 -5
  146. package/dist/texting/index.d.ts +5 -5
  147. package/dist/texting/index.js +1 -94
  148. package/dist/{threadOptions.d-DMOn3mmj.d.ts → threadOptions.d-Cbhjjb9_.d.ts} +2 -2
  149. package/dist/{threadOptions.d-Csmb-XgL.d.cts → threadOptions.d-pZXzsd2d.d.cts} +2 -2
  150. package/dist/{timelineRows.d-B0XZevKx.d.ts → timelineRows.d-BHxMeZzl.d.ts} +1 -1
  151. package/dist/{timelineRows.d-Kllr7Mcu.d.cts → timelineRows.d-DlMs82N1.d.cts} +1 -1
  152. package/dist/unreadStore.d-gCsleb6l.d.ts +74 -0
  153. package/dist/unreadStore.d-w5x6lEpR.d.cts +74 -0
  154. package/dist/{useHealthPlanSubscription.d-bNRntgWe.d.ts → useHealthPlanSubscription.d-BoC7H85G.d.ts} +2 -2
  155. package/dist/{useHealthPlanSubscription.d-C-c_mQ4u.d.cts → useHealthPlanSubscription.d-CZn06-lu.d.cts} +2 -2
  156. package/dist/useInboxUnread.d-DW0dpWdv.d.cts +206 -0
  157. package/dist/useInboxUnread.d-vYpOXVRv.d.ts +206 -0
  158. package/dist/{usePresentation.d-CmQgbrZr.d.ts → usePresentation.d-CgvwGb2A.d.ts} +2 -2
  159. package/dist/{usePresentation.d-BHKhBKQn.d.cts → usePresentation.d-CyCEJ6nj.d.cts} +2 -2
  160. package/dist/{useRecords.d-BYNX01El.d.cts → useRecords.d-BMSW4aRD.d.cts} +46 -3
  161. package/dist/{useRecords.d-DWk61a4c.d.ts → useRecords.d-Cv1nhZrv.d.ts} +46 -3
  162. package/dist/{useRecordsDepth.d-BilHZaR4.d.ts → useRecordsDepth.d-CbXhWbx7.d.ts} +1 -1
  163. package/dist/{useRecordsDepth.d-WW_2cWwU.d.cts → useRecordsDepth.d-CcbL98FD.d.cts} +1 -1
  164. package/dist/{appStateLifecycle.d-JuPhh7Oy.d.ts → useUnread.d-BsZKbLp9.d.ts} +49 -14
  165. package/dist/{appStateLifecycle.d-BQcy4J5O.d.cts → useUnread.d-CfF2Cx-q.d.cts} +49 -14
  166. package/dist/video/index.cjs +1 -94
  167. package/dist/video/index.js +1 -94
  168. package/dist/{view.d-BTnjZu2S.d.cts → view.d-CF3AP3T7.d.cts} +5 -5
  169. package/dist/{view.d-BtN_L_UF.d.ts → view.d-DdyOf0T0.d.ts} +5 -5
  170. package/dist/web/consent/index.cjs +2 -95
  171. package/dist/web/consent/index.d.cts +5 -5
  172. package/dist/web/consent/index.d.ts +5 -5
  173. package/dist/web/consent/index.js +2 -95
  174. package/dist/web/health-plan/index.cjs +1 -94
  175. package/dist/web/health-plan/index.d.cts +12 -12
  176. package/dist/web/health-plan/index.d.ts +12 -12
  177. package/dist/web/health-plan/index.js +1 -94
  178. package/dist/web/inbox/index.cjs +49 -0
  179. package/dist/web/inbox/index.d.cts +191 -0
  180. package/dist/web/inbox/index.d.ts +191 -0
  181. package/dist/web/inbox/index.js +49 -0
  182. package/dist/web/index.cjs +28 -118
  183. package/dist/web/index.d.cts +80 -40
  184. package/dist/web/index.d.ts +80 -40
  185. package/dist/web/index.js +28 -118
  186. package/dist/web/intro/index.cjs +3 -96
  187. package/dist/web/intro/index.d.cts +8 -8
  188. package/dist/web/intro/index.d.ts +8 -8
  189. package/dist/web/intro/index.js +3 -96
  190. package/dist/web/notifications/index.cjs +16 -96
  191. package/dist/web/notifications/index.d.cts +8 -3
  192. package/dist/web/notifications/index.d.ts +8 -3
  193. package/dist/web/notifications/index.js +16 -96
  194. package/dist/web/records/depth/index.cjs +2 -95
  195. package/dist/web/records/depth/index.d.cts +11 -11
  196. package/dist/web/records/depth/index.d.ts +11 -11
  197. package/dist/web/records/depth/index.js +2 -95
  198. package/dist/web/records/index.cjs +16 -107
  199. package/dist/web/records/index.d.cts +43 -19
  200. package/dist/web/records/index.d.ts +43 -19
  201. package/dist/web/records/index.js +16 -107
  202. package/dist/web/records-sheet/index.cjs +2 -95
  203. package/dist/web/records-sheet/index.d.cts +4 -4
  204. package/dist/web/records-sheet/index.d.ts +4 -4
  205. package/dist/web/records-sheet/index.js +2 -95
  206. package/dist/web/shop/index.d.cts +3 -3
  207. package/dist/web/shop/index.d.ts +3 -3
  208. package/dist/web/televet/booking/index.cjs +1 -94
  209. package/dist/web/televet/booking/index.d.cts +6 -6
  210. package/dist/web/televet/booking/index.d.ts +6 -6
  211. package/dist/web/televet/booking/index.js +1 -94
  212. package/dist/web/televet/index.cjs +1 -94
  213. package/dist/web/televet/index.js +1 -94
  214. package/dist/web/texting/index.cjs +1 -94
  215. package/dist/web/texting/index.d.cts +5 -5
  216. package/dist/web/texting/index.d.ts +5 -5
  217. package/dist/web/texting/index.js +1 -94
  218. package/notifications/inbox/package.json +8 -0
  219. package/package.json +29 -1
  220. package/web/inbox/native-blocked.cjs +12 -0
  221. package/web/inbox/package.json +8 -0
package/dist/index.js CHANGED
@@ -1,100 +1,7 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- import{z}from"zod";import{createContext,forwardRef,createElement,useEffect,useState,useSyncExternalStore,useContext,useMemo,useCallback,useRef,useReducer,useLayoutEffect,Component,Fragment as Fragment$1}from"react";import{Platform,TextInput as TextInput$1,StyleSheet,AccessibilityInfo,useColorScheme,Dimensions,PixelRatio,View,AppState,Text as Text$1,KeyboardAvoidingView,Keyboard,Pressable,Modal,ScrollView,ActivityIndicator,Image,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList,Linking}from"react-native";import{SafeAreaProvider,useSafeAreaInsets}from"react-native-safe-area-context";import EventSource from"react-native-sse";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as bookingExperience from"@everfur/sdk/televet/booking";import*as texting from"@everfur/sdk/texting";function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}function ok(value,warning){/* @__PURE__ */
2
+ import{z}from"zod";import{createContext,forwardRef,createElement,useEffect,useState,useSyncExternalStore,useContext,useMemo,useCallback,useRef,useReducer,useLayoutEffect,Component,Fragment as Fragment$1}from"react";import{Platform,TextInput as TextInput$1,StyleSheet,AccessibilityInfo,useColorScheme,Dimensions,PixelRatio,View,AppState,Text as Text$1,Linking,KeyboardAvoidingView,Keyboard,Pressable,Modal,ScrollView,ActivityIndicator,Image,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList}from"react-native";import{SafeAreaProvider,useSafeAreaInsets}from"react-native-safe-area-context";import EventSource from"react-native-sse";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as bookingExperience from"@everfur/sdk/televet/booking";import*as texting from"@everfur/sdk/texting";function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}function ok(value,warning){/* @__PURE__ */
3
3
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
4
- return Object.freeze({ok:false,error:error})}function isOk(r){return r.ok}function isErr(r){return!r.ok}var EverfurThrownError=class _EverfurThrownError extends Error{constructor(error){super(`${error.code}: ${error.displayMessage}`),this.name="EverfurThrownError",this.error=error,this.code=error.code,this.category=error.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(r){if(r.ok)return r.value;throw new EverfurThrownError(r.error)}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var MAX_USER_REF_LEN=128,MAX_PET_REF_LEN=128,CONTROL_CHAR=/[\u0000-\u001F\u007F]/,UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_PET_REF_LEN)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${MAX_PET_REF_LEN} characters`);if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","petRef must be printable (no control characters)");return v}function userRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_USER_REF_LEN)throw new EverfurConfigError("invalid-argument",`userRef must be 1..${MAX_USER_REF_LEN} characters`);if(v.includes("@"))throw new EverfurConfigError("invalid-argument","userRef must not contain '@'");if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","userRef must be printable (no control characters)");return v}function conversationId(raw){if(!UUID_RE.test(raw))throw new EverfurConfigError("invalid-argument","conversationId must be a UUID");return raw}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
5
- /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
6
- /* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
7
- /* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
8
- /* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
9
- /* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
10
- /* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
11
- /* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
12
- /* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
13
- /* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
14
- /* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
15
- /* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
16
- /* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
17
- /* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
18
- /* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
19
- /* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
20
- /* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
21
- /* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
22
- /* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
23
- /* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
24
- /* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
25
- /* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
26
- /* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
27
- /* @__PURE__ */Object.freeze({wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
28
- /* @__PURE__ */Object.freeze({wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
29
- /* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
30
- /* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
31
- /* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
32
- /* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
33
- /* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
34
- /* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
35
- /* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
36
- /* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
37
- /* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
38
- /* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
39
- /* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
40
- /* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
41
- /* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
42
- /* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
43
- /* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
44
- /* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
45
- /* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
46
- /* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
47
- /* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
48
- /* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
49
- /* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
50
- /* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
51
- /* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
52
- /* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
53
- /* @__PURE__ */Object.freeze({wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false}),
54
- /* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
55
- /* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
56
- /* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
57
- /* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
58
- /* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
59
- /* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
60
- /* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
61
- /* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
62
- /* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
63
- /* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
64
- /* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
65
- /* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
66
- /* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
67
- /* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
68
- /* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
69
- /* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
70
- /* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
71
- /* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
72
- /* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
73
- /* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
74
- /* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
75
- /* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
76
- /* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
77
- /* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
78
- /* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
79
- /* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
80
- /* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
81
- /* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
82
- /* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
83
- /* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
84
- /* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
85
- /* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
86
- /* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
87
- /* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
88
- /* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
89
- /* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
90
- /* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
91
- /* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
92
- /* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
93
- /* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
94
- /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
95
- /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
96
- /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
97
- /* @__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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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)}function shouldRetry(code,frameRetryable=false){return frameRetryable||isAutoRetryable(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)}function canRecreateOnNotFound(code){return code==="conversationNotFound"}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)}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var FILENAMES=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function recordsUploadFilename(type){return isAcceptedUploadType(type,RECORDS_PHOTO_CONTENT_TYPES)?FILENAMES[type]:FILENAMES["application/pdf"]}var FILE_FIELD="file",NOT_SENT="multipart upload failed";function postRnMultipart(post){let form;try{form=new FormData;for(let[name,value]of Object.entries(post.fields))form.append(name,value);form.append(FILE_FIELD,post.file)}catch{return Promise.reject(new Error(NOT_SENT))}return post.fetch!==void 0?postWithFetch(post.fetch,post.url,form,post.signal):postWithXhr(post.url,form,post.signal)}function stored(status){return status>=200&&status<300}function postWithXhr(url,form,signal){return new Promise((resolve,reject)=>{let Xhr=globalThis.XMLHttpRequest;if(typeof Xhr!="function"||signal?.aborted===true){reject(new Error(NOT_SENT));return}let onAbort=null,release=()=>{onAbort!==null&&signal?.removeEventListener("abort",onAbort)},fail=()=>{release(),reject(new Error(NOT_SENT))};try{let xhr=new Xhr;xhr.open("POST",url),xhr.withCredentials=!1,xhr.onload=()=>{release(),resolve(stored(xhr.status))},xhr.onerror=fail,xhr.ontimeout=fail,xhr.onabort=fail,signal!==void 0&&(onAbort=()=>{try{xhr.abort()}finally{fail()}},signal.addEventListener("abort",onAbort,{once:!0})),xhr.send(form)}catch{fail()}})}function postWithFetch(send,url,form,signal){return Promise.resolve().then(()=>send(url,{method:"POST",body:form,credentials:"omit",...signal?{signal:signal}:{}})).then(res=>res.ok)}var NO_URI="records upload: the file handle has no uri",FAILED="records upload failed";function createRnRecordsUploadTransport(options={}){/* @__PURE__ */
4
+ return Object.freeze({ok:false,error:error})}function isOk(r){return r.ok}function isErr(r){return!r.ok}var EverfurThrownError=class _EverfurThrownError extends Error{constructor(error){super(`${error.code}: ${error.displayMessage}`),this.name="EverfurThrownError",this.error=error,this.code=error.code,this.category=error.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(r){if(r.ok)return r.value;throw new EverfurThrownError(r.error)}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var MAX_USER_REF_LEN=128,MAX_PET_REF_LEN=128,CONTROL_CHAR=/[\u0000-\u001F\u007F]/,UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_PET_REF_LEN)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${MAX_PET_REF_LEN} characters`);if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","petRef must be printable (no control characters)");return v}function userRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_USER_REF_LEN)throw new EverfurConfigError("invalid-argument",`userRef must be 1..${MAX_USER_REF_LEN} characters`);if(v.includes("@"))throw new EverfurConfigError("invalid-argument","userRef must not contain '@'");if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","userRef must be printable (no control characters)");return v}function conversationId(raw){if(!UUID_RE.test(raw))throw new EverfurConfigError("invalid-argument","conversationId must be a UUID");return raw}var RETRYABILITY_ROWS=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze(RETRYABILITY_ROWS.map(row=>/* @__PURE__ */Object.freeze(row)));/* @__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",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable"}),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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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)}function shouldRetry(code,frameRetryable=false){return frameRetryable||isAutoRetryable(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)}function canRecreateOnNotFound(code){return code==="conversationNotFound"}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)}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var FILENAMES=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function recordsUploadFilename(type){return isAcceptedUploadType(type,RECORDS_PHOTO_CONTENT_TYPES)?FILENAMES[type]:FILENAMES["application/pdf"]}var FILE_FIELD="file",NOT_SENT="multipart upload failed";function postRnMultipart(post){let form;try{form=new FormData;for(let[name,value]of Object.entries(post.fields))form.append(name,value);form.append(FILE_FIELD,post.file)}catch{return Promise.reject(new Error(NOT_SENT))}return post.fetch!==void 0?postWithFetch(post.fetch,post.url,form,post.signal):postWithXhr(post.url,form,post.signal)}function stored(status){return status>=200&&status<300}function postWithXhr(url,form,signal){return new Promise((resolve,reject)=>{let Xhr=globalThis.XMLHttpRequest;if(typeof Xhr!="function"||signal?.aborted===true){reject(new Error(NOT_SENT));return}let onAbort=null,release=()=>{onAbort!==null&&signal?.removeEventListener("abort",onAbort)},fail=()=>{release(),reject(new Error(NOT_SENT))};try{let xhr=new Xhr;xhr.open("POST",url),xhr.withCredentials=!1,xhr.onload=()=>{release(),resolve(stored(xhr.status))},xhr.onerror=fail,xhr.ontimeout=fail,xhr.onabort=fail,signal!==void 0&&(onAbort=()=>{try{xhr.abort()}finally{fail()}},signal.addEventListener("abort",onAbort,{once:!0})),xhr.send(form)}catch{fail()}})}function postWithFetch(send,url,form,signal){return Promise.resolve().then(()=>send(url,{method:"POST",body:form,credentials:"omit",...signal?{signal:signal}:{}})).then(res=>res.ok)}var NO_URI="records upload: the file handle has no uri",FAILED="records upload failed";function createRnRecordsUploadTransport(options={}){/* @__PURE__ */
98
5
  return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:{uri:file.uri,name:recordsUploadFilename(file.mimeType),type:partType(file.mimeType)},signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}function partType(mimeType){return isAcceptedUploadType(mimeType,RECORDS_PHOTO_CONTENT_TYPES)?mimeType:"application/pdf"}var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var defaultErrorPolicy=/* @__PURE__ */Object.freeze({shouldRetry(code,attempt){return isAutoRetryable(code)&&attempt<MAX_RETRY_ATTEMPTS},maxAttempts(){return MAX_RETRY_ATTEMPTS}});var unavailableCamera=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(name,load,validate2){let candidate;try{candidate=load()}catch(cause){return frozenUnavailable(`optional peer '${name}' is not installed: ${describe(cause)}`)}let resolved=unwrapDefault(candidate);return resolved==null?frozenUnavailable(`optional peer '${name}' resolved to no module`):validate2&&!validate2(resolved)?frozenUnavailable(`optional peer '${name}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:resolved})}function unwrapDefault(candidate){return typeof candidate=="object"&&candidate!==null&&"default"in candidate&&Object.keys(candidate).length<=2?candidate.default:candidate}function frozenUnavailable(reason){/* @__PURE__ */
99
6
  return Object.freeze({available:false,module:null,reason:reason})}function describe(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"unknown load error"}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function acceptedFrame(streamId,lastEventId,serverRequestId=null){/* @__PURE__ */
100
7
  return Object.freeze({kind:"accepted",streamId:streamId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function heartbeatFrame(lastEventId,serverRequestId=null){/* @__PURE__ */
@@ -104,11 +11,11 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
104
11
  return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
105
12
  return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
106
13
  return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
107
- return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}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 createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}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}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending.length>0?pending.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=createUtf8Decoder(),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.18.3",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
14
+ return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}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 createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}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}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending.length>0?pending.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=createUtf8Decoder(),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.20.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
108
15
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
109
16
  return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
110
17
  return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
111
- return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line of data.split(`\n`))block+=`data: ${line}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline2=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline2.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline2.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base2,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base2}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline2,caller){if(!caller)return deadline2;let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}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,base2=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 deadline2=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline2.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline2.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(
18
+ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record2=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record2!==null&&namesAWait(record2)?body:{...record2??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line of data.split(`\n`))block+=`data: ${line}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline2=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline2.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline2.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base2,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base2}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline2,caller){if(!caller)return deadline2;let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}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,base2=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 deadline2=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline2.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline2.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(
112
19
  /* @__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,serverRequestId:null})}}/* @__PURE__ */
113
20
  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 at=findResetsAt(error.raw);if(at!==null){let delta=at-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(deadline2,caller){let noop2=()=>{};if(!caller)return{signal:deadline2,dispose:noop2};let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop2};let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline2.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})})}var CHECKIN_ANSWERS=/* @__PURE__ */Object.freeze(["better","same","worse"]),CASE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function invalid(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}function petPath(petRef2){return typeof petRef2!="string"||petRef2.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):hasLoneSurrogate(petRef2)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(petRef2)}/cases`}var str=v=>typeof v=="string"?v:null,count=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function caseFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,caseId=str(o.case_id),status=str(o.status);if(caseId===null||status===null)return null;let last=str(o.last_response);/* @__PURE__ */
114
21
  return Object.freeze({caseId:caseId,status:status,bodyLocation:str(o.body_location),lastResponse:last!==null&&CHECKIN_ANSWERS.includes(last)?last:null,checkInDueAt:str(o.check_in_due_at),openedAt:str(o.opened_at),resolvedAt:str(o.resolved_at),resolutionText:str(o.resolution_text),checkinAskCount:count(o.checkin_ask_count),checkinAnswerCount:count(o.checkin_answer_count)})}function createCasesRepositoryOver(funnel){return{async list(petRef2,opts){let path=petPath(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("cases.list",{method:"GET",path:path,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let rows=typeof res.value=="object"&&res.value!==null?res.value.cases:null;if(!Array.isArray(rows))return malformed();let cases=rows.map(caseFromWire);return cases.every(c=>c!==null)?ok(/* @__PURE__ */Object.freeze(cases)):malformed()},async checkin(petRef2,caseId,answer,opts){let path=petPath(petRef2);if(typeof path!="string")return err(path);if(typeof caseId!="string"||!CASE_ID_PATTERN.test(caseId))return invalid("case_id must be a UUID");if(!CHECKIN_ANSWERS.includes(answer))return invalid("response must be one of better, same, worse");let res=await funnel.send("cases.checkin",{method:"POST",path:`${path}/${caseId}/checkin`,body:{response:answer},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let o=typeof res.value=="object"&&res.value!==null?res.value:{},watchCase=caseFromWire(o.case);return watchCase===null?malformed():ok(/* @__PURE__ */Object.freeze({case:watchCase,ctaDeepLink:str(o.cta_deep_link)}))}}}var unavailableUpload=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}function mergeSignals2(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}var MediaStore=class{constructor(initial){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...initial})}subscribe(listener){return this.listeners.add(listener),()=>{this.listeners.delete(listener)}}getSnapshot(){return this.snapshot}patch(partial){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...partial});for(let listener of this.listeners)listener()}beginOperation(external){this.inFlight?.abort();let ctrl=new AbortController;this.inFlight=ctrl;let epoch=this.epoch;return{signal:external?mergeSignals2(ctrl.signal,external):ctrl.signal,epoch:epoch,settle:()=>{this.inFlight===ctrl&&(this.inFlight=null)}}}alive(epoch){return epoch===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear()}};function makeUser(id,text3,createdAt){/* @__PURE__ */
@@ -118,8 +25,8 @@ return Object.freeze({id:m.id,role:m.role,text:m.text,createdAt:m.createdAt})}fu
118
25
  return Object.freeze({status:s.status,messages:/* @__PURE__ */Object.freeze([...s.messages]),conversationId:s.conversationId,error:s.error,isStreaming:s.isStreaming,isBootstrapping:s.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...s.suggestedPrompts]),unreadCount:s.unreadCount})}function makeError(code,retryable,wireMessage){return makeEverfurError(code,{retryable:retryable,...wireMessage?{wireMessage:wireMessage}:{}})}function errorFromFrame(frame){let code=fromWire(frame.code);return makeEverfurError(code,{retryable:frame.retryable||shouldRetry(code),wireCode:frame.code,wireEnvelope:"sse_frame",...frame.serverRequestId?{requestId:frame.serverRequestId}:{},...frame.wireMessage?{wireMessage:frame.wireMessage}:{},raw:frame})}function synthErrorFrame(error){return errorFrame({code:canonicalWireCode(error.code),retryable:error.retryable,wireMessage:error.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:error.requestId??null})}function canonicalWireCode(code){switch(code){case"authExpired":return"AUTH_EXPIRED";case"authRejected":return"AuthorizationException";case"sessionRequired":return"session_required";case"accessDenied":return"ACCESS_DENIED";case"paymentRequired":return"TIER_UPGRADE_REQUIRED";case"quotaExceeded":return"QUOTA_EXCEEDED";case"rateLimited":return"RATE_LIMITED";case"validationFailed":return"ValidationException";case"sdkUpdateRequired":return"invalidRequest";case"conflict":return"ConflictException";case"idempotencyConflict":return"IDEMPOTENCY_CONFLICT";case"idempotencyInFlight":return"IDEMPOTENCY_KEY_IN_FLIGHT";case"conversationNotFound":return"CONVERSATION_NOT_FOUND";case"petNotFound":return"PET_NOT_FOUND";case"resourceNotFound":return"ResourceNotFoundException";case"streamTimeout":return"STREAM_TIMEOUT";case"mediaUploadFailed":return"MEDIA_UPLOAD_FAILED";case"moderationBlocked":return"MODERATION_BLOCKED";case"upstreamLlmTimeout":return"UPSTREAM_LLM_TIMEOUT";case"internalError":return"INTERNAL_ERROR";case"notImplemented":return"NotImplementedException";case"serviceUnavailable":return"ServiceUnavailableException";case"streamIncomplete":return"STREAM_INCOMPLETE";case"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(code)}}function parsePromptCategories(raw){let list=Array.isArray(raw)?raw:isPlainObject2(raw)&&Array.isArray(raw.categories)?raw.categories:[],out=[];for(let entry of list){if(!isPlainObject2(entry))continue;let category=asStr(entry.category)??asStr(entry.title)??"",prompts=asPromptTextList(entry.prompts??entry.questions);category.length===0&&prompts.length===0||out.push(/* @__PURE__ */Object.freeze({category:category,prompts:/* @__PURE__ */Object.freeze(prompts)}))}/* @__PURE__ */
119
26
  return Object.freeze(out)}function flattenPrompts(categories){let seen=/* @__PURE__ */new Set,out=[];for(let category of categories)for(let prompt of category.prompts){let trimmed=prompt.trim();trimmed.length===0||seen.has(trimmed)||(seen.add(trimmed),out.push(trimmed))}return out}function isPlainObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asStr(v){return typeof v=="string"?v:null}function asPromptTextList(v){if(!Array.isArray(v))return[];let out=[];for(let entry of v)if(typeof entry=="string")out.push(entry);else if(isPlainObject2(entry)){let text3=asStr(entry.text)??asStr(entry.prompt)??asStr(entry.title);text3!==null&&out.push(text3)}return out}function defaultIdFactory(){let counter=0;return()=>`m-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function defaultIdempotencyFactory(){let counter=0;return()=>`chat-send-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var defaultTimers2={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()};async function*withWatchdog(source,budget,signal,timers){let it=source[Symbol.asyncIterator](),overall=deadline(budget.overallMs,timers),idle=deadline(budget.idleMs,timers),abort=abortPromise(signal);try{for(;;){if(signal.aborted)return;let nextTagged=it.next().then(value=>({tag:"next",value:value}),()=>({tag:"streamError"})),outcome=await Promise.race([nextTagged,idle.promise.then(()=>({tag:"idle"})),overall.promise.then(()=>({tag:"overall"})),abort.then(()=>({tag:"abort"}))]);if(outcome.tag==="abort")return;if(outcome.tag==="streamError"){if(signal.aborted)return;yield synthStreamErrorFrame();return}if(outcome.tag==="idle"||outcome.tag==="overall"){yield synthTimeoutFrame();return}let result=outcome.value;if(result.done||(idle.reset(budget.idleMs),yield result.value,result.value.terminal))return}}finally{idle.cancel(),overall.cancel(),Promise.resolve(it.return?.(void 0)).catch(()=>{})}}function synthTimeoutFrame(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function synthStreamErrorFrame(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function deadline(ms,timers){let resolveFn=()=>{},promise=new Promise(resolve=>{resolveFn=resolve}),handle=timers.setTimeout(()=>resolveFn(),ms);return{promise:promise,reset(next){timers.clearTimeout(handle),handle=timers.setTimeout(()=>resolveFn(),next)},cancel(){timers.clearTimeout(handle)}}}function abortPromise(signal){return new Promise(resolve=>{if(signal.aborted){resolve();return}signal.addEventListener("abort",()=>resolve(),{once:true})})}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function isLiveAskAnswered(counts){let{askCount:askCount,answerCount:answerCount}=counts;return typeof askCount!="number"||!Number.isFinite(askCount)||typeof answerCount!="number"||!Number.isFinite(answerCount)||askCount<=0?true:answerCount>=askCount}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}function parseCheckinOriginRef(ref){return parseCheckinOrigin(ref)?.caseId??null}function historyQuery(opts,max){if(opts?.limit!==void 0&&(!Number.isInteger(opts.limit)||opts.limit<1||opts.limit>max))return err(makeEverfurError("validationFailed"));let query=[];for(let[key,value]of[["cursor",opts?.cursor],["pet_ref",opts?.petRef]])if(value!==void 0){if(typeof value!="string"||value.length===0||hasLoneSurrogate(value))return err(makeEverfurError("validationFailed"));query.push(`${key}=${encodeURIComponent(value)}`)}return opts?.limit!==void 0&&query.push(`limit=${opts.limit}`),ok(query.length?`?${query.join("&")}`:"")}function validConversationId(id){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)}function object(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function cursor(value){return value==null||typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}function mapConversationPage(value){let page=object(value);if(!page||!Array.isArray(page.conversations)||!cursor(page.next_cursor))return malformed2();let conversations=[];for(let raw of page.conversations){let row=object(raw);if(!row||typeof row.conversation_id!="string"||!validConversationId(row.conversation_id)||!(row.title==null||typeof row.title=="string")||typeof row.created_at!="string"||typeof row.updated_at!="string")return malformed2();let unread=row.unread_message_count;if(!(unread==null||Number.isInteger(unread)&&unread>=0))return malformed2();let preview=typeof row.preview=="string"?row.preview.replace(/\s+/g," ").trim().slice(0,140):"";conversations.push(/* @__PURE__ */Object.freeze({id:row.conversation_id,title:row.title??null,createdAt:row.created_at,updatedAt:row.updated_at,unreadCount:unread??null,...preview.length>0?{preview:preview}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(conversations),nextCursor:page.next_cursor??null}))}function mapMessagePage(value){let page=object(value);if(!page||!Array.isArray(page.messages)||!cursor(page.next_cursor))return malformed2();let messages=[],seen=/* @__PURE__ */new Set;for(let raw of page.messages){let row=object(raw);if(!row||typeof row.message_id!="string"||!validConversationId(row.message_id)||typeof row.role!="string"||typeof row.content!="string"||typeof row.created_at!="string")return malformed2();if(row.role!=="user"&&row.role!=="assistant"&&row.role!=="vet"||seen.has(row.message_id))continue;if(seen.add(row.message_id),row.role==="vet"){messages.push(vetMessage(row,row.message_id,row.content,row.created_at));continue}let origin=typeof row.proactive_origin_ref=="string"?row.proactive_origin_ref:null,caseId=row.role==="assistant"?parseCheckinOriginRef(origin):null;messages.push(/* @__PURE__ */Object.freeze({id:row.message_id,role:row.role,text:row.content,createdAt:row.created_at,...row.role==="assistant"?{responseId:row.message_id}:{},...row.urgency_level!==void 0?{urgencyLevel:normalizeUrgency(row.urgency_level)}:{},...Array.isArray(row.citations)?{citations:historyCitations(row.citations)}:{},...origin!==null?{proactiveOriginRef:origin}:{},...caseId!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:caseId,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(messages),nextCursor:page.next_cursor??null}))}function vetMessage(row,id,text3,createdAt){let sender=object(row.sender),displayName=trimmedText(sender?.display_name)??trimmedText(row.sender_display_name),specialty=trimmedText(sender?.specialty);/* @__PURE__ */
120
27
  return Object.freeze({id:id,role:"vet",text:text3,createdAt:createdAt,sender:/* @__PURE__ */Object.freeze({displayName:displayName,specialty:specialty})})}function trimmedText(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&!hasLoneSurrogate(trimmed)?trimmed:null}function normalizeUrgency(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}function historyCitations(values){let keys=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
121
- return Object.freeze(values.flatMap(value=>{let row=object(value);if(!row||typeof row.source_name!="string"||typeof row.authority_tier!="string")return[];let citation={};for(let key of keys){let item=row[key];(typeof item=="string"||item===null)&&(citation[key]=item)}return[/* @__PURE__ */Object.freeze(citation)]}))}var CHAT_FEEDBACK_TYPES=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;function validateImageKeys(keys){return keys===void 0?null:!Array.isArray(keys)||keys.length>5?{reason:"too_many_images",error:makeError("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:keys.some(key=>typeof key!="string"||key.trim().length===0)?{reason:"bad_image_key",error:makeError("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function validateMessageText(text3){let raw=typeof text3=="string"?text3:"";if(raw.trim().length===0)return{reason:"empty",error:makeError("validationFailed",false,"message is empty or whitespace-only")};let codePoints=[...raw].length;return codePoints>MESSAGE_MAX_CHARS?{reason:"too_long",error:makeError("validationFailed",false,`message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`)}:null}function urgencyTier(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}async function*singleFrameStream(frame){yield frame}async function*emptyStream(){}var DEFAULT_IDLE_MS=6e4,DEFAULT_OVERALL_MS=18e4,DELTA_FLUSH_MS=24,DELTA_FLUSH_CHARS=512,SEND_IS_SERVER_DEDUPED=false;function createChatController(deps){return new ChatControllerImpl(deps)}var ChatControllerImpl=class extends MediaStore{constructor(deps){super(freezeSnapshot({status:"idle",messages:[],conversationId:deps.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingDelta="";this.flushHandle=null;this.auth=deps.auth,this.funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),this.petRef=deps.petRef??null,this.cases=createCasesRepositoryOver(this.funnel),this.telemetry=deps.telemetry??noopTelemetry,this.onConversationStarted=deps.onConversationStarted,this.errorPolicy=deps.errorPolicy??defaultErrorPolicy,this.timers=deps.timers??defaultTimers2,this.rng=deps.rng??Math.random,this.newId=deps.newId??defaultIdFactory(),this.makeIdempotencyKey=deps.makeIdempotencyKey??defaultIdempotencyFactory(),this.budget={idleMs:deps.budget?.idleMs??DEFAULT_IDLE_MS,overallMs:deps.budget?.overallMs??DEFAULT_OVERALL_MS}}patch(partial){if(partial.messages!==void 0){let frozen=/* @__PURE__ */Object.freeze([...partial.messages]);super.patch({...partial,messages:frozen});return}super.patch(partial)}send(text3,opts,handlers){let options=opts??{};if(this.disposed||this.snapshot.isBootstrapping){let error=makeError(this.disposed?"accessDenied":"internalError",!this.disposed);return handlers?(handlers.onError(error),()=>{}):singleFrameStream(synthErrorFrame(error))}let invalid5=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid5!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),this.patch({status:"error",isStreaming:false,error:invalid5.error}),handlers?(handlers.onError(invalid5.error),()=>{}):singleFrameStream(synthErrorFrame(invalid5.error));if(handlers)return this.driveWithHandlers(text3,options,handlers);let turn=this.beginTurn(text3,options);return this.runTurn(turn,options.signal)}askEverfur(prompt,opts){if(this.disposed)return singleFrameStream(synthErrorFrame(makeError("accessDenied",false)));let invalid5=validateMessageText(prompt);return invalid5!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),singleFrameStream(synthErrorFrame(invalid5.error))):(this.resetThread(),this.send(prompt,opts??{}))}retryLast(){let turn=this.lastTurn;if(turn===null){let id=this.snapshot.conversationId;return id!==null&&this.snapshot.status==="error"?this.retryHistory(id):emptyStream()}turn.assistantMessageId=null,turn.sawDelta=false,turn.conversationIdOverride=null,this.discardPendingDelta();let messages=this.snapshot.messages.some(m=>m.id===turn.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,makeUser(turn.userMessageId,turn.text,this.stamp())];return this.patch({error:null,stopped:false,messages:messages}),this.runTurn(turn,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let stopped=this.snapshot.messages.some(m=>m.role==="user"&&m.pending===true),messages=stopped?this.snapshot.messages.map(m=>m.pending===true?stripPending(m):m):this.snapshot.messages;(this.snapshot.status==="streaming"||stopped)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...stopped?{messages:messages,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot()}resetThread(prompts=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=prompts,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:prompts,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false})}newConversation(){this.disposed||this.resetThread(this.scopePrompts)}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let teardown of this.handlerTeardowns)teardown();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(id){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==id&&this.patch({conversationId:id}))}adoptPrompts(categories){if(this.disposed)return;let prompts=/* @__PURE__ */Object.freeze(flattenPrompts(categories));this.bootstrapPrompts=prompts,this.scopePrompts=prompts,this.replyPrompts===null&&(prompts.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:prompts}))}async listConversations(opts){return this.listConversationsWith(opts)}async listConversationsWith(opts,funnelOpts){let query=historyQuery(opts,100);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},opts?.signal,funnelOpts);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let page=mapConversationPage(result.value);if(page.ok){for(let conversation of page.value.conversations)conversation.unreadCount!==null&&this.unreadByConversation.set(conversation.id,conversation.unreadCount);let active=this.snapshot.conversationId,count2=active===null?void 0:this.unreadByConversation.get(active);count2!==void 0&&count2!==this.snapshot.unreadCount&&this.patch({unreadCount:count2}),this.reflectUnreadDot()}return page}reflectUnreadDot(){let unread=false;for(let count2 of this.unreadByConversation.values())if(count2>0){unread=true;break}unread!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:unread})}async openCheckin(target){if(this.disposed)return err(makeError("accessDenied",false));let named=target?.conversationId??null;if(named!==null){let opened2=await this.resumeConversation(named);return opened2.ok?ok(named):err(opened2.error)}let petRef2=target?.petRef??this.petRef,listed=await this.listConversations({...petRef2===null?{}:{petRef:petRef2},limit:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0)return ok(null);let opened=await this.resumeConversation(head.id);return opened.ok?ok(head.id):err(opened.error)}async markRead(opts){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null)return ok(void 0);let epoch=this.epoch,result=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${id}/read`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?(this.unreadByConversation.set(id,0),this.snapshot.conversationId===id&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),ok(void 0)):err(result.error)}async submitFeedback(responseId,feedbackType,notes,opts){if(this.disposed)return err(makeError("accessDenied",false));if(typeof responseId!="string"||responseId.trim().length===0||hasLoneSurrogate(responseId))return err(makeError("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!CHAT_FEEDBACK_TYPES.includes(feedbackType))return err(makeError("validationFailed",false,`feedback_type must be one of ${CHAT_FEEDBACK_TYPES.join(", ")}`));let note=typeof notes=="string"?notes.trim():"";if([...note].length>FEEDBACK_NOTES_MAX_CHARS)return err(makeError("validationFailed",false,`notes is over ${FEEDBACK_NOTES_MAX_CHARS} characters`));let body={feedback_type:feedbackType};note.length>0&&(body.notes=note);let epoch=this.epoch,result=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(responseId)}/feedback`,body:body},opts?.signal);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let feedbackId=result.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof feedbackId=="string"?feedbackId:""}))}async answerCheckin(caseId,answer,opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??this.petRef;if(petRef2===null)return err(makeError("validationFailed",false,"a check-in needs the pet the case belongs to"));let epoch=this.epoch,result=await this.cases.checkin(petRef2,caseId,answer,opts?.signal?{signal:opts.signal}:{});if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let openedAt=result.value.case.openedAt,checkin=/* @__PURE__ */Object.freeze({caseId:caseId,answer:answer,resolutionText:result.value.case.resolutionText,status:result.value.case.status??null,...openedAt!==null?{openedAt:openedAt}:{}}),carries=m=>m.checkin?.caseId===caseId;return this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,checkin:checkin}):m)}),result}async getMessages(id,opts){if(!validConversationId(id))return err(makeError("validationFailed",false));let query=historyQuery(opts,200);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${id}/messages${query.value}`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?mapMessagePage(result.value):result}async resumeConversation(id){if(this.disposed)return err(makeError("accessDenied",false));if(!validConversationId(id))return err(makeError("validationFailed",false));this.resetThread();let generation=this.historyGeneration;this.patch({conversationId:id,isBootstrapping:true,isLoadingHistory:true});let result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return this.patch({status:"error",error:result.error,isBootstrapping:false,isLoadingHistory:false}),result;let unread=this.unreadByConversation.get(id)??null;return this.patch({messages:result.value.messages,historyCursor:result.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:unread}),this.stampCheckinStatuses(generation),unread!==null&&unread>0&&this.markRead(),ok(void 0)}async stampCheckinStatuses(generation){let petRef2=this.petRef;if(petRef2===null||!this.snapshot.messages.some(m=>m.checkin!==void 0&&m.checkin.status===null))return;let result=await this.cases.list(petRef2);if(!result.ok||generation!==this.historyGeneration||this.disposed)return;let open=new Set(result.value.filter(row=>row.status===CHECKIN_ANSWERABLE_STATUS).map(row=>row.caseId)),byCase=new Map(result.value.map(row=>[row.caseId,row])),changed=false,messages=this.snapshot.messages.map(message=>{let checkin=message.checkin;if(checkin===void 0||checkin.status!==null)return message;changed=true;let row=byCase.get(checkin.caseId),openedAt=checkin.openedAt??row?.openedAt??null,watching=open.has(checkin.caseId),answerOnRecord=row!==void 0&&(!watching||isLiveAskAnswered({askCount:row.checkinAskCount,answerCount:row.checkinAnswerCount}))?row.lastResponse:null;/* @__PURE__ */
122
- return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null||this.snapshot.isStreaming)return ok(void 0);let generation=this.historyGeneration,result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async primeBounded(petRef2){let head=await this.headThreadWithUnread(petRef2);return head.ok?head.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(head.value)).ok?ok(head.value):ok(this.snapshot.conversationId):head.error.code==="accessDenied"||head.error.httpStatus===403?ok(null):err(head.error)}async headThreadWithUnread(petRef2){let listed=await this.listConversationsWith({...petRef2===null?{}:{petRef:petRef2},limit:1},{maxAttempts:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];return head===void 0||head.unreadCount===null||head.unreadCount<=0?ok(null):ok(head.id)}async createConversation(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef2,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef2?{pet_ref:petRef2}:{}},res=await this.authedUnary("chat.createConversation",req,signal,{maxAttempts:1});if(!res.ok)return err(res.error);let raw=res.value?.conversation_id??res.value?.id;return typeof raw!="string"||raw.length===0?err(makeError("internalError",true)):ok(raw)}async getPrompts(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null;if(petRef2!==null&&hasLoneSurrogate(petRef2))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef2!==null?`?pet_ref=${encodeURIComponent(petRef2)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending=needsConversation?this.unadoptedCreate:null;if(pending!==null&&(turn.petRef===null||turn.petRef===pending.petRef)){let primed=await pending.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(primed.value),this.reportConversationStarted(primed.value))}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value),this.reportConversationStarted(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{this.reportSessionRejected();let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk):m);this.patch({messages:messages})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(done,turn){this.flushPendingDelta(turn),this.lastResponseIdValue=done.messageId?done.messageId:null;let nextConv=done.conversationId?done.conversationId:this.snapshot.conversationId,messages;if(turn.assistantMessageId!==null)messages=this.snapshot.messages.map(m=>m.id===turn.assistantMessageId?finalizeAssistant(m,done):m);else{let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true,messages=[...this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m),finalizeAssistant(makeAssistant(assistantId,"",this.stamp()),done)]}let followUps=flattenPrompts([{category:"",prompts:done.followUpQuestions}]);this.replyPrompts=followUps.length>0?/* @__PURE__ */Object.freeze(followUps):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:nextConv,messages:messages,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!done.urgencyProvided&&nextConv!==null&&this.classifyTurn(nextConv,this.lastResponseIdValue)}async classifyTurn(conversationId2,responseId){if(responseId===null||this.disposed)return;let messageId=String(responseId);if(this.classifiedMessageIds.has(messageId))return;this.classifiedMessageIds.add(messageId);let epoch=this.epoch,generation=this.historyGeneration,result=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId2}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId2)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(id){try{this.onConversationStarted?.(id)}catch{}}authRejected(refusal){return refusal===void 0?makeError("authRejected",false):makeEverfurError("authRejected",{retryable:false,...refusal.code?{wireCode:refusal.code}:{},...refusal.serverRequestId?{requestId:refusal.serverRequestId}:{}})}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef2=input.petRef??null,resume=input.resumeConversationId??null,candidateConversationIds=[],sawForbidden=false,sawUnauthorized=false,sawConversationInitFailure=false,authBlock=null,initFailure=null,conversationPromise=resume?controller.resumeConversation(resume).then(result=>result.ok?ok(resume):err(result.error)):controller.primeConversation(petRef2?{petRef:petRef2}:void 0),promptsPromise=controller.getPrompts(petRef2!==null?{petRef:petRef2}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId2=null;if(conversationRes.ok)conversationId2=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
28
+ return Object.freeze(values.flatMap(value=>{let row=object(value);if(!row||typeof row.source_name!="string"||typeof row.authority_tier!="string")return[];let citation={};for(let key of keys){let item=row[key];(typeof item=="string"||item===null)&&(citation[key]=item)}return[/* @__PURE__ */Object.freeze(citation)]}))}var CHAT_FEEDBACK_TYPES=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;function validateImageKeys(keys){return keys===void 0?null:!Array.isArray(keys)||keys.length>5?{reason:"too_many_images",error:makeError("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:keys.some(key=>typeof key!="string"||key.trim().length===0)?{reason:"bad_image_key",error:makeError("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function validateMessageText(text3){let raw=typeof text3=="string"?text3:"";if(raw.trim().length===0)return{reason:"empty",error:makeError("validationFailed",false,"message is empty or whitespace-only")};let codePoints=[...raw].length;return codePoints>MESSAGE_MAX_CHARS?{reason:"too_long",error:makeError("validationFailed",false,`message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`)}:null}function urgencyTier(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}async function*singleFrameStream(frame){yield frame}async function*emptyStream(){}var DEFAULT_IDLE_MS=6e4,DEFAULT_OVERALL_MS=18e4,DELTA_FLUSH_MS=24,DELTA_FLUSH_CHARS=512,SEND_IS_SERVER_DEDUPED=false;function createChatController(deps){return new ChatControllerImpl(deps)}var ChatControllerImpl=class extends MediaStore{constructor(deps){super(freezeSnapshot({status:"idle",messages:[],conversationId:deps.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingDelta="";this.flushHandle=null;this.auth=deps.auth,this.funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),this.petRef=deps.petRef??null,this.cases=createCasesRepositoryOver(this.funnel),this.telemetry=deps.telemetry??noopTelemetry,this.onConversationStarted=deps.onConversationStarted,this.unread=deps.unread,this.errorPolicy=deps.errorPolicy??defaultErrorPolicy,this.timers=deps.timers??defaultTimers2,this.rng=deps.rng??Math.random,this.newId=deps.newId??defaultIdFactory(),this.makeIdempotencyKey=deps.makeIdempotencyKey??defaultIdempotencyFactory(),this.budget={idleMs:deps.budget?.idleMs??DEFAULT_IDLE_MS,overallMs:deps.budget?.overallMs??DEFAULT_OVERALL_MS}}patch(partial){if(partial.messages!==void 0){let frozen=/* @__PURE__ */Object.freeze([...partial.messages]);super.patch({...partial,messages:frozen});return}super.patch(partial)}send(text3,opts,handlers){let options=opts??{};if(this.disposed||this.snapshot.isBootstrapping){let error=makeError(this.disposed?"accessDenied":"internalError",!this.disposed);return handlers?(handlers.onError(error),()=>{}):singleFrameStream(synthErrorFrame(error))}let invalid5=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid5!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),this.patch({status:"error",isStreaming:false,error:invalid5.error}),handlers?(handlers.onError(invalid5.error),()=>{}):singleFrameStream(synthErrorFrame(invalid5.error));if(handlers)return this.driveWithHandlers(text3,options,handlers);let turn=this.beginTurn(text3,options);return this.runTurn(turn,options.signal)}askEverfur(prompt,opts){if(this.disposed)return singleFrameStream(synthErrorFrame(makeError("accessDenied",false)));let invalid5=validateMessageText(prompt);return invalid5!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),singleFrameStream(synthErrorFrame(invalid5.error))):(this.resetThread(),this.send(prompt,opts??{}))}retryLast(){let turn=this.lastTurn;if(turn===null){let id=this.snapshot.conversationId;return id!==null&&this.snapshot.status==="error"?this.retryHistory(id):emptyStream()}turn.assistantMessageId=null,turn.sawDelta=false,turn.conversationIdOverride=null,this.discardPendingDelta();let messages=this.snapshot.messages.some(m=>m.id===turn.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,makeUser(turn.userMessageId,turn.text,this.stamp())];return this.patch({error:null,stopped:false,messages:messages}),this.runTurn(turn,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let stopped=this.snapshot.messages.some(m=>m.role==="user"&&m.pending===true),messages=stopped?this.snapshot.messages.map(m=>m.pending===true?stripPending(m):m):this.snapshot.messages;(this.snapshot.status==="streaming"||stopped)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...stopped?{messages:messages,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot()}resetThread(prompts=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=prompts,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:prompts,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false})}newConversation(){this.disposed||this.resetThread(this.scopePrompts)}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let teardown of this.handlerTeardowns)teardown();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(id){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==id&&this.patch({conversationId:id}))}adoptPrompts(categories){if(this.disposed)return;let prompts=/* @__PURE__ */Object.freeze(flattenPrompts(categories));this.bootstrapPrompts=prompts,this.scopePrompts=prompts,this.replyPrompts===null&&(prompts.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:prompts}))}async listConversations(opts){return this.listConversationsWith(opts)}async listConversationsWith(opts,funnelOpts){let query=historyQuery(opts,100);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},opts?.signal,funnelOpts);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let page=mapConversationPage(result.value);if(page.ok){for(let conversation of page.value.conversations)conversation.unreadCount!==null&&this.unreadByConversation.set(conversation.id,conversation.unreadCount);let active=this.snapshot.conversationId,count3=active===null?void 0:this.unreadByConversation.get(active);count3!==void 0&&count3!==this.snapshot.unreadCount&&this.patch({unreadCount:count3}),this.reflectUnreadDot(),opts?.cursor===void 0&&this.unread?.reportHead(opts?.petRef??null,page.value.conversations[0]??null)}return page}reflectUnreadDot(){let unread=false;for(let count3 of this.unreadByConversation.values())if(count3>0){unread=true;break}unread!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:unread})}async openCheckin(target){if(this.disposed)return err(makeError("accessDenied",false));let named=target?.conversationId??null;if(named!==null){let opened2=await this.resumeConversation(named);return opened2.ok?ok(named):err(opened2.error)}let petRef2=target?.petRef??this.petRef,listed=await this.listConversations({...petRef2===null?{}:{petRef:petRef2},limit:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0)return ok(null);let opened=await this.resumeConversation(head.id);return opened.ok?ok(head.id):err(opened.error)}async markRead(opts){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null)return ok(void 0);let epoch=this.epoch,result=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${id}/read`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?(this.unreadByConversation.set(id,0),this.snapshot.conversationId===id&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(id),ok(void 0)):err(result.error)}async submitFeedback(responseId,feedbackType,notes,opts){if(this.disposed)return err(makeError("accessDenied",false));if(typeof responseId!="string"||responseId.trim().length===0||hasLoneSurrogate(responseId))return err(makeError("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!CHAT_FEEDBACK_TYPES.includes(feedbackType))return err(makeError("validationFailed",false,`feedback_type must be one of ${CHAT_FEEDBACK_TYPES.join(", ")}`));let note=typeof notes=="string"?notes.trim():"";if([...note].length>FEEDBACK_NOTES_MAX_CHARS)return err(makeError("validationFailed",false,`notes is over ${FEEDBACK_NOTES_MAX_CHARS} characters`));let body={feedback_type:feedbackType};note.length>0&&(body.notes=note);let epoch=this.epoch,result=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(responseId)}/feedback`,body:body},opts?.signal);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let feedbackId=result.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof feedbackId=="string"?feedbackId:""}))}async answerCheckin(caseId,answer,opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??this.petRef;if(petRef2===null)return err(makeError("validationFailed",false,"a check-in needs the pet the case belongs to"));let epoch=this.epoch,result=await this.cases.checkin(petRef2,caseId,answer,opts?.signal?{signal:opts.signal}:{});if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let openedAt=result.value.case.openedAt,checkin=/* @__PURE__ */Object.freeze({caseId:caseId,answer:answer,resolutionText:result.value.case.resolutionText,status:result.value.case.status??null,...openedAt!==null?{openedAt:openedAt}:{}}),carries=m=>m.checkin?.caseId===caseId;return this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,checkin:checkin}):m)}),result}async getMessages(id,opts){if(!validConversationId(id))return err(makeError("validationFailed",false));let query=historyQuery(opts,200);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${id}/messages${query.value}`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?mapMessagePage(result.value):result}async resumeConversation(id){if(this.disposed)return err(makeError("accessDenied",false));if(!validConversationId(id))return err(makeError("validationFailed",false));this.resetThread();let generation=this.historyGeneration;this.patch({conversationId:id,isBootstrapping:true,isLoadingHistory:true});let result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return this.patch({status:"error",error:result.error,isBootstrapping:false,isLoadingHistory:false}),result;let unread=this.unreadByConversation.get(id)??null;return this.patch({messages:result.value.messages,historyCursor:result.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:unread}),this.stampCheckinStatuses(generation),unread!==null&&unread>0&&this.markRead(),ok(void 0)}async stampCheckinStatuses(generation){let petRef2=this.petRef;if(petRef2===null||!this.snapshot.messages.some(m=>m.checkin!==void 0&&m.checkin.status===null))return;let result=await this.cases.list(petRef2);if(!result.ok||generation!==this.historyGeneration||this.disposed)return;let open=new Set(result.value.filter(row=>row.status===CHECKIN_ANSWERABLE_STATUS).map(row=>row.caseId)),byCase=new Map(result.value.map(row=>[row.caseId,row])),changed=false,messages=this.snapshot.messages.map(message=>{let checkin=message.checkin;if(checkin===void 0||checkin.status!==null)return message;changed=true;let row=byCase.get(checkin.caseId),openedAt=checkin.openedAt??row?.openedAt??null,watching=open.has(checkin.caseId),answerOnRecord=row!==void 0&&(!watching||isLiveAskAnswered({askCount:row.checkinAskCount,answerCount:row.checkinAnswerCount}))?row.lastResponse:null;/* @__PURE__ */
29
+ return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(options){if(this.disposed)return err(makeError("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let id=this.snapshot.conversationId;if(id===null&&options?.openUnreadHead!==true)return ok(void 0);let generation=this.historyGeneration,listed=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(id===null){if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0||head.unreadCount===null||head.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let opened=await this.resumeConversation(head.id);return opened.ok?ok(void 0):err(opened.error)}let result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async primeBounded(petRef2){let head=await this.headThreadWithUnread(petRef2);return head.ok?head.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(head.value)).ok?ok(head.value):ok(this.snapshot.conversationId):head.error.code==="accessDenied"||head.error.httpStatus===403?ok(null):err(head.error)}async headThreadWithUnread(petRef2){let listed=await this.listConversationsWith({...petRef2===null?{}:{petRef:petRef2},limit:1},{maxAttempts:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];return head===void 0||head.unreadCount===null||head.unreadCount<=0?ok(null):ok(head.id)}async createConversation(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef2,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef2?{pet_ref:petRef2}:{}},res=await this.authedUnary("chat.createConversation",req,signal,{maxAttempts:1});if(!res.ok)return err(res.error);let raw=res.value?.conversation_id??res.value?.id;return typeof raw!="string"||raw.length===0?err(makeError("internalError",true)):ok(raw)}async getPrompts(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null;if(petRef2!==null&&hasLoneSurrogate(petRef2))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef2!==null?`?pet_ref=${encodeURIComponent(petRef2)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending=needsConversation?this.unadoptedCreate:null;if(pending!==null&&(turn.petRef===null||turn.petRef===pending.petRef)){let primed=await pending.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(primed.value),this.reportConversationStarted(primed.value))}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value),this.reportConversationStarted(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{this.reportSessionRejected();let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk):m);this.patch({messages:messages})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(done,turn){this.flushPendingDelta(turn),this.lastResponseIdValue=done.messageId?done.messageId:null;let nextConv=done.conversationId?done.conversationId:this.snapshot.conversationId,messages;if(turn.assistantMessageId!==null)messages=this.snapshot.messages.map(m=>m.id===turn.assistantMessageId?finalizeAssistant(m,done):m);else{let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true,messages=[...this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m),finalizeAssistant(makeAssistant(assistantId,"",this.stamp()),done)]}let followUps=flattenPrompts([{category:"",prompts:done.followUpQuestions}]);this.replyPrompts=followUps.length>0?/* @__PURE__ */Object.freeze(followUps):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:nextConv,messages:messages,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!done.urgencyProvided&&nextConv!==null&&this.classifyTurn(nextConv,this.lastResponseIdValue)}async classifyTurn(conversationId2,responseId){if(responseId===null||this.disposed)return;let messageId=String(responseId);if(this.classifiedMessageIds.has(messageId))return;this.classifiedMessageIds.add(messageId);let epoch=this.epoch,generation=this.historyGeneration,result=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId2}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId2)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(id){try{this.onConversationStarted?.(id)}catch{}}authRejected(refusal){return refusal===void 0?makeError("authRejected",false):makeEverfurError("authRejected",{retryable:false,...refusal.code?{wireCode:refusal.code}:{},...refusal.serverRequestId?{requestId:refusal.serverRequestId}:{}})}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef2=input.petRef??null,resume=input.resumeConversationId??null,candidateConversationIds=[],sawForbidden=false,sawUnauthorized=false,sawConversationInitFailure=false,authBlock=null,initFailure=null,conversationPromise=resume?controller.resumeConversation(resume).then(result=>result.ok?ok(resume):err(result.error)):controller.primeConversation(petRef2?{petRef:petRef2}:void 0),promptsPromise=controller.getPrompts(petRef2!==null?{petRef:petRef2}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId2=null;if(conversationRes.ok)conversationId2=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
123
30
  return Object.freeze({conversationId:conversationId2,petRef:petRef2,suggestedPrompts:suggestedPrompts,error:error,warning:error===null&&conversationId2===null&&sawConversationInitFailure?CONVERSATION_NOT_PRIMED_WARNING:null,cause:authBlock??initFailure,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...candidateConversationIds]),sawForbidden:sawForbidden,sawUnauthorized:sawUnauthorized,sawConversationInitFailure:sawConversationInitFailure})})}var CONVERSATION_NOT_PRIMED_WARNING="Chat is ready. Your first message will start the conversation.";function isUnauthorized(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function isForbidden(e){return e.httpStatus===403||e.code==="accessDenied"}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var MAX_ATTACHMENT_BYTES=10*1024*1024,MAX_ATTACHMENTS_PER_MESSAGE=5,MAX_FILENAME_LENGTH=120,ATTACHMENT_INITIATE_PATH="/widget/v1/uploads/initiate";function isAttachmentMime(mime){return typeof mime=="string"&&ATTACHMENT_MIME_TYPES.includes(mime.trim().toLowerCase())}function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
124
31
  return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str6=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str6(o.upload_id),uploadUrl=str6(o.upload_url),s3Key=str6(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
125
32
  return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str6(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight3=/* @__PURE__ */new Set,listeners2=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed2=false,publish2=()=>{snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners2)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed2&&inFlight3.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight3.add(id),run(row).finally(()=>{inFlight3.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed2||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed2||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed2||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot:()=>snapshot2,get uploading(){return snapshot2.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot2.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed2||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed2||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed2=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners2.clear(),snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str2=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str2(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(o.ref),name:name,dose:str2(o.dose),frequency:str2(o.frequency),startDate:str2(o.start_date),endDate:str2(o.end_date),notes:str2(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
@@ -132,18 +39,20 @@ return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAd
132
39
  return Object.freeze(out)}var MAX_FONT_SOURCES=4,LINE_HEIGHT_RANGE=/* @__PURE__ */Object.freeze({min:1,max:2}),FAMILY_MAX_LENGTH=100,URL_MAX_LENGTH=2048,WEIGHTS=["100","200","300","400","500","600","700","800","900"];function finiteNumber(value){if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value!="string"||value.trim().length===0||value.length>16)return null;let n=Number(value.trim());return Number.isFinite(n)?n:null}function parseFontWeight(value){let n=finiteNumber(value);if(n===null)return null;let name=String(n);return WEIGHTS.includes(name)?name:null}function parseLineHeight(value){let n=finiteNumber(value);return n===null?null:Math.min(LINE_HEIGHT_RANGE.max,Math.max(LINE_HEIGHT_RANGE.min,n))}function fontSourceUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>URL_MAX_LENGTH?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(trimmed)?trimmed:null}function familyName(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>FAMILY_MAX_LENGTH||/[\u0000-\u001F\u007F]/.test(trimmed)?null:trimmed}function pick3(raw,...keys){for(let key of keys)if(raw[key]!==void 0&&raw[key]!==null)return raw[key]}function parseFontSource(raw){if(!isRecord2(raw))return null;let family=familyName(raw.family);if(family===null)return null;let srcRaw=pick3(raw,"src"),cssRaw=pick3(raw,"cssSrc","css_src");if(srcRaw===void 0==(cssRaw===void 0))return null;if(cssRaw!==void 0){let cssSrc=fontSourceUrl(cssRaw);return cssSrc===null?null:/* @__PURE__ */Object.freeze({family:family,cssSrc:cssSrc})}let src=fontSourceUrl(srcRaw);if(src===null)return null;let out={family:family,src:src},weight=parseFontWeight(raw.weight);weight!==null&&(out.weight=weight);let style=typeof raw.style=="string"?raw.style.trim().toLowerCase():null;return(style==="normal"||style==="italic")&&(out.style=style),/* @__PURE__ */Object.freeze(out)}function parseFontSources(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(out.length>=MAX_FONT_SOURCES)break;let source=parseFontSource(entry);source!==null&&out.push(source)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var LOCKABLE_THEME_FIELDS=/* @__PURE__ */Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),SLOT_LOCK_PREFIX="slots.",THEME_SCHEMA_VERSIONS=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(b){return Object.keys(b).every(key=>key==="schemaVersion"||(b[key]??null)===null)}function isKnownBrandingSchema(b){let version=b?.schemaVersion??null;return version===null||THEME_SCHEMA_VERSIONS.includes(version)}function lockedFieldsOf(b){/* @__PURE__ */
133
40
  return new Set(["hide_powered_by",...b?.lockedFields??[]])}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)||isPresentationLockName(name)?true:name.startsWith(SLOT_LOCK_PREFIX)&&THEME_SLOT_NAMES.includes(name.slice(SLOT_LOCK_PREFIX.length))}function parseClientBranding(json){if(json===null||typeof json!="object")return null;let raw=json,flat=parseFlat(raw),expanded=expandAppearance(pick4(raw,"appearance")),branding=expanded===null?flat:overlayFlat(parseFlat(expanded),flat);return isEmptyBranding(branding)?null:/* @__PURE__ */Object.freeze(branding)}function overlayFlat(base2,over){let out={...base2};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base2.slots??null,over.slots??null);return out.slots=Object.keys(slots).length===0?null:slots,out}function parseFlat(raw){return{displayName:parseNonEmptyString(pick4(raw,"display_name","displayName")),logoUrl:parseNonEmptyString(pick4(raw,"logo_url","logoUrl")),primaryColor:parseColor(pick4(raw,"primary_color","primaryColor")),accentColor:parseColor(pick4(raw,"accent_color","accentColor")),brightness:parseBrightness(pick4(raw,"brightness","color_scheme","colorScheme")),fontFamily:parseNonEmptyString(pick4(raw,"font_family","fontFamily")),fontUrl:parseNonEmptyString(pick4(raw,"font_url","fontUrl")),fonts:parseFaceMap(pick4(raw,"fonts")),fontUrls:parseFaceMap(pick4(raw,"font_urls","fontUrls")),placeholder:parseNonEmptyString(pick4(raw,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:parseBool(pick4(raw,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pick4(raw,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pick4(raw,"accent_color_dark","accentColorDark")),surfaceStyle:parseEnum(pick4(raw,"surface_style","surfaceStyle"),SURFACE_STYLES),radiusScale:parseEnum(pick4(raw,"radius_scale","radiusScale"),RADIUS_SCALES),logoUrlDark:parseNonEmptyString(pick4(raw,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pick4(raw,"slots")),accessibilityMaxFontScale:parseMaxFontScale(pick4(raw,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:parseLockedFields(pick4(raw,"locked_fields","lockedFields")),presentation:parsePresentation(pick4(raw,"presentation")),schemaVersion:parseSchemaVersion(pick4(raw,"schema_version","schemaVersion")),backgroundColor:parseColor(pick4(raw,"background_color","backgroundColor")),backgroundColorDark:parseColor(pick4(raw,"background_color_dark","backgroundColorDark")),textColor:parseColor(pick4(raw,"text_color","textColor")),textColorDark:parseColor(pick4(raw,"text_color_dark","textColorDark")),dangerColor:parseColor(pick4(raw,"danger_color","dangerColor")),dangerColorDark:parseColor(pick4(raw,"danger_color_dark","dangerColorDark")),fontSizeBase:parseClamped(pick4(raw,"font_size_base","fontSizeBase"),APPEARANCE_SIZE_RANGES.fontSizeBase),borderRadius:parseClamped(pick4(raw,"border_radius","borderRadius"),APPEARANCE_SIZE_RANGES.borderRadius),spacingUnit:parseClamped(pick4(raw,"spacing_unit","spacingUnit"),APPEARANCE_SIZE_RANGES.spacingUnit),successColor:parseColor(pick4(raw,"success_color","successColor")),successColorDark:parseColor(pick4(raw,"success_color_dark","successColorDark")),warningColor:parseColor(pick4(raw,"warning_color","warningColor")),warningColorDark:parseColor(pick4(raw,"warning_color_dark","warningColorDark")),infoColor:parseColor(pick4(raw,"info_color","infoColor")),infoColorDark:parseColor(pick4(raw,"info_color_dark","infoColorDark")),headingFontFamily:parseNonEmptyString(pick4(raw,"heading_font_family","headingFontFamily")),fontWeightBody:parseFontWeight(pick4(raw,"font_weight_body","fontWeightBody")),fontWeightHeading:parseFontWeight(pick4(raw,"font_weight_heading","fontWeightHeading")),lineHeight:parseLineHeight(pick4(raw,"line_height","lineHeight")),fontSources:parseFontSources(pick4(raw,"font_sources","fontSources")),assistantAvatarUrl:parseNonEmptyString(pick4(raw,"assistant_avatar_url","assistantAvatarUrl"))}}function parseClamped(value,range){let n=parseNumber(typeof value=="string"?value.trim().replace(/px$/i,""):value);return n===null?null:Math.min(range.max,Math.max(range.min,n))}function parseBool(value){if(typeof value=="boolean")return value;if(typeof value=="string"){let lower=value.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false}return null}function pick4(raw,...keys){for(let key of keys)if(Object.prototype.hasOwnProperty.call(raw,key)){let value=raw[key];if(value!==void 0)return value}}function parseNonEmptyString(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}var FONT_FACE_KEYS=["regular","medium","bold","mono","monoMedium","monoBold"];function parseFaceMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;let raw=value,out={};for(let key of FONT_FACE_KEYS){let entry=parseNonEmptyString(pick4(raw,key));entry!==null&&(out[key]=entry)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var SURFACE_STYLES=["white","cream","subtle"],RADIUS_SCALES=["sharp","default","round"];function parseEnum(value,allowed){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return allowed.includes(lower)?lower:null}function parseBrightness(value){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return lower==="light"||lower==="dark"||lower==="auto"?lower:null}function parseNumber(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)&&(typeof value!="string"||value.trim().length>0)?n:null}var MAX_FONT_SCALE_FLOOR=1,MAX_FONT_SCALE_CEILING=3.1;function parseMaxFontScale(value){let n=parseNumber(value);return n===null?null:n<=0?0:Math.min(MAX_FONT_SCALE_CEILING,Math.max(MAX_FONT_SCALE_FLOOR,n))}function parseSchemaVersion(value){if(value==null)return null;let n=parseNumber(value);return n!==null&&Number.isInteger(n)&&n>=1?n:0}function toWireName(name){let trimmed=name.trim();return trimmed.startsWith(SLOT_LOCK_PREFIX)?trimmed:trimmed.startsWith(PRESENTATION_LOCK_PREFIX)?PRESENTATION_LOCK_PREFIX+trimmed.slice(PRESENTATION_LOCK_PREFIX.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():trimmed.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function parseLockedFields(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(typeof entry!="string")continue;let name=toWireName(entry);isThemeLockName(name)&&!out.includes(name)&&out.push(name)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}var BRAND_ASSET_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/brand\/[0-9a-f]{16}\.(png|jpg|webp)$/;function hardenBrandAssetUrl(url){let https=hardenHttpsUrl(url);return https!==null&&BRAND_ASSET_URL.test(https)?https:null}function withServerBranding(base2,b){if(b===null||isEmptyBranding(b))return base2;let palette=(b.brightness==="light"||b.brightness==="dark")&&b.brightness!==base2.brightness?b.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT:base2,compiled=palette.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,dark=palette.brightness==="dark",primaryIn=dark?b.primaryColorDark??darkVariantOf(b.primaryColor):b.primaryColor,accentIn=dark?b.accentColorDark??darkVariantOf(b.accentColor):b.accentColor,primaryRaw=primaryIn??palette.color.primary,accent=accentIn??palette.color.accent,keepsCompiled=primaryIn!==null&&isCompiledPrimary(b,primaryRaw,compiled,dark),primary=keepsCompiled?compiled.color.primary:primaryRaw,pr=primaryIn!==null&&!keepsCompiled?toRgba(primary):null,lift=c=>Math.round(c+(255-c)*.4),brandFamily=pr!==null?{brand:primary,bubbleUser:primary,brandInk:primary,text:{...palette.color.text,secondary:primary},brandSoft:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,brandSofter:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,brandBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,borderHairlineGreen:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,brandBorderStrong:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.55)`,composerBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.75)`,accentEdge:`rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`}:keepsCompiled?compiledBrandFamily(compiled,palette.color.text):{},background=(dark?b.backgroundColorDark:b.backgroundColor)??null,grounds2=surfaceFamily(background),groundFamily={...palette.color,...grounds2},bodyInk=(dark?b.textColorDark:b.textColor)??null,status=(light,darkTwin)=>(dark?darkTwin??darkVariantOf(light??null):light)??null,next={brightness:palette.brightness,highContrast:palette.highContrast,meta:{displayName:b.displayName??palette.meta.displayName,logoUrl:(dark?b.logoUrlDark??b.logoUrl:b.logoUrl)??palette.meta.logoUrl,placeholder:b.placeholder??palette.meta.placeholder,hidePoweredBy:b.hidePoweredBy??palette.meta.hidePoweredBy,assistantAvatarUrl:b.assistantAvatarUrl??palette.meta.assistantAvatarUrl},color:{...palette.color,...brandFamily,...grounds2,...dangerFamily(status(b.dangerColor,b.dangerColorDark)),...successFamily(status(b.successColor,b.successColorDark),dark),...warningFamily(status(b.warningColor,b.warningColorDark),dark),...infoFamily(status(b.infoColor,b.infoColorDark),dark),...bodyInk!==null?{text:{...brandFamily.text??palette.color.text,primary:bodyInk}}:{},...surfaceOf(b.surfaceStyle??null,groundFamily),primary:primary,accent:accent,onPrimary:palette.color.onPrimary,onAccent:palette.color.onAccent},space:spaceFor(b.spacingUnit??null,palette.space,compiled),radius:b.borderRadius!=null?radiiFor(b.borderRadius,compiled):radiusOf(b.radiusScale??null,palette.radius,compiled),type:{...palette.type,...mergeFaces(palette.type,b),size:typeSizesFor(b.fontSizeBase??null,palette.type.size,compiled),maxScale:b.accessibilityMaxFontScale??palette.type.maxScale,lineHeight:lineHeightsFor(b.lineHeight??null,palette.type.lineHeight,compiled),weight:b.fontWeightBody==null?palette.type.weight:{...palette.type.weight,regular:b.fontWeightBody},headingFamily:b.headingFontFamily??palette.type.headingFamily,headingWeight:b.fontWeightHeading??palette.type.headingWeight,fontSources:b.fontSources??palette.type.fontSources},motion:palette.motion,slots:mergeThemeSlots(palette.slots,b.slots??null)};return deepFreeze(next)}var FACE_CHAIN={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},FACE_GROUPS=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function isMonoFace(face2){return face2==="mono"||face2==="monoMedium"||face2==="monoBold"}function mergeFaces(base2,b){let fonts=b.fonts??{},urls=b.fontUrls??{},families={...base2.families},namedFaces={...base2.namedFaces},fontUrls={...base2.fontUrls};for(let face2 of FONT_FACE_KEYS){let named=FACE_CHAIN[face2].map(key=>fonts[key]).find(name=>name!==void 0),legacy=isMonoFace(face2)?null:b.fontFamily;named!==void 0?(families[face2]=named,namedFaces[face2]=true):legacy!==null&&(families[face2]=legacy,namedFaces[face2]=false);let url=urls[face2]??(face2==="regular"?b.fontUrl:null)??null;url!==null?fontUrls[face2]=url:named!==void 0&&delete fontUrls[face2]}for(let group of FACE_GROUPS)for(let face2 of group)namedFaces[face2]&&group.some(other=>other!==face2&&families[other]===families[face2])&&(namedFaces[face2]=false);return{family:families.regular,mono:families.mono,fontUrl:fontUrls.regular??null,families:families,namedFaces:namedFaces,fontUrls:fontUrls}}function darkVariantOf(color){return color===null?null:deriveDarkVariant(color)}function surfaceOf(style,family){if(style===null)return{};let c=family;return{chatGround:style==="white"?c.surface:style==="subtle"?c.surfaceSubtle:c.surfaceCream}}function sameColor2(a,b){return a==null?false:parseColor(a)===parseColor(b)}function isCompiledPrimary(b,primary,compiled,dark){return sameColor2(primary,compiled.color.primary)?true:dark&&(b.primaryColorDark??null)===null&&sameColor2(b.primaryColor,EVERFUR_LIGHT.color.primary)}function compiledBrandFamily(compiled,text3){let c=compiled.color;return{text:{...text3,secondary:c.text.secondary},brand:c.brand,bubbleUser:c.bubbleUser,brandInk:c.brandInk,brandSoft:c.brandSoft,brandSofter:c.brandSofter,brandBorder:c.brandBorder,borderHairlineGreen:c.borderHairlineGreen,brandBorderStrong:c.brandBorderStrong,composerBorder:c.composerBorder,accentEdge:c.accentEdge}}var RADIUS_FACTOR={sharp:.5,default:1,round:1.5};function radiusOf(scale,base2,compiled){if(scale===null)return base2;let f=RADIUS_FACTOR[scale],r=compiled.radius,s=n=>Math.round(n*f);return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var DEFAULT_DISPLAY_NAME="Everfur",TEXT_SCALE_FLOOR=.5;function resolveTheme(input){return finalize(mergeLayers(input),input)}function themeAdjustments(input){let merged=mergeLayers(input);return diffThemeAdjustments(merged,finalize(merged,{...input,highContrast:false}))}function mergeLayers(input){let candidate=input?.branding??null,server=isKnownBrandingSchema(candidate)?candidate:null,client=withoutFields(input?.clientOverride??null,lockedFieldsOf(server)),device=input?.colorScheme==="dark"?"dark":"light",chosen=client?.brightness??server?.brightness??"light",withServer=withServerBranding((chosen==="auto"?device:chosen)==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,withoutBrightness(server));return withServerBranding(withServer,withoutBrightness(client))}function previewTheme(input,hints,options){return resolveTheme({...options,branding:parseClientBranding(hints),clientOverride:parseClientBranding(input)})}function wireNameOf(key){return key==="placeholder"?"chat_placeholder":toWireName(key)}var LOCK_ALIASES={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function isLocked(key,locked){return locked.has(wireNameOf(key))?true:(LOCK_ALIASES[key]??[]).some(name=>locked.has(name))}function withoutFields(b,locked){if(b===null)return null;let changed=false,out={...b};for(let key of Object.keys(b))(b[key]??null)!==null&&(isLocked(key,locked)||key==="lockedFields")&&(out[key]=null,changed=true);let slots=out.slots??null;if(slots!==null){let kept={},dropped=false;for(let name of THEME_SLOT_NAMES){let slot2=slots[name];slot2!==void 0&&(locked.has(`${SLOT_LOCK_PREFIX}${name}`)?dropped=true:kept[name]=slot2)}dropped&&(out.slots=Object.keys(kept).length===0?null:/* @__PURE__ */Object.freeze(kept),changed=true)}if(!changed)return b;let stripped=/* @__PURE__ */Object.freeze(out);return isEmptyBranding(stripped)?null:stripped}function withoutBrightness(b){return b===null||b.brightness===null?b:/* @__PURE__ */Object.freeze({...b,brightness:null})}function scaledSizes(size,scale){if(scale===1)return size;let out={};for(let[key,value]of Object.entries(size))out[key]=Math.round(value*scale*10)/10;return out}function effectiveScale(textScale){return textScale===void 0||!Number.isFinite(textScale)?1:Math.max(TEXT_SCALE_FLOOR,textScale)}var SCALE_TIERS=["content","heading","control","compact","badge"];function tierCaps(maxScale){if(!(maxScale>0))return TEXT_SCALE_TIER_CAPS;let out={};for(let tier of SCALE_TIERS){let cap=TEXT_SCALE_TIER_CAPS[tier];out[tier]=cap===0?0:Math.min(cap,maxScale)}return out}function capped(scale,cap){return cap>0?Math.min(scale,cap):scale}function sizesByTier(size,scale,caps,scaleSizes){let out={};for(let tier of SCALE_TIERS)out[tier]=scaleSizes?scaledSizes(size,capped(scale,caps[tier])):size;return out}function registration(isFontRegistered,family){try{let answer=isFontRegistered(family);return answer===!0||answer===!1?answer:null}catch{return null}}function platformFaces(type,input){let isFontRegistered=input?.isFontRegistered,platformMono=input?.platformMonoFamily?.trim()||null;if(isFontRegistered===void 0&&platformMono===null)return{family:type.family,mono:type.mono,families:type.families,namedFaces:type.namedFaces,headingFamily:type.headingFamily};let headingFamily=type.headingFamily!==null&&isFontRegistered!==void 0&&registration(isFontRegistered,type.headingFamily)===false?null:type.headingFamily,families={...type.families},namedFaces={...type.namedFaces};for(let key of FONT_FACE_KEYS)!(families[key]===SYSTEM_FONT_FAMILY||families[key]===SYSTEM_MONO_FAMILY)&&isFontRegistered!==void 0&&registration(isFontRegistered,families[key])===false&&(families[key]=isMonoFace(key)?SYSTEM_MONO_FAMILY:SYSTEM_FONT_FAMILY,namedFaces[key]=false),platformMono!==null&&isMonoFace(key)&&families[key]===SYSTEM_MONO_FAMILY&&(families[key]=platformMono);return{family:families.regular,mono:families.mono,families:families,namedFaces:namedFaces,headingFamily:headingFamily}}function finalize(theme,input){let displayName=theme.meta.displayName.trim().length===0?DEFAULT_DISPLAY_NAME:theme.meta.displayName,logoUrl=hardenBrandAssetUrl(theme.meta.logoUrl),fontUrls={};for(let face2 of FONT_FACE_KEYS){let url=theme.type.fontUrls[face2];url!==void 0&&(fontUrls[face2]=hardenHttpsUrl(url))}let fontUrl=fontUrls.regular??null,motion=input?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:theme.motion.easing,reducedMotion:true}:theme.motion,maxScale=Number.isFinite(theme.type.maxScale)?theme.type.maxScale:DEFAULT_MAX_FONT_SCALE,scale=effectiveScale(input?.textScale),scaleCaps=tierCaps(maxScale),tierSizes=sizesByTier(theme.type.size,scale,scaleCaps,input?.scaleTypeSizes===true),color=guardInks(theme),finalized={brightness:theme.brightness,highContrast:false,meta:{displayName:displayName,logoUrl:logoUrl,placeholder:theme.meta.placeholder,hidePoweredBy:theme.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(theme.meta.assistantAvatarUrl)},color:color,space:theme.space,radius:theme.radius,type:{...theme.type,...platformFaces(theme.type,input),fontUrl:fontUrl,fontUrls:fontUrls,size:tierSizes.content,tierSizes:tierSizes,scale:scale,maxScale:maxScale,scaleCaps:scaleCaps},motion:motion,slots:guardSlotContrast(theme.slots,slotGrounds(color),slotSurrounds(color))};return input?.highContrast===true?deriveHighContrast(deepFreeze(finalized)):deepFreeze(finalized)}var ENTITLEMENTS_PATH="/widget/v1/entitlements",HTTP_NOT_MODIFIED=304,NOT_MODIFIED=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(auth,args={},funnel=createRequestFunnel({auth:auth})){let result=await funnel.send("entitlements.fetch",buildRequest(args));return result.ok?parseUpdated(result.value):result.error.httpStatus===HTTP_NOT_MODIFIED?NOT_MODIFIED:{kind:"failed",error:result.error}}var REGION_MAX=64;function buildRequest(args){let headers={};return isFiniteNumber(args.cachedRevision)&&(headers["if-none-match"]=`"${args.cachedRevision}"`),args.region&&args.region.length<=REGION_MAX?{method:"GET",path:ENTITLEMENTS_PATH,headers:headers,query:{region:args.region}}:{method:"GET",path:ENTITLEMENTS_PATH,headers:headers}}function parseUpdated(body){if(body===null||typeof body!="object"||!isFiniteNumber(body.revision))return malformed3();let region=typeof body.region=="string"?body.region:"",ttlSeconds=isFiniteNumber(body.ttl_seconds)?body.ttl_seconds:0;/* @__PURE__ */
134
41
  return Object.freeze({kind:"updated",revision:body.revision,region:region,ttlSeconds:ttlSeconds,decisions:mapCapabilities(body.capabilities),branding:parseBranding(body),livemode:body.livemode!==false,...smsProfileOf(body)})}function smsProfileOf(body){let hints=body.render_hints,raw=body.sms_profile_public??(hints!==null&&typeof hints=="object"?hints.sms_profile_public:void 0);return raw!==null&&typeof raw=="object"?{smsProfilePublic:raw}:{}}function parseBranding(body){let direct=parseClientBranding(body.branding);if(direct!==null)return direct;let hints=body.render_hints;if(hints!==null&&typeof hints=="object"){let nested=parseClientBranding(hints.branding);return nested!==null?nested:parseClientBranding(hints)}return null}function mapCapabilities(capabilities){if(capabilities===null||typeof capabilities!="object")/* @__PURE__ */return Object.freeze([]);let out=[];for(let[resource,value]of Object.entries(capabilities))isEnabled(value)&&out.push(/* @__PURE__ */Object.freeze({resource:resource,granted:true}));/* @__PURE__ */
135
- return Object.freeze(out)}function isEnabled(value){return typeof value=="object"&&value!==null&&value.enabled===true}function malformed3(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}var MIN_POLL_INTERVAL_SECONDS=30;function createEntitlementPoller(deps){let scheduler=deps.scheduler??defaultScheduler,resolve=deps.resolve??fetchEntitlements,floorSeconds=Math.max(1,deps.floorSeconds??MIN_POLL_INTERVAL_SECONDS),rng=deps.rng??Math.random,jitteredFloorSeconds=()=>floorSeconds+rng()*floorSeconds,started=false,stopped=false,timer=null,cachedRevision=null,lastCadenceSeconds=floorSeconds,generation=0,clearTimer=()=>{timer!==null&&(scheduler.clear(timer),timer=null)},schedule=seconds=>{stopped||!started||(lastCadenceSeconds=Math.max(floorSeconds,seconds),timer=scheduler.set(()=>{timer=null,run()},lastCadenceSeconds*1e3))},inFlight3=null,tick=async()=>{if(stopped)return null;let myGen=generation;deps.onFetch?.();let args=deps.region?{cachedRevision:cachedRevision,region:deps.region}:{cachedRevision:cachedRevision},resolution;try{resolution=await resolve(deps.authFor(),args)}catch(cause){return deps.telemetry?.track("sdk.entitlements.poll_error",{reason:describe2(cause)}),!stopped&&myGen===generation&&(deps.onSettled?.(),schedule(jitteredFloorSeconds())),null}if(stopped||myGen!==generation)return null;switch(resolution.kind){case"updated":cachedRevision=resolution.revision,resolution.smsProfilePublic!==void 0?deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false,resolution.smsProfilePublic):deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false),schedule(resolution.ttlSeconds);break;case"notModified":schedule(lastCadenceSeconds);break;case"failed":deps.telemetry?.track("sdk.entitlements.poll_failed",{code:resolution.error.code}),schedule(jitteredFloorSeconds());break;default:schedule(jitteredFloorSeconds())}return deps.onSettled?.(),resolution},run=()=>{let current=tick().finally(()=>{inFlight3===current&&(inFlight3=null)});return inFlight3=current,current};return{start(){started||stopped||(started=true,run())},prime(){return stopped?Promise.resolve(null):inFlight3??run()},stop(){stopped||(stopped=true,generation++,clearTimer())},refresh(){stopped||!started||(generation++,cachedRevision=null,clearTimer(),run())}}}var defaultScheduler={set(callback,ms){let handle=setTimeout(callback,ms);return handle.unref?.(),handle},clear(handle){clearTimeout(handle)}};function describe2(cause){return cause instanceof Error?cause.message:"poll failed"}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3,PER_USER_KV_KEYS=/* @__PURE__ */Object.freeze([NOTIFICATIONS_DEVICE_KV_KEY]);function startBeforeLogoutHooks(deps){let{leaving:leaving,identity:identity,hooks:hooks,telemetry:telemetry}=deps;if(leaving===null||identity===null||hooks.size===0)return null;let context=/* @__PURE__ */Object.freeze({userRef:leaving.userRef,auth:deps.graceAuth()}),runs=[...hooks].map(hook=>{try{return Promise.resolve(hook(context))}catch(cause){return Promise.reject(cause)}}),report=(reason,count2)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count2,totalCount:runs.length})}catch{}},settled=Promise.allSettled(runs).then(outcomes=>{let failed=outcomes.filter(outcome=>outcome.status==="rejected").length;failed>0&&report("failed",failed)});return new Promise(resolve=>{let done=false,finish=()=>{done||(done=true,clearTimeout(timer),resolve())},timer=setTimeout(()=>{done||report("timeout",runs.length),finish()},LOGOUT_HOOK_BUDGET_MS);settled.then(finish,finish)})}function graceAuth(deps){let{leaving:leaving,identity:identity,transport:transport,sessionId:sessionId}=deps,token=identity.currentToken();token.catch(()=>{});let frozen={userRef:leaving.userRef,currentToken:()=>token,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:transport,identity:frozen,userRef:leaving.userRef,sessionId:sessionId}}async function sweepPerUserKv(kv,telemetry){if(PER_USER_KV_KEYS.length===0)return;let results=await Promise.allSettled(PER_USER_KV_KEYS.map(key=>kv.removeItem(key))),failedCount=results.filter(result=>result.status==="rejected").length;failedCount>0&&telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:failedCount,totalCount:results.length})}function compiledDefaultDecisions(){/* @__PURE__ */
42
+ return Object.freeze(out)}function isEnabled(value){return typeof value=="object"&&value!==null&&value.enabled===true}function malformed3(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}var MIN_POLL_INTERVAL_SECONDS=30;function createEntitlementPoller(deps){let scheduler=deps.scheduler??defaultScheduler,resolve=deps.resolve??fetchEntitlements,floorSeconds=Math.max(1,deps.floorSeconds??MIN_POLL_INTERVAL_SECONDS),rng=deps.rng??Math.random,jitteredFloorSeconds=()=>floorSeconds+rng()*floorSeconds,started=false,stopped=false,timer=null,cachedRevision=null,lastCadenceSeconds=floorSeconds,generation=0,clearTimer=()=>{timer!==null&&(scheduler.clear(timer),timer=null)},schedule=seconds=>{stopped||!started||(lastCadenceSeconds=Math.max(floorSeconds,seconds),timer=scheduler.set(()=>{timer=null,run()},lastCadenceSeconds*1e3))},inFlight3=null,tick=async()=>{if(stopped)return null;let myGen=generation;deps.onFetch?.();let args=deps.region?{cachedRevision:cachedRevision,region:deps.region}:{cachedRevision:cachedRevision},resolution;try{resolution=await resolve(deps.authFor(),args)}catch(cause){return deps.telemetry?.track("sdk.entitlements.poll_error",{reason:describe2(cause)}),!stopped&&myGen===generation&&(deps.onSettled?.(),schedule(jitteredFloorSeconds())),null}if(stopped||myGen!==generation)return null;switch(resolution.kind){case"updated":cachedRevision=resolution.revision,resolution.smsProfilePublic!==void 0?deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false,resolution.smsProfilePublic):deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false),schedule(resolution.ttlSeconds);break;case"notModified":schedule(lastCadenceSeconds);break;case"failed":deps.telemetry?.track("sdk.entitlements.poll_failed",{code:resolution.error.code}),schedule(jitteredFloorSeconds());break;default:schedule(jitteredFloorSeconds())}return deps.onSettled?.(),resolution},run=()=>{let current=tick().finally(()=>{inFlight3===current&&(inFlight3=null)});return inFlight3=current,current};return{start(){started||stopped||(started=true,run())},prime(){return stopped?Promise.resolve(null):inFlight3??run()},stop(){stopped||(stopped=true,generation++,clearTimer())},refresh(){stopped||!started||(generation++,cachedRevision=null,clearTimer(),run())}}}var defaultScheduler={set(callback,ms){let handle=setTimeout(callback,ms);return handle.unref?.(),handle},clear(handle){clearTimeout(handle)}};function describe2(cause){return cause instanceof Error?cause.message:"poll failed"}function createUnreadStore(deps){let states=/* @__PURE__ */new Map,unknowns=/* @__PURE__ */new Map,unknown=petRef2=>{let key=petRef2??"",state=unknowns.get(key);return state===void 0&&(state=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:petRef2}),unknowns.set(key,state)),state},inFlight3=/* @__PURE__ */new Map,listeners2=/* @__PURE__ */new Set,generation=0,set=(petRef2,next)=>{let key=petRef2??"",previous=states.get(key)??unknown(petRef2);if(!(previous.hasUnread===next.hasUnread&&previous.unreadCount===next.unreadCount&&previous.conversationId===next.conversationId)){states.set(key,next);for(let listener of[...listeners2])listener();listeners2.size>0&&next.hasUnread!==null&&next.unreadCount!==null&&deps.emit({type:"unread_changed",petRef:petRef2,conversationId:next.conversationId,unreadCount:next.unreadCount,hasUnread:next.hasUnread})}},reportHead=(petRef2,head)=>{if(head===null){set(petRef2,/* @__PURE__ */Object.freeze({hasUnread:false,unreadCount:0,conversationId:null,petRef:petRef2}));return}if(head.unreadCount===null){set(petRef2,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:head.id,petRef:petRef2}));return}set(petRef2,/* @__PURE__ */Object.freeze({hasUnread:head.unreadCount>0,unreadCount:head.unreadCount,conversationId:head.id,petRef:petRef2}))};return{subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},get(petRef2){return states.get(petRef2??"")??unknown(petRef2)},refresh(petRef2){let key=petRef2??"",running=inFlight3.get(key);if(running!==void 0)return running;let read=deps.read(petRef2);if(read===null)return Promise.resolve();let at=generation,settled=read.then(result=>{at!==generation||!result.ok||reportHead(petRef2,result.value.conversations[0]??null)},()=>{}).finally(()=>{inFlight3.get(key)===settled&&inFlight3.delete(key)});return inFlight3.set(key,settled),settled},reportHead:reportHead,reportRead(conversationId2){for(let state of[...states.values()])state.conversationId!==conversationId2||state.unreadCount===null||state.unreadCount===0||set(state.petRef,/* @__PURE__ */Object.freeze({...state,hasUnread:false,unreadCount:0}))},reset(){if(generation+=1,inFlight3.clear(),states.size!==0){states.clear();for(let listener of[...listeners2])listener()}}}}function readConversationHead(auth,petRef2,errorPolicy){let query=historyQuery({...petRef2===null?{}:{petRef:petRef2},limit:1},100);return query.ok?createRequestFunnel({auth:auth,...errorPolicy?{errorPolicy:errorPolicy}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},{maxAttempts:1}).then(result=>result.ok?mapConversationPage(result.value):err(result.error)):Promise.resolve(err(query.error))}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3,PER_USER_KV_KEYS=/* @__PURE__ */Object.freeze([NOTIFICATIONS_DEVICE_KV_KEY]);function startBeforeLogoutHooks(deps){let{leaving:leaving,identity:identity,hooks:hooks,telemetry:telemetry}=deps;if(leaving===null||identity===null||hooks.size===0)return null;let context=/* @__PURE__ */Object.freeze({userRef:leaving.userRef,auth:deps.graceAuth()}),runs=[...hooks].map(hook=>{try{return Promise.resolve(hook(context))}catch(cause){return Promise.reject(cause)}}),report=(reason,count3)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count3,totalCount:runs.length})}catch{}},settled=Promise.allSettled(runs).then(outcomes=>{let failed=outcomes.filter(outcome=>outcome.status==="rejected").length;failed>0&&report("failed",failed)});return new Promise(resolve=>{let done=false,finish=()=>{done||(done=true,clearTimeout(timer),resolve())},timer=setTimeout(()=>{done||report("timeout",runs.length),finish()},LOGOUT_HOOK_BUDGET_MS);settled.then(finish,finish)})}function graceAuth(deps){let{leaving:leaving,identity:identity,transport:transport,sessionId:sessionId}=deps,token=identity.currentToken();token.catch(()=>{});let frozen={userRef:leaving.userRef,currentToken:()=>token,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:transport,identity:frozen,userRef:leaving.userRef,sessionId:sessionId}}async function sweepPerUserKv(kv,telemetry){if(PER_USER_KV_KEYS.length===0)return;let results=await Promise.allSettled(PER_USER_KV_KEYS.map(key=>kv.removeItem(key))),failedCount=results.filter(result=>result.status==="rejected").length;failedCount>0&&telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:failedCount,totalCount:results.length})}function compiledDefaultDecisions(){/* @__PURE__ */
136
43
  return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners2=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners2)listener()};return{subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot(){return snapshot2},set(next){snapshot2=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{},...next.smsProfilePublic!==void 0&&next.smsProfilePublic!==null?{smsProfilePublic:next.smsProfilePublic}:{}}),emit()},reset(opts){snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:opts?.keepBranding===true?snapshot2.branding??null:null,...opts?.keepBranding===true&&snapshot2.smsProfilePublic!==void 0?{smsProfilePublic:snapshot2.smsProfilePublic}:{}}),emit()},setPending(pending){snapshot2.isPending!==pending&&(snapshot2=/* @__PURE__ */Object.freeze({...snapshot2,isPending:pending}),emit())}}}var BRANDING_CACHE_KEY_PREFIX="everfur.branding.v1.";function utf8Bytes(text3){let out=[];for(let ch of text3){let cp=ch.codePointAt(0);cp<128?out.push(cp):cp<2048?out.push(192|cp>>6,128|cp&63):cp<65536?out.push(224|cp>>12,128|cp>>6&63,128|cp&63):out.push(240|cp>>18,128|cp>>12&63,128|cp>>6&63,128|cp&63)}return out}function fnv1a64Hex(text3){let hi=3421674724,lo=2216829733;for(let byte2 of utf8Bytes(text3)){lo=(lo^byte2)>>>0;let loProduct=lo*435,carry=Math.floor(loProduct/4294967296),nextLo=loProduct>>>0;hi=hi*435+carry+lo*256>>>0,lo=nextLo}return hi.toString(16).padStart(8,"0")+lo.toString(16).padStart(8,"0")}function brandingCacheKey(scope){return`${BRANDING_CACHE_KEY_PREFIX}${fnv1a64Hex(scope)}`}function serializeBranding(branding){return branding?JSON.stringify(branding):null}async function readCachedBranding(kv,scope){try{let raw=await kv.getItem(brandingCacheKey(scope));if(raw===null)return null;let parsed=parseClientBranding(JSON.parse(raw));return parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,logoUrl:hardenBrandAssetUrl(parsed.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(parsed.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(parsed.assistantAvatarUrl??null)})}catch{return null}}async function writeCachedBranding(kv,scope,serialized){try{serialized===null?await kv.removeItem(brandingCacheKey(scope)):await kv.setItem(brandingCacheKey(scope),serialized)}catch{}}function createBrandingCache(kv,scope){let lastWritten;return{restore(apply){readCachedBranding(kv,scope).then(branding=>{branding!==null&&apply(branding)})},persist(branding){let serialized=serializeBranding(branding);serialized!==lastWritten&&(lastWritten=serialized,writeCachedBranding(kv,scope,serialized))}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
137
44
  return Object.freeze({track(event,props){try{port.track(event,props)}catch{}},trackExpectedFailure(code,props){try{port.trackExpectedFailure(code,props)}catch{}}})}var ENV_HINT=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${ENV_API_BASE_URL} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function reportConfigFailure(failure2,telemetry,platform=SDK_PLATFORM){try{telemetry.trackExpectedFailure("sdk.config.invalid",{reason:failure2.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${failure2.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+ENV_HINT[platform])}function refusingTransport(failure2){/* @__PURE__ */
138
- return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}var IN_MEMORY_KVS=/* @__PURE__ */new WeakSet;function createInMemoryKv(){let map=/* @__PURE__ */new Map,kv={async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}};return IN_MEMORY_KVS.add(kv),kv}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}if(this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&(reportConfigFailure(failure2,this.telemetry,opts?.platform),this.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store,failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,fresh2,livemode,smsProfilePublic)=>{this.verdictLanded=true;let painted=this.store.getSnapshot().branding??null,branding=painted!==null&&fresh2!=null&&serializeBranding(painted)===serializeBranding(fresh2)?painted:fresh2;this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{},...smsProfilePublic!==void 0?{smsProfilePublic:smsProfilePublic}:{}}),this.brandingCache?.persist(branding??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2})});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&&notifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&&current.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),cause=>(identity.reportRejected?.(),err(mintFailedError(cause)))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll({keepBranding:true}))}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(opts){this.epoch+=1,this.disposeAllControllers(),this.store.reset(opts),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot2.branding??null,theme=useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment2=props.seams.isDevelopment;return useEffect(()=>{isDevelopment2===void 0||!safeDevelopment(isDevelopment2)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment2,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment2){try{return isDevelopment2()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=useRef(null),lastPropPetRef=useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var HEADERS_RECEIVED=2;function readEventSourceResponseHeader(instance,name){let xhr=instance?._xhr;if(!xhr||typeof xhr.getResponseHeader!="function"||typeof xhr.readyState=="number"&&xhr.readyState<HEADERS_RECEIVED)return null;let value;try{value=xhr.getResponseHeader(name)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function createRnEventSourceFactory(){let Ctor=EventSource;return(url,init)=>{let instance=new Ctor(url,{method:init.method,headers:init.headers,pollingInterval:init.pollingInterval??0,...init.body!==void 0?{body:init.body}:{}});return Object.assign(instance,{getResponseHeader:name=>readEventSourceResponseHeader(instance,name)})}}function useRnColorScheme(){let colorScheme=useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=useState(false);return useEffect(()=>{let mounted=true,query=AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=useState(false);return useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(AccessibilityInfo);isThenable(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh2=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh2.length===0)return;for(let field of fresh2)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh2.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});function wrapInSafeArea(children){return createElement(SafeAreaProvider,null,children)}var rnSeams=/* @__PURE__ */Object.freeze({platform:"react-native",...Platform.OS==="web"?{}:{eventSourceFactory:createRnEventSourceFactory()},wrap:wrapInSafeArea,theme:rnThemeSeams});function EverfurProvider(props){return createElement(EverfurProviderCore,{...props,seams:rnSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
45
+ return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}var IN_MEMORY_KVS=/* @__PURE__ */new WeakSet;function createInMemoryKv(){let map=/* @__PURE__ */new Map,kv={async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}};return IN_MEMORY_KVS.add(kv),kv}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}if(this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&(reportConfigFailure(failure2,this.telemetry,opts?.platform),this.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store,this.unread=createUnreadStore({read:petRef2=>this.disposed||this.currentUser===null||this.configFailure!==null?null:readConversationHead(this.buildAuth(this.currentUser.userRef),petRef2,this.errorPolicy),emit:event=>this.emit(event)}),failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,fresh2,livemode,smsProfilePublic)=>{this.verdictLanded=true;let painted=this.store.getSnapshot().branding??null,branding=painted!==null&&fresh2!=null&&serializeBranding(painted)===serializeBranding(fresh2)?painted:fresh2;this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{},...smsProfilePublic!==void 0?{smsProfilePublic:smsProfilePublic}:{}}),this.brandingCache?.persist(branding??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2}),unread:this.unread});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&&notifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&&current.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),cause=>(identity.reportRejected?.(),err(mintFailedError(cause)))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll({keepBranding:true}))}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(opts){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(opts),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot2.branding??null,theme=useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment2=props.seams.isDevelopment;return useEffect(()=>{isDevelopment2===void 0||!safeDevelopment(isDevelopment2)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment2,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment2){try{return isDevelopment2()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=useRef(null),lastPropPetRef=useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var HEADERS_RECEIVED=2;function readEventSourceResponseHeader(instance,name){let xhr=instance?._xhr;if(!xhr||typeof xhr.getResponseHeader!="function"||typeof xhr.readyState=="number"&&xhr.readyState<HEADERS_RECEIVED)return null;let value;try{value=xhr.getResponseHeader(name)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function createRnEventSourceFactory(){let Ctor=EventSource;return(url,init)=>{let instance=new Ctor(url,{method:init.method,headers:init.headers,pollingInterval:init.pollingInterval??0,...init.body!==void 0?{body:init.body}:{}});return Object.assign(instance,{getResponseHeader:name=>readEventSourceResponseHeader(instance,name)})}}function useRnColorScheme(){let colorScheme=useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=useState(false);return useEffect(()=>{let mounted=true,query=AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=useState(false);return useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(AccessibilityInfo);isThenable(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh2=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh2.length===0)return;for(let field of fresh2)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh2.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});function wrapInSafeArea(children){return createElement(SafeAreaProvider,null,children)}var rnSeams=/* @__PURE__ */Object.freeze({platform:"react-native",...Platform.OS==="web"?{}:{eventSourceFactory:createRnEventSourceFactory()},wrap:wrapInSafeArea,theme:rnThemeSeams});function EverfurProvider(props){return createElement(EverfurProviderCore,{...props,seams:rnSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
139
46
  return jsx(View,{style:[styles3.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsx(View,{style:styles3.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
140
47
  return jsx(View,{style:[styles3.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsx(Text,{style:styles3.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var TelevetHostSlot=createContext(null);function TelevetHostOutlet(){let Host=useContext(TelevetHostSlot);return Host===null?null:/* @__PURE__ */jsx(Host,{})}var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present2=televetGlobal().presenter;if(present2===null)return"absent";try{return present2(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=useState(null);useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot2=useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot2.activeHost===id?snapshot2.request:null,[module,setModule]=useState(null),wanted=request!==null&&module===null;return useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot2.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>Promise.resolve(bookingExperience));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}={}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetModal:EverfurTelevetModal}=host.module;/* @__PURE__ */
141
48
  return jsx(EverfurTelevetModal,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var str4=(value,max=4e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null;function httpsUrl(value){let s=str4(value,2048);return s===null?null:/^https:\/\/[^\s]+$/i.test(s)?s:null}var DETAIL_ROWS=6;function boundOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=400?value:null}function rowsOf(value,each,max){if(!Array.isArray(value))/* @__PURE__ */return Object.freeze([]);let out=[];for(let raw of value){if(out.length>=max)break;if(raw===null||typeof raw!="object"||Array.isArray(raw))continue;let row=each(raw);row!==null&&out.push(row)}/* @__PURE__ */
142
49
  return Object.freeze(out)}function titledOf(o){let title=str4(o.title,80),body=str4(o.body,600);return title===null||body===null?null:/* @__PURE__ */Object.freeze({title:title,body:body})}function healthPlanItemDetailOf(value){if(value===null||typeof value!="object"||Array.isArray(value))return;let o=value,gallery=[];if(Array.isArray(o.gallery))for(let g of o.gallery){let url=httpsUrl(g);url!==null&&gallery.length<DETAIL_ROWS&&gallery.push(url)}let doses=rowsOf(o.doses,d=>{let label=str4(d.label,60),amount=str4(d.amount,60);return label===null||amount===null?null:/* @__PURE__ */Object.freeze({label:label,amount:amount,minLb:boundOf(d.minLb??d.min_lb),maxLb:boundOf(d.maxLb??d.max_lb)})},DETAIL_ROWS),details=rowsOf(o.details,titledOf,DETAIL_ROWS),fitRaw=o.fit,fitRow=fitRaw!==null&&typeof fitRaw=="object"&&!Array.isArray(fitRaw)?titledOf(fitRaw):null,fit=fitRow!==null&&fitRaw.pet===true?/* @__PURE__ */Object.freeze({...fitRow,pet:true}):fitRow,detail=/* @__PURE__ */Object.freeze({kicker:str4(o.kicker,80),gallery:/* @__PURE__ */Object.freeze(gallery),doses:doses,details:details,fine:str4(o.fine,300),fit:fit});return detail.kicker===null&&gallery.length===0&&doses.length===0&&details.length===0&&detail.fine===null&&fit===null?void 0:detail}var REF_MAX2=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),TONES=/* @__PURE__ */new Set(["y","c","g","r"]),TRACK_STATES=/* @__PURE__ */new Set(["done","now","next"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str5=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str5(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str5(value,REF_MAX2);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
143
50
  return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str5(v,len),max);function focusOf(value){let o=obj(value),kicker=str5(o?.kicker,120),title=str5(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str5(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str5(risk?.lead,300)===null?null:clean({lead:str5(risk?.lead,300),body:str5(risk?.body),kind:kindOf(risk?.kind)}),odds:str5(odds?.label,120)===null||str5(odds?.from,20)===null||str5(odds?.to,20)===null?null:clean({label:str5(odds?.label,120),tag:str5(odds?.tag,40),from:str5(odds?.from,20),to:str5(odds?.to,20),toLabel:str5(odds?.toLabel,120)}),quote:str5(quote?.text)===null?null:clean({kicker:str5(quote?.kicker,120),tag:str5(quote?.tag,40),text:str5(quote?.text)}),jump:str5(jump?.title,300)===null||str5(jump?.go,60)===null?null:clean({title:str5(jump?.title,300),go:str5(jump?.go,60)}),report:reportOf(o.report)})}function reportOf(value){let o=obj(value),label=str5(o?.label,120),text3=str5(o?.text,1200);return label===null||text3===null?null:clean({label:label,text:text3,actions:words(o?.actions,5,300)})}function routineOf(value){let o=obj(value),title=str5(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str5(s?.title,300),tone=s?.tone;return t===null?null:clean({title:t,body:str5(s?.body),source:str5(s?.source,200),tone:typeof tone=="string"&&TONES.has(tone)?tone:null,icon:iconOf(s?.icon),fromVet:s?.fromVet===true?true:null})});return title===null||steps===null?null:clean({title:title,label:str5(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str5(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text3=str5(v?.text),by=str5(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text3===null||by===null?null:clean({stars:Math.round(stars),text:text3,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str5(v?.chip,40),t=str5(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str5(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str5(v?.value,40),label=str5(v?.label,120),kind=v?.kind;return val===null||label===null?null:clean({value:val,label:label,kind:kind==="weight"||kind==="dose"||kind==="days"?kind:null})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,none:o.none===true?true:null,hidden:o.none===true&&o.hidden===true?true:null,productId:idOf(o.productId),partnerSku:str5(o.partnerSku,200),rating:str5(rating?.value,20)===null?null:clean({value:str5(rating?.value,20),label:str5(rating?.label,120)}),line:str5(o.line),reviews:str5(reviews?.label,200)===null||reviewItems===null?null:clean({label:str5(reviews?.label,200),items:reviewItems}),checkoutLine:str5(o.checkoutLine,300),why:str5(why?.title,200)===null||whyRows===null?null:clean({title:str5(why?.title,200),rows:whyRows,score:str5(score?.text,200)===null||str5(score?.value,20)===null?null:clean({text:str5(score?.text,200),value:str5(score?.value,20)})}),dose:str5(dose?.title,200)===null||stats===null?null:clean({title:str5(dose?.title,200),stats:stats,note:str5(dose?.note)}),doseLabel:str5(o.doseLabel,120),ingredients:ingredientItems===null?null:clean({label:str5(ingredients?.label,200),items:ingredientItems}),proof:str5(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str5(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str5(o.more,120),fine:str5(o.fine),checkin:str5(o.checkin,200),detail:healthPlanItemDetailOf(o.detail)??null})}function signsOf(value){let o=obj(value),title=str5(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str5(v?.title,300),body=str5(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null,callVet:v?.callVet===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str5(o?.title,200),questions=words(o?.questions,12,300),add=str5(o?.add,80),added=str5(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str5(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str5(v?.key,REF_MAX2),t=str5(v?.title,300),action=str5(v?.action,80),productId=idOf(v?.productId),added=str5(v?.added,80)??(productId!==null?action:null);return key===null||t===null||action===null||added===null?null:clean({key:key,productId:productId,title:t,body:str5(v?.body),price:str5(v?.price,40),was:str5(v?.was,40),tag:str5(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added,owned:v?.owned===true?true:null,detail:healthPlanItemDetailOf(v?.detail)??null})},6);return title===null||items===null?null:clean({title:title,items:items})}function waitOf(value){let o=obj(value),kicker=str5(o?.kicker,120),title=str5(o?.title,120);return o===null||kicker===null||title===null?null:clean({kicker:kicker,title:title,icon:iconOf(o.icon),track:listOf(o.track,r=>{let v=obj(r),t=str5(v?.title,120),state=v?.state;return t===null?null:clean({title:t,detail:str5(v?.detail,120),state:typeof state=="string"&&TRACK_STATES.has(state)?state:null,tag:str5(v?.tag,40)})},6),heading:str5(o.heading,200),rows:listOf(o.rows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str5(v?.label,120);if(icon===null||label===null)return null;if(v?.fromVet===true)return clean({icon:icon,label:label,text:"",fromVet:true});let text3=str5(v?.text,300);return text3===null?null:clean({icon:icon,label:label,text:text3})},6),note:str5(o.note,300),action:str5(o.action,80)})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str5(o?.title,300),pick5=pickOf(o?.pick);if(o===null||title===null||pick5===null)return null;let byline=obj(o.byline);return clean({eyebrow:str5(o.eyebrow,120),title:title,subtitle:str5(o.subtitle,300),subtitleNoRecords:str5(o.subtitleNoRecords,300),headImageUrl:imageOf(o.headImageUrl),byline:str5(byline?.name,120)===null?null:clean({name:str5(byline?.name,120),role:str5(byline?.role,120),imageUrl:imageOf(byline?.imageUrl),shortName:str5(byline?.shortName,60)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick5,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),wait:waitOf(o.wait),fine:str5(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str5(v?.label,60),val=str5(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef2){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
144
51
  return Object.freeze({petRef:str5(o.pet_ref,REF_MAX2)??petRef2,pet:/* @__PURE__ */Object.freeze({name:str5(pet?.name,120),species:str5(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str5(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid3(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed4(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX2;function base(petRef2){return`/widget/v1/pets/${encodeURIComponent(petRef2)}/plan`}async function readPage(funnel,petRef2,opts){if(!validRef(petRef2))return err(invalid3("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef2)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef2);return page===null?err(malformed4("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef2,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef2,opts)}}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable2(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 isThenable2(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 callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=useRef(refreshKey);useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=HEALTH_PLAN_STALE_MS,SHARED_READS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function sharedReads(){let host=globalThis,stored2=host[SHARED_READS_SYMBOL];if(stored2 instanceof WeakMap)return stored2;let made=/* @__PURE__ */new WeakMap;return host[SHARED_READS_SYMBOL]=made,made}function readShared(reader,runtime,userRef2,petRef2,fresh2){let all=sharedReads(),reads=all.get(runtime);reads===void 0&&(reads=/* @__PURE__ */new Map,all.set(runtime,reads));let map=reads,key=`${userRef2}\0${petRef2}`,hit=map.get(key);if(!fresh2&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef2).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef2,runtime:runtime}=useEverfurContext(),own=useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=useCallback((pet,fresh2)=>hostRepository!==void 0||userRef2==null?repository.getPage(pet):readShared(own,runtime,userRef2,pet,fresh2),[hostRepository,repository,own,runtime,userRef2]),{petRef:petRef2}=options,enabled=options.enabled!==false&&userRef2!=null&&petRef2!==null,[state,setState]=useState({phase:"idle",petRef:null,page:null,error:null}),epoch=useRef(0),quiet=useRef(0),read=useCallback(async fresh2=>{let mine=++epoch.current;if(!enabled||petRef2===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef2,page:prev.petRef===petRef2?prev.page:null,error:null}));let res=await getPage(petRef2,fresh2);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef2,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef2,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef2,page:null,error:res.error}))},[enabled,petRef2,getPage]),load=useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef2,revalidate=useCallback(async()=>{if(!enabled||petRef2===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef2,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef2?{phase:"ready",petRef:petRef2,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef2,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef2;return useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}function definedPresentation(input){let out={};for(let[key,value]of Object.entries(input))value!==void 0&&(out[key]=value);return out}function selectView2(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
145
- return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(state,policy){if(policy===void 0)return visibleFollowUps(state);let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let count2=Math.max(1,Math.min(MAX_POLICY_FOLLOW_UPS,Math.floor(policy.count??MAX_VISIBLE_FOLLOW_UPS))),question=null;for(let i=state.messages.length-1;i>=0;i-=1){let m=state.messages[i];if(m!==void 0&&m.role==="user"){question=m.text;break}}let norm=t=>t.trim().replace(/\s+/g," ").toLowerCase(),seen=new Set(question===null?[]:[norm(question)]),out=[],take=prompt=>{let text3=prompt.trim(),key=norm(text3);out.length>=count2||key.length===0||seen.has(key)||excluded(policy.exclude,text3)||(seen.add(key),out.push(text3))};for(let prompt of state.suggestedPrompts)take(prompt);let fill=[];try{fill=typeof policy.fill=="function"?policy.fill(question):policy.fill??[]}catch{fill=[]}for(let prompt of Array.isArray(fill)?fill:[])typeof prompt=="string"&&take(prompt);/* @__PURE__ */
146
- return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef2,conversationId2){let opts={};return petRef2!==void 0&&(opts.petRef=petRef2),conversationId2!==void 0&&(opts.conversationId=conversationId2),opts}var TELEVET_FOLLOW_UP=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function excludes(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpPolicyFor(host,presentation,countLocked){let televet=presentation.chatFollowUpsExcludeTelevet,count2=host?.count!==void 0&&!countLocked?host.count:presentation.chatFollowUpCount;if(host===void 0&&count2===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count2<=0)return{...host??{},count:1,exclude:NONE,fill:[]};let hostExclude=host?.exclude,exclude=televet?prompt=>TELEVET_FOLLOW_UP.test(prompt)||excludes(hostExclude,prompt):hostExclude;return{...host??{},count:count2,...exclude!==void 0?{exclude:exclude}:{}}}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var NONE2=/* @__PURE__ */Object.freeze({});function useSentImages(messages){let[byMessage,setByMessage]=useState(NONE2),pending=useRef(null),knownIds=useRef([]);knownIds.current=messages.map(message=>message.id),useEffect(()=>{if(messages.length===0){pending.current=null,setByMessage(current=>current===NONE2?current:NONE2);return}let staged=pending.current;if(staged===null)return;let bubble=messages.find(message=>message.role==="user"&&!staged.known.has(message.id));bubble!==void 0&&(pending.current=null,setByMessage(current=>({...current,[bubble.id]:staged.images})))},[messages]);let stage=useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}var NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt,key){let clean3=sanitizeSeedPrompt(prompt),id=clean3===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean3}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight3=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean3===null||id===null||isBootstrapping||done.current===id||inFlight3.current===id)return;let ask=latest.current;if(ask===void 0)return;inFlight3.current=id;let settle=result=>{inFlight3.current===id&&(inFlight3.current=null),!isChatNotReadyResult(result)&&current.current===id&&(done.current=id)};Promise.resolve(ask(clean3)).then(settle,()=>settle(void 0))},[clean3,id,isBootstrapping,askEverfur])}function isCoalesced(trigger,conversationId2,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId2=state.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:petName?.trim()||CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason(petName)}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=useState(null),[expanded,setExpanded]=useState(false);useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
52
+ return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(state,policy){if(policy===void 0)return visibleFollowUps(state);let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let count3=Math.max(1,Math.min(MAX_POLICY_FOLLOW_UPS,Math.floor(policy.count??MAX_VISIBLE_FOLLOW_UPS))),question=null;for(let i=state.messages.length-1;i>=0;i-=1){let m=state.messages[i];if(m!==void 0&&m.role==="user"){question=m.text;break}}let norm=t=>t.trim().replace(/\s+/g," ").toLowerCase(),seen=new Set(question===null?[]:[norm(question)]),out=[],take=prompt=>{let text3=prompt.trim(),key=norm(text3);out.length>=count3||key.length===0||seen.has(key)||excluded(policy.exclude,text3)||(seen.add(key),out.push(text3))};for(let prompt of state.suggestedPrompts)take(prompt);let fill=[];try{fill=typeof policy.fill=="function"?policy.fill(question):policy.fill??[]}catch{fill=[]}for(let prompt of Array.isArray(fill)?fill:[])typeof prompt=="string"&&take(prompt);/* @__PURE__ */
53
+ return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef2,conversationId2){let opts={};return petRef2!==void 0&&(opts.petRef=petRef2),conversationId2!==void 0&&(opts.conversationId=conversationId2),opts}var TELEVET_FOLLOW_UP=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function excludes(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpPolicyFor(host,presentation,countLocked){let televet=presentation.chatFollowUpsExcludeTelevet,count3=host?.count!==void 0&&!countLocked?host.count:presentation.chatFollowUpCount;if(host===void 0&&count3===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count3<=0)return{...host??{},count:1,exclude:NONE,fill:[]};let hostExclude=host?.exclude,exclude=televet?prompt=>TELEVET_FOLLOW_UP.test(prompt)||excludes(hostExclude,prompt):hostExclude;return{...host??{},count:count3,...exclude!==void 0?{exclude:exclude}:{}}}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var NONE2=/* @__PURE__ */Object.freeze({});function useSentImages(messages){let[byMessage,setByMessage]=useState(NONE2),pending=useRef(null),knownIds=useRef([]);knownIds.current=messages.map(message=>message.id),useEffect(()=>{if(messages.length===0){pending.current=null,setByMessage(current=>current===NONE2?current:NONE2);return}let staged=pending.current;if(staged===null)return;let bubble=messages.find(message=>message.role==="user"&&!staged.known.has(message.id));bubble!==void 0&&(pending.current=null,setByMessage(current=>({...current,[bubble.id]:staged.images})))},[messages]);let stage=useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}var NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt,key){let clean3=sanitizeSeedPrompt(prompt),id=clean3===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean3}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight3=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean3===null||id===null||isBootstrapping||done.current===id||inFlight3.current===id)return;let ask=latest.current;if(ask===void 0)return;inFlight3.current=id;let settle=result=>{inFlight3.current===id&&(inFlight3.current=null),!isChatNotReadyResult(result)&&current.current===id&&(done.current=id)};Promise.resolve(ask(clean3)).then(settle,()=>settle(void 0))},[clean3,id,isBootstrapping,askEverfur])}function isCoalesced(trigger,conversationId2,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId2=state.activeConversationId===null||state.activeConversationId.length===0?null:state.activeConversationId;return conversationId2===null&&state.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}var OPEN_UNREAD_HEAD=/* @__PURE__ */Object.freeze({openUnreadHead:true});function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh,refreshesBlankThread:refreshesBlankThread}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,refreshesBlankThread:refreshesBlankThread===true,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}var HANDOFF_TOKEN=/^efch_[A-Za-z0-9_-]{43}$/,FRAGMENT_KEY="efch";function isChatHandoffToken(value){return typeof value=="string"&&HANDOFF_TOKEN.test(value)}function chatHandoffTokenFromUrl(url){if(typeof url!="string")return null;let hash=url.indexOf("#");if(hash<0)return null;for(let pair of url.slice(hash+1).split("&")){if(!pair.startsWith(`${FRAGMENT_KEY}=`))continue;let value=pair.slice(FRAGMENT_KEY.length+1);return isChatHandoffToken(value)?value:null}return null}var MAX_PET_REF_LENGTH=128,CONTROL_CHAR2=/[\u0000-\u001f\u007f]/;function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:null}function petRefOf(value){return typeof value!="string"||value.length===0||value.length>MAX_PET_REF_LENGTH||CONTROL_CHAR2.test(value)||value.includes("://")?null:value}function targetOf(body){if(body===null)return null;let conversationId2=body.conversation_id,petRef2=petRefOf(body.pet_ref);return typeof conversationId2!="string"||!validConversationId(conversationId2)||petRef2===null?null:{conversationId:conversationId2,petRef:petRef2}}function redeemChatHandoff(auth,token,errorPolicy){return isChatHandoffToken(token)?createRequestFunnel({auth:auth,...errorPolicy?{errorPolicy:errorPolicy}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:token}},{maxAttempts:1}).then(result=>result.ok?ok(targetOf(record(result.value))):result.error.httpStatus===404?ok(null):err(result.error),()=>err(makeError("internalError",false))):Promise.resolve(ok(null))}function useChatHandoffTarget(token,context){let runtime=context?.runtime??null,userRef2=context?.userRef??null,valid=isChatHandoffToken(token)?token:null,key=valid===null||userRef2===null?null:`${String(userRef2)}|${valid}`,[landed,setLanded]=useState(null);return useEffect(()=>{if(key===null||valid===null||userRef2===null||runtime===null)return;let live=true,services=runtime.registry.services;return redeemChatHandoff(services.authFor(userRef2),valid,services.errorPolicy).then(result=>{!live||!result.ok||result.value===null||setLanded({key:key,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:result.value.conversationId,petRef:result.value.petRef})})}),()=>{live=false}},[key,runtime,valid,userRef2]),landed!==null&&landed.key===key?landed.target:void 0}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target,scope){let key=targetKey(target),forChat=target?.kind==="chat",wanted=target?.petRef??null,elsewhere=forChat&&!scope.pinned&&wanted!==null&&scope.petRef!==null&&wanted!==scope.petRef,latest=useRef({openCheckin:openCheckin,target:target,selectPet:scope.selectPet});latest.current={openCheckin:openCheckin,target:target,selectPet:scope.selectPet};let opened=useRef(null),moved=useRef(null),petRef2=scope.petRef;useEffect(()=>{if(key===null||opened.current===key)return;let{openCheckin:open,target:current,selectPet:selectPet}=latest.current;if(elsewhere&&wanted!==null){if(moved.current?.key!==key){moved.current={key:key,from:petRef2},selectPet(wanted);return}petRef2!==moved.current.from&&(opened.current=key);return}forChat&&!scope.ready||(opened.current=key,!(open===void 0||current===void 0)&&Promise.resolve(open(current)).catch(()=>{}))},[key,forChat,elsewhere,wanted,petRef2,scope.ready])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count3,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count3}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:petName?.trim()||CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason(petName)}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=useState(null),[expanded,setExpanded]=useState(false);useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}var EVERFUR_LINK_DOMAIN="everfur.com",MAX_LINK_LENGTH=2048,HOST_ENTRY=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function normalizeLinkHosts(hosts){if(!Array.isArray(hosts))return[];let out=/* @__PURE__ */new Set;for(let entry of hosts){if(typeof entry!="string")continue;let host=entry.trim().toLowerCase();host.length<=253&&HOST_ENTRY.test(host)&&out.add(host)}/* @__PURE__ */
54
+ return Object.freeze([...out])}function isLinkHost(hostname,hosts){if(hostname===EVERFUR_LINK_DOMAIN||hostname.endsWith(`.${EVERFUR_LINK_DOMAIN}`))return true;for(let entry of hosts)if(entry.startsWith("*.")?hostname.endsWith(entry.slice(1)):hostname===entry)return true;return false}function linkHref(raw,hosts){if(typeof raw!="string"||raw.length===0||raw.length>MAX_LINK_LENGTH||!/^https:\/\//i.test(raw))return null;let url=parseUrl(raw);return url===null||url.protocol!=="https:"||url.username!==""||url.password!==""||url.port!==""?null:isLinkHost(url.hostname,hosts)?url.href:null}function openInBrowser(href){try{Promise.resolve(Linking.openURL(href)).catch(()=>{})}catch{}}var MessageLinksContext=createContext(null);function useMessageLinks(){return useContext(MessageLinksContext)??void 0}function MessageLinksScope({linkHosts:linkHosts,onOpenUrl:onOpenUrl,children:children}){let key=Array.isArray(linkHosts)?linkHosts.join(`\n`):null,value=useMemo(()=>{if(key===null)return null;let hosts=normalizeLinkHosts(key===""?[]:key.split(`\n`));/* @__PURE__ */
55
+ return Object.freeze({hosts:hosts,open:onOpenUrl!==void 0?href=>{callHost(onOpenUrl,href,"message")}:openInBrowser})},[key,onOpenUrl]);return createElement(MessageLinksContext.Provider,{value:value},children)}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
147
56
  return jsxs(View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
148
57
  /* @__PURE__ */jsx(View,{style:bar}),
149
58
  /* @__PURE__ */jsx(View,{style:bar}),
@@ -291,10 +200,10 @@ return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:option.lab
291
200
  /* @__PURE__ */jsx(TextInput,{style:styles3.input,placeholder:CHAT_COPY.feedbackNotesPlaceholder,placeholderTextColor:theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.feedbackNotesPlaceholder,value:note,onChangeText:setNote,multiline:true,editable:!pending}),note.length>0?/* @__PURE__ */jsx(Text,{tier:"compact",style:[styles3.counter,overLimit?styles3.counterOver:null],children:`${[...note].length}/${FEEDBACK_NOTES_MAX_CHARS}`}):null]}),failed?/* @__PURE__ */jsx(Text,{style:styles3.failed,accessibilityRole:"alert",children:CHAT_COPY.feedbackFailed}):null,
292
201
  /* @__PURE__ */jsxs(View,{style:styles3.actions,children:[
293
202
  /* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSubmit,accessibilityState:{busy:pending,disabled:pending||overLimit},disabled:pending||overLimit,style:[styles3.submit,pending||overLimit?styles3.submitDisabled:null],onPress:()=>{submit()},children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.submitLabel,children:CHAT_COPY.feedbackSubmit})}),
294
- /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles3.skip,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles10(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots,dialogText=slotText(slots.dialog);return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ABSOLUTE_FILL,backgroundColor:SCRIM},sheet:{backgroundColor:c.surface,borderTopLeftRadius:SHEET_RADIUS,borderTopRightRadius:SHEET_RADIUS,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:HANDLE_WIDTH,height:HANDLE_HEIGHT,borderRadius:HANDLE_HEIGHT/2,backgroundColor:c.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:BADGE_SIZE,height:BADGE_SIZE,borderRadius:BADGE_SIZE/2,alignItems:"center",justifyContent:"center",backgroundColor:c.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(theme,"bold"),fontSize:20,lineHeight:28,color:c.text.primary,letterSpacing:t.letterSpacing.tight,...dialogText},subtitle:{...face(theme,"regular"),fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.relaxed,color:c.text.muted,...dialogText},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:r.md,borderWidth:StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface,...slotBox(slots.chip,StyleSheet.hairlineWidth)},optionSelected:{borderColor:c.brandInk,backgroundColor:c.brandSoft},optionLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.primary,...slotText(slots.chip)},optionLabelSelected:{color:c.brandInk},radio:{width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:RADIO_SIZE/2,borderWidth:2,borderColor:c.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:c.brandInk,backgroundColor:c.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(theme,"regular"),fontSize:t.size.body,color:c.text.primary,textAlignVertical:"top",...slotBox(slots.input,1),...slotText(slots.input)},counter:{...face(theme,"mono"),alignSelf:"flex-end",fontSize:t.size.caption,letterSpacing:.3,color:c.text.placeholder},counterOver:{color:c.danger},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.xl,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.onPrimary,...slotText(slots.primaryButton)},skip:{minHeight:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.lg},skipLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.muted}})}var KEY2=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function shared2(){let g=globalThis,hit=g[KEY2];if(hit!==void 0)return hit;let fresh2={factory:createContext(null),home:createContext(null)};return g[KEY2]=fresh2,fresh2}var AskHomeFactoryContext=shared2().factory,AskHomeContext=shared2().home;function useAskHomeFactory(){return useContext(AskHomeFactoryContext)}function useAskHome(){return useContext(AskHomeContext)?.kit??null}function useAskHomeTitle(){return useContext(AskHomeContext)}var BAR_SIZE=15,UNREAD_DOT=8;function HistoryBar({bar:bar,history:history,empty:empty,unread:unread,extra:extra}){let theme=useEverfurTheme(),home=useAskHome(),styles3=useMemo(()=>home!==null?homeStyles(theme,home):makeStyles11(theme),[theme,home]),count2=history.cursor===null?history.rows.length:0,icon=name=>{let render=bar.renderIcon;return render===void 0?null:/* @__PURE__ */jsx(HostRender,{render:()=>render(name),fallback:null})};/* @__PURE__ */
203
+ /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles3.skip,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles10(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots,dialogText=slotText(slots.dialog);return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ABSOLUTE_FILL,backgroundColor:SCRIM},sheet:{backgroundColor:c.surface,borderTopLeftRadius:SHEET_RADIUS,borderTopRightRadius:SHEET_RADIUS,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:HANDLE_WIDTH,height:HANDLE_HEIGHT,borderRadius:HANDLE_HEIGHT/2,backgroundColor:c.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:BADGE_SIZE,height:BADGE_SIZE,borderRadius:BADGE_SIZE/2,alignItems:"center",justifyContent:"center",backgroundColor:c.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(theme,"bold"),fontSize:20,lineHeight:28,color:c.text.primary,letterSpacing:t.letterSpacing.tight,...dialogText},subtitle:{...face(theme,"regular"),fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.relaxed,color:c.text.muted,...dialogText},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:r.md,borderWidth:StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface,...slotBox(slots.chip,StyleSheet.hairlineWidth)},optionSelected:{borderColor:c.brandInk,backgroundColor:c.brandSoft},optionLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.primary,...slotText(slots.chip)},optionLabelSelected:{color:c.brandInk},radio:{width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:RADIO_SIZE/2,borderWidth:2,borderColor:c.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:c.brandInk,backgroundColor:c.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(theme,"regular"),fontSize:t.size.body,color:c.text.primary,textAlignVertical:"top",...slotBox(slots.input,1),...slotText(slots.input)},counter:{...face(theme,"mono"),alignSelf:"flex-end",fontSize:t.size.caption,letterSpacing:.3,color:c.text.placeholder},counterOver:{color:c.danger},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.xl,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.onPrimary,...slotText(slots.primaryButton)},skip:{minHeight:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.lg},skipLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.muted}})}var KEY2=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function shared2(){let g=globalThis,hit=g[KEY2];if(hit!==void 0)return hit;let fresh2={factory:createContext(null),home:createContext(null)};return g[KEY2]=fresh2,fresh2}var AskHomeFactoryContext=shared2().factory,AskHomeContext=shared2().home;function useAskHomeFactory(){return useContext(AskHomeFactoryContext)}function useAskHome(){return useContext(AskHomeContext)?.kit??null}function useAskHomeTitle(){return useContext(AskHomeContext)}var BAR_SIZE=15,UNREAD_DOT=8;function HistoryBar({bar:bar,history:history,empty:empty,unread:unread,extra:extra}){let theme=useEverfurTheme(),home=useAskHome(),styles3=useMemo(()=>home!==null?homeStyles(theme,home):makeStyles11(theme),[theme,home]),count3=history.cursor===null?history.rows.length:0,icon=name=>{let render=bar.renderIcon;return render===void 0?null:/* @__PURE__ */jsx(HostRender,{render:()=>render(name),fallback:null})};/* @__PURE__ */
295
204
  return jsxs(View,{style:styles3.bar,testID:"everfur-history-bar",children:[
296
- /* @__PURE__ */jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:count2>0?`${bar.chats} ${count2}`:bar.chats,accessibilityState:{expanded:history.open},onPress:history.open?history.close:history.show,style:styles3.control,hitSlop:home!==null?HOME_SLOP:void 0,children:[icon("history"),
297
- /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.label,children:bar.chats}),count2>0?/* @__PURE__ */jsx(View,{style:styles3.count,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles3.countText,children:String(count2)})}):null,unread?/* @__PURE__ */jsx(View,{style:styles3.dot,testID:"everfur-chat-history-bar-unread"}):null]}),bar.extra??null,extra??null,
205
+ /* @__PURE__ */jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:count3>0?`${bar.chats} ${count3}`:bar.chats,accessibilityState:{expanded:history.open},onPress:history.open?history.close:history.show,style:styles3.control,hitSlop:home!==null?HOME_SLOP:void 0,children:[icon("history"),
206
+ /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.label,children:bar.chats}),count3>0?/* @__PURE__ */jsx(View,{style:styles3.count,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles3.countText,children:String(count3)})}):null,unread?/* @__PURE__ */jsx(View,{style:styles3.dot,testID:"everfur-chat-history-bar-unread"}):null]}),bar.extra??null,extra??null,
298
207
  /* @__PURE__ */jsx(View,{style:styles3.spacer}),empty?null:/* @__PURE__ */jsxs(Pressable,{accessibilityRole:"button",accessibilityLabel:bar.newChat,onPress:history.newConversation,style:styles3.control,hitSlop:home!==null?HOME_SLOP:void 0,children:[icon("edit"),
299
208
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.label,children:bar.newChat})]})]})}var HOME_SLOP=4;function homeStyles(theme,home){return{...makeStyles11(theme),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm},control:home.view(".thread__hist"),label:home.text(".thread__hist"),count:home.view(".thread__count"),countText:home.text(".thread__count")}}function makeStyles11(theme){let c=theme.color,s=theme.space;return StyleSheet.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm,paddingHorizontal:s.lg,paddingVertical:s.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:MIN_TOUCH_TARGET},label:{...face(theme,"bold"),fontSize:BAR_SIZE,color:c.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,alignItems:"center"},countText:{...face(theme,"bold"),fontSize:theme.type.size.caption,color:c.text.primary},dot:{width:UNREAD_DOT,height:UNREAD_DOT,borderRadius:UNREAD_DOT/2,backgroundColor:c.danger},spacer:{flexGrow:1}})}var PANEL_WIDTH_FRACTION=.88,PANEL_MAX_WIDTH=420,PANEL_PADDING_TOP=58,BACKDROP3="rgba(17,17,17,0.28)",ACTIVE_ROW_ALPHA=.15,ACTION_SIZE=14,LABEL_SIZE=12,CONTROL_SIZE=44,CLOSE_GLYPH2=16,CARD_RADIUS2=14,ERROR_RADIUS=12,SEARCH_GLYPH=14,UNREAD_DOT2=8,HALF_STEP2=2,END_REACHED_THRESHOLD=.5,STANDARD2=bezierEasing(CHAT_EASING.standard);function drawerPanelWidth(windowWidth){return Math.min(Math.round(windowWidth*PANEL_WIDTH_FRACTION),PANEL_MAX_WIDTH)}function HistoryDrawer({chat:chat,history:history}){let[mounted,setMounted]=useState(history.open),onHidden=useCallback(()=>setMounted(false),[]);return history.open&&!mounted&&setMounted(true),mounted?/* @__PURE__ */jsx(DrawerModal,{chat:chat,history:history,onHidden:onHidden}):null}function DrawerModal({chat:chat,history:history,onHidden:onHidden}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles12(theme),[theme]),motion=useChatMotion(),insets=useSafeAreaInsets(),{width:width}=useWindowDimensions(),panelWidth=drawerPanelWidth(width),open=history.open,progress=useRef(null);progress.current===null&&(progress.current=new Animated.Value(motion.drawerMs<=0&&open?1:0));let value=progress.current;useEffect(()=>{if(!open&&motion.drawerMs<=0){onHidden();return}let animation=Animated.timing(value,{toValue:open?1:0,duration:motion.drawerMs,easing:STANDARD2,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&!open&&onHidden()}),()=>animation.stop()},[open,value,motion.drawerMs,onHidden]);let translateX=value.interpolate({inputRange:[0,1],outputRange:[-panelWidth,0]}),rows=history.filtered,hasNoConversations=history.rows.length===0,complete=history.cursor===null&&!history.loading&&history.error===null,empty=hasNoConversations&&history.loading?/* @__PURE__ */jsxs(View,{style:styles3.emptyCard,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
300
209
  /* @__PURE__ */jsx(ActivityIndicator,{color:styles3.emptyTitle.color}),
@@ -360,20 +269,21 @@ return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:hostFinder
360
269
  /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.actionLabel,{color:ink2}],children:label})]})}let ink=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??tier.textColor;/* @__PURE__ */
361
270
  return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},style:[styles3.findVetButton,{borderColor:tier.borderColor,backgroundColor:tier.pillColor},styles3.findVetSlotBox,busy?styles3.findVetBusy:null],onPress:onPress,children:[
362
271
  /* @__PURE__ */jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink,strokeWidth:1.5}),
363
- /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles15(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},erLine:{...face(theme,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT2,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useStalePetHold(runtime,userRef2,petRef2,scopeEpoch){let[owner,setOwner]=useState({pet:petRef2,user:userRef2}),adopt=owner.pet!==petRef2||owner.user===null&&userRef2!==null;adopt&&setOwner({pet:petRef2,user:userRef2});let current=adopt?{user:userRef2}:owner,held=petRef2!==null&&current.user!==null&&current.user!==userRef2;return useEffect(()=>{if(!held||userRef2===null||petRef2===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef2)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef2)&&setOwner({pet:petRef2,user:userRef2})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef2,petRef2,scopeEpoch]),held}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,held=useStalePetHold(runtime,userRef2,petRef2,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef2,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return chatNotReadyResult()}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=useCallback(petRef2=>handle.setActivePet(petRef2),[handle]);return useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=useRef(false),scope=useRef({send:chat.send,id:chat.conversationId});useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:avatarUrl,named:named,styles:styles3}){let image=useBrandImage(avatarUrl);return image.shown?/* @__PURE__ */jsxs(View,{style:styles3.assistantSender,testID:"everfur-assistant-sender",children:[
272
+ /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles15(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},erLine:{...face(theme,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT2,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useStalePetHold(runtime,userRef2,petRef2,scopeEpoch){let[owner,setOwner]=useState({pet:petRef2,user:userRef2}),adopt=owner.pet!==petRef2||owner.user===null&&userRef2!==null;adopt&&setOwner({pet:petRef2,user:userRef2});let current=adopt?{user:userRef2}:owner,held=petRef2!==null&&current.user!==null&&current.user!==userRef2;return useEffect(()=>{if(!held||userRef2===null||petRef2===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef2)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef2)&&setOwner({pet:petRef2,user:userRef2})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef2,petRef2,scopeEpoch]),held}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,held=useStalePetHold(runtime,userRef2,petRef2,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:options=>run(current=>current.refreshActiveThread(options)),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef2,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return chatNotReadyResult()}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=useCallback(petRef2=>handle.setActivePet(petRef2),[handle]);return useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=useRef(false),scope=useRef({send:chat.send,id:chat.conversationId});useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:avatarUrl,named:named,styles:styles3}){let image=useBrandImage(avatarUrl);return image.shown?/* @__PURE__ */jsxs(View,{style:styles3.assistantSender,testID:"everfur-assistant-sender",children:[
364
273
  /* @__PURE__ */jsx(BrandImage,{uri:avatarUrl,decorative:true,style:styles3.assistantAvatar,resizeMode:"cover",onError:image.onError,testID:"everfur-assistant-avatar"}),named?/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.assistantName,styles3.assistantNameInRow],children:CHAT_COPY.assistantName}):null]}):named?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl2(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
365
- return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl2(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count2){return count2===1?`1 ${CHAT_COPY.sourceSingular}`:`${count2} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count2,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count2)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}function answerParagraphs(text3){let parts=text3.split(/\n\s*\n/).map(part=>part.trim()).filter(part=>part.length>0);return parts.length>0?parts:[text3]}var BULLET_LINE=/^\s*[-*]\s+(\S.*)$/,NUMBERED_LINE=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function answerBlocks(paragraph){let blocks=[],text3=[],list=null,flushText=()=>{text3.length>0&&blocks.push({kind:"text",text:text3.join(`\n`)}),text3=[]},flushList=()=>{list!==null&&blocks.push(list.ordered?{kind:"list",ordered:true,start:list.start,items:list.items}:{kind:"list",ordered:false,items:list.items}),list=null};for(let line of paragraph.split(`\n`)){let bullet=BULLET_LINE.exec(line),numbered=bullet===null?NUMBERED_LINE.exec(line):null,item=bullet?.[1]??numbered?.[2];if(item===void 0){flushList(),text3.push(line);continue}let ordered=numbered!==null;flushText(),list!==null&&list.ordered!==ordered&&flushList(),list===null&&(list={ordered:ordered,start:numbered===null?1:Number(numbered[1]),items:[]}),list.items.push(item.trim())}return flushText(),flushList(),blocks}function questionFor(messages,messageId){let at=messages.findIndex(message=>message.id===messageId);for(let i=at-1;i>=0;i-=1){let message=messages[i];if(message!==void 0&&message.role==="user")return message.text}return null}function hostList(fn,context){if(fn===void 0)return[];try{let out=fn(context);return Array.isArray(out)?out:[]}catch{return[]}}function tileImageUrl(url){return hardenHttpsUrl(url.trim())}function followUpActionsFor(chat,options){if(options?.followUpActions===void 0||chat.isStreaming||chat.status==="error")return[];let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true?[]:hostList(options.followUpActions,{answer:last.text,question:questionFor(chat.messages,last.id),messageId:last.id})}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor2=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor2&&runs.push({kind:"text",text:text3.slice(cursor2,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor2=match.index+match[0].length}return cursor2<text3.length&&runs.push({kind:"text",text:text3.slice(cursor2)}),runs}function renderInlineMarkdown(text3,styles3){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
366
- return jsx(Text,{style:styles3.bold,children:run.text},key);case"italic":return styles3.italic?/* @__PURE__ */jsx(Text,{style:styles3.italic,children:run.text},key):run.text;case"code":return styles3.code?/* @__PURE__ */jsx(Text,{style:styles3.code,children:run.text},key):run.text;default:return run.text}}):text3}var MONO_SIZE2=10.5,BODY_SIZE2=15.5,BODY_LEAD=1.5,CARD_RADIUS4=16,CARD_PAD2=12,TILE=38,TILE_RADIUS=11,CARD_TITLE=15,STAT_SIZE=22,CHIP_HEIGHT=32,CHIP_SIZE=13.5,ROW_RADIUS2=14,ROW_SIZE=15,CHEVRON=16,LABEL_SIZE2=13,PILL_SIZE2=13,PILL_HEIGHT=26,TILE_GLYPH2=20;function useCardStyles(){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles16(theme),[theme]);return{theme:theme,styles:styles3}}function Chevron({options:options,color:color}){let glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:CHEVRON,color:color,strokeWidth:2,direction:"right"}),render=options?.renderIcon;return render===void 0?glyph:/* @__PURE__ */jsx(HostRender,{render:()=>render("chevron"),fallback:glyph})}function AnswerCard({card:card,options:options}){let{theme:theme,styles:styles3}=useCardStyles();if(card.render!==void 0){let render=card.render;/* @__PURE__ */
274
+ return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl2(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count3){return count3===1?`1 ${CHAT_COPY.sourceSingular}`:`${count3} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count3,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count3)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}function answerParagraphs(text3){let parts=text3.split(/\n\s*\n/).map(part=>part.trim()).filter(part=>part.length>0);return parts.length>0?parts:[text3]}var BULLET_LINE=/^\s*[-*]\s+(\S.*)$/,NUMBERED_LINE=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function answerBlocks(paragraph){let blocks=[],text3=[],list=null,flushText=()=>{text3.length>0&&blocks.push({kind:"text",text:text3.join(`\n`)}),text3=[]},flushList=()=>{list!==null&&blocks.push(list.ordered?{kind:"list",ordered:true,start:list.start,items:list.items}:{kind:"list",ordered:false,items:list.items}),list=null};for(let line of paragraph.split(`\n`)){let bullet=BULLET_LINE.exec(line),numbered=bullet===null?NUMBERED_LINE.exec(line):null,item=bullet?.[1]??numbered?.[2];if(item===void 0){flushList(),text3.push(line);continue}let ordered=numbered!==null;flushText(),list!==null&&list.ordered!==ordered&&flushList(),list===null&&(list={ordered:ordered,start:numbered===null?1:Number(numbered[1]),items:[]}),list.items.push(item.trim())}return flushText(),flushList(),blocks}function questionFor(messages,messageId){let at=messages.findIndex(message=>message.id===messageId);for(let i=at-1;i>=0;i-=1){let message=messages[i];if(message!==void 0&&message.role==="user")return message.text}return null}function hostList(fn,context){if(fn===void 0)return[];try{let out=fn(context);return Array.isArray(out)?out:[]}catch{return[]}}function tileImageUrl(url){return hardenHttpsUrl(url.trim())}function followUpActionsFor(chat,options){if(options?.followUpActions===void 0||chat.isStreaming||chat.status==="error")return[];let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true?[]:hostList(options.followUpActions,{answer:last.text,question:questionFor(chat.messages,last.id),messageId:last.id})}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,LINK_TOKEN=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${MAX_LINK_LENGTH}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${MAX_LINK_LENGTH}})`,"gi"),HAS_ADDRESS=/https:\/\//i,SENTENCE_END=`.,;:!?'"`;function hasInlineMarkup(text3,linkHosts){return text3.includes("*")||text3.includes("`")||linkHosts!==void 0&&HAS_ADDRESS.test(text3)}function tokenizeInlineMarkdown(text3,linkHosts){let runs=[],plain=slice=>{linkHosts===void 0?runs.push({kind:"text",text:slice}):pushLinked(runs,slice,linkHosts)},cursor2=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor2&&plain(text3.slice(cursor2,match.index));let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor2=match.index+match[0].length}return cursor2<text3.length&&plain(text3.slice(cursor2)),runs}function trimAddress(address){let end=address.length;for(;;){let last=address[end-1];if(last===void 0)break;if(SENTENCE_END.includes(last))end-=1;else if(last===")"&&count2(address,"(",end)<count2(address,")",end))end-=1;else break}return address.slice(0,end)}function count2(value,char,end){let n=0;for(let i=0;i<end;i+=1)value[i]===char&&(n+=1);return n}function pushLinked(runs,slice,linkHosts){if(!HAS_ADDRESS.test(slice)){runs.push({kind:"text",text:slice});return}let cursor2=0;LINK_TOKEN.lastIndex=0;for(let match=LINK_TOKEN.exec(slice);match!==null;match=LINK_TOKEN.exec(slice)){let label=match[1],labelled=match[2],raw=match[3],text3,href,consumed;if(label!==void 0&&labelled!==void 0)text3=label.trim(),href=text3.length>0?linkHref(labelled,linkHosts):null,consumed=match[0].length;else if(raw!==void 0)text3=trimAddress(raw),href=linkHref(text3,linkHosts),consumed=text3.length;else continue;href!==null&&(match.index>cursor2&&runs.push({kind:"text",text:slice.slice(cursor2,match.index)}),runs.push({kind:"link",text:text3,href:href}),cursor2=match.index+consumed,LINK_TOKEN.lastIndex=cursor2)}cursor2<slice.length&&runs.push({kind:"text",text:slice.slice(cursor2)})}var LINK_STYLE=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function hasMessageLink(text3,links){return links===void 0||!hasInlineMarkup(text3,links.hosts)?false:tokenizeInlineMarkdown(text3,links.hosts).some(run=>run.kind==="link")}function renderInlineMarkdown(text3,styles3,links){let hosts=links?.hosts;return hasInlineMarkup(text3,hosts)?tokenizeInlineMarkdown(text3,hosts).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
275
+ return jsx(Text,{style:styles3.bold,children:run.text},key);case"italic":return styles3.italic?/* @__PURE__ */jsx(Text,{style:styles3.italic,children:run.text},key):run.text;case"code":return styles3.code?/* @__PURE__ */jsx(Text,{style:styles3.code,children:run.text},key):run.text;case"link":{if(links===void 0)return run.text;let{href:href}=run;/* @__PURE__ */
276
+ return jsx(Text,{style:LINK_STYLE,accessibilityRole:"link",accessibilityLabel:run.text,onPress:()=>links.open(href),children:run.text},key)}default:return run.text}}):text3}var MONO_SIZE2=10.5,BODY_SIZE2=15.5,BODY_LEAD=1.5,CARD_RADIUS4=16,CARD_PAD2=12,TILE=38,TILE_RADIUS=11,CARD_TITLE=15,STAT_SIZE=22,CHIP_HEIGHT=32,CHIP_SIZE=13.5,ROW_RADIUS2=14,ROW_SIZE=15,CHEVRON=16,LABEL_SIZE2=13,PILL_SIZE2=13,PILL_HEIGHT=26,TILE_GLYPH2=20;function useCardStyles(){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles16(theme),[theme]);return{theme:theme,styles:styles3}}function Chevron({options:options,color:color}){let glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:CHEVRON,color:color,strokeWidth:2,direction:"right"}),render=options?.renderIcon;return render===void 0?glyph:/* @__PURE__ */jsx(HostRender,{render:()=>render("chevron"),fallback:glyph})}function AnswerCard({card:card,options:options}){let{theme:theme,styles:styles3}=useCardStyles();if(card.render!==void 0){let render=card.render;/* @__PURE__ */
367
277
  return jsx(View,{style:[styles3.card,card.variant!==void 0?options?.styles?.cardVariant?.[card.variant]:null],accessible:false,accessibilityLabel:card.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */jsx(HostRender,{render:render,fallback:null})})}let stat=card.value!==void 0,host=options?.styles,cardStyle=[styles3.card,stat?host?.cardStat:null,card.variant!==void 0?host?.cardVariant?.[card.variant]:null],tileTone=card.tile?.tone,pillTone=card.pill?.tone,image=card.tile?.imageUrl!==void 0?tileImageUrl(card.tile.imageUrl):null,body=/* @__PURE__ */jsxs(Fragment,{children:[stat?null:/* @__PURE__ */jsx(View,{style:[styles3.tile,tileTone!==void 0?host?.tileTone?.[tileTone]:null],children:image!==null?/* @__PURE__ */jsx(Image,{source:{uri:image},style:styles3.tileImage,accessibilityIgnoresInvertColors:true}):card.tile?.icon??null}),
368
278
  /* @__PURE__ */jsxs(View,{style:styles3.cardWords,children:[
369
279
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.cardTitle,children:card.title}),card.meta!==void 0?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.cardMeta,children:card.meta}):null]}),stat?/* @__PURE__ */jsxs(Text,{tier:"control",style:styles3.stat,children:[card.value?.amount,card.value?.unit!==void 0?/* @__PURE__ */jsx(Text,{style:styles3.statUnit,children:card.value.unit}):null]}):/* @__PURE__ */jsxs(Fragment,{children:[card.pill!==void 0?/* @__PURE__ */jsx(View,{style:[styles3.pill,pillTone!==void 0?host?.pillTone?.[pillTone]:null],children:/* @__PURE__ */jsx(Text,{tier:"badge",style:[styles3.pillText,pillTone!==void 0?host?.pillToneText?.[pillTone]:null],numberOfLines:1,children:card.pill.label})}):null,card.onPress!==void 0?/* @__PURE__ */jsx(Chevron,{options:options,color:theme.color.text.muted}):null]})]});if(card.onPress!==void 0){let onPress=card.onPress;/* @__PURE__ */
370
280
  return jsx(Pressable,{onPress:()=>{callHost(onPress)},accessibilityRole:"button",accessibilityLabel:card.title,style:cardStyle,children:body})}/* @__PURE__ */
371
- return jsx(View,{style:cardStyle,children:body})}function CardsAnswer({message:message,text:text3,streaming:streaming,messages:messages,options:options,sentiment:sentiment,onSentiment:onSentiment,sender:sender,footer:footer,onOpenUrl:onOpenUrl}){let{styles:styles3}=useCardStyles(),context=useMemo(()=>({answer:message.text,question:questionFor(messages,message.id),messageId:message.id}),[message.text,message.id,messages]),settled=!streaming&&message.pending!==true,hostCards=settled?hostList(options?.cards,context):[],sources=useMemo(()=>settled?toCitationCards(message.citations):[],[settled,message.citations]),byline=options?.byline,chips=options?.feedback!==void 0&&message.responseId!==void 0&&onSentiment!==void 0?options.feedback:null,inline={bold:styles3.bold,italic:styles3.italic,code:styles3.code};/* @__PURE__ */
281
+ return jsx(View,{style:cardStyle,children:body})}function CardsAnswer({message:message,text:text3,streaming:streaming,messages:messages,options:options,sentiment:sentiment,onSentiment:onSentiment,sender:sender,footer:footer,onOpenUrl:onOpenUrl}){let{styles:styles3}=useCardStyles(),context=useMemo(()=>({answer:message.text,question:questionFor(messages,message.id),messageId:message.id}),[message.text,message.id,messages]),settled=!streaming&&message.pending!==true,hostCards=settled?hostList(options?.cards,context):[],sources=useMemo(()=>settled?toCitationCards(message.citations):[],[settled,message.citations]),byline=options?.byline,chips=options?.feedback!==void 0&&message.responseId!==void 0&&onSentiment!==void 0?options.feedback:null,inline={bold:styles3.bold,italic:styles3.italic,code:styles3.code},messageLinks=useMessageLinks(),links=settled?messageLinks:void 0;/* @__PURE__ */
372
282
  return jsxs(View,{style:styles3.answer,testID:"everfur-answer-cards",children:[byline!==void 0?/* @__PURE__ */jsxs(View,{style:styles3.byline,children:[byline.icon??null,
373
283
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.bylineText,children:byline.label})]}):sender,
374
- /* @__PURE__ */jsx(View,{style:styles3.body,children:answerParagraphs(text3).flatMap((paragraph,index)=>answerBlocks(paragraph).map((block,at)=>{let key=`${index}-${at}`;return block.kind==="text"?/* @__PURE__ */jsx(Text,{style:styles3.paragraph,children:renderInlineMarkdown(block.text,inline)},key):/* @__PURE__ */jsx(View,{style:styles3.list,children:block.items.map((item,n)=>/* @__PURE__ */jsxs(View,{style:styles3.listItem,children:[
284
+ /* @__PURE__ */jsx(View,{style:styles3.body,children:answerParagraphs(text3).flatMap((paragraph,index)=>answerBlocks(paragraph).map((block,at)=>{let key=`${index}-${at}`;return block.kind==="text"?/* @__PURE__ */jsx(Text,{style:styles3.paragraph,children:renderInlineMarkdown(block.text,inline,links)},key):/* @__PURE__ */jsx(View,{style:styles3.list,children:block.items.map((item,n)=>/* @__PURE__ */jsxs(View,{style:styles3.listItem,children:[
375
285
  /* @__PURE__ */jsx(Text,{style:styles3.paragraph,children:block.ordered?`${block.start+n}.`:"•"}),
376
- /* @__PURE__ */jsx(Text,{style:[styles3.paragraph,styles3.listText],children:renderInlineMarkdown(item,inline)})]},n))},key)}))}),hostCards.length>0?/* @__PURE__ */jsx(View,{style:styles3.cards,children:hostCards.map(card=>/* @__PURE__ */jsx(AnswerCard,{card:card,options:options},card.key))}):null,sources.length>0?/* @__PURE__ */jsxs(View,{style:styles3.cards,accessibilityLabel:sourcesLabel(sources.length),children:[
286
+ /* @__PURE__ */jsx(Text,{style:[styles3.paragraph,styles3.listText],children:renderInlineMarkdown(item,inline,links)})]},n))},key)}))}),hostCards.length>0?/* @__PURE__ */jsx(View,{style:styles3.cards,children:hostCards.map(card=>/* @__PURE__ */jsx(AnswerCard,{card:card,options:options},card.key))}):null,sources.length>0?/* @__PURE__ */jsxs(View,{style:styles3.cards,accessibilityLabel:sourcesLabel(sources.length),children:[
377
287
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.label,children:sourcesLabel(sources.length)}),sources.map(source=>{let url=source.url;/* @__PURE__ */
378
288
  return jsx(AnswerCard,{card:{key:source.key,title:source.title,...source.meta!==null?{meta:source.meta}:{},tile:{icon:/* @__PURE__ */jsx(SourceTileGlyph,{})},...onOpenUrl!==void 0&&url!==null?{onPress:()=>onOpenUrl(url)}:{}},options:options},source.key)})]}):null,settled&&chips!==null&&onSentiment!==void 0?/* @__PURE__ */jsxs(View,{style:[styles3.feedback,options?.styles?.feedback],children:[
379
289
  /* @__PURE__ */jsx(FeedbackChip,{label:chips.helpful,on:sentiment==="up",onPress:()=>onSentiment("up"),styles:styles3,host:options?.styles}),
@@ -389,11 +299,11 @@ return jsxs(View,{style:styles3.card,accessibilityLabel:CHECKIN_COPY.eyebrow,onL
389
299
  /* @__PURE__ */jsxs(View,{style:styles3.head,children:[
390
300
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.eyebrow,children:CHECKIN_COPY.eyebrow}),day!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.headDay,children:fillCopy(CHECKIN_COPY.day,{day:day})}):null]}),
391
301
  /* @__PURE__ */jsx(Text,{style:styles3.question,accessibilityRole:"text",children:message.text}),answerable?/* @__PURE__ */jsx(View,{style:[styles3.row,state.pending?styles3.rowPending:null],children:CHECKIN_OPTIONS.map(({answer:answer,label:label})=>{let selected=(state.pending??state.answer)===answer;/* @__PURE__ */
392
- return jsx(Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles3.pill,selected?styles3.pillSelected:null],children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.pillLabel,selected?styles3.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsx(Text,{style:styles3.logged,children:CHECKIN_COPY.logged}):null,state.escalated?/* @__PURE__ */jsx(CheckinFindVet,{petRef:petRef2??null,onFindVet:onFindVet,vet:vet,styles:styles3}):null,checkin.resolutionText?/* @__PURE__ */jsx(Text,{style:styles3.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsx(Text,{style:styles3.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function CheckinFindVet({petRef:petRef2,onFindVet:onFindVet,vet:vet,styles:styles3}){return useVetVisit(chatVetVisitOptions(petRef2,vet)).available&&petRef2!==null?/* @__PURE__ */jsx(VetVisitButtonCore,{entry:"chat",petRef:petRef2,label:CHECKIN_COPY.findVet,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles3.findVet,labelStyle:styles3.findVetLabel}):onFindVet===void 0?null:/* @__PURE__ */jsx(Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles3.findVet,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.findVetLabel,children:CHECKIN_COPY.findVet})})}function makeStyles17(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,card=ownGroundSlot(theme.slots.card),cardText=slotText(card);return StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:c.brandBorder,...slotBox(card,StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm},eyebrow:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},headDay:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},question:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},row:{flexDirection:"row",gap:s.sm,marginTop:s.xs},rowPending:{opacity:PENDING_OPACITY2},pill:{flex:1,minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",paddingHorizontal:s.md,borderRadius:r.pill,borderWidth:1,borderColor:c.controlEdge,backgroundColor:c.surface},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk},pillLabel:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body},pillLabelSelected:{color:c.onPrimary},logged:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,...cardText},resolution:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},error:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption},findVet:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",borderRadius:r.pill,borderWidth:1.5,borderColor:c.controlEdge,backgroundColor:c.surface},findVetLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.body}})}var CARD_WIDTH=244,TIER_DOT=8,PILL_GLYPH=13,LINK_GLYPH=14,TOGGLE_TRACKING=.3,TITLE_TRACKING=-.24,TITLE_LINE=22,META_LINE=10,EXCERPT_LINE=15;function CitationCards({citations:citations,onOpenUrl:onOpenUrl}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles18(theme),[theme]),cards=useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=useState(false);if(cards.length===0)return null;let count2=cards.length;/* @__PURE__ */
302
+ return jsx(Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles3.pill,selected?styles3.pillSelected:null],children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.pillLabel,selected?styles3.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsx(Text,{style:styles3.logged,children:CHECKIN_COPY.logged}):null,state.escalated?/* @__PURE__ */jsx(CheckinFindVet,{petRef:petRef2??null,onFindVet:onFindVet,vet:vet,styles:styles3}):null,checkin.resolutionText?/* @__PURE__ */jsx(Text,{style:styles3.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsx(Text,{style:styles3.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function CheckinFindVet({petRef:petRef2,onFindVet:onFindVet,vet:vet,styles:styles3}){return useVetVisit(chatVetVisitOptions(petRef2,vet)).available&&petRef2!==null?/* @__PURE__ */jsx(VetVisitButtonCore,{entry:"chat",petRef:petRef2,label:CHECKIN_COPY.findVet,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles3.findVet,labelStyle:styles3.findVetLabel}):onFindVet===void 0?null:/* @__PURE__ */jsx(Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles3.findVet,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.findVetLabel,children:CHECKIN_COPY.findVet})})}function makeStyles17(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,card=ownGroundSlot(theme.slots.card),cardText=slotText(card);return StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:c.brandBorder,...slotBox(card,StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm},eyebrow:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},headDay:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},question:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},row:{flexDirection:"row",gap:s.sm,marginTop:s.xs},rowPending:{opacity:PENDING_OPACITY2},pill:{flex:1,minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",paddingHorizontal:s.md,borderRadius:r.pill,borderWidth:1,borderColor:c.controlEdge,backgroundColor:c.surface},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk},pillLabel:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body},pillLabelSelected:{color:c.onPrimary},logged:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,...cardText},resolution:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},error:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption},findVet:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",borderRadius:r.pill,borderWidth:1.5,borderColor:c.controlEdge,backgroundColor:c.surface},findVetLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.body}})}var CARD_WIDTH=244,TIER_DOT=8,PILL_GLYPH=13,LINK_GLYPH=14,TOGGLE_TRACKING=.3,TITLE_TRACKING=-.24,TITLE_LINE=22,META_LINE=10,EXCERPT_LINE=15;function CitationCards({citations:citations,onOpenUrl:onOpenUrl}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles18(theme),[theme]),cards=useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=useState(false);if(cards.length===0)return null;let count3=cards.length;/* @__PURE__ */
393
303
  return jsxs(View,{style:styles3.block,children:[
394
- /* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:sourcesToggleLabel(count2,expanded),accessibilityState:{expanded:expanded},containerStyle:styles3.toggleSlot,style:styles3.togglePill,onPress:()=>setExpanded(current=>!current),children:[
304
+ /* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:sourcesToggleLabel(count3,expanded),accessibilityState:{expanded:expanded},containerStyle:styles3.toggleSlot,style:styles3.togglePill,onPress:()=>setExpanded(current=>!current),children:[
395
305
  /* @__PURE__ */jsx(BookGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}),
396
- /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.toggleLabel,children:sourcesLabel(count2)}),
306
+ /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.toggleLabel,children:sourcesLabel(count3)}),
397
307
  /* @__PURE__ */jsx(ChevronGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5,direction:expanded?"up":"down"})]}),expanded?/* @__PURE__ */jsx(Deck,{cards:cards,styles:styles3,open:onOpenUrl}):null]})}function Deck({cards:cards,styles:styles3,open:open}){let motion=useChatMotion(),fade=useFadeIn(motion.citationsInMs,{risePx:motion.citationsRisePx});/* @__PURE__ */
398
308
  return jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:styles3.row,children:cards.map(card=>/* @__PURE__ */jsx(Card,{card:card,styles:styles3,open:open},card.key))})})}function Card({card:card,styles:styles3,open:open}){let theme=useEverfurTheme(),linked=card.url!==null&&open!==void 0,label=citationA11yLabel(linked?card:{...card,url:null}),inner=/* @__PURE__ */jsxs(Fragment,{children:[
399
309
  /* @__PURE__ */jsxs(View,{style:styles3.cardHeader,children:[
@@ -437,17 +347,17 @@ return jsxs(ScrollView,{ref:follow.ref,style:styles3.list,contentContainerStyle:
437
347
  return jsxs(View,{style:[styles3.turnNotice,error?styles3.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
438
348
  /* @__PURE__ */jsx(Text,{tier:"control",style:[styles3.turnNoticeTitle,error?styles3.turnNoticeTitleError:null],children:notice.title}),
439
349
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.turnNoticeBody,children:notice.body}),
440
- /* @__PURE__ */jsx(Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles3.turnNoticeAction,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),NO_ACTIONS=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,note:note,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering,answerCards:answerCards,messages:messages}){let{theme:theme,styles:styles3}=useChatTheme(),motion=useChatMotion(),enter=useBubbleEnter(entering,motion),shown=useRevealedText(message.text,revealing,motion),isUser=message.role==="user",isVet=message.role==="vet",isAssistant=message.role==="assistant",namesAssistant=isAssistant&&!theme.meta.hidePoweredBy,sender=isUser?CHAT_COPY.senderUser:isVet?vetSenderLabel(message):namesAssistant?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,vetTime=isVet?formatMessageTime(message.createdAt):null,rate=useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true,senderLine=isAssistant&&theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:namesAssistant,styles:styles3}):namesAssistant?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null;return isAssistant&&answerCards!==null?/* @__PURE__ */jsx(Animated.View,{style:[styles3.rowBlock,enter],onLayout:onLayout,accessibilityLabel:`${sender}: ${message.text}`,children:/* @__PURE__ */jsx(CardsAnswer,{message:message,text:shown,streaming:revealing,messages:messages,options:answerCards,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,sender:senderLine,onOpenUrl:onOpenUrl,footer:withThumbs=>/* @__PURE__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:withThumbs&&message.responseId!==void 0?rate:void 0,note:note})})}):/* @__PURE__ */jsxs(View,{style:[styles3.rowBlock,isUser?styles3.rowBlockUser:styles3.rowBlockAssistant],onLayout:onLayout,children:[
441
- /* @__PURE__ */jsx(View,{style:[styles3.row,isUser?styles3.rowUser:styles3.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxs(Animated.View,{style:[styles3.bubble,isUser?styles3.bubbleSideUser:null,enter],children:[senderLine,isVet?/* @__PURE__ */jsxs(View,{style:styles3.vetHeader,children:[
350
+ /* @__PURE__ */jsx(Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles3.turnNoticeAction,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),NO_ACTIONS=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,note:note,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering,answerCards:answerCards,messages:messages}){let{theme:theme,styles:styles3}=useChatTheme(),motion=useChatMotion(),enter=useBubbleEnter(entering,motion),shown=useRevealedText(message.text,revealing,motion),isUser=message.role==="user",isVet=message.role==="vet",isAssistant=message.role==="assistant",messageLinks=useMessageLinks(),links=isAssistant&&!revealing?messageLinks:void 0,linked=links!==void 0&&hasMessageLink(message.text,links),namesAssistant=isAssistant&&!theme.meta.hidePoweredBy,sender=isUser?CHAT_COPY.senderUser:isVet?vetSenderLabel(message):namesAssistant?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,vetTime=isVet?formatMessageTime(message.createdAt):null,rate=useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true,senderLine=isAssistant&&theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:namesAssistant,styles:styles3}):namesAssistant?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null;return isAssistant&&answerCards!==null?/* @__PURE__ */jsx(Animated.View,{style:[styles3.rowBlock,enter],onLayout:onLayout,accessibilityLabel:`${sender}: ${message.text}`,children:/* @__PURE__ */jsx(CardsAnswer,{message:message,text:shown,streaming:revealing,messages:messages,options:answerCards,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,sender:senderLine,onOpenUrl:onOpenUrl,footer:withThumbs=>/* @__PURE__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:withThumbs&&message.responseId!==void 0?rate:void 0,note:note})})}):/* @__PURE__ */jsxs(View,{style:[styles3.rowBlock,isUser?styles3.rowBlockUser:styles3.rowBlockAssistant],onLayout:onLayout,children:[
351
+ /* @__PURE__ */jsx(View,{style:[styles3.row,isUser?styles3.rowUser:styles3.rowAssistant],accessible:!linked,accessibilityRole:linked?void 0:"text",accessibilityLabel:linked?void 0:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxs(Animated.View,{style:[styles3.bubble,isUser?styles3.bubbleSideUser:null,enter],children:[senderLine,isVet?/* @__PURE__ */jsxs(View,{style:styles3.vetHeader,children:[
442
352
  /* @__PURE__ */jsx(Text,{tier:"control",style:styles3.vetSender,children:sender}),vetTime!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.vetTime,children:vetTime}):null]}):null,
443
353
  /* @__PURE__ */jsxs(View,{style:[isUser?styles3.bubbleUser:isVet?styles3.bubbleVet:styles3.bubbleAssistant,message.pending?styles3.bubblePending:null],children:[isUser&&images.length>0?/* @__PURE__ */jsx(SentImages,{images:images,onPreview:image=>onPreview({uri:image.uri,label:image.filename})}):null,
444
- /* @__PURE__ */jsx(Text,{style:isUser?styles3.bubbleTextUser:isVet?styles3.bubbleTextVet:styles3.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles3.bubbleBold,italic:styles3.bubbleItalic,code:styles3.bubbleCode}):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled&&!(isUser&&answerCards!==null)?/* @__PURE__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,note:note}):null]})}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT2:source.getSnapshot,snapshot2=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot2!==null&&decideCapability("texting",snapshot2.decisions,{isPending:snapshot2.isPending}).enabled,[snapshot2])}var NOTHING=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function useChatTextingAsk(enabled,chat,headerEntry=false){let[ask,setAsk]=useState(null);if(!enabled)return NOTHING;let runner=/* @__PURE__ */jsx(AskRunner,{ready:textingAskThreadReady(chat),onAsk:setAsk,entry:headerEntry}),chip=headerEntry&&ask!==null&&ask.canOpen?{label:texting.textingAskLines(ask).accept,onOpen:ask.open}:null;if(ask===null||ask.stage==="hidden"||ask.stage==="dismissed")return{runner:runner,line:null,entry:null,stage:null,headerEntry:chip};let lines=texting.textingAskLines(ask),line=/* @__PURE__ */jsx(AskLine,{stage:ask.stage,text:ask.stage==="verified"?lines.verified:lines.line,accept:lines.accept,dismiss:lines.dismiss,onAccept:ask.accept,onDismiss:ask.dismiss}),entry=ask.stage==="enrolling"?/* @__PURE__ */jsx(texting.ChatTextingAskComposer,{ask:ask}):null;return{runner:runner,line:line,entry:entry,stage:ask.stage,headerEntry:chip}}function AskRunner({ready:ready,onAsk:onAsk,entry:entry}){let{userRef:userRef2}=useEverfurContext(),granted=useTextingGranted(),wanted=userRef2!==null&&granted;return useEffect(()=>{wanted||onAsk(null)},[wanted,onAsk]),wanted?/* @__PURE__ */jsx(texting.ChatTextingAskController,{enabled:true,ready:ready,onAsk:onAsk,entry:entry}):null}function AskLine({stage:stage,text:text3,accept:accept,dismiss:dismiss,onAccept:onAccept,onDismiss:onDismiss}){let{theme:theme,styles:styles3}=useChatTheme(),named=!theme.meta.hidePoweredBy,sender=named?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,senderLine=theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:named,styles:styles3}):named?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null;/* @__PURE__ */
354
+ /* @__PURE__ */jsx(Text,{style:isUser?styles3.bubbleTextUser:isVet?styles3.bubbleTextVet:styles3.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles3.bubbleBold,italic:styles3.bubbleItalic,code:styles3.bubbleCode},links):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled&&!(isUser&&answerCards!==null)?/* @__PURE__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,note:note}):null]})}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT2:source.getSnapshot,snapshot2=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot2!==null&&decideCapability("texting",snapshot2.decisions,{isPending:snapshot2.isPending}).enabled,[snapshot2])}var NOTHING=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function useChatTextingAsk(enabled,chat,headerEntry=false){let[ask,setAsk]=useState(null);if(!enabled)return NOTHING;let runner=/* @__PURE__ */jsx(AskRunner,{ready:textingAskThreadReady(chat),onAsk:setAsk,entry:headerEntry}),chip=headerEntry&&ask!==null&&ask.canOpen?{label:texting.textingAskLines(ask).accept,onOpen:ask.open}:null;if(ask===null||ask.stage==="hidden"||ask.stage==="dismissed")return{runner:runner,line:null,entry:null,stage:null,headerEntry:chip};let lines=texting.textingAskLines(ask),line=/* @__PURE__ */jsx(AskLine,{stage:ask.stage,text:ask.stage==="verified"?lines.verified:lines.line,accept:lines.accept,dismiss:lines.dismiss,onAccept:ask.accept,onDismiss:ask.dismiss}),entry=ask.stage==="enrolling"?/* @__PURE__ */jsx(texting.ChatTextingAskComposer,{ask:ask}):null;return{runner:runner,line:line,entry:entry,stage:ask.stage,headerEntry:chip}}function AskRunner({ready:ready,onAsk:onAsk,entry:entry}){let{userRef:userRef2}=useEverfurContext(),granted=useTextingGranted(),wanted=userRef2!==null&&granted;return useEffect(()=>{wanted||onAsk(null)},[wanted,onAsk]),wanted?/* @__PURE__ */jsx(texting.ChatTextingAskController,{enabled:true,ready:ready,onAsk:onAsk,entry:entry}):null}function AskLine({stage:stage,text:text3,accept:accept,dismiss:dismiss,onAccept:onAccept,onDismiss:onDismiss}){let{theme:theme,styles:styles3}=useChatTheme(),named=!theme.meta.hidePoweredBy,sender=named?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,senderLine=theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:named,styles:styles3}):named?/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.assistantName,children:CHAT_COPY.assistantName}):null;/* @__PURE__ */
445
355
  return jsxs(View,{style:[styles3.rowBlock,styles3.rowBlockAssistant],testID:`everfur-texting-ask-${stage}`,children:[
446
356
  /* @__PURE__ */jsx(View,{style:[styles3.row,styles3.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${text3}`,children:/* @__PURE__ */jsxs(View,{style:styles3.bubble,children:[senderLine,
447
357
  /* @__PURE__ */jsx(View,{style:styles3.bubbleAssistant,children:/* @__PURE__ */jsx(Text,{style:styles3.bubbleTextAssistant,children:text3})})]})}),stage==="offered"?/* @__PURE__ */jsx(View,{style:styles3.askChips,children:[{label:accept,onPress:onAccept,testID:"everfur-texting-ask-accept"},{label:dismiss,onPress:onDismiss,testID:"everfur-texting-ask-dismiss"}].map(answer=>/* @__PURE__ */jsx(PressScale,{onPress:answer.onPress,accessibilityRole:"button",accessibilityLabel:answer.label,style:styles3.askChip,testID:answer.testID,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.askChipText,children:answer.label})},answer.testID))}):null]})}function EverfurChatCore(props){let{style:style,renderPending:renderPending}=props;/* @__PURE__ */
448
- return jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(ChatBody,{...props})})}function useOptionalEverfurContext(){try{return useEverfurContext()}catch{return null}}function hostPresentation(props){return definedPresentation({...props.presentation,chatComposerMic:props.presentation?.chatComposerMic??(props.dictation===void 0?void 0:props.dictation!==false),chatComposerUpload:props.presentation?.chatComposerUpload??(props.attachments===void 0?void 0:true)})}function ChatBody(props){let context=useOptionalEverfurContext();return context===null?/* @__PURE__ */jsx(ChatBodyAlone,{...props}):/* @__PURE__ */jsx(ChatBodyInProvider,{...props,activePet:context.activePet,telemetry:context.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(props){let client=hostPresentation(props),key=JSON.stringify(client),planPetRef=props.petRef??null,settings=useMemo(()=>({presentation:resolvePresentation({server:null,locked:null,client:client}),isLocked:()=>false,planPage:null,planPetRef:planPetRef,inProvider:false,telemetry:null}),[key,planPetRef]);/* @__PURE__ */
358
+ return jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(MessageLinksScope,{linkHosts:props.linkHosts,onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(ChatBody,{...props})})})}function useOptionalEverfurContext(){try{return useEverfurContext()}catch{return null}}function hostPresentation(props){return definedPresentation({...props.presentation,chatComposerMic:props.presentation?.chatComposerMic??(props.dictation===void 0?void 0:props.dictation!==false),chatComposerUpload:props.presentation?.chatComposerUpload??(props.attachments===void 0?void 0:true)})}function ChatBody(props){let context=useOptionalEverfurContext();return context===null?/* @__PURE__ */jsx(ChatBodyAlone,{...props}):/* @__PURE__ */jsx(ChatBodyInProvider,{...props,activePet:context.activePet,telemetry:context.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(props){let client=hostPresentation(props),key=JSON.stringify(client),planPetRef=props.petRef??null,settings=useMemo(()=>({presentation:resolvePresentation({server:null,locked:null,client:client}),isLocked:()=>false,planPage:null,planPetRef:planPetRef,inProvider:false,telemetry:null}),[key,planPetRef]);/* @__PURE__ */
449
359
  return jsx(ChatSurface,{...props,settings:settings})}function ChatBodyInProvider({activePet:activePet,telemetry:telemetry,...props}){let{presentation:presentation,isLocked:isLocked2}=useEverfurPresentationState(hostPresentation(props)),planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&props.topCard===void 0&&planEnabled,planPetRef=props.petRef??activePet??null,plan=useHealthPlanPage({petRef:planPetRef,enabled:wantsPlan}),planPage=wantsPlan&&plan.phase==="ready"?plan.page:null,settings=useMemo(()=>({presentation:presentation,isLocked:isLocked2,planPage:planPage,planPetRef:planPetRef,inProvider:true,telemetry:telemetry}),[presentation,isLocked2,planPage,planPetRef,telemetry]);/* @__PURE__ */
450
- return jsx(ChatSurface,{...props,settings:settings})}function ChatSurface({settings:settings,petRef:petRef2,conversationId:conversationId2,style:style,renderPending:renderPending,onCopy:onCopy,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,attachments:attachments,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset,topCard:hostTopCard,onOpenHealthPlan:onOpenHealthPlan,answerCards:answerCards,historySheet:historySheet,historyBar:historyBar,starterPrompts:starterPrompts,emptyState:emptyState,header:header=true,textingEntry:textingEntry=true,renderEmptyHeader:renderEmptyHeader,followUpPolicy:hostFollowUpPolicy,initialAskCard:initialAskCard}){let{presentation:presentation,isLocked:isLocked2,planPage:planPage,planPetRef:planPetRef}=settings,{theme:theme,styles:styles3}=useChatTheme(),askHomeFactory=useAskHomeFactory(),askHome=useMemo(()=>askHomeFactory===null?null:askHomeFactory(theme),[askHomeFactory,theme]),hostPoweredBy=useHostPoweredBy(),motion=useChatMotion(),chatOpts=useMemo(()=>buildChatOpts(petRef2,conversationId2),[petRef2,conversationId2]),chat=useEverfurChat(chatOpts),view=selectView2(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=useSafeAreaInsets(),notice=turnNotice(chat,"web"),onCheckinFindVet=useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=useMemo(()=>vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer},[vetReturnTo,vetUsState,vetPrefer]),shownPet=headerPet(pets.pets,chat.petRef),urgencySource=useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion),useCheckinTarget(chat.openCheckin,checkinTarget),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),openingCard=useMemo(()=>initialAskCard!==void 0&&askPrompt!==null?{card:initialAskCard,prompt:askPrompt}:void 0,[initialAskCard,askPrompt]),lifecyclePort=useMemo(()=>lifecycle===void 0?createAppStateLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refresh:chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=useState(null),closePreview=useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=useState(null),[feedbackNote,setFeedbackNote]=useState(null),thanksTimer=useRef(null);useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showNote=useCallback((responseId,kind)=>{setFeedbackNote({responseId:String(responseId),kind:kind}),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=kind==="thanks"?setTimeout(()=>{setFeedbackNote(null),thanksTimer.current=null},THANKS_VISIBLE_MS):null},[]),onSentiment=useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];setFeedbackNote(note=>note?.responseId===String(responseId)?null:note),chat.feedback(responseId,sentiment).then(result=>{result.ok||showNote(responseId,"failed")}),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat,showNote]),submitReasons=useCallback(async(reason,notes)=>feedbackTarget===null||!(reason==null&&notes===null?{ok:true}:await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showNote(feedbackTarget,"thanks"),true),[chat,feedbackTarget,showNote]),skipReasons=useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=Platform.OS==="ios"?"padding":void 0,keyboard=useChatKeyboardOffset(keyboardVerticalOffset,avoidBehavior!==void 0),topInset=keyboard.topInWindow===null?insets.top:Math.max(0,insets.top-keyboard.topInWindow),keyboardOpen=useKeyboardOpen(),openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>hostTopCard===void 0?healthPlanTopCard(planPage,{onOpenPlan:openPlan}):void 0,[hostTopCard,planPage,openPlan]),card=presentation.chatTopCard==="focus"?hostTopCard??planCard:void 0,[cardOpen,setCardOpen]=useState(true),onCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),followUpPolicy=useMemo(()=>followUpPolicyFor(hostFollowUpPolicy,presentation,isLocked2("chatFollowUpCount")),[hostFollowUpPolicy,presentation,isLocked2]),sheet=presentation.chatHistoryStyle==="sheet",threadEmpty=chat.messages.length===0,pill=card!==void 0?/* @__PURE__ */jsx(TopCardPill,{card:card,open:cardOpen,onOpenChange:setCardOpen}):null,barNode=historyBar!==void 0?/* @__PURE__ */jsx(HistoryBar,{bar:historyBar,history:history,empty:threadEmpty,unread:historyUnread,extra:pill}):null,barInThread=presentation.chatHistoryBar==="scroll"&&(view==="empty"||view==="populated"),cardNode=card===void 0?null:/* @__PURE__ */jsxs(Fragment,{children:[
360
+ return jsx(ChatSurface,{...props,settings:settings})}function ChatSurface({settings:settings,petRef:petRef2,conversationId:conversationId2,style:style,renderPending:renderPending,onCopy:onCopy,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,attachments:attachments,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,handoffToken:handoffToken,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,openUnreadOnRefresh:openUnreadOnRefresh,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset,topCard:hostTopCard,onOpenHealthPlan:onOpenHealthPlan,answerCards:answerCards,historySheet:historySheet,historyBar:historyBar,starterPrompts:starterPrompts,emptyState:emptyState,header:header=true,textingEntry:textingEntry=true,renderEmptyHeader:renderEmptyHeader,followUpPolicy:hostFollowUpPolicy,initialAskCard:initialAskCard}){let{presentation:presentation,isLocked:isLocked2,planPage:planPage,planPetRef:planPetRef}=settings,{theme:theme,styles:styles3}=useChatTheme(),askHomeFactory=useAskHomeFactory(),askHome=useMemo(()=>askHomeFactory===null?null:askHomeFactory(theme),[askHomeFactory,theme]),hostPoweredBy=useHostPoweredBy(),motion=useChatMotion(),chatOpts=useMemo(()=>buildChatOpts(petRef2,conversationId2),[petRef2,conversationId2]),chat=useEverfurChat(chatOpts),view=selectView2(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=useSafeAreaInsets(),notice=turnNotice(chat,"web"),onCheckinFindVet=useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=useMemo(()=>vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer},[vetReturnTo,vetUsState,vetPrefer]),shownPet=headerPet(pets.pets,chat.petRef),urgencySource=useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion);let providerContext=useOptionalEverfurContext(),handoffTarget=useChatHandoffTarget(handoffToken,providerContext);useCheckinTarget(chat.openCheckin,checkinTarget??handoffTarget,{petRef:chat.petRef,pinned:petRef2!==void 0,ready:!chat.isBootstrapping,selectPet:next=>{pets.setActivePet(next),callHost(onPetChange,next)}}),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),openingCard=useMemo(()=>initialAskCard!==void 0&&askPrompt!==null?{card:initialAskCard,prompt:askPrompt}:void 0,[initialAskCard,askPrompt]),lifecyclePort=useMemo(()=>lifecycle===void 0?createAppStateLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refreshesBlankThread:openUnreadOnRefresh===true,refresh:openUnreadOnRefresh===true?()=>chat.refreshActiveThread?.(OPEN_UNREAD_HEAD)??Promise.resolve():chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=useState(null),closePreview=useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=useState(null),[feedbackNote,setFeedbackNote]=useState(null),thanksTimer=useRef(null);useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showNote=useCallback((responseId,kind)=>{setFeedbackNote({responseId:String(responseId),kind:kind}),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=kind==="thanks"?setTimeout(()=>{setFeedbackNote(null),thanksTimer.current=null},THANKS_VISIBLE_MS):null},[]),onSentiment=useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];setFeedbackNote(note=>note?.responseId===String(responseId)?null:note),chat.feedback(responseId,sentiment).then(result=>{result.ok||showNote(responseId,"failed")}),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat,showNote]),submitReasons=useCallback(async(reason,notes)=>feedbackTarget===null||!(reason==null&&notes===null?{ok:true}:await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showNote(feedbackTarget,"thanks"),true),[chat,feedbackTarget,showNote]),skipReasons=useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=Platform.OS==="ios"?"padding":void 0,keyboard=useChatKeyboardOffset(keyboardVerticalOffset,avoidBehavior!==void 0),topInset=keyboard.topInWindow===null?insets.top:Math.max(0,insets.top-keyboard.topInWindow),keyboardOpen=useKeyboardOpen(),openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>hostTopCard===void 0?healthPlanTopCard(planPage,{onOpenPlan:openPlan}):void 0,[hostTopCard,planPage,openPlan]),card=presentation.chatTopCard==="focus"?hostTopCard??planCard:void 0,[cardOpen,setCardOpen]=useState(true),onCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),followUpPolicy=useMemo(()=>followUpPolicyFor(hostFollowUpPolicy,presentation,isLocked2("chatFollowUpCount")),[hostFollowUpPolicy,presentation,isLocked2]),sheet=presentation.chatHistoryStyle==="sheet",threadEmpty=chat.messages.length===0,pill=card!==void 0?/* @__PURE__ */jsx(TopCardPill,{card:card,open:cardOpen,onOpenChange:setCardOpen}):null,barNode=historyBar!==void 0?/* @__PURE__ */jsx(HistoryBar,{bar:historyBar,history:history,empty:threadEmpty,unread:historyUnread,extra:pill}):null,barInThread=presentation.chatHistoryBar==="scroll"&&(view==="empty"||view==="populated"),cardNode=card===void 0?null:/* @__PURE__ */jsxs(Fragment,{children:[
451
361
  /* @__PURE__ */jsx(TopCard,{card:card,open:cardOpen,onOpenChange:setCardOpen,ask:onCardAsk}),historyBar===void 0?pill:null]}),barShown=historyBar!==void 0,historyLoad=history.load,historyOpen=history.open;useEffect(()=>{barShown&&!historyOpen&&historyLoad()},[barShown,historyOpen,chat.conversationId,historyLoad]);let composerProps={send:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,onStage:sentImages.stage,onPreview:setPreview,petName:shownPet?.name??null,petBreed:shownPet?.breed??null,compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",mood:composerMood(view,urgency.source?.level??null),dictation:presentation.chatComposerMic,telemetry:settings.telemetry},textingAsk=useChatTextingAsk(presentation.chatTextingAsk&&settings.inProvider,chat,textingEntry),uploadOn=attachments!==void 0&&presentation.chatComposerUpload,bannerHidden=!presentation.chatGeneralBanner&&urgency.source?.level==="general",footnoteInThread=presentation.safetyDisclaimerPlacement==="answer_footer"&&(view==="empty"||view==="populated"),footnote=/* @__PURE__ */jsx(Text,{tier:"compact",style:footnoteInThread?styles3.footnoteInThread:styles3.footnote,accessibilityRole:"text",children:forPet(CHAT_COPY.footnoteWeb,shownPet?.name)});
452
362
  /* @__PURE__ */
453
363
  return jsx(AskHomeContext.Provider,{value:askHome,children:/* @__PURE__ */jsxs(KeyboardAvoidingView,{style:[styles3.container,{paddingTop:topInset},style],behavior:avoidBehavior,...keyboard.avoidingProps,children:[
@@ -458,4 +368,4 @@ return jsx(AskHomeContext.Provider,{value:askHome,children:/* @__PURE__ */jsxs(K
458
368
  /* @__PURE__ */jsx(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:petRef2,pet:pet,onRegistered:onRegistered}){let{styles:styles3}=useChatTheme(),setup=useChatPetRegistration(petRef2,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxs(View,{style:styles3.setupNotice,accessible:true,accessibilityRole:"alert",children:[
459
369
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.setupNoticeText,children:setup.error.displayMessage}),
460
370
  /* @__PURE__ */jsx(Pressable,{onPress:setup.retry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,hitSlop:TEXT_ACTION_HIT_SLOP,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.setupNoticeAction,children:CHAT_COPY.retry})})]})}var NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({});function composerMood(view,level){return level==="emergency"?"urgent":view==="populated"?"followUp":"ask"}function EverfurChat(props){/* @__PURE__ */
461
- return jsx(TelevetHostSlot.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */jsx(EverfurChatCore,{...props})})}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state,setState]=useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state.key===key?state:{profile:null,loading:petRef2!==null,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;if(key.petRef===null){setState({key:key,profile:null,loading:false,error:null});return}setState(previous=>({key:key,profile:previous.key===key?previous.profile:null,loading:true,error:null}));let result=await key.repository.getPetProfile(key.petRef);request===generation.current&&setState(result.ok?{key:key,profile:result.value,loading:false,error:null}:{key:key,profile:null,loading:false,error:result.error})},[key]);return useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:rnThemeSeams,children:props.children})}export{APPEARANCE_PRESETS,APPEARANCE_PRESET_NAMES,APPEARANCE_SIZE_RANGES,CapabilityGate,EverfurChat,EverfurConfigError,EverfurProvider,EverfurThemeProvider,EverfurThrownError,THEME_SLOT_KEYS,THEME_SLOT_KEYS_BY_SLOT,THEME_SLOT_NAMES,canonicalPetSpecies,categoryFor,conversationId,createAppStateLifecycle,createRnRecordsUploadTransport,expandAppearance,face,headingFace,isErr,isOk,isRetryableCode,petRef,previewTheme,registerEverfurDictation,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurTheme,userFacingError,userRef};
371
+ return jsx(TelevetHostSlot.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */jsx(EverfurChatCore,{...props})})}var NONE3=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function useUnreadState(petOption,lifecycle){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),store=runtime.unread??null,petRef2=petOption===void 0?activePet:petOption,subscribe2=useCallback(listener=>store===null?NO_SUBSCRIPTION():store.subscribe(listener),[store]),read=useCallback(()=>store===null||userRef2===null?NONE3:store.get(petRef2),[store,userRef2,petRef2]),unread=useSyncExternalStore(subscribe2,read,read),refresh=useCallback(()=>store===null||userRef2===null?Promise.resolve():store.refresh(petRef2),[store,userRef2,petRef2]);return useEffect(()=>{refresh()},[refresh,scopeEpoch]),useChatLifecycle(lifecycle,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:refresh}),useMemo(()=>({...unread,refresh:refresh}),[unread,refresh])}function useEverfurUnread(options={}){let{lifecycle:lifecycle}=options,port=useMemo(()=>lifecycle===void 0?createAppStateLifecycle():lifecycle??void 0,[lifecycle]);return useUnreadState(options.petRef,port)}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state,setState]=useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state.key===key?state:{profile:null,loading:petRef2!==null,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;if(key.petRef===null){setState({key:key,profile:null,loading:false,error:null});return}setState(previous=>({key:key,profile:previous.key===key?previous.profile:null,loading:true,error:null}));let result=await key.repository.getPetProfile(key.petRef);request===generation.current&&setState(result.ok?{key:key,profile:result.value,loading:false,error:null}:{key:key,profile:null,loading:false,error:result.error})},[key]);return useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:rnThemeSeams,children:props.children})}export{APPEARANCE_PRESETS,APPEARANCE_PRESET_NAMES,APPEARANCE_SIZE_RANGES,CapabilityGate,EverfurChat,EverfurConfigError,EverfurProvider,EverfurThemeProvider,EverfurThrownError,THEME_SLOT_KEYS,THEME_SLOT_KEYS_BY_SLOT,THEME_SLOT_NAMES,canonicalPetSpecies,categoryFor,chatHandoffTokenFromUrl,conversationId,createAppStateLifecycle,createRnRecordsUploadTransport,expandAppearance,face,headingFace,isErr,isOk,isRetryableCode,petRef,previewTheme,registerEverfurDictation,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurTheme,useEverfurUnread,userFacingError,userRef};