@everfur/sdk 1.4.0 → 1.5.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.
- package/README.md +2 -2
- package/dist/{Chat.d-BXuEjJsg.d.ts → Chat.d-BCfyvzX8.d.ts} +1 -1
- package/dist/{Chat.d-D9n8tSDD.d.cts → Chat.d-Od44h51D.d.cts} +1 -1
- package/dist/{DepthViews.d-PmjccZLr.d.cts → DepthViews.d-BGspxovy.d.cts} +1 -1
- package/dist/{DepthViews.d-aOChkwU2.d.ts → DepthViews.d-BIHVrf9r.d.ts} +1 -1
- package/dist/{DepthViews.d-ktxIIsnb.d.cts → DepthViews.d-BaLh7Lsi.d.cts} +1 -1
- package/dist/{DepthViews.d-CpF_Y_z9.d.ts → DepthViews.d-CEVk9poG.d.ts} +1 -1
- package/dist/ErrorPolicyPort.d-BIdmYQnk.d.cts +43 -0
- package/dist/ErrorPolicyPort.d-BnI5qWg4.d.ts +43 -0
- package/dist/{RecordsPage.d-BfMSOsg_.d.ts → RecordsPage.d-D10RIgdc.d.ts} +1 -1
- package/dist/{RecordsPage.d-DWjFpZs1.d.cts → RecordsPage.d-DbhYNSbq.d.cts} +1 -1
- package/dist/animations/index.cjs +1 -1
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/animations/index.js +1 -1
- package/dist/{attachments.d-DjWUR-h9.d.ts → attachments.d-BlukNfIf.d.ts} +2 -2
- package/dist/{attachments.d-Bsg6duaq.d.cts → attachments.d-CF4lLuGK.d.cts} +2 -2
- package/dist/{bookingCopy.d-ITpabqPr.d.ts → bookingCopy.d-BuDv16WP.d.ts} +12 -12
- package/dist/{bookingCopy.d-B39JAmIZ.d.cts → bookingCopy.d-rnBSqOSN.d.cts} +12 -12
- package/dist/{branding.d-Bzs4HJoN.d.cts → branding.d-CqDLKj1U.d.cts} +1 -1
- package/dist/{branding.d-CiC6xfGT.d.ts → branding.d-XrZYClN4.d.ts} +1 -1
- package/dist/{callCopy.d-Bw6oZT54.d.cts → callCopy.d-BQxpwXqT.d.cts} +3 -3
- package/dist/{callCopy.d-Bw6oZT54.d.ts → callCopy.d-BQxpwXqT.d.ts} +3 -3
- package/dist/{callRoom.d-B1DoYdJe.d.cts → callRoom.d-9Dm7XnUr.d.cts} +1 -1
- package/dist/{callRoom.d-Dqm1rUqT.d.ts → callRoom.d-t-khijDv.d.ts} +1 -1
- package/dist/{casesRepository.d-De4ZtgJ_.d.cts → casesRepository.d-CVuKTkJo.d.cts} +1 -1
- package/dist/{casesRepository.d-DsEeFd0F.d.ts → casesRepository.d-Dn1fK1b2.d.ts} +1 -1
- package/dist/chat/index.cjs +195 -195
- package/dist/chat/index.d.cts +14 -14
- package/dist/chat/index.d.ts +14 -14
- package/dist/chat/index.js +203 -203
- package/dist/chat/lite/index.cjs +206 -206
- package/dist/chat/lite/index.d.cts +14 -14
- package/dist/chat/lite/index.d.ts +14 -14
- package/dist/chat/lite/index.js +206 -206
- package/dist/{chatHandoffToken.d-sbumx0He.d.cts → chatHandoffToken.d-BjfmIxXk.d.cts} +7 -7
- package/dist/{chatHandoffToken.d-YJY6TZbj.d.ts → chatHandoffToken.d-CFiI6IMc.d.ts} +7 -7
- package/dist/{checkin.d-DxpoRutq.d.cts → checkin.d-BP3ZWBfX.d.cts} +19 -7
- package/dist/{checkin.d-C6vh9KVr.d.ts → checkin.d-CokpahFL.d.ts} +19 -7
- package/dist/{chunk-FZ6DAQFH.js → chunk-4KFFE42Z.js} +20 -20
- package/dist/{chunk-ZPIOCHKW.js → chunk-6IHY7HS7.js} +1 -1
- package/dist/{chunk-II4QDD6F.js → chunk-BMYNDBUR.js} +1 -1
- package/dist/{chunk-AJEELSFO.js → chunk-HHCGXQJR.js} +13 -13
- package/dist/client/index.cjs +31 -31
- package/dist/client/index.d.cts +24 -21
- package/dist/client/index.d.ts +24 -21
- package/dist/client/index.js +31 -31
- package/dist/{clinicBatch.d-B3YJc8IO.d.cts → clinicBatch.d-C0xx5L4j.d.cts} +3 -3
- package/dist/{clinicBatch.d-DhvQuPHV.d.ts → clinicBatch.d-DNi4UURs.d.ts} +3 -3
- package/dist/{config.d-DRoQ2lAx.d.ts → config.d-B7Z-KTGq.d.ts} +10 -2
- package/dist/{config.d-BiVy0fLx.d.cts → config.d-ClAI2RZ6.d.cts} +10 -2
- package/dist/consent/index.cjs +1 -1
- package/dist/consent/index.d.cts +6 -6
- package/dist/consent/index.d.ts +6 -6
- package/dist/consent/index.js +2 -2
- package/dist/{context.d-Cq2C4vdh.d.cts → context.d-Bj6-xYPA.d.cts} +13 -7
- package/dist/{context.d-D1l56nFr.d.ts → context.d-DS1GXUEY.d.ts} +13 -7
- package/dist/{copy.d-Ce_8KuZg.d.cts → copy.d--F5A9cXK.d.cts} +3 -3
- package/dist/{copy.d-BP36f_63.d.ts → copy.d-DmxuFJFe.d.ts} +3 -3
- package/dist/core/index.cjs +42 -41
- package/dist/core/index.d.cts +20 -20
- package/dist/core/index.d.ts +20 -20
- package/dist/core/index.js +42 -41
- package/dist/{depth.d-DzMMmRN4.d.ts → depth.d-CgzYE6_n.d.ts} +3 -3
- package/dist/{depth.d-BtlcIqPJ.d.cts → depth.d-DLaP0o8Y.d.cts} +3 -3
- package/dist/{entitlementRepository.d-x2YFdgYD.d.ts → entitlementRepository.d-CkUTlVAb.d.ts} +3 -3
- package/dist/{entitlementRepository.d-CEDU1gZE.d.cts → entitlementRepository.d-DVTp-BB9.d.cts} +3 -3
- package/dist/{focus.d-BX7oahFk.d.cts → focus.d-CLTjm6In.d.cts} +1 -1
- package/dist/{focus.d-armXecf0.d.ts → focus.d-u-HYvim0.d.ts} +1 -1
- package/dist/health-plan/index.cjs +1 -1
- package/dist/health-plan/index.d.cts +17 -17
- package/dist/health-plan/index.d.ts +17 -17
- package/dist/health-plan/index.js +1 -1
- package/dist/{healthPlanRepository.d-DBx7-NLE.d.cts → healthPlanRepository.d-B22kjrYa.d.cts} +3 -3
- package/dist/{healthPlanRepository.d-C7K9dJK5.d.ts → healthPlanRepository.d-CwRXeoM7.d.ts} +3 -3
- package/dist/{idempotency.d-Dak2-pON.d.cts → idempotency.d-CFVMhWcv.d.cts} +1 -1
- package/dist/{idempotency.d-symqJ8Tt.d.ts → idempotency.d-dOFfV91-.d.ts} +1 -1
- package/dist/{identity.d-DOKJFaiz.d.ts → identity.d-D4VtpqRr.d.ts} +1 -1
- package/dist/{identity.d-DIH9h3Le.d.cts → identity.d-DDpXOtas.d.cts} +1 -1
- package/dist/{inbox.d-AuGKeaZv.d.cts → inbox.d-CPcMMz-Y.d.cts} +2 -2
- package/dist/{inbox.d-B5b57OXc.d.ts → inbox.d-DJ9xgU1Z.d.ts} +2 -2
- package/dist/index.cjs +248 -247
- package/dist/index.d.cts +22 -22
- package/dist/index.d.ts +22 -22
- package/dist/index.js +247 -246
- package/dist/{introEvents.d-ehik7PEn.d.cts → introEvents.d-B7acmGwf.d.cts} +1 -1
- package/dist/{introEvents.d-S4Q4BOSt.d.ts → introEvents.d-DW3gLljE.d.ts} +1 -1
- package/dist/{layout.d-Bm2_1wa4.d.ts → layout.d-C8y_ki1V.d.ts} +1 -1
- package/dist/{layout.d-CFF-nBXf.d.cts → layout.d-DfaFM_lp.d.cts} +1 -1
- package/dist/{models.d-DOwpK1ZF.d.ts → models.d-BKmOfoqV.d.cts} +2 -2
- package/dist/{models.d-Su_BBBTW.d.cts → models.d-BULqCO2R.d.ts} +2 -2
- package/dist/notifications/inbox/index.cjs +9 -9
- package/dist/notifications/inbox/index.d.cts +7 -7
- package/dist/notifications/inbox/index.d.ts +7 -7
- package/dist/notifications/inbox/index.js +9 -9
- package/dist/notifications/index.cjs +3 -3
- package/dist/notifications/index.d.cts +8 -8
- package/dist/notifications/index.d.ts +8 -8
- package/dist/notifications/index.js +6 -6
- package/dist/{optInView.d-DbGx1A9R.d.cts → optInView.d-ByDJMrMv.d.cts} +13 -13
- package/dist/{optInView.d-xnIxCLlH.d.ts → optInView.d-DVshLxbD.d.ts} +13 -13
- package/dist/{parse.d-DtHmpAMT.d.cts → parse.d-BDZ7ffgj.d.cts} +4 -1
- package/dist/{parse.d-DtHmpAMT.d.ts → parse.d-BDZ7ffgj.d.ts} +4 -1
- package/dist/{pets.d-BEqKykpu.d.ts → pets.d-BpLObpfM.d.ts} +1 -1
- package/dist/{pets.d-BS6sLxY-.d.cts → pets.d-DXhzTNuI.d.cts} +1 -1
- package/dist/{petsRepository.d-iHrHkXM2.d.ts → petsRepository.d-_QfM7F6T.d.ts} +1 -1
- package/dist/{petsRepository.d-DB5CNKsK.d.cts → petsRepository.d-ai_tZ3lu.d.cts} +1 -1
- package/dist/photo/index.cjs +1 -1
- package/dist/photo/index.js +23 -23
- package/dist/{presentation.d-CWGjwq8Z.d.cts → presentation.d-BkIvMtIl.d.cts} +3 -3
- package/dist/{presentation.d-CWGjwq8Z.d.ts → presentation.d-BkIvMtIl.d.ts} +3 -3
- package/dist/records/depth/index.cjs +1 -1
- package/dist/records/depth/index.d.cts +10 -10
- package/dist/records/depth/index.d.ts +10 -10
- package/dist/records/depth/index.js +1 -1
- package/dist/records/index.cjs +2 -2
- package/dist/records/index.d.cts +13 -13
- package/dist/records/index.d.ts +13 -13
- package/dist/records/index.js +71 -71
- package/dist/{requestFunnel.d-SySe6xHp.d.cts → requestFunnel.d-BwZDfWVD.d.cts} +3 -3
- package/dist/{requestFunnel.d-CehftayS.d.ts → requestFunnel.d-DKBPTpsy.d.ts} +3 -3
- package/dist/{route.d-9wclfD-y.d.cts → route.d-DCzQh4ix.d.cts} +3 -3
- package/dist/{route.d-IP_gkOWL.d.ts → route.d-DSYEd2MR.d.ts} +3 -3
- package/dist/{runtimeTypes.d-BdUe3tYs.d.ts → runtimeTypes.d-BzUig75K.d.ts} +15 -11
- package/dist/{runtimeTypes.d-_UZ6rMUY.d.cts → runtimeTypes.d-CL4l7ta4.d.cts} +15 -11
- package/dist/{screenProps.d-Bd2yphad.d.cts → screenProps.d-6xmE1C-V.d.cts} +2 -2
- package/dist/{screenProps.d-D9Vi-Afl.d.ts → screenProps.d-fHBKArt_.d.ts} +2 -2
- package/dist/{sdkConfigStore.d-VPvsIL8E.d.ts → sdkConfigStore.d-BNCVVEWC.d.ts} +1 -1
- package/dist/{sdkConfigStore.d-BHrzkVpP.d.cts → sdkConfigStore.d-C2BAr9kI.d.cts} +1 -1
- package/dist/server/events/index.cjs +4 -4
- package/dist/server/events/index.d.cts +2 -2
- package/dist/server/events/index.d.ts +2 -2
- package/dist/server/events/index.js +4 -4
- package/dist/server/index.cjs +9 -9
- package/dist/server/index.d.cts +18 -4
- package/dist/server/index.d.ts +18 -4
- package/dist/server/index.js +9 -9
- package/dist/shop/index.d.cts +3 -3
- package/dist/shop/index.d.ts +3 -3
- package/dist/slots/index.cjs +1 -1
- package/dist/slots/index.d.cts +6 -6
- package/dist/slots/index.d.ts +6 -6
- package/dist/slots/index.js +1 -1
- package/dist/tabs/index.cjs +88 -85
- package/dist/tabs/index.d.cts +15 -15
- package/dist/tabs/index.d.ts +15 -15
- package/dist/tabs/index.js +87 -84
- package/dist/televet/booking/index.cjs +41 -41
- package/dist/televet/booking/index.d.cts +8 -8
- package/dist/televet/booking/index.d.ts +8 -8
- package/dist/televet/booking/index.js +4 -4
- package/dist/televet/call/index.d.cts +2 -2
- package/dist/televet/call/index.d.ts +2 -2
- package/dist/televet/index.cjs +1 -1
- package/dist/televet/index.js +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/rn/index.cjs +8 -8
- package/dist/testing/rn/index.d.cts +13 -13
- package/dist/testing/rn/index.d.ts +13 -13
- package/dist/testing/rn/index.js +9 -9
- package/dist/testing/web/index.cjs +3 -3
- package/dist/testing/web/index.d.cts +13 -13
- package/dist/testing/web/index.d.ts +13 -13
- package/dist/testing/web/index.js +1 -1
- package/dist/texting/index.cjs +1 -1
- package/dist/texting/index.d.cts +6 -6
- package/dist/texting/index.d.ts +6 -6
- package/dist/texting/index.js +26 -26
- package/dist/{threadOptions.d-bEAFkIsC.d.cts → threadOptions.d-Bqy5d5Fx.d.cts} +1 -1
- package/dist/{threadOptions.d-U5YBUKM-.d.ts → threadOptions.d-DOEIpk1t.d.ts} +1 -1
- package/dist/{threadOptions.d-BW0rePcs.d.cts → threadOptions.d-Dc57dm7h.d.cts} +7 -7
- package/dist/{threadOptions.d-CrAb71J2.d.ts → threadOptions.d-NSlFx-Lp.d.ts} +7 -7
- package/dist/{timelineRows.d-DXppCSCg.d.cts → timelineRows.d-7w8NsNi4.d.cts} +1 -1
- package/dist/{timelineRows.d-9Uhf4q5d.d.ts → timelineRows.d-CthNM5hV.d.ts} +1 -1
- package/dist/{typeStyle.d-rzVzCfLz.d.ts → typeStyle.d-8mcLhtbH.d.ts} +1 -1
- package/dist/{typeStyle.d-B-YgiWcS.d.cts → typeStyle.d-CLrQZW-r.d.cts} +1 -1
- package/dist/{unreadStore.d-gCsleb6l.d.ts → unreadStore.d-CLnChKca.d.ts} +17 -9
- package/dist/{unreadStore.d-w5x6lEpR.d.cts → unreadStore.d-Donv4bcF.d.cts} +17 -9
- package/dist/{useHealthPlanSubscription.d-CRBPMlsc.d.ts → useHealthPlanSubscription.d-CV7M21HS.d.ts} +3 -3
- package/dist/{useHealthPlanSubscription.d-DfjTYv1u.d.cts → useHealthPlanSubscription.d-SA9-SuKe.d.cts} +3 -3
- package/dist/{useInboxUnread.d-CP3KwSkn.d.ts → useInboxUnread.d-CXiaR3BZ.d.ts} +1 -1
- package/dist/{useInboxUnread.d-DiE_NbtS.d.cts → useInboxUnread.d-DERpMelw.d.cts} +1 -1
- package/dist/{usePresentation.d-DefUwatV.d.cts → usePresentation.d-BJzFicRQ.d.cts} +3 -3
- package/dist/{usePresentation.d-w5_oWKmh.d.ts → usePresentation.d-DgSGIWS-.d.ts} +3 -3
- package/dist/{useRecordsDepth.d-l6D0ZS4l.d.cts → useRecordsDepth.d-C9W45gwS.d.cts} +1 -1
- package/dist/{useRecordsDepth.d-DG2GiAyt.d.ts → useRecordsDepth.d-ZX2rhcUx.d.ts} +1 -1
- package/dist/{useUnread.d-xDOpYyqx.d.ts → useUnread.d-CedFK4k6.d.ts} +5 -5
- package/dist/{useUnread.d-DeRDFtTb.d.cts → useUnread.d-DST1GMmL.d.cts} +5 -5
- package/dist/video/index.cjs +1 -1
- package/dist/video/index.js +1 -1
- package/dist/{view.d-ufGX_MKK.d.cts → view.d-3lxzyJlL.d.cts} +6 -6
- package/dist/{view.d-iTInze7B.d.ts → view.d-DRiYNQJ8.d.ts} +6 -6
- package/dist/web/consent/index.cjs +3 -3
- package/dist/web/consent/index.d.cts +6 -6
- package/dist/web/consent/index.d.ts +6 -6
- package/dist/web/consent/index.js +5 -5
- package/dist/web/health-plan/index.cjs +2 -2
- package/dist/web/health-plan/index.d.cts +17 -17
- package/dist/web/health-plan/index.d.ts +17 -17
- package/dist/web/health-plan/index.js +1 -1
- package/dist/web/inbox/index.cjs +5 -5
- package/dist/web/inbox/index.d.cts +9 -8
- package/dist/web/inbox/index.d.ts +9 -8
- package/dist/web/inbox/index.js +5 -5
- package/dist/web/index.cjs +196 -195
- package/dist/web/index.d.cts +34 -34
- package/dist/web/index.d.ts +34 -34
- package/dist/web/index.js +196 -195
- package/dist/web/intro/index.cjs +10 -10
- package/dist/web/intro/index.d.cts +8 -8
- package/dist/web/intro/index.d.ts +8 -8
- package/dist/web/intro/index.js +6 -6
- package/dist/web/notifications/index.cjs +5 -5
- package/dist/web/notifications/index.d.cts +7 -7
- package/dist/web/notifications/index.d.ts +7 -7
- package/dist/web/notifications/index.js +1 -1
- package/dist/web/records/depth/index.cjs +1 -1
- package/dist/web/records/depth/index.d.cts +10 -10
- package/dist/web/records/depth/index.d.ts +10 -10
- package/dist/web/records/depth/index.js +1 -1
- package/dist/web/records/index.cjs +1 -1
- package/dist/web/records/index.d.cts +13 -13
- package/dist/web/records/index.d.ts +13 -13
- package/dist/web/records/index.js +1 -1
- package/dist/web/records-sheet/index.cjs +2 -2
- package/dist/web/records-sheet/index.js +2 -2
- package/dist/web/shop/index.cjs +1 -1
- package/dist/web/shop/index.d.cts +3 -3
- package/dist/web/shop/index.d.ts +3 -3
- package/dist/web/shop/index.js +15 -15
- package/dist/web/televet/booking/index.cjs +7 -7
- package/dist/web/televet/booking/index.d.cts +9 -9
- package/dist/web/televet/booking/index.d.ts +9 -9
- package/dist/web/televet/booking/index.js +69 -69
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.d.cts +2 -2
- package/dist/web/televet/call/index.d.ts +2 -2
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +6 -6
- package/dist/web/televet/index.js +1 -1
- package/dist/web/texting/index.cjs +1 -1
- package/dist/web/texting/index.d.cts +6 -6
- package/dist/web/texting/index.d.ts +6 -6
- package/dist/web/texting/index.js +1 -1
- package/dist/web/ui/index.cjs +1 -1
- package/dist/web/ui/index.js +32 -32
- package/package.json +1 -32
- package/dist/ErrorPolicyPort.d-68yrE3BE.d.ts +0 -23
- package/dist/ErrorPolicyPort.d-DirW9hgO.d.cts +0 -23
package/dist/index.js
CHANGED
|
@@ -1,7 +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
2
|
import{z as e}from"zod";import{createContext,forwardRef as t,createElement as r,useEffect as n,useState as l,useSyncExternalStore as i,useContext as o,useMemo as a,useCallback as s,useRef as u,useReducer as c,useLayoutEffect as d,Component as f,Fragment as h}from"react";import{Platform as p,TextInput as g,StyleSheet as b,AccessibilityInfo as m,useColorScheme as y,Dimensions as v,PixelRatio as k,View as w,AppState as C,Text as S,Linking as x,KeyboardAvoidingView as _,Pressable as R,Keyboard as T,Modal as I,ScrollView as z,ActivityIndicator as P,Image as O,UIManager as E,LayoutAnimation as j,Animated as F,useWindowDimensions as A,FlatList as D}from"react-native";import{SafeAreaProvider as M,useSafeAreaInsets as L}from"react-native-safe-area-context";import B from"react-native-sse";import{jsx as H,jsxs as U,Fragment as N}from"react/jsx-runtime";import*as $ from"@everfur/sdk/televet/booking";import*as W from"@everfur/sdk/texting";function V(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))return true;t+=1}else if(r>=56320&&r<=57343)return true}return false}function q(e){return[...e].length}function ok(e,t){/* @__PURE__ */
|
|
3
3
|
return Object.freeze({ok:true,value:e})}function err(e){/* @__PURE__ */
|
|
4
|
-
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var G=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new G(e.error)}var K=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var Y=128,Q=128,J=/[\u0000-\u001F\u007F]/,X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=q(t);if(r===0||r>Q)throw new K("invalid-argument",`petRef must be 1..${Q} characters`);if(J.test(t))throw new K("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=q(t);if(r===0||r>Y)throw new K("invalid-argument",`userRef must be 1..${Y} characters`);if(t.includes("@"))throw new K("invalid-argument","userRef must not contain '@'");if(J.test(t))throw new K("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!X.test(e))throw new K("invalid-argument","conversationId must be a UUID");return e}var Z=[{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:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,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:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{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:"environment_mismatch",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:"not_found",envelope:"http_envelope",httpStatus:404,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:"restricted_key",envelope:"http_envelope",httpStatus:403,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:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,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}],ee=/* @__PURE__ */Object.freeze(Z.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(ee.map(e=>e.wireCode));var te=/* @__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",anonTokenInvalid:"authRejected",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",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound"}),re=/* @__PURE__ */Object.freeze(ee.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:te[e.wireCode]}))),ne=new Map(re.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),le=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(re.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...le]){let t=ne.get(e+r);if(t)return t}}var ie=/* @__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(e){return ie[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){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"FREECAPREACHED":return"paymentRequired";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(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var oe=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return oe.has(e)}var ae=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||ae.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var se=500,ue=8e3,ce=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(se*2**r,ue);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var de="This feature isn't available on your account right now.",fe="Something in that request was not right. Check the details and try again.",he=/* @__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:de,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:fe,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:de,runtimeDisposed:fe,unknown:"Something went wrong. Please try again."}),pe="This session has ended. Please sign in again.",ge="linked_account_read_only";function be(e,t,r){return e==="conflict"&&r===ge?de:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?pe:userFacingError(e)}function userFacingError(e){return he[e]}function me(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var ye=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===ge,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:be(e,t?.wireCode,n?ge:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&ye.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&me(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&me(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var ve=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function ke(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return xe(e)}var we=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,Ce=/[\s\u0000-\u001f\u007f\\]/,Se={"http:":"80","https:":"443"};function xe(e,t){let r=e.trim();let n=Ce.test(r)?null:we.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===Se[f]?"":String(h),g=Se[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var _e="application/pdf",Re=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Te=e=>Re.includes(e);function Ie(e,t){return e===_e||t!==void 0&&Te(e)&&t.includes(e)}var ze=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function Pe(e){return Ie(e,Re)?ze[e]:ze["application/pdf"]}var Oe="file",Ee="multipart upload failed";function je(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Oe,e.file)}catch{return Promise.reject(new Error(Ee))}return e.fetch!==void 0?De(e.fetch,e.url,t,e.signal):Ae(e.url,t,e.signal)}function Fe(e){return e>=200&&e<300}function Ae(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(Ee));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(Ee))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Fe(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function De(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var Me="records upload: the file handle has no uri",Le="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
4
|
+
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var G=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new G(e.error)}var K=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var Y=128,Q=128,J=/[\u0000-\u001F\u007F]/,X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=q(t);if(r===0||r>Q)throw new K("invalid-argument",`petRef must be 1..${Q} characters`);if(J.test(t))throw new K("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=q(t);if(r===0||r>Y)throw new K("invalid-argument",`userRef must be 1..${Y} characters`);if(t.includes("@"))throw new K("invalid-argument","userRef must not contain '@'");if(J.test(t))throw new K("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!X.test(e))throw new K("invalid-argument","conversationId must be a UUID");return e}var Z=[{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:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,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:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{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:"environment_mismatch",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:"not_found",envelope:"http_envelope",httpStatus:404,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:"restricted_key",envelope:"http_envelope",httpStatus:403,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:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{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}],ee=/* @__PURE__ */Object.freeze(Z.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(ee.map(e=>e.wireCode));var te=/* @__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",anonTokenInvalid:"authRejected",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",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),re=/* @__PURE__ */Object.freeze(ee.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:te[e.wireCode]}))),ne=new Map(re.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),le=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(re.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...le]){let t=ne.get(e+r);if(t)return t}}var ie=/* @__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(e){return ie[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){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"FREECAPREACHED":return"paymentRequired";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(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var oe=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return oe.has(e)}var ae=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||ae.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var se=500,ue=8e3,ce=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(se*2**r,ue);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var de="This feature isn't available on your account right now.",fe="Something in that request was not right. Check the details and try again.",he=/* @__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:de,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:fe,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:de,runtimeDisposed:fe,unknown:"Something went wrong. Please try again."}),pe="This session has ended. Please sign in again.",ge="linked_account_read_only";function be(e,t,r){return e==="conflict"&&r===ge?de:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?pe:userFacingError(e)}function userFacingError(e){return he[e]}function me(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var ye=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===ge,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:be(e,t?.wireCode,n?ge:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&ye.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&me(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&me(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var ve=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function ke(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return xe(e)}var we=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,Ce=/[\s\u0000-\u001f\u007f\\]/,Se={"http:":"80","https:":"443"};function xe(e,t){let r=e.trim();let n=Ce.test(r)?null:we.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===Se[f]?"":String(h),g=Se[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var _e="application/pdf",Re=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Te=e=>Re.includes(e);function Ie(e,t){return e===_e||t!==void 0&&Te(e)&&t.includes(e)}var ze=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function Pe(e){return Ie(e,Re)?ze[e]:ze["application/pdf"]}var Oe="file",Ee="multipart upload failed";function je(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Oe,e.file)}catch{return Promise.reject(new Error(Ee))}return e.fetch!==void 0?De(e.fetch,e.url,t,e.signal):Ae(e.url,t,e.signal)}function Fe(e){return e>=200&&e<300}function Ae(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(Ee));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(Ee))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Fe(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function De(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var Me="records upload: the file handle has no uri",Le="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
5
5
|
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Me));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(Le));return l?.aborted===true?o():je({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:Pe(r.mimeType),type:Be(r.mimeType)},signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}function Be(e){return Ie(e,Re)?e:"application/pdf"}var He=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var Ue=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<ce},maxAttempts(){return ce}});var Ne=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(e,t,r){let n;try{n=t()}catch(t){return We(`optional peer '${e}' is not installed: ${Ve(t)}`)}let l=$e(n);return l==null?We(`optional peer '${e}' resolved to no module`):r&&!r(l)?We(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:l})}function $e(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function We(e){/* @__PURE__ */
|
|
6
6
|
return Object.freeze({available:false,module:null,reason:e})}function Ve(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function acceptedFrame(e,t,r=null){/* @__PURE__ */
|
|
7
7
|
return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}function heartbeatFrame(e,t=null){/* @__PURE__ */
|
|
@@ -12,374 +12,375 @@ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryab
|
|
|
12
12
|
return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
|
|
13
13
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
|
|
14
14
|
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var qe="/widget/v1/anon-identity",Ge="x-everfur-anon-token",Ke="anonTokenInvalid";function Ye(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let l=null,i=null,o=null,a=null,s=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs-2592e5),d=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,a={method:"POST",path:qe,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},s=await e.request(a),u=s.ok?s.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(l={token:c,mintedAtMs:n(),ttlMs:Ye(u?.expires_at,i)},o=null,c)}catch{return o=n(),d()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(a,3e4)?Promise.resolve(l?.token??null):(a=n(),l=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function Qe(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function Je(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let l=null,i=false,o=null,a=false,s=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new K("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:Xe(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(a)throw new K("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:s()},hasToken(){return!a&&l!==null},clear(){a=true,l=null},reportRejected(){a||i||(i=true,n?.())}}}function Xe(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[Ge]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...Ze(e.headers),...authHeaders(t)}}}function Ze(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===Ge||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await Qe(t),n=await t.transport.request(withAuthHeaders(e,et(t,r)));if(n.ok||rt(n.error.raw)!==Ke||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,et(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(Je(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(Je(e,{wireCode:rt(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(tt(i.error))):i}function et(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function tt(e){let t=e.raw,r=rt(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function rt(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var nt="DAILY_QUOTA_EXCEEDED",lt=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function it(e,t){if(!lt.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?nt:e}var ot="free_cap_reached";function at(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function st(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==ot&&n.code!==ot)return null;let l=at(n.limit),i=at(n.used);if(l===null||i===null)return null;let o=n.resets_at,a=n.emergency_guidance;/* @__PURE__ */
|
|
15
|
-
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ut(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:st(t)}function ct(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function dt(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ct()}var ft=`\n\n`,ht=1048576,pt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),gt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=dt(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(ft,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+ft.length),o=0;let r=bt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>ht){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=bt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function bt(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=pt.safeParse(l);return i.success?mt(i.data,r,t):null}function mt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:yt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:yt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:st(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:yt(e.conversation_id)??"",messageId:yt(e.message_id),title:yt(e.title),followUpQuestions:Ct(e.follow_up_questions),citations:xt(e.citations),citationStatus:yt(e.citation_status),urgencyLevel:kt(e.urgency_level),urgencyReason:yt(e.urgency_reason),urgencyProvided:wt(e),resultId:yt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(yt(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=yt(e.delta)??yt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(yt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:yt(e.result_id),analysisType:yt(e.analysis_type),modelVersion:yt(e.model_version),confidence:vt(e.confidence),detections:xt(e.detections),interpretation:yt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function yt(e){return typeof e=="string"?e:null}function vt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function kt(e){return typeof e=="string"&>.includes(e)?e:null}function wt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||kt(t)!==null}function Ct(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e){return Array.isArray(e)?e.filter(St):[]}var
|
|
15
|
+
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ut(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:st(t)}function ct(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function dt(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ct()}var ft=`\n\n`,ht=1048576,pt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),gt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=dt(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(ft,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+ft.length),o=0;let r=bt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>ht){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=bt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function bt(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=pt.safeParse(l);return i.success?mt(i.data,r,t):null}function mt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:yt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:yt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:st(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:yt(e.conversation_id)??"",messageId:yt(e.message_id),title:yt(e.title),followUpQuestions:Ct(e.follow_up_questions),citations:xt(e.citations),citationStatus:yt(e.citation_status),urgencyLevel:kt(e.urgency_level),urgencyReason:yt(e.urgency_reason),urgencyProvided:wt(e),resultId:yt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(yt(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=yt(e.delta)??yt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(yt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:yt(e.result_id),analysisType:yt(e.analysis_type),modelVersion:yt(e.model_version),confidence:vt(e.confidence),detections:xt(e.detections),interpretation:yt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function yt(e){return typeof e=="string"?e:null}function vt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function kt(e){return typeof e=="string"&>.includes(e)?e:null}function wt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||kt(t)!==null}function Ct(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e){return Array.isArray(e)?e.filter(St):[]}function _t(e,t,r){return{...e,surface:t,requestId:r||null}}var Rt=64,Tt=/^[A-Za-z0-9._+() -]+$/;function It(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Rt?null:Tt.test(t)?t:null}var zt="1.5.0";var Pt="react-native",Ot="2026-09-19",Et="EVERFUR_API_BASE_URL";function jt(e,t){/* @__PURE__ */
|
|
16
16
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{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(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
|
|
17
|
-
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||
|
|
18
|
-
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:
|
|
19
|
-
return Object.freeze({ok:true,value:o})}function
|
|
17
|
+
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||Ot,o=It(e.appVersion);/* @__PURE__ */
|
|
18
|
+
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:zt,platform:t?.platform??Pt,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:Ht(Et);return r?Lt(r):jt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Et}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function Ft(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function At(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function Dt(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:At(t)}function Mt(e,t){return`${e}://${t}`}function Lt(e){let t=e.trim(),r=ve.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return jt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=Ft(r[2]);if(l.length===0)return jt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=Dt(t,l)?`: ${Mt(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&Bt(l)))return n==="http"?jt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):jt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
19
|
+
return Object.freeze({ok:true,value:o})}function Bt(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function Ht(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Ut(e,t){if(e.status!==429&&e.status!==503)return t;let r=$t(e.headers.get(Nt),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&Wt(n)?t:{...n??{},retry_after_seconds:r}}var Nt="retry-after";function $t(e,t){if(e===null)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r);let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):null}function Wt(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var Vt=3e4,qt="x-request-id";async function*fetchByteSource(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)break;r&&r.length>0&&(yield r)}}finally{await(t.cancel?.())}}function eventSourceByteSource(e){let t=new TextEncoder,r=Kt(),n=false,l=e=>{let n="";e.lastEventId&&(n+=`id: ${e.lastEventId}\n`);let l=e.data??"";for(let e of l.split(`\n`))n+=`data: ${e}\n`;n+=`\n`,r.push(t.encode(n))},i=()=>{a(),r.end()},o=e=>{let n=typeof e.xhrStatus=="number"?e.xhrStatus:0;if(n>=400){let l=er(e.message);if(l!==null){let e={type:"error",code:ot,retryable:false,limit:l.limit,used:l.used,resets_at:l.resetsAt,emergency_guidance:l.emergencyGuidance};r.push(t.encode(`data: ${JSON.stringify(e)}\n\n`))}else{let e=Xt(n),l=isAutoRetryable(fromWire(e));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:e,retryable:l})}\n\n`))}}a(),r.end()};e.addEventListener("message",l),e.addEventListener("done",i),e.addEventListener("error",o);function a(){if(!n){n=true,e.removeEventListener("message",l),e.removeEventListener("done",i),e.removeEventListener("error",o);try{e.close()}catch{}}}return Gt(r.source,a)}async function*Gt(e,t){try{yield*e}finally{t()}}function Kt(){let e=[],t=false,r=null,n=()=>{if(r){let e=r;r=null,e()}};async function*l(){for(;;){let n=e.shift();if(n!==void 0){yield n;continue}if(t)return;await new Promise(e=>{r=e})}}return{source:l(),push:t=>{e.push(t),n()},end:()=>{t=true,n()}}}async function requestJson(e,t){let r=t.fetchImpl??getGlobalFetch(),n=tr(t.config.apiBaseUrl,e.path,e.query),l=rr(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),i=ir(Vt),o=or(i.signal,e.signal),a;try{a=await r(n,nr({...e,signal:o},l))}catch(e){return err(networkError(e))}finally{i.cancel()}if(e.onResponseHeaders)try{e.onResponseHeaders(e=>a.headers.get(e))}catch{}if(e.rawText&&a.ok)try{return ok(Number(a.headers.get("content-length"))>e.rawText?null:await a.text())}catch(e){return err(networkError(e))}let s=await ar(a);return a.ok?ok(s):err(errorFromResponse(a.status,Ut(a,s),requestIdOf(a)))}function createHttpTransport(e){return{request:t=>requestJson(t,e),stream:(t,r)=>Yt(lr(t,r),e)}}async function*Yt(e,t){let r=tr(t.config.apiBaseUrl,e.path,e.query),n=rr(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Qt(e,n));yield*parseSse(eventSourceByteSource(l),()=>eventSourceRequestId(l));return}let l=t.fetchImpl??getGlobalFetch(),i;try{i=await l(r,nr(e,n))}catch(e){yield Zt("",true,fr(e));return}let o=requestIdOf(i);if(!i.ok){let e=await ar(i),t=ur(e)??Xt(i.status),r=dr(e)||isAutoRetryable(fromWire(t));yield Zt(t,r,cr(e),o,st(e));return}if(i.body){yield*parseSse(fetchByteSource(i.body),o);return}yield*parseSse(fetchByteSource(null),o)}function Qt(e,t){return{method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}function errorFromResponse(e,t,r){let n=ur(t),l=n?fromWire(n):fromHttpStatus(e),i=cr(t);return makeEverfurError(l,{httpStatus:e,...dr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...sr(t)?{reasonCode:sr(t)}:{},...Jt(t)!==null?{retryAfterSeconds:Jt(t)}:{},...i?{wireMessage:i}:{},...t!=null?{raw:t}:{}})}function Jt(e){let t=e,r=t?.retry_after_seconds??t?.error?.retry_after_seconds;return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null}function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:fr(e)})}function requestIdOf(e){let t=e.headers.get(qt);return typeof t=="string"&&t.length>0?t:null}function eventSourceRequestId(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(qt)}catch{return null}return typeof t=="string"&&t.length>0?t:null}function Xt(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}function Zt(e,t,r,n=null,l=null){return errorFrame({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n,freeCap:l})}function er(e){if(typeof e!="string"||e.length===0)return null;try{return st(JSON.parse(e))}catch{return null}}function getGlobalFetch(){let e=globalThis.fetch;if(typeof e!="function")throw new K("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}function tr(e,t,r){let n=t.startsWith("/")?t:`/${t}`,l=`${e}${n}`;if(r){let e=Object.entries(r).filter(e=>e[1]!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");e&&(l+=`?${e}`)}return l}function rr(e,t,r,n){let l={...buildBaseHeaders(e),accept:r};return n&&(l["content-type"]="application/json"),t&&Object.assign(l,t),l}function nr(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}function lr(e,t){return e.signal?e:{...e,signal:t}}function ir(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function or(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}async function ar(e){try{return await e.json()}catch{return null}}function sr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}function ur(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?it(r,e):st(e)!==null?ot:null}function cr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}function dr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}function fr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var hr=3e4,pr=ue*2,gr="idempotency-key",br=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),mr=/* @__PURE__ */Object.freeze({onEvent(){}}),yr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function vr(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??mr,r=e.timers??yr,n=e.rng??Math.random,l=e.sleep??((e,t)=>Ar(e,r,t)),i=e.maxAttempts??ce,o=e.unaryTimeoutMs??hr,a=e.newIdempotencyKey??wr(),s=e=>{try{t.onEvent(e)}catch{}};async function u(t,u,c){let d=c?.maxAttempts,f=Math.max(1,d??i),h=c?.idempotent??br.has(u.method),p=c?.idempotencyKey===void 0?null:vr(c.idempotencyKey),g=h?p??a():null,b=kr(u,g),m=0;for(;;){let i=e=>/* @__PURE__ */Object.freeze({call:t,method:u.method,path:u.path,attempt:m,...g?{idempotencyKey:g}:{},...e});s(i({phase:"attempt"}));let a=jr(o,r),c=Fr(a.signal,u.signal),h;try{h=await authedSend({...b,signal:c.signal},e.auth)}catch(e){h=err(networkError(e))}finally{c.dispose(),a.cancel()}if(h.ok)return s(i({phase:"settled",ok:true,reason:"ok"})),h;let p=h.error,y=Sr(p,m,{maxAttempts:f,rng:n,now:r.now(),aborted:u.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:p.code,reason:y.reason,...p.httpStatus!==void 0?{httpStatus:p.httpStatus}:{},...p.requestId!==void 0?{requestId:p.requestId}:{}};if(!y.retry)return s(i({phase:"settled",...v})),err(p);if(s(i({phase:"retry",...v,delayMs:y.delayMs})),await l(y.delayMs,u.signal),u.signal?.aborted===true)return s(i({phase:"settled",...v,reason:"aborted"})),err(p);m+=1}}async function c(t){return withAuthHeaders(t,await Er(e.auth))}async function*d(t,r,n){s(
|
|
20
20
|
/* @__PURE__ */Object.freeze({call:t,phase:"stream.open",method:r.method,path:r.path,attempt:0}));try{yield*e.auth.transport.stream(r,n)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null})}}/* @__PURE__ */
|
|
21
|
-
return Object.freeze({send:u,authorize:c,stream:d})}function
|
|
22
|
-
return Object.freeze({caseId:r,status:n,bodyLocation:
|
|
23
|
-
return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function
|
|
24
|
-
return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function
|
|
25
|
-
return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function
|
|
26
|
-
return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function
|
|
27
|
-
return Object.freeze(r)}function
|
|
28
|
-
return Object.freeze({conversationId:r,message:c,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==
|
|
29
|
-
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function
|
|
30
|
-
return Object.freeze(e.flatMap(e=>{let r=In(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function Mn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Ln=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Bn=4e3;var Hn=4e3;function Un(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:en("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:en("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Nn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:en("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Hn?{reason:"too_long",error:en("validationFailed",false,`message is ${r} characters; the server accepts at most ${Hn}`)}:null}function $n(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Wn(e){yield e}async function*Vn(){}var qn=6e4,Gn=18e4,Kn=24,Yn=512,Qn=false;function createChatController(e){return new el(e)}function Jn(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Xn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function Zn(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var el=class extends Gr{constructor(e){super(Zr({status:"idle",messages:[],conversationId:e.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.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Hr(this.funnel),this.telemetry=e.telemetry??He,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??Ue,this.timers=e.timers??fn,this.rng=e.rng??Math.random,this.newId=e.newId??cn(),this.makeIdempotencyKey=e.makeIdempotencyKey??dn(),this.budget={idleMs:e.budget?.idleMs??qn,overallMs:e.budget?.overallMs??Gn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=en(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Wn(rn(e))}let l=Nn(e)??Un(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Wn(rn(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Wn(rn(en("accessDenied",false)));let r=Nn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Wn(rn(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):Vn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Kr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?Qr(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(on(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=Rn(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(en("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(en("accessDenied",false));if(!l.ok)return l;let i=On(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return i}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Cn(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Xn(n.error)?n.error:null;if(n.error.category==="notFound"&&Zn(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=wn(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}Jn(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(en("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(en("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(en("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(en("accessDenied",false));if(typeof e!="string"||e.trim().length===0||V(e))return err(en("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Ln.includes(t))return err(en("validationFailed",false,`feedback_type must be one of ${Ln.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>Bn)return err(en("validationFailed",false,`notes is over ${Bn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(en("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(en("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(en("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(en("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!Tn(e))return err(en("validationFailed",false));let r=Rn(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(en("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(en("accessDenied",false)):l.ok?En(l.value):l}async resumeConversation(e){if(this.disposed)return err(en("accessDenied",false));if(!Tn(e))return err(en("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===kn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||Sn({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
-
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?kn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(en("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(!i.ok)return err(i.error);let o=Mn(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.reportLoadFailures===true&&!n.ok&&Xn(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(en("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield rn(t.error))}async primeConversation(e){if(this.disposed)return err(en("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(en("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(en("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(en("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(en("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(en("accessDenied",false));let r=e?.petRef??null;if(r!==null&&V(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(en("accessDenied",false)):l.ok?ok(ln(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=qr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Kr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,rn(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=en("internalError",!0);yield*this.emitTerminal(e,t,rn(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=qr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,rn(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Ge]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of hn(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=en("streamIncomplete",!0);yield*this.emitTerminal(e,t,rn(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===Ke||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,tn(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(Qn&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,tn(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Qr(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,Yr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Yn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Kn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Jr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?Xr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Qr(e):e),Xr(Yr(r,"",this.stamp()),e)]}let l=on([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=$n(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?Qr(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.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(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?en("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,rl(e)?(a=true,u=e):(nl(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){rl(e)?(a=true,u===null&&(u=e)):nl(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
32
|
-
return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:b,error:y,warning:y===null&&g===null&&s?
|
|
33
|
-
return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return
|
|
34
|
-
return Object.freeze({upload_id:l,upload_url:i,upload_fields:/* @__PURE__ */Object.freeze(a),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??
|
|
35
|
-
return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:
|
|
36
|
-
return Object.freeze({petRef:
|
|
37
|
-
return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return
|
|
21
|
+
return Object.freeze({send:u,authorize:c,stream:d})}function kr(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==gr&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function wr(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var Cr=10;function Sr(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=xr(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=n==="burst"?"burst-throttle":"retryable-code";if((()=>{if(r.policy===void 0)return false;try{return!r.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let i=()=>{if(r.policy===void 0)return null;let t;try{t=r.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Cr,Math.floor(t)))},o=r.perCallMaxAttempts??i()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let a=_r(e,r.now);return a!==null?a>pr?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:a}:{retry:true,reason:l,delayMs:backoffDelayMs(t,r.rng)}}function xr(e){let t=e.code==="unknown"?fromWire(Pr(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function _r(e,t){let r=Tr(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=Rr(e.raw);return n===null?null:Math.round(n*1e3)}function Rr(e){for(let t of Ir(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Tr(e){for(let t of Ir(e)){let e=t.resets_at,r=zr(e);if(r!==null)return r}return null}function Ir(e){if(!Or(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];Or(n)&&t.push(n)}return t}function zr(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function Pr(e){for(let t of Ir(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function Or(e){return typeof e=="object"&&e!==null}async function Er(e){if(e.mode==="anonymous"){let t=await Qe(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function jr(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function Fr(e,t){let r=()=>{};if(!t)return{signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let l=()=>n.abort();return e.addEventListener("abort",l,{once:true}),t.addEventListener("abort",l,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",l),t.removeEventListener("abort",l)}}}function Ar(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let l=t.setTimeout(()=>{r?.removeEventListener("abort",i),n()},e),i=()=>{t.clearTimeout(l),n()};r?.addEventListener("abort",i,{once:true})})}var Dr=/* @__PURE__ */Object.freeze(["better","same","worse"]),Mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Lr(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Br(){return err(makeEverfurError("internalError",{retryable:false}))}function Hr(e){return typeof e!="string"||e.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):V(e)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}var Ur=e=>typeof e=="string"?e:null,Nr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function $r(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ur(t.case_id),n=Ur(t.status);if(r===null||n===null)return null;let l=Ur(t.last_response);/* @__PURE__ */
|
|
22
|
+
return Object.freeze({caseId:r,status:n,bodyLocation:Ur(t.body_location),lastResponse:l!==null&&Dr.includes(l)?l:null,checkInDueAt:Ur(t.check_in_due_at),openedAt:Ur(t.opened_at),resolvedAt:Ur(t.resolved_at),resolutionText:Ur(t.resolution_text),checkinAskCount:Nr(t.checkin_ask_count),checkinAnswerCount:Nr(t.checkin_answer_count)})}function Wr(e){return{async list(t,r){let n=Hr(t);if(typeof n!="string")return err(n);let l=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!l.ok)return err(l.error);let i=typeof l.value=="object"&&l.value!==null?l.value.cases:null;if(!Array.isArray(i))return Br();let o=i.map($r);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):Br()},async checkin(t,r,n,l){let i=Hr(t);if(typeof i!="string")return err(i);if(typeof r!="string"||!Mr.test(r))return Lr("case_id must be a UUID");if(!Dr.includes(n))return Lr("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${i}/${r}/checkin`,body:{response:n},...l?.signal?{signal:l.signal}:{}});if(!o.ok)return err(o.error);let a=typeof o.value=="object"&&o.value!==null?o.value:{},s=$r(a.case);return s===null?Br():ok(/* @__PURE__ */Object.freeze({case:s,ctaDeepLink:Ur(a.cta_deep_link)}))}}}function Vr(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}function qr(e,t){let r=t.activeConversationId===null||t.activeConversationId.length===0?null:t.activeConversationId;return r===null&&t.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:Vr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var Gr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var Kr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Yr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let l={handle:void 0},i=()=>{r.clearTimeout(l.handle),t.removeEventListener("abort",i),n()};l.handle=r.setTimeout(i,e),t.addEventListener("abort",i,{once:true})})}function Qr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}var Jr=class{constructor(e){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...e})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){return this.snapshot}patch(e){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...e});for(let e of this.listeners)e()}beginOperation(e){this.inFlight?.abort();let t=new AbortController;this.inFlight=t;let r=this.epoch;return{signal:e?Qr(t.signal,e):t.signal,epoch:r,settle:()=>{this.inFlight===t&&(this.inFlight=null)}}}alive(e){return e===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 Xr(e,t,r){/* @__PURE__ */
|
|
23
|
+
return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function Zr(e,t,r){/* @__PURE__ */
|
|
24
|
+
return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function en(e){/* @__PURE__ */
|
|
25
|
+
return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function tn(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),/* @__PURE__ */Object.freeze(r)}function rn(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,/* @__PURE__ */Object.freeze(r)}function nn(e){/* @__PURE__ */
|
|
26
|
+
return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function ln(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function on(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function an(e){return errorFrame({code:sn(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function sn(e){switch(e){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(e)}}function un(e){let t=Array.isArray(e)?e:dn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!dn(e))continue;let t=fn(e.category)??fn(e.title)??"",n=hn(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
|
|
27
|
+
return Object.freeze(r)}function cn(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fn(e){return typeof e=="string"?e:null}function hn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(dn(r)){let e=fn(r.text)??fn(r.prompt)??fn(r.title);e!==null&&t.push(e)}return t}function pn(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function gn(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var bn={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*mn(e,t,r,n){let l=e[Symbol.asyncIterator](),i=kn(t.overallMs,n),o=kn(t.idleMs,n),a=wn(r);try{for(;;){if(r.aborted)return;let e=l.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),i.promise.then(()=>({tag:"overall"})),a.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield vn();return}if(n.tag==="idle"||n.tag==="overall"){yield yn();return}let s=n.value;if(s.done||(o.reset(t.idleMs),yield s.value,s.value.terminal))return}}finally{o.cancel(),i.cancel(),Promise.resolve(l.return?.(void 0)).catch(()=>{})}}function yn(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function vn(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function kn(e,t){let r=()=>{},n=new Promise(e=>{r=e}),l=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(l),l=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(l)}}}function wn(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var Cn="checkin",Sn=/^\d{4}-\d{2}-\d{2}$/,xn="watching";function _n(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function Rn(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,l=t.question,i=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof l!="string"||l.trim().length===0)return null;let o=typeof i=="string"&&i.length>0?i:null,a=In(o),s=a===null?null:/* @__PURE__ */Object.freeze({caseId:a.caseId,answer:null,resolutionText:null,status:null}),u=typeof t.created_at=="string"?t.created_at:"",c=/* @__PURE__ */Object.freeze({id:n,role:"assistant",text:l,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...s===null?{}:{checkin:s}});/* @__PURE__ */
|
|
28
|
+
return Object.freeze({conversationId:r,message:c,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==xn}function Tn(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}function In(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==Cn||n===void 0||l===void 0||!Mr.test(n)||!Sn.test(l)?null:{caseId:n,dueDay:l}}function zn(e){return In(e)?.caseId??null}function Pn(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||V(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function On(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function En(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function jn(e){return e==null||typeof e=="string"&&e.length>0&&!V(e)}function Fn(){return err(makeEverfurError("internalError",{retryable:false}))}function An(e){let t=En(e);if(!t||!Array.isArray(t.conversations)||!jn(t.next_cursor))return Fn();let r=[];for(let e of t.conversations){let t=En(e);if(!t||typeof t.conversation_id!="string"||!On(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return Fn();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return Fn();let l=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...l.length>0?{preview:l}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Dn(e){let t=En(e);if(!t||!Array.isArray(t.messages)||!jn(t.next_cursor))return Fn();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=En(e);if(!t||typeof t.message_id!="string"||!On(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return Fn();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Mn(t,t.message_id,t.content,t.created_at));continue}let l=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,i=t.role==="assistant"?zn(l):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:Bn(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Hn(t.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...i!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:i,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Mn(e,t,r,n){let l=En(e.sender),i=Ln(l?.display_name)??Ln(e.sender_display_name),o=Ln(l?.specialty);/* @__PURE__ */
|
|
29
|
+
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function Ln(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!V(t)?t:null}function Bn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function Hn(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
|
|
30
|
+
return Object.freeze(e.flatMap(e=>{let r=En(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function Un(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Nn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),$n=4e3;var Wn=4e3;function Vn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:ln("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:ln("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function qn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:ln("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Wn?{reason:"too_long",error:ln("validationFailed",false,`message is ${r} characters; the server accepts at most ${Wn}`)}:null}function Gn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Kn(e){yield e}async function*Yn(){}var Qn=6e4,Jn=18e4,Xn=24,Zn=512,el=false;function createChatController(e){return new ll(e)}function tl(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function rl(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function nl(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var ll=class extends Jr{constructor(e){super(nn({status:"idle",messages:[],conversationId:e.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.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Wr(this.funnel),this.telemetry=e.telemetry??He,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??Ue,this.timers=e.timers??bn,this.rng=e.rng??Math.random,this.newId=e.newId??pn(),this.makeIdempotencyKey=e.makeIdempotencyKey??gn(),this.budget={idleMs:e.budget?.idleMs??Qn,overallMs:e.budget?.overallMs??Jn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=ln(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Kn(an(e))}let l=qn(e)??Vn(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Kn(an(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Kn(an(ln("accessDenied",false)));let r=qn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Kn(an(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):Yn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Xr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?en(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(cn(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=Pn(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(ln("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(ln("accessDenied",false));if(!l.ok)return l;let i=An(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,i.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return i}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Rn(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),rl(n.error)?n.error:null;if(n.error.category==="notFound"&&nl(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=_n(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}tl(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(ln("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(ln("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(ln("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(ln("accessDenied",false));if(typeof e!="string"||e.trim().length===0||V(e))return err(ln("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Nn.includes(t))return err(ln("validationFailed",false,`feedback_type must be one of ${Nn.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>$n)return err(ln("validationFailed",false,`notes is over ${$n} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(ln("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(ln("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(ln("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(ln("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!On(e))return err(ln("validationFailed",false));let r=Pn(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(ln("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(ln("accessDenied",false)):l.ok?Dn(l.value):l}async resumeConversation(e){if(this.disposed)return err(ln("accessDenied",false));if(!On(e))return err(ln("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(ln("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===xn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||Tn({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
+
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?xn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(ln("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(ln("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(ln("accessDenied",false));if(!i.ok)return err(i.error);let o=Un(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&rl(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(ln("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(ln("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield an(t.error))}async primeConversation(e){if(this.disposed)return err(ln("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(ln("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(ln("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(ln("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(ln("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(ln("accessDenied",false));let r=e?.petRef??null;if(r!==null&&V(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(ln("accessDenied",false)):l.ok?ok(un(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=Qr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Xr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,an(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=ln("internalError",!0);yield*this.emitTerminal(e,t,an(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=Qr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,an(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Ge]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of mn(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=ln("streamIncomplete",!0);yield*this.emitTerminal(e,t,an(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===Ke||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,on(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(el&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,on(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?en(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,Zr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Zn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Xn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?tn(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?rn(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?en(e):e),rn(Zr(r,"",this.stamp()),e)]}let l=cn([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=Gn(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?en(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.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(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?ln("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,ol(e)?(a=true,u=e):(al(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){ol(e)?(a=true,u===null&&(u=e)):al(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
32
|
+
return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:b,error:y,warning:y===null&&g===null&&s?il:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...i]),sawForbidden:o,sawUnauthorized:a,sawConversationInitFailure:s})})}var il="Chat is ready. Your first message will start the conversation.";function ol(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function al(e){return e.httpStatus===403||e.code==="accessDenied"}var sl=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function ul(e){return e!==sl}var cl=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var dl=10*1024*1024,fl=5,hl=120,pl="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&cl.includes(e.trim().toLowerCase())}function sanitizeFilename(e){if(!e)return"attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return"attachment";if(t.length<=hl)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,hl);let n=t.slice(r);return n.length>=hl?t.slice(0,hl):`${t.slice(0,r).slice(0,hl-n.length)}${n}`}function formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}var gl=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),bl=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function ml(e,t,r,n){/* @__PURE__ */
|
|
33
|
+
return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return bl(ml("unsupported_type",false,t));let n=attachmentSize(e);return n===null?bl(ml("unknown",false,t)):n>dl?bl(ml("too_large",false,t,{sizeBytes:n})):gl(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function yl(e){if(typeof e!="object"||e===null)return null;let t=e,r=e=>typeof e=="string"&&e.length>0?e:null,n=e=>typeof e=="number"&&Number.isFinite(e)?e:null,l=r(t.upload_id),i=r(t.upload_url),o=r(t.s3_key);if(l===null||i===null||o===null)return null;let a={},s=t.upload_fields;if(typeof s=="object"&&s!==null)for(let[e,t]of Object.entries(s))typeof t=="string"&&(a[e]=t);/* @__PURE__ */
|
|
34
|
+
return Object.freeze({upload_id:l,upload_url:i,upload_fields:/* @__PURE__ */Object.freeze(a),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??dl,s3_key:o,purpose:r(t.purpose)})}function vl(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return ml("quota_exceeded",false,t,{cause:e});case"rateLimited":return ml("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return ml("idempotency_conflict",true,t,{cause:e});case"validationFailed":return ml("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return ml("network",true,t,{cause:e});default:return r===429?ml("rate_limited",true,t,{cause:e}):r===503?ml("network",true,t,{cause:e}):r===void 0?ml("network",true,t,{cause:e}):ml("server",e.retryable,t,{httpStatus:r,cause:e})}}async function initiateAttachmentUpload(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:pl,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return bl(vl(n.error,t.filename));let l=yl(n.value);return l===null?bl(ml("server",false,t.filename)):gl(l)}async function uploadAttachmentBytes(e,t,r,n){let l=()=>n?.signal?.aborted===true;if(l())return bl(ml("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),gl(void 0)}catch{return l()?bl(ml("cancelled",true,r.filename)):bl(ml("server",true,r.filename))}}var kl=2,wl=3,Cl=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Sl=0;function xl(){return Sl+=1,`attachment-${Sl}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??kl),r=Math.max(1,e.maxAttempts??wl),n=e.backoffMs??Cl,l=Math.max(1,e.maxPerMessage??fl),i=e.timers??Kr,o=e.newId??xl,a=ul(e.transport),s=/* @__PURE__ */new Map,u=[],c=[],d=/* @__PURE__ */new Set,f=/* @__PURE__ */new Set,h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),p=false,g=()=>{h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(u.flatMap(e=>{let t=s.get(e);return t===void 0?[]:[t.state]}))});for(let e of f)e()},b=(e,t)=>{e.state=/* @__PURE__ */Object.freeze({...e.state,...t}),g()},m=()=>{for(;!p&&d.size<t&&c.length>0;){let e=c.shift(),t=s.get(e);t!==void 0&&(d.add(e),y(t).finally(()=>{d.delete(e),m()}))}},y=async t=>{let{attachment:l}=t;for(;t.attempts<r;){if(p||t.controller.signal.aborted)return;t.attempts+=1;let o=t.controller.signal;b(t,{status:"uploading",error:null,progress:0});let a=await initiateAttachmentUpload(e.funnel,l,{signal:o});if(p||o.aborted)return;let s;if(!a.ok)s=bl(a.error);else{let r=await uploadAttachmentBytes(e.transport,a.value,l,{signal:o,onProgress:e=>{!o.aborted&&t.state.status==="uploading"&&b(t,{progress:_l(e)})}});if(p||o.aborted)return;s=r.ok?gl(a.value.s3_key):bl(r.error)}if(s.ok){b(t,{status:"uploaded",s3Key:s.value,error:null,progress:1});return}let u=s.error,c=u.retryable&&t.attempts<r;if(b(t,{status:c?"uploading":"failed",error:u,progress:0}),!c)return;let d=n[Math.min(t.attempts-1,n.length-1)]??0;await Yr(d,o,i)}},v=e=>{c.push(e.state.id),m()},k={available:a,subscribe(e){return f.add(e),()=>{f.delete(e)}},getSnapshot:()=>h,get uploading(){return h.attachments.some(e=>e.status==="uploading")},get s3Keys(){return h.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[])},add(e){let t=validateAttachment(e);if(!t.ok)return t;if(p||u.length>=l)return bl(ml("too_many",false,t.value.filename));let r=o(),n={attachment:t.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:r,filename:t.value.filename,previewUri:e.uri,contentType:t.value.contentType,sizeBytes:t.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return s.set(r,n),u.push(r),g(),v(n),gl(n.state)},retry(e){let t=s.get(e);t===void 0||p||t.state.status!=="failed"||(t.controller=new AbortController,t.attempts=0,b(t,{status:"uploading",error:null,progress:0,s3Key:null}),v(t))},remove(e){let t=s.get(e);if(t===void 0)return;t.controller.abort(),s.delete(e);let r=u.indexOf(e);r>=0&&u.splice(r,1);let n=c.indexOf(e);n>=0&&c.splice(n,1),g()},clear(){for(let e of[...u])k.remove(e)},dispose(){p=true;for(let e of s.values())e.controller.abort();s.clear(),u.length=0,c.length=0,f.clear(),h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return k}function _l(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var Rl=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Rl,t)?Rl[t]:null}var Tl=50,Il=128,zl=120,Pl=120,Ol=2e3,El=120,jl=80,Fl=/* @__PURE__ */new Set(["male","female","unknown"]),Al=/* @__PURE__ */new Set(["day","month","year"]),Dl=/* @__PURE__ */new Set(["low","medium","high","athletic"]),Ml=/* @__PURE__ */new Set(["indoor","outdoor","both"]),Ll=/* @__PURE__ */new Set(["mild","moderate","severe"]),Bl=/^(\d{4})-(\d{2})-(\d{2})$/,Hl=[["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"]],Ul=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...Hl,...Ul].map(([e])=>e));function Nl(e){let t=Bl.exec(e);if(t===null)return false;let[r,n,l]=[Number(t[1]),Number(t[2]),Number(t[3])],i=new Date(Date.UTC(r,n-1,l));return i.getUTCFullYear()===r&&i.getUTCMonth()===n-1&&i.getUTCDate()===l}var $l=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,Wl=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,Vl=(e,t)=>typeof t=="string"&&Nl(t)?null:`${e} must be a real date written YYYY-MM-DD`,ql=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(V(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let l=t.trimmed?n.trim():n;if(t.required&&l.length===0)return`${r} is required and must not be blank`;let i=q(l);return i<=e?null:`${r} is ${i} characters; the server accepts at most ${e}`},Gl={sex:$l(Fl),spayedNeutered:Wl,birthDate:Vl,birthDatePrecision:$l(Al),activityLevel:$l(Dl),indoorOutdoor:$l(Ml),foodBrand:ql(El),foodType:ql(El),microchipId:ql(jl)},Kl=["ref","ref",false,ql(Il,{required:true,trimmed:true})],Yl=["notes","notes",false,ql(Ol,{trimmed:true})],Ql=[Kl,["name","name",true,ql(zl,{required:true,trimmed:true})],["dose","dose",false,ql(Pl,{trimmed:true})],["frequency","frequency",false,ql(Pl,{trimmed:true})],["startDate","start_date",false,Vl],["endDate","end_date",false,Vl],Yl],Jl={allergies:[Kl,["allergen","allergen",true,ql(zl,{required:true,trimmed:true})],["severity","severity",false,$l(Ll)],Yl],medications:Ql,supplements:Ql,conditions:[Kl,["conditionName","condition_name",true,ql(zl,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Vl],Yl]};function Xl(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return{error:`${n} must be an object`};let l=r,i={};for(let[t,r,o,a]of Jl[e]){let e=l[t];if(e==null){if(o)return{error:`${n}.${t} is required`};e===null&&(i[r]=null);continue}let s=a(`${n}.${t}`,e);if(s!==null)return{error:s};i[r]=e}let o=i.start_date,a=i.end_date;return typeof o=="string"&&typeof a=="string"&&a<o?{error:`${n}.endDate must not be before startDate`}:{item:i}}function Zl(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>Tl)return{error:`${e} has ${t.length} items; the server accepts at most ${Tl}`};let r=[],n=/* @__PURE__ */new Set;for(let l=0;l<t.length;l+=1){let i=Xl(e,l,t[l]);if("error"in i)return i;let o=i.item.ref;if(typeof o=="string"){let t=o.trim();if(n.has(t))return{error:`${e}: ref ${JSON.stringify(t)} is used twice; a ref names one item`};n.add(t)}r.push(i.item)}return{items:r}}function ei(e,t){let r=e,n={};for(let[e,t]of Hl){let l=r[e];if(l!==void 0){if(l!==null){let t=Gl[e](e,l);if(t!==null)return{error:t}}n[t]=l}}let l=r.birthDate!==void 0,i=r.birthDatePrecision!==void 0;if(l!==i||l&&r.birthDate===null!=(r.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[e,t]of Ul){let l=r[e];if(l===void 0)continue;let i=Zl(e,l);if("error"in i)return i;n[t]=i.items}return Object.keys(n).length>0&&t!==void 0&&canonicalPetSpecies(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}var ti=e=>typeof e=="string"?e:null,ri=(e,t)=>typeof t=="string"&&e.has(t)?t:null,ni=e=>typeof e=="boolean"?e:null;function li(e,t){return Array.isArray(e)?/* @__PURE__ */Object.freeze(e.flatMap(e=>{if(typeof e!="object"||e===null||Array.isArray(e))return[];let r=t(e);return r===null?[]:[r]})):/* @__PURE__ */Object.freeze([])}function ii(e){let t=ti(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:ti(e.ref),name:t,dose:ti(e.dose),frequency:ti(e.frequency),startDate:ti(e.start_date),endDate:ti(e.end_date),notes:ti(e.notes)})}function oi(e){let t=e.profile_version;/* @__PURE__ */
|
|
35
|
+
return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:ri(Fl,e.sex),spayedNeutered:ni(e.spayed_neutered),birthDate:ti(e.birth_date),birthDatePrecision:ri(Al,e.birth_date_precision),activityLevel:ri(Dl,e.activity_level),indoorOutdoor:ri(Ml,e.indoor_outdoor),foodBrand:ti(e.food_brand),foodType:ti(e.food_type),microchipId:ti(e.microchip_id),allergies:li(e.allergies,e=>{let t=ti(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:ti(e.ref),allergen:t,severity:ri(Ll,e.severity),notes:ti(e.notes)})}),medications:li(e.medications,ii),supplements:li(e.supplements,ii),conditions:li(e.conditions,e=>{let t=ti(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:ti(e.ref),conditionName:t,diagnosedDate:ti(e.diagnosed_date),notes:ti(e.notes)})})})}var ai=100,si=50,ui=100,ci=50,di=500,fi=128,hi=6e4;function pi(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function gi(e,t,r){if(typeof t!="string")return pi(`${e} must be a string`);let n=q(t);return n<=r?null:pi(`${e} is ${n} characters; the server accepts at most ${r}`)}function bi(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:pi(`${e} must be a finite number between 0 and ${r}`)}function mi(e,t){if(typeof e!="string")return pi("pet_ref must be a string");if(e.trim().length===0)return pi("pet_ref must not be blank");if(V(e))return pi("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return pi("profile must be an object");let r=[gi("pet_ref",e,fi)];return t?.name!==void 0&&r.push(gi("name",t.name,ai)),t?.species!==void 0&&r.push(gi("species",t.species,si)),t?.breed!==void 0&&r.push(gi("breed",t.breed,ui)),t?.ageYears!==void 0&&r.push(bi("age_years",t.ageYears,ci)),t?.weightKg!==void 0&&r.push(bi("weight_kg",t.weightKg,di)),r.find(e=>e!==null)??null}function yi(e,t){let r=ei(e,t);return"error"in r?{error:pi(r.error)}:r}function vi(e){if(typeof e!="object"||e===null)return{error:pi("patch must be an object")};let t=e,r=[["name","name",e=>gi("name",e,ai)],["species","species",e=>gi("species",e,si)],["breed","breed",e=>gi("breed",e,ui)],["ageYears","age_years",e=>bi("age_years",e,ci)],["weightKg","weight_kg",e=>bi("weight_kg",e,di)]],n={};for(let[e,l,i]of r){let r=t[e];if(r!==void 0){if(r!==null){let e=i(r);if(e!==null)return{error:e}}n[l]=r}}let l=yi(t,t.species);return"error"in l?l:(Object.assign(n,l.body),Object.keys(n).length===0?{error:pi("patch must change at least one field")}:{body:n})}function ki(e){if(e==null)return{body:{}};let t=yi(e,e.species);return"error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}var wi=e=>typeof e=="string"?e:null,Ci=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Si(e,t){let r=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
|
|
36
|
+
return Object.freeze({petRef:wi(r.pet_ref)??t,name:wi(r.name),species:wi(r.species),breed:wi(r.breed),ageYears:Ci(r.age_years),weightKg:Ci(r.weight_kg)})}function widgetPetFromWire(e){if(typeof e!="object"||e===null)return null;let t=e,r=wi(t.pet_ref);return r===null||r.length===0?null:/* @__PURE__ */Object.freeze({petId:wi(t.pet_id),petRef:r,name:wi(t.name),species:wi(t.species),breed:wi(t.breed),ageYears:Ci(t.age_years),weightKg:Ci(t.weight_kg),updatedAt:wi(t.updated_at)})}function xi(e){let t=widgetPetFromWire(e);return t===null?null:/* @__PURE__ */Object.freeze({...t,...oi(e)})}function _i(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];/* @__PURE__ */
|
|
37
|
+
return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return Ri(createRequestFunnel({auth:e}),createRequestFunnel({auth:e,unaryTimeoutMs:hi}))}function Ri(e,t=e){let r=(e,t)=>t?{...e,signal:t}:e,n=e=>mi(e,void 0)??`/widget/v1/pets/${encodeURIComponent(e)}`;return{async list(t){let n=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},t?.signal));return n.ok?ok(_i(n.value)):err(n.error)},async registerPet(t,r,n){let l=mi(t,r);if(l!==null)return err(l);let i=ki(r);if("error"in i)return err(i.error);let o={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(t)}`,body:i.body},a=await e.send("pets.registerPet",n?.signal?{...o,signal:n.signal}:o);return a.ok?ok(Si(a.value,t)):err(a.error)},async updatePet(t,l,i){let o=n(t);if(typeof o!="string")return err(o);let a=vi(l);if("error"in a)return err(a.error);let s=await e.send("pets.updatePet",r({method:"PATCH",path:o,body:a.body},i?.signal));return s.ok?ok(Si(s.value,t)):err(s.error)},async getPetProfile(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.getPetProfile",r({method:"GET",path:`${i}/profile`},l?.signal));if(!o.ok)return err(o.error);let a=xi(o.value);return a===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(a)},async deletePet(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.deletePet",r({method:"DELETE",path:i},l?.signal));return o.ok?ok(void 0):err(o.error)},async eraseUserData(e){let n=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},e?.signal),{maxAttempts:1});return n.ok?ok(void 0):err(n.error)}}}var Ti=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(e){return Ti[e]}function deniedDecisionsFor(e,t){let r=/* @__PURE__ */Object.freeze({reason:t,level:e,recoverable:false}),n=[],l=/* @__PURE__ */new Set;for(let e of Object.keys(Ti))for(let t of Ti[e])l.has(t)||(l.add(t),n.push(/* @__PURE__ */Object.freeze({resource:t,granted:false,disabled:r}))/* @__PURE__ */);return Object.freeze(n)}function decideCapability(e,t,r){let n=requires(e),l=/* @__PURE__ */new Map;for(let e of t)l.set(e.resource,e);if(r?.isPending===true&&n.some(e=>!l.has(e)))return Pi({name:e,enabled:false,isPending:true,limits:{}});let i=Ii(n,l);return n.filter(e=>l.get(e)?.granted!==true).length===0?Pi({name:e,enabled:true,isPending:false,limits:i}):Pi({name:e,enabled:false,isPending:false,limits:i,disabled:zi(n,l)})}function Ii(e,t){let r={};for(let n of e){let e=t.get(n)?.limits;if(e)for(let[t,n]of Object.entries(e)){let e=r[t];r[t]=e===void 0?n:Math.min(e,n)}}return r}function zi(e,t){for(let r of e){let e=t.get(r)?.disabled;if(e)/* @__PURE__ */
|
|
38
38
|
return Object.freeze({reason:e.reason,level:e.level,recoverable:e.recoverable})}/* @__PURE__ */
|
|
39
|
-
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function Ri(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function Ti(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,Ii)}catch(e){Ii(e)}}function Ii(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var zi=/* @__PURE__ */new WeakMap,Pi=/* @__PURE__ */new Map;function Oi(e,t){zi.set(e,t)}function Ei(e,t,r,n){let l=zi.get(e);if(l===void 0)return null;let i;if(t.mode==="personalized"&&typeof t.userRef=="string")i=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")i=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${l}|${i}|${r}|${Fi(n)}`}function ji(e,t){if(e===null)return t();let r=Pi.get(e);if(r!==void 0)return r;let n=t().finally(()=>{Pi.get(e)===n&&Pi.delete(e)});return Pi.set(e,n),n}function Fi(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Fi).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Fi(t)}`).join(",")}}`}var Ai=/* @__PURE__ */new WeakMap;function Di(e,t){let r=Ai.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,Ai.set(e,r)),r.add(t),()=>{r?.delete(t)}}function Mi(e){let t=Ai.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var Li=/* @__PURE__ */new Map;function Bi(e,t){return()=>{let r=Li.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let l=n.finally(()=>{Li.get(e)===l&&Li.delete(e)});return Li.set(e,l),l}}function parseColor(e){let t=Hi(e);return t===null?null:Gi(t)}function Hi(e){if(typeof e=="number")return $i(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Ui(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Ui(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ni(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=Ui(t);if(e!==null)return e}return/^\d+$/.test(t)?$i(Number.parseInt(t,10)):null}function Ui(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:Vi(t[0]),g:Vi(t[1]),b:Vi(t[2]),a:1};if(t.length===6)return{r:Wi(t,0),g:Wi(t,2),b:Wi(t,4),a:1};if(t.length===8){let e=Wi(t,0);return{r:Wi(t,2),g:Wi(t,4),b:Wi(t,6),a:e/255}}return null}function Ni(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(e=>e.trim());if(n.length<3)return null;let l=qi(Number(n[0])),i=qi(Number(n[1])),o=qi(Number(n[2]));if(l===null||i===null||o===null)return null;let a=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;a=Math.min(1,Math.max(0,e))}return{r:l,g:i,b:o,a:a}}function $i(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return{r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}function Wi(e,t){return Number.parseInt(e.slice(t,t+2),16)}function Vi(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function qi(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function Gi(e){if(e.a>=1)return Ki(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function Ki(e,t,r){return`#${Yi(e)}${Yi(t)}${Yi(r)}`.toUpperCase()}function Yi(e){return e.toString(16).padStart(2,"0")}var Qi="#111111",Ji="#FFFFFF",Xi="#000000";function readableOn(e){let t=Hi(e);if(t===null)return Ji;let r=to(t),n=to({r:17,g:17,b:17}),l=to({r:255,g:255,b:255});return no(r,l)>=no(r,n)?Ji:Qi}function Zi(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(Ji,e)>=contrastRatio(Xi,e)?Ji:Xi}function eo(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(Ji)>=t(Xi)?Ji:Xi}function to(e){let t=ro(e.r/255),r=ro(e.g/255),n=ro(e.b/255);return.2126*t+.7152*r+.0722*n}function ro(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function no(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=Hi(e),n=Hi(t);if(r===null||n===null)return 1;let l=n.a>=1?n:{...n},i=r.a>=1?r:lo(r,l);return no(to(i),to(l))}function lo(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function io(e,t){let r=Hi(e),n=Hi(t);if(r===null||n===null)return null;let l=r.a>=1?r:lo(r,{...n});return Ki(l.r,l.g,l.b)}function oo(e,t){let r=Hi(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var ao=.05;function so(e,t,r,n){let l=t[0];if(l===void 0)return r;let i=e=>t.every(t=>contrastRatio(e,t)>=n);if(Hi(e)===null)return r;if(i(e))return e;let o=io(e,l),a=o===null?null:Hi(o),s=Hi(r);if(a===null||s===null)return r;for(let e=1;e<1/ao;e+=1){let t=e*ao,r=(e,r)=>Math.round(e+(r-e)*t),n=Ki(r(a.r,s.r),r(a.g,s.g),r(a.b,s.b));if(i(n))return n}return r}function uo(e,t,r){let n=e/255,l=t/255,i=r/255,o=Math.max(n,l,i),a=Math.min(n,l,i),s=(o+a)/2;if(o===a)return{h:0,s:0,l:s};let u=o-a,c=u/(1-Math.abs(2*s-1)),d;return o===n?(d=(l-i)/u*60,d<0&&(d=d+360)):o===l?d=((i-n)/u+2)*60:d=((n-l)/u+4)*60,{h:d,s:c,l:s}}function co(e){let{h:t,s:r,l:n}=e,l=(1-Math.abs(2*n-1))*r,i=t/60,o=l*(1-Math.abs(i%2-1)),a=n-l/2,s=Math.floor(i)%6,u=[[l,o,0],[o,l,0],[0,l,o],[0,o,l],[o,0,l],[l,0,o]],[c,d,f]=u[s];return{r:fo(c+a),g:fo(d+a),b:fo(f+a)}}function fo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var ho=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),po=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),go=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return go[e]??po}var bo=4.5,mo=/* @__PURE__ */Object.freeze({});function yo(e){return ho.includes(e)}function vo(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,l]of Object.entries(e)){if(!yo(n)||l===null||typeof l!="object")continue;let e=Co(l);if(e===null)continue;let i=ko(n,e);i!==null&&(t[n]=i,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function ko(e,t){let r=go[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function wo(e,t,r){return e[t]!==void 0?e[t]:e[r]}function Co(e){let t={},r=parseColor(wo(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(wo(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let l=vo(wo(e,"border_radius","borderRadius"));l!==null&&(t.borderRadius=l);let i=parseColor(wo(e,"text_color","textColor"));return i!==null&&(t.textColor=i),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??mo:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function So(e){let t=Hi(e);return t!==null&&t.a>=1}var xo=3,_o=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function Ro(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function To(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>io(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=xo))return null;let l=[...t,...n,...r];return so(n[0],l,eo(l),xo)}function Io(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>io(e,t)??t)}function zo(e,t){let r=eo(e);return e.every(e=>contrastRatio(r,e)>=t)}function Po(e,t){let r=t[0];return r===void 0?null:io(e,r)}function Oo(e){let t=Zi(e[0],bo);return e.every(e=>contrastRatio(t,e)>=bo)?t:eo(e)}function Eo(e,t,r,n,l){return _o.has(e)?false:l?true:r!==void 0&&Ro(t,r)?false:!(n!==void 0&&r!==void 0&&So(r))}function guardSlotContrast(e,t,r){let n=false,l={};for(let i of ho){let o=e[i];if(o===void 0)continue;let a=o.backgroundColor,s=t?.[i]??[],u=Io(a,s),c={...o},d=false;if(a!==void 0&&u.length>1&&!zo(u,bo)){let e=Po(a,s);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[i],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&So(h)&&To(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(a!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<bo))&&(c.textColor=Oo(u),d=true);else if(e!==void 0){let t=so(e,u,eo(u),bo);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&Eo(i,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=so(o.borderColor,e,eo(e),xo);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=To(h,f,u);e!==null&&(c.borderColor=e,d=true)}l[i]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(l):e}var jo=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),Fo=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var Ao=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Ao(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var Do=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Mo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),Lo={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Bo={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Ho={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},Uo={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},No={regular:"400",medium:"500",bold:"700"},$o={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},Wo=0,Vo="System",qo="monospace",Go=["content","heading","control","compact","badge"];function Ko(e){let t={};for(let r of Go)t[r]=e;return t}var Yo=[];function Qo(){return{family:Vo,mono:qo,fontUrl:null,families:{regular:Vo,medium:Vo,bold:Vo,mono:qo,monoMedium:qo,monoBold:qo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Ho,tierSizes:Ko(Ho),lineHeight:Uo,weight:No,letterSpacing:$o,scale:1,maxScale:Wo,scaleCaps:Do,headingFamily:null,headingWeight:null,fontSources:Yo,roles:Fo,typeScale:1}}var Jo={},Xo=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(e){return`cubic-bezier(${e.join(", ")})`}var Zo={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(Xo.standard),emphasized:cssCubicBezier(Xo.emphasized),exit:cssCubicBezier(Xo.exit)},reducedMotion:false},ea={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},ta=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:ea,space:Lo,radius:Bo,type:Qo(),motion:Zo,slots:Jo}),ra={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},na=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:ra,space:Lo,radius:Bo,type:Qo(),motion:Zo,slots:Jo});function la(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function ia(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function oa(e){return ia(e).every(t=>contrastRatio(e.brand,t)>=xo)}function aa(e){return[e.chatGround,e.surface,e.surfaceCream]}function sa(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...ua(e,t)]}function ua(e,t){return[io(t,e.surface)??e.surface,io(t,e.surfaceCream)??e.surfaceCream]}function ca(e){return[e.composerFill,e.chatGround]}var da=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function fa(e,t){let r=new Set(la(t));return la(e).every(e=>r.has(e))}function ha(e){let t=e.color,r=(e.brightness==="dark"?na:ta).color,n=(e.brightness==="dark"?ta:na).color,l=la(t),i=eo(l)!==eo(la(r)),o=fa(t,r),a=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,s=(e,t,r,n,l,s)=>{let u=t===r&&(e!=="errorRed"||a);return u&&o&&da.has(e)?t:so(u&&i?n:t,l,eo(l),s)},u=(e,l,i)=>s(`text.${e}`,t.text[e],r.text[e],n.text[e],l,i),c=(e,t,l,i)=>s(e,t,r[e],n[e],l,i),d=e=>i&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=Zi(f,bo),p=c("danger",t.danger,[...l,...ua(t,t.badgeBgCritical)],bo),g={...t,onPrimary:h,onAccent:Zi(t.accent,bo),onDanger:contrastRatio(h,p)>=bo?h:Zi(p,bo),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,l,bo),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,aa(t),bo),text:{...t.text,primary:u("primary",l,bo),secondary:u("secondary",l,bo),muted:u("muted",l,bo),metaCool:u("metaCool",l,bo),timestamp:u("timestamp",l,bo),placeholder:u("placeholder",ia(t),xo)},danger:p,errorRed:c("errorRed",t.errorRed,sa(t,t.badgeBgCritical),bo),warningStrong:c("warningStrong",t.warningStrong,sa(t,t.badgeBgCaution),bo),composerBorder:c("composerBorder",t.composerBorder,ca(t),xo),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,ia(t),xo)},b={...g,...wa(g,r,o)};return{...b,...pa(t,b,r)}}function pa(e,t,r){let n={},l=(e,t,r)=>so(e,t,eo(t),r);if((!ya(e.success,r.success)||!ya(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=l(e.success,sa(t,e.badgeBgPositive),bo)),(!ya(e.cautionAccent,r.cautionAccent)||!ya(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=l(e.cautionAccent,sa(t,e.badgeBgCaution),bo)),ga(e,r)){n.info=l(e.info,sa(t,e.badgeBgInfo),bo);let r=[t.surface,t.chatGround,...ua(t,e.badgeBgInfo)];n.infoEdge=l(e.infoEdge,r,xo)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function ga(e,t){return!ya(e.info,t.info)||!ya(e.badgeBgInfo,t.badgeBgInfo)}var ba=.24,ma=.3;function ya(e,t){return parseColor(e)===parseColor(t)}function va(e,t){return ya(e.accent,t.accent)?ya(e.brand,t.brand)?null:e.brand:e.accent}function ka(e,t,r){let n=oo(e,r);return(n===null?null:io(n,t))??t}function wa(e,t,r){let n=va(e,t),l=ia(e),i=eo(l),o=eo([e.surface])===Ji,a=n===null&&r,s;a?s=t.highlight:n===null?s=o?ka(ta.color.highlight,e.surface,ma):ta.color.highlight:s=ka(n,e.surface,o?ma:ba);let u=a?t.onHighlight:so(e.text.primary,[s],eo([s]),bo),c=n===null?t.mark:so(n,l,i,xo),d=oa(e)?e.brand:i,f=(e,t,n)=>r&&ya(e,t)?n:so(e,l,d,xo),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=xo)?e.primary:so(e.primary,h,eo(h),xo);return{highlight:s,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var Ca=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Sa(e,t){let r=(e.brightness==="dark"?na:ta).color,n=e.color,l=t.color,i=[],o=(e,t,r,n)=>{i.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},a=(e,t)=>!Ca(e,t);a(n.text.primary,r.text.primary)&&!Ca(l.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,l.text.primary),a(n.brand,r.brand)&&(Ca(l.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,l.brandInk),Ca(l.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,l.primaryEdge),!Ca(l.controlEdge,n.brandBorder)&&!oa({...l,brand:n.brand})&&o("primary_color","control outline",n.brand,l.controlEdge)),a(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!Ca(l.linkInk,n.accent)&&o("accent_color","link text",n.accent,l.linkInk),a(n.danger,r.danger)&&!Ca(l.danger,n.danger)&&o("danger_color","error text",n.danger,l.danger),a(n.success,r.success)&&!Ca(l.success,n.success)&&o("success_color","positive status",n.success,l.success),a(n.warningStrong,r.warningStrong)&&!Ca(l.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,l.warningStrong),a(n.cautionAccent,r.cautionAccent)&&!Ca(l.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,l.cautionAccent),(a(n.info,r.info)||a(n.badgeBgInfo,r.badgeBgInfo))&&(Ca(l.info,n.info)||o("info_color","information text",n.info,l.info),Ca(l.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,l.infoEdge));for(let r of ho){let n=e.slots[r],l=t.slots[r];n===void 0||l===void 0||n===l||(l.backgroundColor!==void 0&&!Ca(l.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,l.backgroundColor),n.textColor!==void 0&&l.textColor!==void 0&&!Ca(l.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,l.textColor),l.borderColor!==void 0&&!Ca(l.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,l.borderColor))}/* @__PURE__ */
|
|
40
|
-
return Object.freeze(i)}var xa=/* @__PURE__ */new Set;function _a(e){if(e.length===0)return;let t=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(xa.has(t))return;xa.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var Ra="#23272C",Ta=4.5,Ia=.6,za=.9,Pa=.02,Oa="#FFFFFF",Ea="#111111";function ja(e){return contrastRatio(e,Ra)>=Ta&&Math.max(contrastRatio(e,Oa),contrastRatio(e,Ea))>=Ta}function deriveDarkVariant(e){let t=Hi(e);if(t===null)return null;let{h:r,s:n,l:l}=uo(t.r,t.g,t.b),i=Math.min(Math.max(l,Ia),za);for(let e=0;;e+=1){let t=i+e*Pa;if(t>za)break;let l=co({h:r,s:n,l:t}),o=Ki(l.r,l.g,l.b);if(ja(o))return o}let o=co({h:r,s:n,l:za});return Ki(o.r,o.g,o.b)}var Fa=7,Aa=.05,Da="#000000",Ma="#FFFFFF";function La(e,t,r,n){let l=io(e,t);if(l===null)return r;if(contrastRatio(l,t)>=n)return l;let i=Hi(l),o=Hi(r);if(i===null||o===null)return r;for(let e=1;e<1/Aa;e+=1){let r=e*Aa,l=(e,t)=>Math.round(e+(t-e)*r),a=Ki(l(i.r,o.r),l(i.g,o.g),l(i.b,o.b));if(contrastRatio(a,t)>=n)return a}return r}function Ba(e,t){let r=la(e),n=r[0],l=Ha(n);for(let e of r){let r=Ha(e);(t?r>l:r<l)&&(n=e,l=r)}return n}function Ha(e){let t=Hi(e);return t===null?0:to(t)}function Ua(e,t){return io(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=eo(la(t))===Ma,n=r?Ma:Da,l=Ba(t,r),i=e=>La(e,l,n,Fa),o={...t,brandSoft:Ua(t.brandSoft,t.surface),brandSofter:Ua(t.brandSofter,t.surface),brandBorder:i(t.brandBorder),borderHairlineGreen:i(t.borderHairlineGreen),brandBorderStrong:i(t.brandBorderStrong),controlEdge:i(t.controlEdge),structureEdge:i(t.structureEdge),brandInk:i(t.brandInk),linkInk:i(t.linkInk),borderRingCream:i(t.borderRingCream),composerBorder:i(t.composerBorder),text:{primary:i(t.text.primary),secondary:i(t.text.secondary),muted:i(t.text.muted),placeholder:i(t.text.placeholder),onBrand:t.text.onBrand,metaCool:i(t.text.metaCool),timestamp:i(t.text.timestamp)},badgeBgPositive:Ua(t.badgeBgPositive,t.surface),badgeBgCaution:Ua(t.badgeBgCaution,t.surface),badgeBgCritical:Ua(t.badgeBgCritical,t.surface),badgeBgNeutral:Ua(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Ua(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Ua(t.checkupCardConcernBg,t.surface),info:i(t.info),infoEdge:i(t.infoEdge),badgeBgInfo:Ua(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var Na=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),$a=Na.cream,Wa=Na.subtle,Va=Na.ring,qa=10;function Ga(e,t,r){let n=Hi(e),l=Hi(t);if(n===null||l===null)return null;let i=(e,t)=>Math.round(e+(t-e)*r);return Ki(i(n.r,l.r),i(n.g,l.g),i(n.b,l.b))}function Ka(e){if(e===null)return{};let t=eo([e]),r=Ga(e,t,$a),n=Ga(e,t,Wa),l=Ga(e,t,Va);return r===null||n===null||l===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:l}}function Ya(e){if(e===null)return{};let t=Hi(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function Qa(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let l={};for(let[e,t]of Object.entries(r.type.size))l[e]=Math.max(qa,Math.round(t*n*10)/10);return l}function Ja(e,t,r){if(e===null)return t;let n=e/r.space.xs,l=e=>Math.round(e*n),i=r.space;return{xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),xxl:l(i.xxl)}}function Xa(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),l=t.radius;return{tile:n(l.tile),xs:n(l.xs),sm:n(l.sm),md:n(l.md),lg:n(l.lg),xl:n(l.xl),pill:l.pill}}var Za=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function es(e,t){let r=Hi(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function ts(e,t){if(e===null)return{};let r=es(e,t?Za.success.dark:Za.success.light),n=es(e,t?Za.successCard.dark:Za.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function rs(e,t){if(e===null)return{};let r=es(e,t?Za.warning.dark:Za.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function ns(e,t){if(e===null)return{};let r=es(e,t?Za.info.dark:Za.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function ls(e,t,r){if(e===null)return t;let n=r.type.lineHeight,l=e/n.normal;if(l===1)return n;let i=e=>Math.round(e*l*100)/100;return{tight:i(n.tight),snug:i(n.snug),normal:i(n.normal),relaxed:i(n.relaxed)}}function is(e){return{composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:aa(e),header:[e.surface,e.background,e.chatGround],banner:[io(e.badgeBgInfo,e.surface)??e.surface,io(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function os(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function as(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ss=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),us=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),cs=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function ds(e){return typeof e=="string"&&ss.includes(e.trim().toLowerCase())}function fs(e,t){let r=e[t];return r??void 0}var hs=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>hs)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var ps=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],gs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],bs=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],ms=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],ys=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!as(e))return null;let t=ds(e.theme)?us[e.theme.trim().toLowerCase()]:{},r=as(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let l={},i=fs(n,"colorScheme"),o=typeof i=="string"?i.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(l.color_scheme=o);let a=o==="dark"?"_dark":"";for(let[e,t]of ps){let r=fs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of gs){let r=fs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of ms){let r=fs(n,e);typeof r=="string"&&r.trim().length>0&&(l[t]=r.trim())}for(let[e,t]of ys){let r=parsePx(fs(n,e));r!==void 0&&(l[t]=r)}for(let[e,t]of bs){let r=fs(n,e);(typeof r=="number"||typeof r=="string")&&(l[t]=r)}let s=e.fonts;Array.isArray(s)&&s.length>0&&(l.font_sources=s);let u=e.rules;if(as(u)){let e={};for(let t of ho){let r=u[t];as(r)&&(e[t]=r)}Object.keys(e).length>0&&(l.slots=e)}return Object.keys(l).length===0?null:/* @__PURE__ */Object.freeze(l)}var vs="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function ks(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var ws=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?ks(__EVERFUR_BRAND_CDN_ORIGIN__):vs;var Cs=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),Ss=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),xs=Object.keys(Ss),_s="presentation",Rs="presentation.";function isPresentationLockName(e){if(e===_s)return true;if(!e.startsWith(Rs))return false;let t=e.slice(Rs.length);return Object.values(Ss).includes(t)}var Ts={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},Is=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function zs(e,t){if(t==null)return;let r=Ts[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:Is.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of xs){let n=Ss[e],l=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],i=zs(e,l);i!==void 0&&(r[e]=i)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${Rs}${Ss[e]}`;for(let e of t)if(e===_s||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,l=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},i=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,a={};for(let e of xs){let t=l[e],r=isPresentationFieldLocked(e,o)?void 0:i[e];a[e]=r??t??Cs[e]}/* @__PURE__ */
|
|
41
|
-
return Object.freeze(a)}var
|
|
42
|
-
return Object.freeze(o)}function
|
|
43
|
-
return new Set(["hide_powered_by",...e?.lockedFields??[]])}function uu(e){return e==="hide_powered_by"||ou.includes(e)||isPresentationLockName(e)?true:e.startsWith(au)&&ho.includes(e.slice(au.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=du(t),n=expandAppearance(pu(t,"appearance")),l=n===null?r:cu(du(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function cu(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function du(e){return{displayName:gu(pu(e,"display_name","displayName")),logoUrl:gu(pu(e,"logo_url","logoUrl")),primaryColor:parseColor(pu(e,"primary_color","primaryColor")),accentColor:parseColor(pu(e,"accent_color","accentColor")),brightness:wu(pu(e,"brightness","color_scheme","colorScheme")),fontFamily:gu(pu(e,"font_family","fontFamily")),fontUrl:gu(pu(e,"font_url","fontUrl")),fonts:mu(pu(e,"fonts")),fontUrls:mu(pu(e,"font_urls","fontUrls")),placeholder:gu(pu(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:hu(pu(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pu(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pu(e,"accent_color_dark","accentColorDark")),surfaceStyle:ku(pu(e,"surface_style","surfaceStyle"),yu),radiusScale:ku(pu(e,"radius_scale","radiusScale"),vu),logoUrlDark:gu(pu(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pu(e,"slots")),accessibilityMaxFontScale:_u(pu(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Iu(pu(e,"locked_fields","lockedFields")),presentation:parsePresentation(pu(e,"presentation")),schemaVersion:Ru(pu(e,"schema_version","schemaVersion")),backgroundColor:parseColor(pu(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(pu(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(pu(e,"text_color","textColor")),textColorDark:parseColor(pu(e,"text_color_dark","textColorDark")),dangerColor:parseColor(pu(e,"danger_color","dangerColor")),dangerColorDark:parseColor(pu(e,"danger_color_dark","dangerColorDark")),fontSizeBase:fu(pu(e,"font_size_base","fontSizeBase"),cs.fontSizeBase),borderRadius:fu(pu(e,"border_radius","borderRadius"),cs.borderRadius),spacingUnit:fu(pu(e,"spacing_unit","spacingUnit"),cs.spacingUnit),successColor:parseColor(pu(e,"success_color","successColor")),successColorDark:parseColor(pu(e,"success_color_dark","successColorDark")),warningColor:parseColor(pu(e,"warning_color","warningColor")),warningColorDark:parseColor(pu(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(pu(e,"info_color","infoColor")),infoColorDark:parseColor(pu(e,"info_color_dark","infoColorDark")),headingFontFamily:gu(pu(e,"heading_font_family","headingFontFamily")),fontWeightBody:Ds(pu(e,"font_weight_body","fontWeightBody")),fontWeightHeading:Ds(pu(e,"font_weight_heading","fontWeightHeading")),lineHeight:Ms(pu(e,"line_height","lineHeight")),fontSources:Ns(pu(e,"font_sources","fontSources")),assistantAvatarUrl:gu(pu(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:Xs(pu(e,"text_scale_caps","textScaleCaps")),typeScale:Js(pu(e,"type_scale","typeScale")),typeRoles:eu(pu(e,"type_roles","typeRoles"))}}function fu(e,t){let r=Cu(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function hu(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}function pu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function gu(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var bu=["regular","medium","bold","mono","monoMedium","monoBold"];function mu(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of bu){let n=gu(pu(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var yu=["white","cream","subtle"],vu=["sharp","default","round"];function ku(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function wu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Cu(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}var Su=1,xu=3.1;function _u(e){let t=Cu(e);return t===null?null:t<=0?0:Math.min(xu,Math.max(Su,t))}function Ru(e){if(e==null)return null;let t=Cu(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Tu(e){let t=e.trim();return t.startsWith(au)?t:t.startsWith(Rs)?Rs+t.slice(Rs.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Iu(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=Tu(r);uu(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var zu=/* @__PURE__ */new RegExp(`^${ws}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&zu.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?na:ta:e,n=r.brightness==="dark"?na:ta,l=r.brightness==="dark",i=l?t.primaryColorDark??Fu(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??Fu(t.accentColor):t.accentColor,a=i??r.color.primary,s=o??r.color.accent,u=i!==null&&Mu(t,a,n,l),c=u?n.color.primary:a,d=i!==null&&!u?Hi(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?Lu(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=Ka(p),b={...r.color,...g},m=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??Fu(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...Ya(y(t.dangerColor,t.dangerColorDark)),...ts(y(t.successColor,t.successColorDark),l),...rs(y(t.warningColor,t.warningColorDark),l),...ns(y(t.infoColor,t.infoColorDark),l),...m!==null?{text:{...h.text??r.color.text,primary:m}}:{},...Au(t.surfaceStyle??null,b),primary:c,accent:s,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:Ja(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Xa(t.borderRadius,n):Hu(t.radiusScale??null,r.radius,n),type:{...r.type,...ju(r.type,t),size:Qa(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:ls(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:nu(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var Pu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Ou=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Eu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function ju(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of bu){let a=Pu[e].map(e=>r[e]).find(e=>e!==void 0),s=Eu(e)?null:t.fontFamily;a!==void 0?(l[e]=a,i[e]=true):s!==null&&(l[e]=s,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:a!==void 0&&delete o[e]}for(let e of Ou)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function Fu(e){return e===null?null:deriveDarkVariant(e)}function Au(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function Du(e,t){return e==null?false:parseColor(e)===parseColor(t)}function Mu(e,t,r,n){return Du(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Du(e.primaryColor,ta.color.primary)}function Lu(e,t){let r=e.color;return{text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}var Bu={sharp:.5,default:1,round:1.5};function Hu(e,t,r){if(e===null)return t;let n=Bu[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var Uu="Everfur",Nu=.5;function resolveTheme(e){return lc($u(e),e)}function themeAdjustments(e){let t=$u(e);return Sa(t,lc(t,{...e,highContrast:false}))}function $u(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=Gu(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=Yu((i==="auto"?l:i)==="dark"?na:ta,e?.typeProfile),a=withServerBranding(o,Ku(r));return withServerBranding(a,Ku(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Wu(e){return e==="placeholder"?"chat_placeholder":Tu(e)}var Vu={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 qu(e,t){return t.has(Wu(e))?true:(Vu[e]??[]).some(e=>t.has(e))}function Gu(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(qu(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of ho){let n=l[r];n!==void 0&&(t.has(`${au}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function Ku(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function Yu(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:Mo}})}function Qu(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function Ju(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Nu,e)}var Xu=["content","heading","control","compact","badge"];function Zu(e,t){let r={};for(let n of Xu){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:Do[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return Xu.every(e=>r[e]===Do[e])?Do:r}function ec(e,t){return t>0?Math.min(e,t):e}function tc(e,t,r,n){let l={};for(let i of Xu)l[i]=n?Qu(e,ec(t,r[i])):e;return l}function rc(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function nc(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return{family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces,headingFamily:e.headingFamily};let l=e.headingFamily!==null&&r!==void 0&&rc(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of bu)!(i[e]===Vo||i[e]===qo)&&r!==void 0&&rc(r,i[e])===false&&(i[e]=Eu(e)?qo:Vo,o[e]=false),n!==null&&Eu(e)&&i[e]===qo&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function lc(e,t){let r=e.meta.displayName.trim().length===0?Uu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of bu){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.regular??null,o=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,a=Number.isFinite(e.type.maxScale)?e.type.maxScale:Wo,s=Ju(t?.textScale),u=Zu(e.type.scaleCaps,a),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=lu(e.type.roles,()=>d),h=c?lu(f,e=>ec(s,u[e.tier])):f,p=t?.typeProfile==="phone"?iu(e.type.size,f,d):Qu(e.type.size,d),g=tc(p,s,u,c),b=ha(e),m={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:b,space:e.space,radius:e.radius,type:{...e.type,...nc(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:s,maxScale:a,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,is(b),os(b))};return t?.highContrast===true?deriveHighContrast(deepFreeze(m)):deepFreeze(m)}var ic="/widget/v1/entitlements",oc=304,ac=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",uc(t));return n.ok?cc(n.value):n.error.httpStatus===oc?ac:{kind:"failed",error:n.error}}var sc=64;function uc(e){let t={};return bc(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=sc?{method:"GET",path:ic,headers:t,query:{region:e.region}}:{method:"GET",path:ic,headers:t}}function cc(e){if(e===null||typeof e!="object"||!bc(e.revision))return gc();let t=typeof e.region=="string"?e.region:"",r=bc(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
|
|
44
|
-
return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:
|
|
45
|
-
return Object.freeze(t)}function
|
|
46
|
-
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function
|
|
47
|
-
return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(
|
|
48
|
-
return Object.freeze({request(){return Promise.resolve(err(Nc(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){r.aborted||(yield n)}}}})}var Kc=/* @__PURE__ */new WeakSet;function Yc(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return Kc.add(t),t}var Qc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new Xc(e,t)}var Jc=6e4,Xc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;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 r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new K("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=r.telemetry?Wc(r.telemetry):He,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=Gc(l);else if(r.transport!==void 0)o=r.transport;else{let e=$c(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=Gc(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Oi(this,this.mintScope),this.transport=o,l!==null&&(qc(l,this.telemetry,t?.platform),this.emit({type:"error",code:Nc(l).code,requestId:null})),this.errorPolicy=r.errorPolicy,this.camera=r.camera??Ne,this.upload=r.upload??$r,this.uploadTransport=r.uploadTransport??ll,this.imageCache=r.imageCache??Qc,this.kv=r.storage??Yc(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Oc():Oc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",Zc(e),()=>this.buildChatController(e),ed),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${Zc(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=kc({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:wc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Bc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?Uc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=Bi(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-Jc,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Ti(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&Dc(l)===Dc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){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:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await zc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return Tc({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>Ic({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>ji(Ei(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(td(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&Mi(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?td("prepare"):r===null?null:Nc(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(Je(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}return s==="ready"?this.emit({type:"ready"}):s==="failed"&&!i.ok&&r===null&&!this.disposed&&this.emit({type:"error",code:i.error.code,requestId:i.error.requestId??null}),/* @__PURE__ */Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",Zc(t),()=>this.buildChatController(t),ed,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function Zc(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function ed(e){e.dispose()}function td(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function rd(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function nd(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function ld(e){return e.ok?e:err(nd(e.error))}function id(e){return{send:async(...t)=>ld(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var od=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),ad=globalThis,sd=ad[od]??(ad[od]=createContext(null));sd.displayName??="EverfurContext";function ud(){let e=o(sd);if(e===null)throw new K("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return ud().handle}var cd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),dd=globalThis,fd=dd[cd]??(dd[cd]=createContext(ta));fd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(fd)}var hd=()=>()=>{},pd=()=>null;function gd(e,t){return i(t?.subscribe??hd,t?.get??pd,t?.get??pd)??e}function EverfurThemeProviderCore(e){let{runtime:t}=ud(),l=t.entitlements,o=i(l.subscribe,l.getSnapshot,l.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),c=e.seams.useTextScale(),d=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,h=e.seams.typeProfile,p=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,b=e.clientTheme?bd(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=gd(o.branding??null,t.sdkConfigHost?.branding),v=a(()=>resolveTheme({branding:y,clientOverride:m,colorScheme:s,reducedMotion:u,textScale:c,scaleTypeSizes:f,highContrast:d,...h===void 0?{}:{typeProfile:h},...p===void 0?{}:{platformMonoFamily:p},...g===void 0?{}:{isFontRegistered:g}}),[y,m,s,u,c,f,h,d,p,g]);e.seams.useResolvedTheme?.(v);let k=e.seams.isDevelopment;return n(()=>{k===void 0||!md(k)||_a(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(fd.Provider,{value:v},e.children)}function bd(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function md(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:l,activePet:i,theme:o,warmUp:s,children:f,seams:h}=e,p=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=u(null),b=u(null),m=u(t?.onEvent);m.current=t?.onEvent;let y=u(e=>{m.current?.(e)}),[v,k]=c(e=>e+1,0),w=u(null),C=u(void 0),S=l?.userRef??null;C.current!==S&&(C.current!==void 0&&(w.current=null),C.current=S);let x=w.current!==null?w.current.user:l??null,_=u(null),R=u(void 0),T=i??null;R.current!==T&&(R.current!==void 0&&(_.current=null),R.current=T);let I=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==p||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(b.current=g.current.runtime),g.current={key:p,runtime:createEverfurRuntime({config:yd(h.withDefaults?h.withDefaults(t):t,y.current),user:x,activePet:I,theme:o??null},{platform:h.platform,...h.eventSourceFactory?{eventSourceFactory:h.eventSourceFactory}:{}})});let z=g.current.runtime,P=u(null);n(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||P.current!==e&&(P.current=e,k())}),n(()=>{let e=b.current;e!==null&&(b.current=null,e.dispose())});let O=x?.userRef??null;d(()=>{z.setUser(x)},[z,O]),d(()=>{z.setActivePet(I)},[z,I]);let E=u(null);n(()=>(E.current===z&&(E.current=null),()=>{E.current=z,vd(()=>{E.current===z&&(E.current=null,z.dispose())})}),[z]),n(()=>{s==="onMount"&&z.prepare(I===null?{}:{petRef:I})},[z,s,O,I]);let j=a(()=>({setUser:e=>{w.current={user:e},z.setUser(e),k()},setActivePet:e=>{_.current={pet:e},z.setActivePet(e),k()},open:e=>z.open(e),prepare:e=>z.prepare(e),registerPet:(e,t)=>z.registerPet(e,t),updatePet:(e,t)=>z.updatePet(e,t),deletePet:e=>z.deletePet(e),eraseUserData:()=>z.eraseUserData(),logout:()=>{w.current={user:null};let e=z.logout();return k(),e}}),[z,k]),F=a(()=>({runtime:z,handle:j,userRef:O,activePet:I,scopeEpoch:z.scopeEpoch,publishableKey:kd(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:f});return r(sd.Provider,{value:F},h.wrap?h.wrap(A):A)}function yd(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function vd(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function kd(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var wd=2;function Cd(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<wd)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function Sd(){let e=B;return(t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:e=>Cd(n,e)})}}function xd(){let e=y();return e==="dark"?"dark":e==="light"?"light":null}function _d(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Rd(){let[e,t]=l(false);return n(()=>{let e=true,r=m?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(m);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=m?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Td(){let e=k?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(k);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function Id(e){let t=v?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(v,"change",e);return()=>r?.remove?.()}function zd(){return i(Id,Td,Td)}function Pd(){try{let e=p?.OS;return typeof e=="string"?e:null}catch{return null}}function Od(){return Pd()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function Ed(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=Od(),l=m?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(m);_d(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=m?.addEventListener,o=typeof i=="function"?i.call(m,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function jd(){return Pd()==="ios"?"Menlo":qo}function Fd(){return globalThis.__DEV__!==false}var Ad=/* @__PURE__ */new Set;function Dd(e){if(!Fd()||Ad.has(e))return;Ad.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", 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 Md(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t)}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let l=n.includes(e);return l||Dd(e),l}var Ld=/* @__PURE__ */new Set;function Bd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var Hd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Ud(e){if(!Fd())return;let t=Bd(e).filter(e=>!Ld.has(e));if(t.length===0)return;for(let e of t)Ld.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Hd[e]).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 Nd(e){n(()=>{try{Ud(e)}catch{}},[e])}var $d=/* @__PURE__ */Object.freeze({useColorScheme:xd,useReducedMotion:Rd,useTextScale:zd,useHighContrast:Ed,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:jd,isFontRegistered:Md,useResolvedTheme:Nd,isDevelopment:Fd});function Wd(e){return r(M,null,e)}var Vd=/* @__PURE__ */Object.freeze({platform:"react-native",...p.OS==="web"?{}:{eventSourceFactory:Sd()},wrap:Wd,theme:$d});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:Vd})}function useCapability(e){let{runtime:t}=ud(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function qd(e){let{runtime:t}=ud(),r=t.entitlements,n=s(e=>r===void 0?()=>{}:r.subscribe(e),[r]),l=s(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return i(n,l,l)}var Gd=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Gd[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[Gd[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function Kd(e){return e<=450?"regular":e<=650?"medium":"bold"}var Yd={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=Qd.get(e);r===void 0&&(r=/* @__PURE__ */new Map,Qd.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=Jd(e,t);return r.set(t,l),l}var Qd=/* @__PURE__ */new WeakMap;function Jd(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=Kd(Number(n)),i=r.face==="mono"?face(e,Yd[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,a=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},s=r.size,u={...a,fontSize:s,lineHeight:Math.round(s*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(s*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function Xd(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:t,...n}){let l=useEverfurTheme(),i=t===void 0?void 0:l.type.roles[t],o=Xd(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(S,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var Zd=t(function(e,t){return r(g,{...e,...t===null?{}:{ref:t}})});var ef=class extends f{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:t,resetKey:n}){return r(ef,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var tf=48;function rf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:l,style:i}=e,o=useCapability(t),s=a(()=>rf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */H(HostRender,{render:l,fallback:/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */H(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */H(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */H(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>nf(r),[r]);/* @__PURE__ */
|
|
49
|
-
return H(w,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */H(w,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>nf(r),[r]),l=e.disabled?.reason??"";/* @__PURE__ */
|
|
50
|
-
return H(w,{style:[n.offstate,t],accessible:true,
|
|
51
|
-
return H(
|
|
52
|
-
return
|
|
53
|
-
return Object.freeze(
|
|
54
|
-
return Object.freeze(
|
|
55
|
-
return Object.freeze(n)}
|
|
56
|
-
return Object.freeze(a)}function Lh(e){return e.sender?.displayName??wf.senderVet}function Bh(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var Hh=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 Uh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Nh(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===Eh&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>Hh.test(e)||Uh(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var $h="pet_not_registered";function Wh(e){return e!=null&&e.reasonCode===$h}var Vh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function qh(e,t,r){let{runtime:i,userRef:o,scopeEpoch:c}=ud(),d=s((e,t)=>{let r=i.registry.services.authFor(o);return ji(Ei(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,c]),f=a(()=>t===void 0?null:Fi(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=u(0),b=u(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${c}|${e}|${f}`,y=s(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=s(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?Vh:h.key!==m?{status:"registering",error:null,registered:null,retry:v}:{status:h.status,error:h.error,registered:h.registered,retry:v},[m,h,v])}var Gh=/* @__PURE__ */Object.freeze({});function Kh(e){let[t,r]=l(Gh),i=u(null),o=u([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===Gh?e:Gh);return}let t=i.current;if(t===null)return;let n=e.find(e=>e.role==="user"&&!t.known.has(e.id));n!==void 0&&(i.current=null,r(e=>({...e,[n.id]:t.images})))},[e]);let c=s(e=>{i.current=e.length===0?null:{images:e,known:new Set(o.current)}},[]);return a(()=>({byMessage:t,stage:c}),[t,c])}var Yh=/* @__PURE__ */new WeakSet;function Qh(){let e=makeEverfurError("internalError",{retryable:true});return Yh.add(e),err(e)}function Jh(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&Yh.has(t)}var Xh=500;function Zh(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,Xh):null}function ep(e,t,r,l){let i=Zh(r),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=u(e);a.current=e;let s=u(null),c=u(null),d=u(o);d.current=o,n(()=>{if(i===null||o===null||t||s.current===o||c.current===o)return;let e=a.current;if(e===void 0)return;c.current=o;let r=e=>{c.current===o&&(c.current=null),!Jh(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var tp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),rp=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),np=3e5;function lp(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function ip(e,t,r){let l=u(t);l.current=t;let i=u(null),o=u(null),a=u(false),s=u(0),c=u(0),d=u(3e4),f=()=>e?.isOffline===void 0?false:fh(()=>e.isOffline?.()===!0)===true,h=f(),p=u(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:u}=l.current,h=Nr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:u===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,lp(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,np),c.current=Date.now()+s.current):(s.current=0,c.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},n(()=>{if(t.isTurnInFlight||h)return;let e=o.current;e!==null&&p.current(e)},[t.isTurnInFlight,h]),n(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=fh(()=>e(()=>{p.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)fh(e)}},[e]);let g=r?.intervalMs??null,b=r?.isVisibleFallback;n(()=>{if(e===void 0||g===null||!Number.isFinite(g)||g<=0)return;d.current=g;let t=setInterval(()=>{if(Date.now()<c.current)return;let t=e.isVisible===void 0?b:e.isVisible.bind(e);(t===void 0||fh(()=>t()!==!1)===true)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var op=/^efch_[A-Za-z0-9_-]{43}$/,ap="efch";function sp(e){return typeof e=="string"&&op.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${ap}=`))continue;let e=r.slice(ap.length+1);return sp(e)?e:null}return null}var up=128,cp=/[\u0000-\u001f\u007f]/;function dp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function fp(e){return typeof e!="string"||e.length===0||e.length>up||cp.test(e)||e.includes("://")?null:e}function hp(e){if(e===null)return null;let t=e.conversation_id,r=fp(e.pet_ref);return typeof t!="string"||!Tn(t)||r===null?null:{conversationId:t,petRef:r}}function pp(e,t,r){return sp(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(hp(dp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(en("internalError",false))):Promise.resolve(ok(null))}function gp(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=sp(e)?e:null,a=o===null||i===null?null:`${String(i)}|${o}`,[s,u]=l(null);return n(()=>{if(a===null||o===null||i===null||r===null)return;let e=true,t=r.registry.services;return pp(t.authFor(i),o,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||u({key:a,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[a,r,o,i]),s!==null&&s.key===a?s.target:void 0}function bp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function mp(e,t,r){let l=bp(t),i=t?.kind==="chat",o=t?.petRef??null,a=i&&!r.pinned&&o!==null&&r.petRef!==null&&o!==r.petRef,s=u({openCheckin:e,target:t,selectPet:r.selectPet});s.current={openCheckin:e,target:t,selectPet:r.selectPet};let c=u(null),d=u(null),f=r.petRef;n(()=>{if(l===null||c.current===l)return;let{openCheckin:e,target:t,selectPet:n}=s.current;if(a&&o!==null){if(d.current?.key!==l){d.current={key:l,from:f},n(o);return}f!==d.current.from&&(c.current=l);return}i&&!r.ready||(c.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,f,r.ready])}var yp=/* @__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 vp(e){let t=e?.replace(/\s+/g," ").trim();return t||yp.untitled}function kp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function wp(e){let t=kp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?yp.newReply.replace("{date}",t):t}function Cp(e,t){return t?`${yp.countLabel}${yp.countSeparator}${e}`:yp.countLabel}function Sp(e){return`${e.unreadCount!==null&&e.unreadCount>0?yp.unreadPrefix:""}${yp.openConversation} ${vp(e.title)}`}function xp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function _p(e,t){let r=xp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=xp(vp(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function Rp(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function Tp(e){let[t,r]=l(false),[i,o]=l(""),c=e.listConversations,d=u(0),[f,h]=l(()=>Rp(c)),p=f.scope===c?f:Rp(c);n(()=>(d.current+=1,r(false),o(""),h(Rp(c)),()=>{d.current+=1}),[c]);let g=s(async t=>{let r=++d.current,n=t!==void 0;h(e=>({...e,scope:c,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===d.current){if(!l.ok){h(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}h(e=>{let r=t&&e.scope===c?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:c,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,c]),b=()=>{r(true),o(""),g()},m=()=>{d.current+=1,r(false)},y=async t=>{let n=++d.current;h(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);n===d.current&&(h(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&r(false))},v=async()=>{let t=d.current,r=await e.loadOlderMessages();t===d.current&&!r.ok&&h(e=>({...e,error:r.error.displayMessage}))},k=()=>{e.newConversation(),d.current+=1,r(false)},w=()=>{p.cursor===null||p.loading||p.loadingMore||i.trim().length>0||g(p.cursor)},C=a(()=>_p(p.rows,i),[p.rows,i]),S=i.trim().length>0;return{...p,open:t,show:b,close:m,load:g,resume:y,earlier:v,newConversation:k,loadMore:w,query:i,setQuery:o,searching:S,filtered:C,emptyKind:p.rows.length===0?"empty":"noMatch"}}var Ip="#111111",zp="#FFFFFF",Pp=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Ip,pillColor:zp,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Ip,pillColor:zp,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Ip,pillColor:zp,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Ip,pillColor:zp,showsVetAction:false})});function Op(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function Ep(e){return Cf(wf.urgencyGeneralReason,{petName:e?.trim()||wf.emptyTitlePetFallback})}function jp(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:Fp(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Ep(t)}:null}return null}function Fp(e){return typeof e=="string"&&e.trim().length>0?e:null}function Ap(e){let t=e===null?null:Op(e),[r,i]=l(null),[o,u]=l(false);n(()=>u(false),[t]);let c=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:Pp[e.level],f=e!==null&&!c&&e.level!=="general",h=s(()=>{t!==null&&i(t),u(false)},[t]),p=s(()=>u(true),[]);return a(()=>({source:e,tier:d,signature:t,showBanner:c,showCompactIcon:f,showVetAction:c&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:Cf(wf.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var Dp="everfur.com",Mp=2048,Lp=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Bp(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&Lp.test(e)&&t.add(e)}/* @__PURE__ */
|
|
57
|
-
return Object.freeze([...t])}function Hp(e,t){if(e===Dp||e.endsWith(`.${Dp}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function Up(e,t){if(typeof e!="string"||e.length===0||e.length>Mp||!/^https:\/\//i.test(e))return null;let r=ke(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:Hp(r.hostname,t)?r.href:null}function Np(e){try{Promise.resolve(x.openURL(e)).catch(()=>{})}catch{}}var $p=createContext(null);function Wp(){return o($p)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:t,children:n}){let l=e===false?null:Array.isArray(e)?e.join(`\n`):"",i=a(()=>{if(l===null)return null;let e=Bp(l===""?[]:l.split(`\n`));/* @__PURE__ */
|
|
58
|
-
return Object.freeze(
|
|
59
|
-
return
|
|
39
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function Pi(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function Oi(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,Ei)}catch(e){Ei(e)}}function Ei(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var ji=/* @__PURE__ */new WeakMap,Fi=/* @__PURE__ */new Map;function Ai(e,t){ji.set(e,t)}function Di(e,t,r,n){let l=ji.get(e);if(l===void 0)return null;let i;if(t.mode==="personalized"&&typeof t.userRef=="string")i=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")i=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${l}|${i}|${r}|${Li(n)}`}function Mi(e,t){if(e===null)return t();let r=Fi.get(e);if(r!==void 0)return r;let n=t().finally(()=>{Fi.get(e)===n&&Fi.delete(e)});return Fi.set(e,n),n}function Li(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Li).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Li(t)}`).join(",")}}`}var Bi=/* @__PURE__ */new WeakMap;function Hi(e,t){let r=Bi.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,Bi.set(e,r)),r.add(t),()=>{r?.delete(t)}}function Ui(e){let t=Bi.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var Ni=/* @__PURE__ */new Map;function $i(e,t){return()=>{let r=Ni.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let l=n.finally(()=>{Ni.get(e)===l&&Ni.delete(e)});return Ni.set(e,l),l}}function parseColor(e){let t=Wi(e);return t===null?null:Ji(t)}function Wi(e){if(typeof e=="number")return Gi(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Vi(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Vi(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return qi(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=Vi(t);if(e!==null)return e}return/^\d+$/.test(t)?Gi(Number.parseInt(t,10)):null}function Vi(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:Yi(t[0]),g:Yi(t[1]),b:Yi(t[2]),a:1};if(t.length===6)return{r:Ki(t,0),g:Ki(t,2),b:Ki(t,4),a:1};if(t.length===8){let e=Ki(t,0);return{r:Ki(t,2),g:Ki(t,4),b:Ki(t,6),a:e/255}}return null}function qi(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(e=>e.trim());if(n.length<3)return null;let l=Qi(Number(n[0])),i=Qi(Number(n[1])),o=Qi(Number(n[2]));if(l===null||i===null||o===null)return null;let a=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;a=Math.min(1,Math.max(0,e))}return{r:l,g:i,b:o,a:a}}function Gi(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return{r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}function Ki(e,t){return Number.parseInt(e.slice(t,t+2),16)}function Yi(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function Qi(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function Ji(e){if(e.a>=1)return Xi(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function Xi(e,t,r){return`#${Zi(e)}${Zi(t)}${Zi(r)}`.toUpperCase()}function Zi(e){return e.toString(16).padStart(2,"0")}var eo="#111111",to="#FFFFFF",ro="#000000";function readableOn(e){let t=Wi(e);if(t===null)return to;let r=io(t),n=io({r:17,g:17,b:17}),l=io({r:255,g:255,b:255});return ao(r,l)>=ao(r,n)?to:eo}function no(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(to,e)>=contrastRatio(ro,e)?to:ro}function lo(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(to)>=t(ro)?to:ro}function io(e){let t=oo(e.r/255),r=oo(e.g/255),n=oo(e.b/255);return.2126*t+.7152*r+.0722*n}function oo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function ao(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=Wi(e),n=Wi(t);if(r===null||n===null)return 1;let l=n.a>=1?n:{...n},i=r.a>=1?r:so(r,l);return ao(io(i),io(l))}function so(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function uo(e,t){let r=Wi(e),n=Wi(t);if(r===null||n===null)return null;let l=r.a>=1?r:so(r,{...n});return Xi(l.r,l.g,l.b)}function co(e,t){let r=Wi(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var fo=.05;function ho(e,t,r,n){let l=t[0];if(l===void 0)return r;let i=e=>t.every(t=>contrastRatio(e,t)>=n);if(Wi(e)===null)return r;if(i(e))return e;let o=uo(e,l),a=o===null?null:Wi(o),s=Wi(r);if(a===null||s===null)return r;for(let e=1;e<1/fo;e+=1){let t=e*fo,r=(e,r)=>Math.round(e+(r-e)*t),n=Xi(r(a.r,s.r),r(a.g,s.g),r(a.b,s.b));if(i(n))return n}return r}function po(e,t,r){let n=e/255,l=t/255,i=r/255,o=Math.max(n,l,i),a=Math.min(n,l,i),s=(o+a)/2;if(o===a)return{h:0,s:0,l:s};let u=o-a,c=u/(1-Math.abs(2*s-1)),d;return o===n?(d=(l-i)/u*60,d<0&&(d=d+360)):o===l?d=((i-n)/u+2)*60:d=((n-l)/u+4)*60,{h:d,s:c,l:s}}function go(e){let{h:t,s:r,l:n}=e,l=(1-Math.abs(2*n-1))*r,i=t/60,o=l*(1-Math.abs(i%2-1)),a=n-l/2,s=Math.floor(i)%6,u=[[l,o,0],[o,l,0],[0,l,o],[0,o,l],[o,0,l],[l,0,o]],[c,d,f]=u[s];return{r:bo(c+a),g:bo(d+a),b:bo(f+a)}}function bo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var mo=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),yo=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),vo=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return vo[e]??yo}var ko=4.5,wo=/* @__PURE__ */Object.freeze({});function Co(e){return mo.includes(e)}function So(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,l]of Object.entries(e)){if(!Co(n)||l===null||typeof l!="object")continue;let e=Ro(l);if(e===null)continue;let i=xo(n,e);i!==null&&(t[n]=i,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function xo(e,t){let r=vo[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function _o(e,t,r){return e[t]!==void 0?e[t]:e[r]}function Ro(e){let t={},r=parseColor(_o(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(_o(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let l=So(_o(e,"border_radius","borderRadius"));l!==null&&(t.borderRadius=l);let i=parseColor(_o(e,"text_color","textColor"));return i!==null&&(t.textColor=i),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??wo:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function To(e){let t=Wi(e);return t!==null&&t.a>=1}var Io=3,zo=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function Po(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function Oo(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>uo(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=Io))return null;let l=[...t,...n,...r];return ho(n[0],l,lo(l),Io)}function Eo(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>uo(e,t)??t)}function jo(e,t){let r=lo(e);return e.every(e=>contrastRatio(r,e)>=t)}function Fo(e,t){let r=t[0];return r===void 0?null:uo(e,r)}function Ao(e){let t=no(e[0],ko);return e.every(e=>contrastRatio(t,e)>=ko)?t:lo(e)}function Do(e,t,r,n,l){return zo.has(e)?false:l?true:r!==void 0&&Po(t,r)?false:!(n!==void 0&&r!==void 0&&To(r))}function guardSlotContrast(e,t,r){let n=false,l={};for(let i of mo){let o=e[i];if(o===void 0)continue;let a=o.backgroundColor,s=t?.[i]??[],u=Eo(a,s),c={...o},d=false;if(a!==void 0&&u.length>1&&!jo(u,ko)){let e=Fo(a,s);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[i],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&To(h)&&Oo(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(a!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<ko))&&(c.textColor=Ao(u),d=true);else if(e!==void 0){let t=ho(e,u,lo(u),ko);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&Do(i,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=ho(o.borderColor,e,lo(e),Io);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=Oo(h,f,u);e!==null&&(c.borderColor=e,d=true)}l[i]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(l):e}var Mo=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),Lo=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var Bo=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Bo(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var Ho=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Uo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),No={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},$o={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Wo={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},Vo={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},qo={regular:"400",medium:"500",bold:"700"},Go={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},Ko=0,Yo="System",Qo="monospace",Jo=["content","heading","control","compact","badge"];function Xo(e){let t={};for(let r of Jo)t[r]=e;return t}var Zo=[];function ea(){return{family:Yo,mono:Qo,fontUrl:null,families:{regular:Yo,medium:Yo,bold:Yo,mono:Qo,monoMedium:Qo,monoBold:Qo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Wo,tierSizes:Xo(Wo),lineHeight:Vo,weight:qo,letterSpacing:Go,scale:1,maxScale:Ko,scaleCaps:Ho,headingFamily:null,headingWeight:null,fontSources:Zo,roles:Lo,typeScale:1}}var ta={},ra=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(e){return`cubic-bezier(${e.join(", ")})`}var na={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(ra.standard),emphasized:cssCubicBezier(ra.emphasized),exit:cssCubicBezier(ra.exit)},reducedMotion:false},la={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},ia=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:la,space:No,radius:$o,type:ea(),motion:na,slots:ta}),oa={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},aa=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:oa,space:No,radius:$o,type:ea(),motion:na,slots:ta});function sa(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function ua(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function ca(e){return ua(e).every(t=>contrastRatio(e.brand,t)>=Io)}function da(e){return[e.chatGround,e.surface,e.surfaceCream]}function fa(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...ha(e,t)]}function ha(e,t){return[uo(t,e.surface)??e.surface,uo(t,e.surfaceCream)??e.surfaceCream]}function pa(e){return[e.composerFill,e.chatGround]}var ga=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function ba(e,t){let r=new Set(sa(t));return sa(e).every(e=>r.has(e))}function ma(e){let t=e.color,r=(e.brightness==="dark"?aa:ia).color,n=(e.brightness==="dark"?ia:aa).color,l=sa(t),i=lo(l)!==lo(sa(r)),o=ba(t,r),a=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,s=(e,t,r,n,l,s)=>{let u=t===r&&(e!=="errorRed"||a);return u&&o&&ga.has(e)?t:ho(u&&i?n:t,l,lo(l),s)},u=(e,l,i)=>s(`text.${e}`,t.text[e],r.text[e],n.text[e],l,i),c=(e,t,l,i)=>s(e,t,r[e],n[e],l,i),d=e=>i&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=no(f,ko),p=c("danger",t.danger,[...l,...ha(t,t.badgeBgCritical)],ko),g={...t,onPrimary:h,onAccent:no(t.accent,ko),onDanger:contrastRatio(h,p)>=ko?h:no(p,ko),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,l,ko),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,da(t),ko),text:{...t.text,primary:u("primary",l,ko),secondary:u("secondary",l,ko),muted:u("muted",l,ko),metaCool:u("metaCool",l,ko),timestamp:u("timestamp",l,ko),placeholder:u("placeholder",ua(t),Io)},danger:p,errorRed:c("errorRed",t.errorRed,fa(t,t.badgeBgCritical),ko),warningStrong:c("warningStrong",t.warningStrong,fa(t,t.badgeBgCaution),ko),composerBorder:c("composerBorder",t.composerBorder,pa(t),Io),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,ua(t),Io)},b={...g,..._a(g,r,o)};return{...b,...ya(t,b,r)}}function ya(e,t,r){let n={},l=(e,t,r)=>ho(e,t,lo(t),r);if((!Ca(e.success,r.success)||!Ca(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=l(e.success,fa(t,e.badgeBgPositive),ko)),(!Ca(e.cautionAccent,r.cautionAccent)||!Ca(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=l(e.cautionAccent,fa(t,e.badgeBgCaution),ko)),va(e,r)){n.info=l(e.info,fa(t,e.badgeBgInfo),ko);let r=[t.surface,t.chatGround,...ha(t,e.badgeBgInfo)];n.infoEdge=l(e.infoEdge,r,Io)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function va(e,t){return!Ca(e.info,t.info)||!Ca(e.badgeBgInfo,t.badgeBgInfo)}var ka=.24,wa=.3;function Ca(e,t){return parseColor(e)===parseColor(t)}function Sa(e,t){return Ca(e.accent,t.accent)?Ca(e.brand,t.brand)?null:e.brand:e.accent}function xa(e,t,r){let n=co(e,r);return(n===null?null:uo(n,t))??t}function _a(e,t,r){let n=Sa(e,t),l=ua(e),i=lo(l),o=lo([e.surface])===to,a=n===null&&r,s;a?s=t.highlight:n===null?s=o?xa(ia.color.highlight,e.surface,wa):ia.color.highlight:s=xa(n,e.surface,o?wa:ka);let u=a?t.onHighlight:ho(e.text.primary,[s],lo([s]),ko),c=n===null?t.mark:ho(n,l,i,Io),d=ca(e)?e.brand:i,f=(e,t,n)=>r&&Ca(e,t)?n:ho(e,l,d,Io),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=Io)?e.primary:ho(e.primary,h,lo(h),Io);return{highlight:s,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var Ra=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Ta(e,t){let r=(e.brightness==="dark"?aa:ia).color,n=e.color,l=t.color,i=[],o=(e,t,r,n)=>{i.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},a=(e,t)=>!Ra(e,t);a(n.text.primary,r.text.primary)&&!Ra(l.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,l.text.primary),a(n.brand,r.brand)&&(Ra(l.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,l.brandInk),Ra(l.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,l.primaryEdge),!Ra(l.controlEdge,n.brandBorder)&&!ca({...l,brand:n.brand})&&o("primary_color","control outline",n.brand,l.controlEdge)),a(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!Ra(l.linkInk,n.accent)&&o("accent_color","link text",n.accent,l.linkInk),a(n.danger,r.danger)&&!Ra(l.danger,n.danger)&&o("danger_color","error text",n.danger,l.danger),a(n.success,r.success)&&!Ra(l.success,n.success)&&o("success_color","positive status",n.success,l.success),a(n.warningStrong,r.warningStrong)&&!Ra(l.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,l.warningStrong),a(n.cautionAccent,r.cautionAccent)&&!Ra(l.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,l.cautionAccent),(a(n.info,r.info)||a(n.badgeBgInfo,r.badgeBgInfo))&&(Ra(l.info,n.info)||o("info_color","information text",n.info,l.info),Ra(l.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,l.infoEdge));for(let r of mo){let n=e.slots[r],l=t.slots[r];n===void 0||l===void 0||n===l||(l.backgroundColor!==void 0&&!Ra(l.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,l.backgroundColor),n.textColor!==void 0&&l.textColor!==void 0&&!Ra(l.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,l.textColor),l.borderColor!==void 0&&!Ra(l.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,l.borderColor))}/* @__PURE__ */
|
|
40
|
+
return Object.freeze(i)}var Ia=/* @__PURE__ */new Set;function za(e){if(e.length===0)return;let t=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(Ia.has(t))return;Ia.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var Pa="#23272C",Oa=4.5,Ea=.6,ja=.9,Fa=.02,Aa="#FFFFFF",Da="#111111";function Ma(e){return contrastRatio(e,Pa)>=Oa&&Math.max(contrastRatio(e,Aa),contrastRatio(e,Da))>=Oa}function deriveDarkVariant(e){let t=Wi(e);if(t===null)return null;let{h:r,s:n,l:l}=po(t.r,t.g,t.b),i=Math.min(Math.max(l,Ea),ja);for(let e=0;;e+=1){let t=i+e*Fa;if(t>ja)break;let l=go({h:r,s:n,l:t}),o=Xi(l.r,l.g,l.b);if(Ma(o))return o}let o=go({h:r,s:n,l:ja});return Xi(o.r,o.g,o.b)}var La=7,Ba=.05,Ha="#000000",Ua="#FFFFFF";function Na(e,t,r,n){let l=uo(e,t);if(l===null)return r;if(contrastRatio(l,t)>=n)return l;let i=Wi(l),o=Wi(r);if(i===null||o===null)return r;for(let e=1;e<1/Ba;e+=1){let r=e*Ba,l=(e,t)=>Math.round(e+(t-e)*r),a=Xi(l(i.r,o.r),l(i.g,o.g),l(i.b,o.b));if(contrastRatio(a,t)>=n)return a}return r}function $a(e,t){let r=sa(e),n=r[0],l=Wa(n);for(let e of r){let r=Wa(e);(t?r>l:r<l)&&(n=e,l=r)}return n}function Wa(e){let t=Wi(e);return t===null?0:io(t)}function Va(e,t){return uo(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=lo(sa(t))===Ua,n=r?Ua:Ha,l=$a(t,r),i=e=>Na(e,l,n,La),o={...t,brandSoft:Va(t.brandSoft,t.surface),brandSofter:Va(t.brandSofter,t.surface),brandBorder:i(t.brandBorder),borderHairlineGreen:i(t.borderHairlineGreen),brandBorderStrong:i(t.brandBorderStrong),controlEdge:i(t.controlEdge),structureEdge:i(t.structureEdge),brandInk:i(t.brandInk),linkInk:i(t.linkInk),borderRingCream:i(t.borderRingCream),composerBorder:i(t.composerBorder),text:{primary:i(t.text.primary),secondary:i(t.text.secondary),muted:i(t.text.muted),placeholder:i(t.text.placeholder),onBrand:t.text.onBrand,metaCool:i(t.text.metaCool),timestamp:i(t.text.timestamp)},badgeBgPositive:Va(t.badgeBgPositive,t.surface),badgeBgCaution:Va(t.badgeBgCaution,t.surface),badgeBgCritical:Va(t.badgeBgCritical,t.surface),badgeBgNeutral:Va(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Va(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Va(t.checkupCardConcernBg,t.surface),info:i(t.info),infoEdge:i(t.infoEdge),badgeBgInfo:Va(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var qa=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),Ga=qa.cream,Ka=qa.subtle,Ya=qa.ring,Qa=10;function Ja(e,t,r){let n=Wi(e),l=Wi(t);if(n===null||l===null)return null;let i=(e,t)=>Math.round(e+(t-e)*r);return Xi(i(n.r,l.r),i(n.g,l.g),i(n.b,l.b))}function Xa(e){if(e===null)return{};let t=lo([e]),r=Ja(e,t,Ga),n=Ja(e,t,Ka),l=Ja(e,t,Ya);return r===null||n===null||l===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:l}}function Za(e){if(e===null)return{};let t=Wi(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function es(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let l={};for(let[e,t]of Object.entries(r.type.size))l[e]=Math.max(Qa,Math.round(t*n*10)/10);return l}function ts(e,t,r){if(e===null)return t;let n=e/r.space.xs,l=e=>Math.round(e*n),i=r.space;return{xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),xxl:l(i.xxl)}}function rs(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),l=t.radius;return{tile:n(l.tile),xs:n(l.xs),sm:n(l.sm),md:n(l.md),lg:n(l.lg),xl:n(l.xl),pill:l.pill}}var ns=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function ls(e,t){let r=Wi(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function is(e,t){if(e===null)return{};let r=ls(e,t?ns.success.dark:ns.success.light),n=ls(e,t?ns.successCard.dark:ns.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function os(e,t){if(e===null)return{};let r=ls(e,t?ns.warning.dark:ns.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function as(e,t){if(e===null)return{};let r=ls(e,t?ns.info.dark:ns.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function ss(e,t,r){if(e===null)return t;let n=r.type.lineHeight,l=e/n.normal;if(l===1)return n;let i=e=>Math.round(e*l*100)/100;return{tight:i(n.tight),snug:i(n.snug),normal:i(n.normal),relaxed:i(n.relaxed)}}function us(e){return{composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:da(e),header:[e.surface,e.background,e.chatGround],banner:[uo(e.badgeBgInfo,e.surface)??e.surface,uo(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function cs(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var fs=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),hs=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),ps=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function gs(e){return typeof e=="string"&&fs.includes(e.trim().toLowerCase())}function bs(e,t){let r=e[t];return r??void 0}var ms=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>ms)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var ys=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],vs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],ks=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],ws=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],Cs=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!ds(e))return null;let t=gs(e.theme)?hs[e.theme.trim().toLowerCase()]:{},r=ds(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let l={},i=bs(n,"colorScheme"),o=typeof i=="string"?i.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(l.color_scheme=o);let a=o==="dark"?"_dark":"";for(let[e,t]of ys){let r=bs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of vs){let r=bs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of ws){let r=bs(n,e);typeof r=="string"&&r.trim().length>0&&(l[t]=r.trim())}for(let[e,t]of Cs){let r=parsePx(bs(n,e));r!==void 0&&(l[t]=r)}for(let[e,t]of ks){let r=bs(n,e);(typeof r=="number"||typeof r=="string")&&(l[t]=r)}let s=e.fonts;Array.isArray(s)&&s.length>0&&(l.font_sources=s);let u=e.rules;if(ds(u)){let e={};for(let t of mo){let r=u[t];ds(r)&&(e[t]=r)}Object.keys(e).length>0&&(l.slots=e)}return Object.keys(l).length===0?null:/* @__PURE__ */Object.freeze(l)}var Ss="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function xs(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var _s=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?xs(__EVERFUR_BRAND_CDN_ORIGIN__):Ss;var Rs=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),Ts=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),Is=Object.keys(Ts),zs="presentation",Ps="presentation.";function isPresentationLockName(e){if(e===zs)return true;if(!e.startsWith(Ps))return false;let t=e.slice(Ps.length);return Object.values(Ts).includes(t)}var Os={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},Es=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function js(e,t){if(t==null)return;let r=Os[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:Es.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Is){let n=Ts[e],l=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],i=js(e,l);i!==void 0&&(r[e]=i)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${Ps}${Ts[e]}`;for(let e of t)if(e===zs||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,l=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},i=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,a={};for(let e of Is){let t=l[e],r=isPresentationFieldLocked(e,o)?void 0:i[e];a[e]=r??t??Rs[e]}/* @__PURE__ */
|
|
41
|
+
return Object.freeze(a)}var Fs=4,As=/* @__PURE__ */Object.freeze({min:1,max:2}),Ds=100,Ms=2048,Ls=["100","200","300","400","500","600","700","800","900"];function Bs(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim().length===0||e.length>16)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function Hs(e){let t=Bs(e);if(t===null)return null;let r=String(t);return Ls.includes(r)?r:null}function Us(e){let t=Bs(e);return t===null?null:Math.min(As.max,Math.max(As.min,t))}function Ns(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Ms?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(t)?t:null}function $s(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Ds||/[\u0000-\u001F\u007F]/.test(t)?null:t}function Ws(e,...t){for(let r of t)if(e[r]!==void 0&&e[r]!==null)return e[r]}function Vs(e){if(!ds(e))return null;let t=$s(e.family);if(t===null)return null;let r=Ws(e,"src"),n=Ws(e,"cssSrc","css_src");if(r===void 0==(n===void 0))return null;if(n!==void 0){let e=Ns(n);return e===null?null:/* @__PURE__ */Object.freeze({family:t,cssSrc:e})}let l=Ns(r);if(l===null)return null;let i={family:t,src:l},o=Hs(e.weight);o!==null&&(i.weight=o);let a=typeof e.style=="string"?e.style.trim().toLowerCase():null;return(a==="normal"||a==="italic")&&(i.style=a),/* @__PURE__ */Object.freeze(i)}function qs(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=Fs)break;let e=Vs(r);e!==null&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}var Gs=/* @__PURE__ */Object.freeze({size:/* @__PURE__ */Object.freeze({min:8,max:48}),letterSpacing:/* @__PURE__ */Object.freeze({min:-.1,max:.3}),typeScale:/* @__PURE__ */Object.freeze({min:.8,max:1.3})}),Ks=["content","heading","control","compact","badge"],Ys=["sans","heading","mono"],Qs=/* @__PURE__ */Object.freeze({min:1,max:3.1});function Js(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e.trim().replace(/px$/i,"")):Number.NaN;return Number.isFinite(t)?t:null}function Xs(e,t){return Math.min(t.max,Math.max(t.min,e))}function Zs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function eu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==void 0)return e[r]}function tu(e){let t=Js(e);return t===null?null:Xs(t,Gs.typeScale)}function ru(e){if(!Zs(e))return null;let t={};for(let r of Ks){let n=Js(eu(e,r));n!==null&&(t[r]=n<=0?0:Xs(n,Qs))}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function nu(e){if(!Zs(e))return null;let t={},r=Js(eu(e,"size","fontSize","font_size"));r!==null&&(t.size=Xs(r,Gs.size));let n=Us(eu(e,"lineHeight","line_height"));n!==null&&(t.lineHeight=n);let l=Hs(eu(e,"weight","fontWeight","font_weight"));l!==null&&(t.weight=l);let i=eu(e,"face");typeof i=="string"&&Ys.includes(i.trim())&&(t.face=i.trim());let o=Js(eu(e,"letterSpacing","letter_spacing"));o!==null&&(t.letterSpacing=Xs(o,Gs.letterSpacing));let a=eu(e,"uppercase");return typeof a=="boolean"&&(t.uppercase=a),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function lu(e){if(!Zs(e))return null;let t={};for(let r of Mo){let n=nu(eu(e,r));n!==null&&(t[r]=n)}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}var iu=e=>Math.round(e*10)/10,ou=e=>Math.round(e*100)/100;function au(e,t,r,n){if(t===null&&r===null&&n===null)return e;let l=t===null?null:t/Lo.body.size,i=r===null?null:r/Lo.body.lineHeight,o={};for(let t of Mo){let r=e[t],a=Lo[t];o[t]=/* @__PURE__ */Object.freeze({...r,...l===null?{}:{size:iu(a.size*l)},...i===null?{}:{lineHeight:ou(a.lineHeight*i)},...n?.[t]??{}})}/* @__PURE__ */
|
|
42
|
+
return Object.freeze(o)}function su(e,t){let r=false,n={};for(let l of Mo){let i=e[l],o=t(i);o===1?n[l]=i:(r=true,n[l]=/* @__PURE__ */Object.freeze({...i,size:iu(i.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function uu(e,t,r){return{nano:iu(e.nano*r),small:iu(e.small*r),micro:iu(e.micro*r),tiny:iu(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:iu(e.verdict*r)}}var cu=/* @__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"]),du="slots.",fu=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}function isKnownBrandingSchema(e){let t=e?.schemaVersion??null;return t===null||fu.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
|
|
43
|
+
return new Set(["hide_powered_by",...e?.lockedFields??[]])}function hu(e){return e==="hide_powered_by"||cu.includes(e)||isPresentationLockName(e)?true:e.startsWith(du)&&mo.includes(e.slice(du.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=gu(t),n=expandAppearance(yu(t,"appearance")),l=n===null?r:pu(gu(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function pu(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function gu(e){return{displayName:vu(yu(e,"display_name","displayName")),logoUrl:vu(yu(e,"logo_url","logoUrl")),primaryColor:parseColor(yu(e,"primary_color","primaryColor")),accentColor:parseColor(yu(e,"accent_color","accentColor")),brightness:_u(yu(e,"brightness","color_scheme","colorScheme")),fontFamily:vu(yu(e,"font_family","fontFamily")),fontUrl:vu(yu(e,"font_url","fontUrl")),fonts:wu(yu(e,"fonts")),fontUrls:wu(yu(e,"font_urls","fontUrls")),placeholder:vu(yu(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:mu(yu(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(yu(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(yu(e,"accent_color_dark","accentColorDark")),surfaceStyle:xu(yu(e,"surface_style","surfaceStyle"),Cu),radiusScale:xu(yu(e,"radius_scale","radiusScale"),Su),logoUrlDark:vu(yu(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(yu(e,"slots")),accessibilityMaxFontScale:zu(yu(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Eu(yu(e,"locked_fields","lockedFields")),presentation:parsePresentation(yu(e,"presentation")),schemaVersion:Pu(yu(e,"schema_version","schemaVersion")),backgroundColor:parseColor(yu(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(yu(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(yu(e,"text_color","textColor")),textColorDark:parseColor(yu(e,"text_color_dark","textColorDark")),dangerColor:parseColor(yu(e,"danger_color","dangerColor")),dangerColorDark:parseColor(yu(e,"danger_color_dark","dangerColorDark")),fontSizeBase:bu(yu(e,"font_size_base","fontSizeBase"),ps.fontSizeBase),borderRadius:bu(yu(e,"border_radius","borderRadius"),ps.borderRadius),spacingUnit:bu(yu(e,"spacing_unit","spacingUnit"),ps.spacingUnit),successColor:parseColor(yu(e,"success_color","successColor")),successColorDark:parseColor(yu(e,"success_color_dark","successColorDark")),warningColor:parseColor(yu(e,"warning_color","warningColor")),warningColorDark:parseColor(yu(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(yu(e,"info_color","infoColor")),infoColorDark:parseColor(yu(e,"info_color_dark","infoColorDark")),headingFontFamily:vu(yu(e,"heading_font_family","headingFontFamily")),fontWeightBody:Hs(yu(e,"font_weight_body","fontWeightBody")),fontWeightHeading:Hs(yu(e,"font_weight_heading","fontWeightHeading")),lineHeight:Us(yu(e,"line_height","lineHeight")),fontSources:qs(yu(e,"font_sources","fontSources")),assistantAvatarUrl:vu(yu(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:ru(yu(e,"text_scale_caps","textScaleCaps")),typeScale:tu(yu(e,"type_scale","typeScale")),typeRoles:lu(yu(e,"type_roles","typeRoles"))}}function bu(e,t){let r=Ru(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function mu(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}function yu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function vu(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var ku=["regular","medium","bold","mono","monoMedium","monoBold"];function wu(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of ku){let n=vu(yu(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var Cu=["white","cream","subtle"],Su=["sharp","default","round"];function xu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function _u(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Ru(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}var Tu=1,Iu=3.1;function zu(e){let t=Ru(e);return t===null?null:t<=0?0:Math.min(Iu,Math.max(Tu,t))}function Pu(e){if(e==null)return null;let t=Ru(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Ou(e){let t=e.trim();return t.startsWith(du)?t:t.startsWith(Ps)?Ps+t.slice(Ps.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Eu(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=Ou(r);hu(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var ju=/* @__PURE__ */new RegExp(`^${_s}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&ju.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?aa:ia:e,n=r.brightness==="dark"?aa:ia,l=r.brightness==="dark",i=l?t.primaryColorDark??Lu(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??Lu(t.accentColor):t.accentColor,a=i??r.color.primary,s=o??r.color.accent,u=i!==null&&Uu(t,a,n,l),c=u?n.color.primary:a,d=i!==null&&!u?Wi(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?Nu(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=Xa(p),b={...r.color,...g},m=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??Lu(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...Za(y(t.dangerColor,t.dangerColorDark)),...is(y(t.successColor,t.successColorDark),l),...os(y(t.warningColor,t.warningColorDark),l),...as(y(t.infoColor,t.infoColorDark),l),...m!==null?{text:{...h.text??r.color.text,primary:m}}:{},...Bu(t.surfaceStyle??null,b),primary:c,accent:s,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:ts(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?rs(t.borderRadius,n):Wu(t.radiusScale??null,r.radius,n),type:{...r.type,...Mu(r.type,t),size:es(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:ss(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:au(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var Fu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Au=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Du(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function Mu(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of ku){let a=Fu[e].map(e=>r[e]).find(e=>e!==void 0),s=Du(e)?null:t.fontFamily;a!==void 0?(l[e]=a,i[e]=true):s!==null&&(l[e]=s,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:a!==void 0&&delete o[e]}for(let e of Au)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function Lu(e){return e===null?null:deriveDarkVariant(e)}function Bu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function Hu(e,t){return e==null?false:parseColor(e)===parseColor(t)}function Uu(e,t,r,n){return Hu(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Hu(e.primaryColor,ia.color.primary)}function Nu(e,t){let r=e.color;return{text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}var $u={sharp:.5,default:1,round:1.5};function Wu(e,t,r){if(e===null)return t;let n=$u[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var Vu="Everfur",qu=.5;function resolveTheme(e){return sc(Gu(e),e)}function themeAdjustments(e){let t=Gu(e);return Ta(t,sc(t,{...e,highContrast:false}))}function Gu(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=Ju(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=Zu((i==="auto"?l:i)==="dark"?aa:ia,e?.typeProfile),a=withServerBranding(o,Xu(r));return withServerBranding(a,Xu(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Ku(e){return e==="placeholder"?"chat_placeholder":Ou(e)}var Yu={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 Qu(e,t){return t.has(Ku(e))?true:(Yu[e]??[]).some(e=>t.has(e))}function Ju(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(Qu(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of mo){let n=l[r];n!==void 0&&(t.has(`${du}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function Xu(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function Zu(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:Uo}})}function ec(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function tc(e){return e===void 0||!Number.isFinite(e)?1:Math.max(qu,e)}var rc=["content","heading","control","compact","badge"];function nc(e,t){let r={};for(let n of rc){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:Ho[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return rc.every(e=>r[e]===Ho[e])?Ho:r}function lc(e,t){return t>0?Math.min(e,t):e}function ic(e,t,r,n){let l={};for(let i of rc)l[i]=n?ec(e,lc(t,r[i])):e;return l}function oc(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function ac(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return{family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces,headingFamily:e.headingFamily};let l=e.headingFamily!==null&&r!==void 0&&oc(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of ku)!(i[e]===Yo||i[e]===Qo)&&r!==void 0&&oc(r,i[e])===false&&(i[e]=Du(e)?Qo:Yo,o[e]=false),n!==null&&Du(e)&&i[e]===Qo&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function sc(e,t){let r=e.meta.displayName.trim().length===0?Vu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of ku){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.regular??null,o=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,a=Number.isFinite(e.type.maxScale)?e.type.maxScale:Ko,s=tc(t?.textScale),u=nc(e.type.scaleCaps,a),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=su(e.type.roles,()=>d),h=c?su(f,e=>lc(s,u[e.tier])):f,p=t?.typeProfile==="phone"?uu(e.type.size,f,d):ec(e.type.size,d),g=ic(p,s,u,c),b=ma(e),m={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:b,space:e.space,radius:e.radius,type:{...e.type,...ac(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:s,maxScale:a,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,us(b),cs(b))};return t?.highContrast===true?deriveHighContrast(deepFreeze(m)):deepFreeze(m)}var uc="/widget/v1/entitlements",cc=304,dc=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",hc(t));return n.ok?pc(n.value):n.error.httpStatus===cc?dc:{kind:"failed",error:n.error}}var fc=64;function hc(e){let t={};return kc(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=fc?{method:"GET",path:uc,headers:t,query:{region:e.region}}:{method:"GET",path:uc,headers:t}}function pc(e){if(e===null||typeof e!="object"||!kc(e.revision))return vc();let t=typeof e.region=="string"?e.region:"",r=kc(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
|
|
44
|
+
return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:mc(e.capabilities),branding:bc(e),livemode:e.livemode!==false,...gc(e)})}function gc(e){let t=e.render_hints,r=e.sms_profile_public??(t!==null&&typeof t=="object"?t.sms_profile_public:void 0);return r!==null&&typeof r=="object"?{smsProfilePublic:r}:{}}function bc(e){let t=parseClientBranding(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let e=parseClientBranding(r.branding);return e!==null?e:parseClientBranding(r)}return null}function mc(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))yc(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
|
|
45
|
+
return Object.freeze(t)}function yc(e){return typeof e=="object"&&e!==null&&e.enabled===true}function vc(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function kc(e){return typeof e=="number"&&Number.isFinite(e)}var wc=30;function createEntitlementPoller(e){let t=e.scheduler??Cc,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??wc),l=e.rng??Math.random,i=()=>n+l()*n,o=false,a=false,s=null,u=null,c=n,d=0,f=()=>{s!==null&&(t.clear(s),s=null)},h=e=>{a||!o||(c=Math.max(n,e),s=t.set(()=>{s=null,b()},c*1e3))},p=null,g=async()=>{if(a)return null;let t=d;e.onFetch?.();let n=e.region?{cachedRevision:u,region:e.region}:{cachedRevision:u},l;try{l=await r(e.authFor(),n)}catch(r){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Sc(r)}),!a&&t===d&&(e.onSettled?.(),h(i())),null}if(a||t!==d)return null;switch(l.kind){case"updated":u=l.revision,l.smsProfilePublic!==void 0?e.update(l.decisions,l.branding??null,l.livemode!==false,l.smsProfilePublic):e.update(l.decisions,l.branding??null,l.livemode!==false),h(l.ttlSeconds);break;case"notModified":h(c);break;case"failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:l.error.code}),h(i());break;default:h(i())}return e.onSettled?.(),l},b=()=>{let e=g().finally(()=>{p===e&&(p=null)});return p=e,e};return{start(){o||a||(o=true,b())},prime(){return a?Promise.resolve(null):p??b()},stop(){a||(a=true,d++,f())},refresh(){a||!o||(d++,u=null,f(),b())}}}var Cc={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function Sc(e){return e instanceof Error?e.message:"poll failed"}var xc=20;function _c(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map,n=e=>{let t=e??"",n=r.get(t);return n===void 0&&(n=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:e}),r.set(t,n)),n},l=/* @__PURE__ */new Map,i=/* @__PURE__ */new Set,o=0,a=/* @__PURE__ */new Map,s=(r,l)=>{let o=r??"",a=t.get(o)??n(r);if(!(a.hasUnread===l.hasUnread&&a.unreadCount===l.unreadCount&&a.conversationId===l.conversationId)){t.set(o,l);for(let e of[...i])e();i.size>0&&l.hasUnread!==null&&l.unreadCount!==null&&e.emit({type:"unread_changed",petRef:r,conversationId:l.conversationId,unreadCount:l.unreadCount,hasUnread:l.hasUnread})}},u=(e,t)=>{a.set(e??"",t);let r=0,n=null;for(let e of t){let t=e.unreadCount??0;r+=t,t>0&&n===null&&(n=e.id)}s(e,/* @__PURE__ */Object.freeze({hasUnread:r>0,unreadCount:r,conversationId:n??t[0]?.id??null,petRef:e}))},c=(e,t,r)=>{if(t.some(e=>e.unreadCount===null)){a.delete(e??""),s(e,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:t[0]?.id??null,petRef:e}));return}let n=t.slice(0,xc).map(e=>/* @__PURE__ */Object.freeze({id:e.id,unreadCount:e.unreadCount}));if(r||n.length===0){u(e,n);return}let l=new Set(n.map(e=>e.id)),i=(a.get(e??"")??[]).filter(e=>!l.has(e.id));u(e,[...n,...i].slice(0,xc))};return{subscribe(e){return i.add(e),()=>{i.delete(e)}},get(e){return t.get(e??"")??n(e)},refresh(t){let r=t??"",n=l.get(r);if(n!==void 0)return n;let i=e.read(t);if(i===null)return Promise.resolve();let a=o,s=i.then(e=>{a!==o||!e.ok||c(t,e.value.conversations,true)},()=>{}).finally(()=>{l.get(r)===s&&l.delete(r)});return l.set(r,s),s},reportPage(e,t){c(e,t,false)},reportHead(e,t){c(e,t===null?[]:[t],false)},reportRead(e){for(let r of[...t.values()]){let t=a.get(r.petRef??"");t===void 0||!t.some(t=>t.id===e&&(t.unreadCount??0)>0)||u(r.petRef,t.map(t=>t.id===e?/* @__PURE__ */Object.freeze({id:t.id,unreadCount:0}):t))}},reset(){if(o+=1,l.clear(),a.clear(),t.size!==0){t.clear();for(let e of[...i])e()}}}}function Rc(e,t,r){let n=Pn({...t===null?{}:{petRef:t},limit:xc},100);return n.ok?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${n.value}`},{maxAttempts:1}).then(e=>e.ok?An(e.value):err(e.error)):Promise.resolve(err(n.error))}var Tc="everfur.notifications.device";var Ic="everfur.slots.v2",zc="everfur.slots.installId.v2";var Pc=3e3,Oc=/* @__PURE__ */Object.freeze([Tc,Ic,zc]);function Ec(e){let{leaving:t,identity:r,hooks:n,telemetry:l}=e;if(t===null||r===null||n.size===0)return null;let i=/* @__PURE__ */Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),o=[...n].map(e=>{try{return Promise.resolve(e(i))}catch(e){return Promise.reject(e)}}),a=(e,t)=>{try{l.track("sdk.logout.hookFailed",{reason:e,count:t,totalCount:o.length})}catch{}},s=Promise.allSettled(o).then(e=>{let t=e.filter(e=>e.status==="rejected").length;t>0&&a("failed",t)});return new Promise(e=>{let t=false,r=()=>{t||(t=true,clearTimeout(n),e())},n=setTimeout(()=>{t||a("timeout",o.length),r()},Pc);s.then(r,r)})}function jc(e){let{leaving:t,identity:r,transport:n,sessionId:l}=e,i=r.currentToken();i.catch(()=>{});let o={userRef:t.userRef,currentToken:()=>i,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:n,identity:o,userRef:t.userRef,sessionId:l}}async function Fc(e,t){if(Oc.length===0)return;let r=await Promise.allSettled(Oc.map(t=>e.removeItem(t))),n=r.filter(e=>e.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length})}function Ac(){/* @__PURE__ */
|
|
46
|
+
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function Dc(e=Ac){let t=/* @__PURE__ */new Set,r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:null}),n=()=>{for(let e of t)e()};return{subscribe(e){return t.add(e),()=>{t.delete(e)}},getSnapshot(){return r},set(e){r=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...e.decisions]),isPending:e.isPending,branding:e.branding??null,...e.livemode===false?{livemode:false}:{},...e.smsProfilePublic!==void 0&&e.smsProfilePublic!==null?{smsProfilePublic:e.smsProfilePublic}:{}}),n()},reset(t){r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:t?.keepBranding===true?r.branding??null:null,...t?.keepBranding===true&&r.smsProfilePublic!==void 0?{smsProfilePublic:r.smsProfilePublic}:{}}),n()},setPending(e){r.isPending!==e&&(r=/* @__PURE__ */Object.freeze({...r,isPending:e}),n())}}}var Mc="everfur.branding.v1.";function Lc(e){let t=[];for(let r of e){let e=r.codePointAt(0);e<128?t.push(e):e<2048?t.push(192|e>>6,128|e&63):e<65536?t.push(224|e>>12,128|e>>6&63,128|e&63):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63)}return t}function Bc(e){let t=3421674724,r=2216829733;for(let n of Lc(e)){r=(r^n)>>>0;let e=r*435,l=Math.floor(e/4294967296),i=e>>>0;t=t*435+l+r*256>>>0,r=i}return t.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")}function Hc(e){return`${Mc}${Bc(e)}`}function Uc(e){return e?JSON.stringify(e):null}async function Nc(e,t){try{let r=await e.getItem(Hc(t));if(r===null)return null;let n=parseClientBranding(JSON.parse(r));return n===null?null:/* @__PURE__ */Object.freeze({...n,logoUrl:hardenBrandAssetUrl(n.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(n.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(n.assistantAvatarUrl??null)})}catch{return null}}async function $c(e,t,r){try{r===null?await e.removeItem(Hc(t)):await e.setItem(Hc(t),r)}catch{}}function Wc(e,t){let r;return{restore(r){Nc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let l=Uc(n);l!==r&&(r=l,$c(e,t,l))}}}function Vc(){let e=null,t=/* @__PURE__ */new Set;return{get:()=>e,subscribe(e){return t.add(e),()=>{t.delete(e)}},set(r){if(r!==e){e=r;for(let e of[...t])try{e()}catch{}}}}}function qc(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:Vc(),store:null,disposed:false}}function Gc(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function Kc(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{},...e.appVersion!==void 0?{appVersion:e.appVersion}:{}};return tryResolveClientConfig(r,t===void 0?void 0:{platform:t})}function Yc(e,t){/* @__PURE__ */
|
|
47
|
+
return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:Qc(r,n,t))}catch{}}})}function Qc(e,t,r){let n=e.indexOf("."),l=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",i=typeof t?.requestId=="string"?t.requestId:null;return{..._t(r,l,i),...t}}function Jc(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(l,i)=>n.call(e,l,i??_t(t,r,l.requestId))}:{}}}var Xc=/* @__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 ${Et} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Zc(e,t,r=Pt){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+Xc[r])}function ed(e){/* @__PURE__ */
|
|
48
|
+
return Object.freeze({request(){return Promise.resolve(err(Gc(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){r.aborted||(yield n)}}}})}var td=/* @__PURE__ */new WeakSet;function rd(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return td.add(t),t}var nd=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new id(e,t)}var ld=6e4,id=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;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 r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new K("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.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:zt,platform:t?.platform??Pt,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:It(r?.appVersion)}),this.telemetry=r.telemetry?Yc(r.telemetry,this.errorContext):He,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=ed(l);else if(r.transport!==void 0)o=r.transport;else{let e=Kc(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=ed(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Ai(this,this.mintScope),this.transport=o,l!==null&&(Zc(l,this.telemetry,t?.platform),this.emit({type:"error",code:Gc(l).code,requestId:null,context:_t(this.errorContext,"runtime",null)})),this.errorPolicy=Jc(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??Ne,this.upload=r.upload??Gr,this.uploadTransport=r.uploadTransport??sl,this.imageCache=r.imageCache??nd,this.kv=r.storage??rd(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Dc():Dc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",od(e),()=>this.buildChatController(e),ad),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${od(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=_c({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Rc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Wc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?qc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=$i(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-ld,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Oi(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&Uc(l)===Uc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:Jc(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){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:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await Fc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return Ec({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>jc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>Mi(Di(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(sd(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&Ui(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?sd("prepare"):r===null?null:Gc(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(Je(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}if(s==="ready")this.emit({type:"ready"});else if(s==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:_t(this.errorContext,"runtime",e)})}/* @__PURE__ */
|
|
49
|
+
return Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",od(t),()=>this.buildChatController(t),ad,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function od(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function ad(e){e.dispose()}function sd(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function ud(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function cd(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function dd(e){return e.ok?e:err(cd(e.error))}function fd(e){return{send:async(...t)=>dd(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var hd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),pd=globalThis,gd=pd[hd]??(pd[hd]=createContext(null));gd.displayName??="EverfurContext";function bd(){let e=o(gd);if(e===null)throw new K("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return bd().handle}var md=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),yd=globalThis,vd=yd[md]??(yd[md]=createContext(ia));vd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(vd)}var kd=()=>()=>{},wd=()=>null;function Cd(e,t){return i(t?.subscribe??kd,t?.get??wd,t?.get??wd)??e}function EverfurThemeProviderCore(e){let{runtime:t}=bd(),l=t.entitlements,o=i(l.subscribe,l.getSnapshot,l.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),c=e.seams.useTextScale(),d=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,h=e.seams.typeProfile,p=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,b=e.clientTheme?Sd(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=Cd(o.branding??null,t.sdkConfigHost?.branding),v=a(()=>resolveTheme({branding:y,clientOverride:m,colorScheme:s,reducedMotion:u,textScale:c,scaleTypeSizes:f,highContrast:d,...h===void 0?{}:{typeProfile:h},...p===void 0?{}:{platformMonoFamily:p},...g===void 0?{}:{isFontRegistered:g}}),[y,m,s,u,c,f,h,d,p,g]);e.seams.useResolvedTheme?.(v);let k=e.seams.isDevelopment;return n(()=>{k===void 0||!xd(k)||za(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(vd.Provider,{value:v},e.children)}function Sd(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function xd(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:l,activePet:i,theme:o,warmUp:s,children:f,seams:h}=e,p=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=u(null),b=u(null),m=u(t?.onEvent);m.current=t?.onEvent;let y=u(e=>{m.current?.(e)}),[v,k]=c(e=>e+1,0),w=u(null),C=u(void 0),S=l?.userRef??null;C.current!==S&&(C.current!==void 0&&(w.current=null),C.current=S);let x=w.current!==null?w.current.user:l??null,_=u(null),R=u(void 0),T=i??null;R.current!==T&&(R.current!==void 0&&(_.current=null),R.current=T);let I=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==p||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(b.current=g.current.runtime),g.current={key:p,runtime:createEverfurRuntime({config:_d(h.withDefaults?h.withDefaults(t):t,y.current),user:x,activePet:I,theme:o??null},{platform:h.platform,...h.eventSourceFactory?{eventSourceFactory:h.eventSourceFactory}:{}})});let z=g.current.runtime,P=u(null);n(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||P.current!==e&&(P.current=e,k())}),n(()=>{let e=b.current;e!==null&&(b.current=null,e.dispose())});let O=x?.userRef??null;d(()=>{z.setUser(x)},[z,O]),d(()=>{z.setActivePet(I)},[z,I]);let E=u(null);n(()=>(E.current===z&&(E.current=null),()=>{E.current=z,Rd(()=>{E.current===z&&(E.current=null,z.dispose())})}),[z]),n(()=>{s==="onMount"&&z.prepare(I===null?{}:{petRef:I})},[z,s,O,I]);let j=a(()=>({setUser:e=>{w.current={user:e},z.setUser(e),k()},setActivePet:e=>{_.current={pet:e},z.setActivePet(e),k()},open:e=>z.open(e),prepare:e=>z.prepare(e),registerPet:(e,t)=>z.registerPet(e,t),updatePet:(e,t)=>z.updatePet(e,t),deletePet:e=>z.deletePet(e),eraseUserData:()=>z.eraseUserData(),logout:()=>{w.current={user:null};let e=z.logout();return k(),e}}),[z,k]),F=a(()=>({runtime:z,handle:j,userRef:O,activePet:I,scopeEpoch:z.scopeEpoch,publishableKey:Td(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:f});return r(gd.Provider,{value:F},h.wrap?h.wrap(A):A)}function _d(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Rd(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Td(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Id=2;function zd(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Id)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function Pd(){let e=B;return(t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:e=>zd(n,e)})}}function Od(){let e=y();return e==="dark"?"dark":e==="light"?"light":null}function Ed(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function jd(){let[e,t]=l(false);return n(()=>{let e=true,r=m?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(m);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=m?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Fd(){let e=k?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(k);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function Ad(e){let t=v?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(v,"change",e);return()=>r?.remove?.()}function Dd(){return i(Ad,Fd,Fd)}function Md(){try{let e=p?.OS;return typeof e=="string"?e:null}catch{return null}}function Ld(){return Md()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function Bd(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=Ld(),l=m?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(m);Ed(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=m?.addEventListener,o=typeof i=="function"?i.call(m,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function Hd(){return Md()==="ios"?"Menlo":Qo}function Ud(){return globalThis.__DEV__!==false}var Nd=/* @__PURE__ */new Set;function $d(e){if(!Ud()||Nd.has(e))return;Nd.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", 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 Wd(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t)}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let l=n.includes(e);return l||$d(e),l}var Vd=/* @__PURE__ */new Set;function qd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var Gd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Kd(e){if(!Ud())return;let t=qd(e).filter(e=>!Vd.has(e));if(t.length===0)return;for(let e of t)Vd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Gd[e]).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 Yd(e){n(()=>{try{Kd(e)}catch{}},[e])}var Qd=/* @__PURE__ */Object.freeze({useColorScheme:Od,useReducedMotion:jd,useTextScale:Dd,useHighContrast:Bd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:Hd,isFontRegistered:Wd,useResolvedTheme:Yd,isDevelopment:Ud});function Jd(e){return r(M,null,e)}var Xd=/* @__PURE__ */Object.freeze({platform:"react-native",...p.OS==="web"?{}:{eventSourceFactory:Pd()},wrap:Jd,theme:Qd});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:Xd})}function useCapability(e){let{runtime:t}=bd(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function Zd(e){let{runtime:t}=bd(),r=t.entitlements,n=s(e=>r===void 0?()=>{}:r.subscribe(e),[r]),l=s(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return i(n,l,l)}var ef=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[ef[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[ef[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function tf(e){return e<=450?"regular":e<=650?"medium":"bold"}var rf={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=nf.get(e);r===void 0&&(r=/* @__PURE__ */new Map,nf.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=lf(e,t);return r.set(t,l),l}var nf=/* @__PURE__ */new WeakMap;function lf(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=tf(Number(n)),i=r.face==="mono"?face(e,rf[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,a=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},s=r.size,u={...a,fontSize:s,lineHeight:Math.round(s*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(s*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function of(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:t,...n}){let l=useEverfurTheme(),i=t===void 0?void 0:l.type.roles[t],o=of(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(S,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var af=t(function(e,t){return r(g,{...e,...t===null?{}:{ref:t}})});var sf=class extends f{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:t,resetKey:n}){return r(sf,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var uf=48;function cf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:l,style:i}=e,o=useCapability(t),s=a(()=>cf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */H(HostRender,{render:l,fallback:/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */H(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */H(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */H(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>df(r),[r]);/* @__PURE__ */
|
|
50
|
+
return H(w,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */H(w,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>df(r),[r]),l=e.disabled?.reason??"";/* @__PURE__ */
|
|
51
|
+
return H(w,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:l,children:l.length>0?/* @__PURE__ */H(Text,{style:n.offstateText,children:l}):null})}function df(e){let{color:t,space:r,radius:n,type:l}=e;return b.create({offstate:{minHeight:uf,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:b.hairlineWidth,borderColor:t.brandBorder},offstateText:{...face(e,"regular"),fontSize:l.size.body,lineHeight:Math.round(l.size.body*l.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}var ff=createContext(null);function TelevetHostOutlet(){let e=o(ff);return e===null?null:/* @__PURE__ */H(e,{})}var hf=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function pf(){let e=globalThis,t=e[hf];if(t!==void 0)return t;let r={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return e[hf]=r,r}function gf(e){let t=pf();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function bf(e){let t=pf().presenter;if(t===null)return"absent";try{return t(e)===!1?"declined":"presented"}catch(e){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",e),"threw"}}function mf(e){let t=pf();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function yf(){return pf().snapshot}function vf(){return pf().hosts.length>0}function kf(e){if(!vf())return false;let t=/* @__PURE__ */Object.freeze({...e});return gf({request:t,serial:pf().snapshot.serial+1}),true}function wf(){pf().snapshot.request!==null&&gf({request:null})}function Cf(){let e=pf(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],gf({activeHost:e.hosts[0]??null}),t}function Sf(e){let t=pf();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;gf(r===null?{activeHost:r,request:null}:{activeHost:r})}function xf(e){let t=null;return()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null)}),r}}function _f(e){let[t,r]=l(null);n(()=>{let e=Cf();return r(e),()=>{Sf(e)}},[]);let o=i(mf,yf,yf),a=t!==null&&o.activeHost===t?o.request:null,[s,u]=l(null),c=a!==null&&s===null;return n(()=>{if(!c)return;let t=true;return e().then(e=>{t&&u(()=>e)},e=>{t&&(console.warn("[everfur] The in-app vet visit could not load its screens.",e),wf())}),()=>{t=false}},[c,e]),a===null||s===null?null:{module:s,request:a,serial:o.serial,dismiss:wf}}var Rf=xf(()=>Promise.resolve($));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let l=_f(Rf);if(l===null)return null;let{EverfurTelevetModal:i}=l.module;/* @__PURE__ */
|
|
52
|
+
return H(i,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var Tf="Go to the nearest emergency vet now.";var If=/* @__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",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",sourcesHeading:"Sources",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:Tf,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",capReached:"You've used your {cap} free messages this month.",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 zf(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function Pf(e){return e?.trim()||If.emptyTitlePetFallback}function Of(e,t){return zf(e,{petName:Pf(t)})}var Ef="tel:+18884264435";var jf=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function Ff(e){let t=jf(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var Af=6;function Df(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function Mf(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let l of e){if(n.length>=r)break;if(l===null||typeof l!="object"||Array.isArray(l))continue;let e=t(l);e!==null&&n.push(e)}/* @__PURE__ */
|
|
53
|
+
return Object.freeze(n)}function Lf(e){let t=jf(e.title,80),r=jf(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function Bf(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=[];if(Array.isArray(t.gallery))for(let e of t.gallery){let t=Ff(e);t!==null&&r.length<Af&&r.push(t)}let n=Mf(t.doses,e=>{let t=jf(e.label,60),r=jf(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:Df(e.minLb??e.min_lb),maxLb:Df(e.maxLb??e.max_lb)})},Af),l=Mf(t.details,Lf,Af),i=t.fit,o=i!==null&&typeof i=="object"&&!Array.isArray(i)?Lf(i):null,a=o!==null&&i.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,s=/* @__PURE__ */Object.freeze({kicker:jf(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:l,fine:jf(t.fine,300),fit:a});return s.kicker===null&&r.length===0&&n.length===0&&l.length===0&&s.fine===null&&a===null?void 0:s}var Hf=128;var Uf=/* @__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"]),Nf=/* @__PURE__ */new Set(["y","c","g","r"]),$f=/* @__PURE__ */new Set(["done","now","next"]),Wf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,Vf=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,qf=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,Gf=e=>typeof e=="string"&&Uf.has(e)?e:null;function Kf(e){let t=Vf(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var Yf=e=>typeof e=="number"&&Number.isInteger(e)?String(e):Vf(e,Hf);function Qf(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Jf(e){/* @__PURE__ */
|
|
54
|
+
return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function Xf(e,t,r=20){if(!Array.isArray(e))return null;let n=[];for(let l of e){if(n.length>=r)break;let e=t(l);e!==null&&n.push(e)}return n.length===0?null:/* @__PURE__ */Object.freeze(n)}var Zf=(e,t=12,r=300)=>Xf(e,e=>Vf(e,r),t);function eh(e){let t=Wf(e),r=Vf(t?.kicker,120),n=Vf(t?.title,300);if(t===null||r===null||n===null)return null;let l=Wf(t.risk),i=Wf(t.odds),o=Wf(t.quote),a=Wf(t.jump);return Jf({kicker:r,title:n,sources:Xf(t.sources,e=>{let t=Vf(Wf(e)?.label,60);return t===null?null:Jf({label:t,kind:qf(Wf(e)?.kind)})},6),risk:Vf(l?.lead,300)===null?null:Jf({lead:Vf(l?.lead,300),body:Vf(l?.body),kind:qf(l?.kind)}),odds:Vf(i?.label,120)===null||Vf(i?.from,20)===null||Vf(i?.to,20)===null?null:Jf({label:Vf(i?.label,120),tag:Vf(i?.tag,40),from:Vf(i?.from,20),to:Vf(i?.to,20),toLabel:Vf(i?.toLabel,120)}),quote:Vf(o?.text)===null?null:Jf({kicker:Vf(o?.kicker,120),tag:Vf(o?.tag,40),text:Vf(o?.text)}),jump:Vf(a?.title,300)===null||Vf(a?.go,60)===null?null:Jf({title:Vf(a?.title,300),go:Vf(a?.go,60)}),report:th(t.report)})}function th(e){let t=Wf(e),r=Vf(t?.label,120),n=Vf(t?.text,1200);return r===null||n===null?null:Jf({label:r,text:n,actions:Zf(t?.actions,5,300)})}function rh(e){let t=Wf(e),r=Vf(t?.title,300),n=Xf(t?.steps,e=>{let t=Wf(e),r=Vf(t?.title,300),n=t?.tone;return r===null?null:Jf({title:r,body:Vf(t?.body),source:Vf(t?.source,200),tone:typeof n=="string"&&Nf.has(n)?n:null,icon:Gf(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:Jf({title:r,label:Vf(t?.label,60),steps:n})}function nh(e){let t=Wf(e),r=Vf(t?.title,300);if(t===null||r===null)return null;let n=Wf(t.rating),l=Wf(t.reviews),i=Wf(t.why),o=Wf(i?.score),a=Wf(t.dose),s=Wf(t.ingredients),u=Xf(l?.items,e=>{let t=Wf(e),r=t?.stars,n=Vf(t?.text),l=Vf(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||l===null?null:Jf({stars:Math.round(r),text:n,by:l})},5),c=Xf(i?.rows,e=>{let t=Wf(e),r=Vf(t?.chip,40),n=Vf(t?.title,300);return r===null||n===null?null:Jf({chip:r,kind:qf(t?.kind),title:n,body:Vf(t?.body)})}),d=Xf(a?.stats,e=>{let t=Wf(e),r=Vf(t?.value,40),n=Vf(t?.label,120),l=t?.kind;return r===null||n===null?null:Jf({value:r,label:n,kind:l==="weight"||l==="dose"||l==="days"?l:null})},6),f=Zf(s?.items,12,80);return Jf({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:Yf(t.productId),partnerSku:Vf(t.partnerSku,200),rating:Vf(n?.value,20)===null?null:Jf({value:Vf(n?.value,20),label:Vf(n?.label,120)}),line:Vf(t.line),reviews:Vf(l?.label,200)===null||u===null?null:Jf({label:Vf(l?.label,200),items:u}),checkoutLine:Vf(t.checkoutLine,300),why:Vf(i?.title,200)===null||c===null?null:Jf({title:Vf(i?.title,200),rows:c,score:Vf(o?.text,200)===null||Vf(o?.value,20)===null?null:Jf({text:Vf(o?.text,200),value:Vf(o?.value,20)})}),dose:Vf(a?.title,200)===null||d===null?null:Jf({title:Vf(a?.title,200),stats:d,note:Vf(a?.note)}),doseLabel:Vf(t.doseLabel,120),ingredients:f===null?null:Jf({label:Vf(s?.label,200),items:f}),proof:Vf(t.proof,300),trust:Xf(t.trust,e=>{let t=Wf(e),r=Gf(t?.icon),n=Vf(t?.label,120);return r===null||n===null?null:Jf({icon:r,label:n})},6),more:Vf(t.more,120),fine:Vf(t.fine),checkin:Vf(t.checkin,200),detail:Bf(t.detail)??null})}function lh(e){let t=Wf(e),r=Vf(t?.title,200),n=Xf(t?.items,e=>{let t=Wf(e),r=Vf(t?.title,300),n=Vf(t?.body);return r===null||n===null?null:Jf({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:Jf({title:r,items:n})}function ih(e){let t=Wf(e),r=Vf(t?.title,200),n=Zf(t?.questions,12,300),l=Vf(t?.add,80),i=Vf(t?.added,80);return r===null||n===null||l===null||i===null?null:Jf({title:r,questions:n,add:l,added:i})}function oh(e){let t=Wf(e),r=Vf(t?.title,200),n=Xf(t?.items,e=>{let t=Wf(e),r=Vf(t?.key,Hf),n=Vf(t?.title,300),l=Vf(t?.action,80),i=Yf(t?.productId),o=Vf(t?.added,80)??(i!==null?l:null);return r===null||n===null||l===null||o===null?null:Jf({key:r,productId:i,title:n,body:Vf(t?.body),price:Vf(t?.price,40),was:Vf(t?.was,40),tag:Vf(t?.tag,40),imageUrl:Kf(t?.imageUrl),icon:Gf(t?.icon),kind:qf(t?.kind),action:l,added:o,owned:t?.owned===true?true:null,detail:Bf(t?.detail)??null})},6);return r===null||n===null?null:Jf({title:r,items:n})}function ah(e){let t=Wf(e),r=Vf(t?.kicker,120),n=Vf(t?.title,120);return t===null||r===null||n===null?null:Jf({kicker:r,title:n,icon:Gf(t.icon),track:Xf(t.track,e=>{let t=Wf(e),r=Vf(t?.title,120),n=t?.state;return r===null?null:Jf({title:r,detail:Vf(t?.detail,120),state:typeof n=="string"&&$f.has(n)?n:null,tag:Vf(t?.tag,40)})},6),heading:Vf(t.heading,200),rows:Xf(t.rows,e=>{let t=Wf(e),r=Gf(t?.icon),n=Vf(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return Jf({icon:r,label:n,text:"",fromVet:true});let l=Vf(t?.text,300);return l===null?null:Jf({icon:r,label:n,text:l})},6),note:Vf(t.note,300),action:Vf(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=Wf(e),r=Vf(t?.title,300),n=nh(t?.pick);if(t===null||r===null||n===null)return null;let l=Wf(t.byline);return Jf({eyebrow:Vf(t.eyebrow,120),title:r,subtitle:Vf(t.subtitle,300),subtitleNoRecords:Vf(t.subtitleNoRecords,300),headImageUrl:Kf(t.headImageUrl),byline:Vf(l?.name,120)===null?null:Jf({name:Vf(l?.name,120),role:Vf(l?.role,120),imageUrl:Kf(l?.imageUrl),shortName:Vf(l?.shortName,60)}),focus:eh(t.focus),routine:rh(t.routine),pick:n,signs:lh(t.signs),checkup:ih(t.checkup),extras:oh(t.extras),wait:ah(t.wait),fine:Vf(t.fine),checkoutRows:Xf(t.checkoutRows,e=>{let t=Wf(e),r=Gf(t?.icon),n=Vf(t?.label,60),l=Vf(t?.value,200);return r===null||n===null||l===null?null:Jf({icon:r,label:n,value:l})},6)})}function healthPlanPageFromWire(e,t){let r=Wf(e);if(r===null||!("page"in r))return null;let n=Wf(r.pet),l=n?.sex;/* @__PURE__ */
|
|
55
|
+
return Object.freeze({petRef:Vf(r.pet_ref,Hf)??t,pet:/* @__PURE__ */Object.freeze({name:Vf(n?.name,120),species:Vf(n?.species,60),sex:l==="female"||l==="male"?l:null,breed:Vf(n?.breed,120),weightKg:Qf(n?.weight_kg),weightLb:Qf(n?.weight_lb)}),checkout:r.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(r.page),vetReviewed:r.vet_reviewed===true,trackingTextsEnabled:r.tracking_texts_enabled===true})}function sh(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function uh(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function ch(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}var dh=e=>typeof e=="string"&&e.length>0&&e.length<=Hf;function fh(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function hh(e,t,r){if(!dh(t))return err(sh("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${fh(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let l=healthPlanPageFromWire(n.value,t);return l===null?err(uh("healthPlan.page.read")):ok(l)}var ph=/* @__PURE__ */new WeakMap;function gh(e){let t=ph.get(e);if(t!==void 0)return t;let r=bh(e);return ph.set(e,r),r}function bh(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(ch("getPage")));let{services:n}=e.registry,l=fd(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return hh(l,t,r)}}}function mh(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function yh(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function vh(e,...t){if(typeof e=="function")try{let r=e(...t);return yh(r)&&Promise.resolve(r).then(void 0,mh),r}catch(e){mh(e);return}}var kh=/* @__PURE__ */new WeakMap;function wh(e){if(typeof e!="function")return;let t=kh.get(e);if(t!==void 0)return t;let r=(...t)=>{vh(e,...t)};return kh.set(e,r),r}function Ch(e,...t){let r;try{r=e(...t)}catch(e){return mh(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var Sh=6e4;function xh({lifecycle:e,refreshKey:t,readyAt:r,revalidate:l,refresh:i,now:o=Date.now}){let a=u({readyAt:r,revalidate:l,refresh:i??l,now:o});a.current={readyAt:r,revalidate:l,refresh:i??l,now:o},n(()=>{if(e==null)return;let t=vh(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=a.current;e!==null&&r()-e>=Sh&&t()}));return()=>{typeof t=="function"&&vh(t)}},[e]);let s=u(t);n(()=>{Object.is(s.current,t)||(s.current=t,a.current.refresh())},[t])}var _h=Sh,Rh=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function Th(){let e=globalThis,t=e[Rh];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[Rh]=r,r}function Ih(e,t,r,n,l){let i=Th(),o=i.get(t);o===void 0&&(o=/* @__PURE__ */new Map,i.set(t,o));let a=o,s=`${r}\0${n}`,u=a.get(s);if(!l&&u!==void 0&&(u.at===null||Date.now()-u.at<_h))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(a.get(s)===c&&(e.ok||ud(e.error)?c.at=Date.now():a.delete(s)),e))};return a.set(s,c),c.promise}function useHealthPlanPage(e){let{userRef:t,runtime:r}=bd(),i=a(()=>gh(r),[r]),o=e.repository,c=o??i,d=s((e,n)=>o!==void 0||t==null?c.getPage(e):Ih(i,r,t,e,n),[o,c,i,r,t]),{petRef:f}=e,h=e.enabled!==false&&t!=null&&f!==null,[p,g]=l({phase:"idle",petRef:null,page:null,error:null}),b=u(0),m=u(0),y=s(async e=>{let t=++b.current;if(!h||f===null){g(e=>e.phase==="idle"&&e.petRef===null?e:{phase:"idle",petRef:null,page:null,error:null});return}g(e=>({phase:"loading",petRef:f,page:e.petRef===f?e.page:null,error:null}));let r=await d(f,e);t===b.current&&(r.ok?g({phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}):ud(r.error)?g({phase:"ready",petRef:f,page:null,error:null,missing:true,readyAt:Date.now()}):g({phase:"failed",petRef:f,page:null,error:r.error}))},[h,f,d]),v=s(()=>y(true),[y]),k=p.phase==="ready"&&p.petRef===f,w=s(async()=>{if(!h||f===null||!k)return;let e=b.current,t=++m.current,r=await d(f,true);e!==b.current||t!==m.current||!r.ok||g(e=>e.phase==="ready"&&e.petRef===f?{phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}:e)},[h,f,k,d]);xh({lifecycle:e.lifecycle,refreshKey:e.refreshKey,readyAt:k?p.readyAt??null:null,revalidate:()=>{w()},refresh:()=>{k?w():v()}}),n(()=>(y(false),()=>{b.current+=1}),[y]);let C=h&&p.petRef!==f;return a(()=>({phase:C?"loading":p.phase,page:C?null:p.page,error:C?null:p.error,missing:!C&&p.missing===true,refresh:v}),[C,p,v])}var zh=/* @__PURE__ */Object.freeze({branding:null}),Ph=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>zh});function Oh(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function Eh(e){let{runtime:t}=bd(),r=t?.entitlements??Ph,n=s(()=>r.getSnapshot()?.branding??null,[r]),l=Cd(i(r.subscribe,n,n),t?.sdkConfigHost?.branding),o=Oh(e);return a(()=>{let t=l?.lockedFields??null;return{presentation:resolvePresentation({server:l?.presentation??null,locked:t,client:e??null}),isLocked:e=>isPresentationFieldLocked(e,t)}},[l,o])}function jh(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function Fh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function Ah(e){let t=ut(e);return t===null?null:{reached:If.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function Dh(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function Mh(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=Dh(r),n=t==="web",l=Ah(r);return{tone:"error",title:l!==null?l.reached:e?If.turnUnreachableTitle:n?If.turnFailedTitleWeb:If.turnFailedTitle,body:r.displayMessage,actionLabel:e?If.turnStartNewChat:n?If.retry:If.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:If.turnStoppedTitle,body:If.turnStoppedBody,actionLabel:If.turnRetry,action:"retry"}:null}function Lh(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var Bh=3,Hh=/* @__PURE__ */Object.freeze([]);function Uh(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Hh;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),l=e.replace(/\s+/g," ").toLowerCase();if(!(l.length===0||r.has(l))&&(r.add(l),n.push(e),n.length===Bh))break}/* @__PURE__ */
|
|
56
|
+
return Object.freeze(n)}var Nh=5;function $h(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Wh(e,t){if(t===void 0)return Uh(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return Hh;let n=Math.max(1,Math.min(Nh,Math.floor(t.count??Bh))),l=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){l=r.text;break}}let i=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(l===null?[]:[i(l)]),a=[],s=e=>{let r=e.trim(),l=i(r);a.length>=n||l.length===0||o.has(l)||$h(t.exclude,r)||(o.add(l),a.push(r))};for(let t of e.suggestedPrompts)s(t);let u=[];try{u=typeof t.fill=="function"?t.fill(l):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&s(e);/* @__PURE__ */
|
|
57
|
+
return Object.freeze(a)}function Vh(e){return e.sender?.displayName??If.senderVet}function qh(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var Gh=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 Kh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Yh(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===Bh&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>Gh.test(e)||Kh(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var Qh="pet_not_registered";function Jh(e){return e!=null&&e.reasonCode===Qh}var Xh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function Zh(e,t,r){let{runtime:i,userRef:o,scopeEpoch:c}=bd(),d=s((e,t)=>{let r=i.registry.services.authFor(o);return Mi(Di(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,c]),f=a(()=>t===void 0?null:Li(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=u(0),b=u(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${c}|${e}|${f}`,y=s(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=s(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?Xh:h.key!==m?{status:"registering",error:null,registered:null,retry:v}:{status:h.status,error:h.error,registered:h.registered,retry:v},[m,h,v])}var ep=/* @__PURE__ */Object.freeze({});function tp(e){let[t,r]=l(ep),i=u(null),o=u([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===ep?e:ep);return}let t=i.current;if(t===null)return;let n=e.find(e=>e.role==="user"&&!t.known.has(e.id));n!==void 0&&(i.current=null,r(e=>({...e,[n.id]:t.images})))},[e]);let c=s(e=>{i.current=e.length===0?null:{images:e,known:new Set(o.current)}},[]);return a(()=>({byMessage:t,stage:c}),[t,c])}var rp=/* @__PURE__ */new WeakSet;function np(){let e=makeEverfurError("internalError",{retryable:true});return rp.add(e),err(e)}function lp(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&rp.has(t)}var ip=500;function op(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,ip):null}function ap(e,t,r,l){let i=op(r),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=u(e);a.current=e;let s=u(null),c=u(null),d=u(o);d.current=o,n(()=>{if(i===null||o===null||t||s.current===o||c.current===o)return;let e=a.current;if(e===void 0)return;c.current=o;let r=e=>{c.current===o&&(c.current=null),!lp(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var sp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),up=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),cp=/* @__PURE__ */Object.freeze({...sp,markRead:true}),dp=/* @__PURE__ */Object.freeze({...up,markRead:true});function fp(e,t){return e?t?cp:sp:t?dp:up}function hp(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:vh(()=>r()!==!1)===true}function pp(e,t){let r=u({target:e,isVisible:t});r.current={target:e,isVisible:t};let l=u(e.isStreaming);n(()=>{let t=l.current;if(l.current=e.isStreaming,!t||e.isStreaming)return;let{target:n,isVisible:i}=r.current;n.status!=="complete"||n.conversationId===null||n.unreadCount===null||!i()||n.markRead()},[e.isStreaming])}var gp=3e5;function bp(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function mp(e,t,r){let l=u(t);l.current=t;let i=u(null),o=u(null),a=u(false),s=u(0),c=u(0),d=u(3e4),f=()=>e?.isOffline===void 0?false:vh(()=>e.isOffline?.()===!0)===true,h=f(),p=u(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:u}=l.current,h=qr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:u===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,bp(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,gp),c.current=Date.now()+s.current):(s.current=0,c.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},n(()=>{if(t.isTurnInFlight||h)return;let e=o.current;e!==null&&p.current(e)},[t.isTurnInFlight,h]),n(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=vh(()=>e(()=>{p.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)vh(e)}},[e]);let g=r?.intervalMs??null,b=r?.isVisibleFallback;n(()=>{if(e===void 0||g===null||!Number.isFinite(g)||g<=0)return;d.current=g;let t=setInterval(()=>{Date.now()<c.current||hp(e,b)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var yp=/^efch_[A-Za-z0-9_-]{43}$/,vp="efch";function kp(e){return typeof e=="string"&&yp.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${vp}=`))continue;let e=r.slice(vp.length+1);return kp(e)?e:null}return null}var wp=128,Cp=/[\u0000-\u001f\u007f]/;function Sp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function xp(e){return typeof e!="string"||e.length===0||e.length>wp||Cp.test(e)||e.includes("://")?null:e}function _p(e){if(e===null)return null;let t=e.conversation_id,r=xp(e.pet_ref);return typeof t!="string"||!On(t)||r===null?null:{conversationId:t,petRef:r}}function Rp(e,t,r){return kp(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(_p(Sp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(ln("internalError",false))):Promise.resolve(ok(null))}function Tp(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=kp(e)?e:null,a=o===null||i===null?null:`${String(i)}|${o}`,[s,u]=l(null);return n(()=>{if(a===null||o===null||i===null||r===null)return;let e=true,t=r.registry.services;return Rp(t.authFor(i),o,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||u({key:a,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[a,r,o,i]),s!==null&&s.key===a?s.target:void 0}function Ip(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function zp(e,t,r){let l=Ip(t),i=t?.kind==="chat",o=t?.petRef??null,a=i&&!r.pinned&&o!==null&&r.petRef!==null&&o!==r.petRef,s=u({openCheckin:e,target:t,selectPet:r.selectPet});s.current={openCheckin:e,target:t,selectPet:r.selectPet};let c=u(null),d=u(null),f=r.petRef;n(()=>{if(l===null||c.current===l)return;let{openCheckin:e,target:t,selectPet:n}=s.current;if(a&&o!==null){if(d.current?.key!==l){d.current={key:l,from:f},n(o);return}f!==d.current.from&&(c.current=l);return}i&&!r.ready||(c.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,f,r.ready])}var Pp=/* @__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 Op(e){let t=e?.replace(/\s+/g," ").trim();return t||Pp.untitled}function Ep(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function jp(e){let t=Ep(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?Pp.newReply.replace("{date}",t):t}function Fp(e,t){return t?`${Pp.countLabel}${Pp.countSeparator}${e}`:Pp.countLabel}function Ap(e){return`${e.unreadCount!==null&&e.unreadCount>0?Pp.unreadPrefix:""}${Pp.openConversation} ${Op(e.title)}`}function Dp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function Mp(e,t){let r=Dp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=Dp(Op(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function Lp(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function Bp(e){let[t,r]=l(false),[i,o]=l(""),c=e.listConversations,d=u(0),[f,h]=l(()=>Lp(c)),p=f.scope===c?f:Lp(c);n(()=>(d.current+=1,r(false),o(""),h(Lp(c)),()=>{d.current+=1}),[c]);let g=s(async t=>{let r=++d.current,n=t!==void 0;h(e=>({...e,scope:c,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===d.current){if(!l.ok){h(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}h(e=>{let r=t&&e.scope===c?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:c,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,c]),b=()=>{r(true),o(""),g()},m=()=>{d.current+=1,r(false)},y=async t=>{let n=++d.current;h(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);n===d.current&&(h(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&r(false))},v=async()=>{let t=d.current,r=await e.loadOlderMessages();t===d.current&&!r.ok&&h(e=>({...e,error:r.error.displayMessage}))},k=()=>{e.newConversation(),d.current+=1,r(false)},w=()=>{p.cursor===null||p.loading||p.loadingMore||i.trim().length>0||g(p.cursor)},C=a(()=>Mp(p.rows,i),[p.rows,i]),S=i.trim().length>0;return{...p,open:t,show:b,close:m,load:g,resume:y,earlier:v,newConversation:k,loadMore:w,query:i,setQuery:o,searching:S,filtered:C,emptyKind:p.rows.length===0?"empty":"noMatch"}}var Hp="#111111",Up="#FFFFFF",Np=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Hp,pillColor:Up,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Hp,pillColor:Up,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Hp,pillColor:Up,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Hp,pillColor:Up,showsVetAction:false})});function $p(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function Wp(e){return zf(If.urgencyGeneralReason,{petName:e?.trim()||If.emptyTitlePetFallback})}function Vp(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:qp(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Wp(t)}:null}return null}function qp(e){return typeof e=="string"&&e.trim().length>0?e:null}function Gp(e){let t=e===null?null:$p(e),[r,i]=l(null),[o,u]=l(false);n(()=>u(false),[t]);let c=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:Np[e.level],f=e!==null&&!c&&e.level!=="general",h=s(()=>{t!==null&&i(t),u(false)},[t]),p=s(()=>u(true),[]);return a(()=>({source:e,tier:d,signature:t,showBanner:c,showCompactIcon:f,showVetAction:c&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:zf(If.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var Kp="everfur.com",Yp=2048,Qp=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Jp(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&Qp.test(e)&&t.add(e)}/* @__PURE__ */
|
|
58
|
+
return Object.freeze([...t])}function Xp(e,t){if(e===Kp||e.endsWith(`.${Kp}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function Zp(e,t){if(typeof e!="string"||e.length===0||e.length>Yp||!/^https:\/\//i.test(e))return null;let r=ke(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:Xp(r.hostname,t)?r.href:null}function eg(e){try{Promise.resolve(x.openURL(e)).catch(()=>{})}catch{}}var tg=createContext(null);function rg(){return o(tg)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:t,children:n}){let l=e===false?null:Array.isArray(e)?e.join(`\n`):"",i=a(()=>{if(l===null)return null;let e=Jp(l===""?[]:l.split(`\n`));/* @__PURE__ */
|
|
59
|
+
return Object.freeze({hosts:e,open:t!==void 0?e=>{vh(t,e,"message")}:eg})},[l,t]);return r(tg.Provider,{value:i},n)}var ng={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function lg(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function ig(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l={width:e*.82,height:n,borderRadius:n,backgroundColor:t};/* @__PURE__ */
|
|
60
|
+
return U(w,{style:[lg(e),{gap:e*.22}],...ng,children:[
|
|
60
61
|
/* @__PURE__ */H(w,{style:l}),
|
|
61
62
|
/* @__PURE__ */H(w,{style:l}),
|
|
62
|
-
/* @__PURE__ */H(w,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=
|
|
63
|
-
return U(w,{style:[
|
|
63
|
+
/* @__PURE__ */H(w,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=ig(e,r),i=e*.78;/* @__PURE__ */
|
|
64
|
+
return U(w,{style:[lg(e),{transform:[{rotate:n}]}],...ng,children:[
|
|
64
65
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:i,height:l,borderRadius:l,backgroundColor:t}}),
|
|
65
66
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:l,height:i,borderRadius:l,backgroundColor:t}})]})}function PlusGlyph(e){/* @__PURE__ */
|
|
66
67
|
return H(Cross,{...e,rotate:"0deg"})}function CloseGlyph(e){/* @__PURE__ */
|
|
67
|
-
return H(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
68
|
-
return H(w,{style:
|
|
69
|
-
return H(w,{style:
|
|
70
|
-
return U(w,{style:[
|
|
68
|
+
return H(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r);/* @__PURE__ */
|
|
69
|
+
return H(w,{style:lg(e),...ng,children:/* @__PURE__ */H(w,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}var og={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:e,color:t,strokeWidth:r,direction:n}){let l=ig(e,r),i=e*.46,o=og[n];/* @__PURE__ */
|
|
70
|
+
return H(w,{style:lg(e),...ng,children:/* @__PURE__ */H(w,{style:{width:i,height:i,borderRightWidth:l,borderBottomWidth:l,borderColor:t,marginTop:i*o.marginTop,marginLeft:i*o.marginLeft,transform:[{rotate:o.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};/* @__PURE__ */
|
|
71
|
+
return U(w,{style:[lg(e),{flexDirection:"row",gap:1}],...ng,children:[
|
|
71
72
|
/* @__PURE__ */H(w,{style:[l,{borderTopLeftRadius:e*.2}]}),
|
|
72
|
-
/* @__PURE__ */H(w,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
73
|
-
return U(w,{style:
|
|
73
|
+
/* @__PURE__ */H(w,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l=e*.5;/* @__PURE__ */
|
|
74
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
74
75
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),
|
|
75
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
76
|
-
return U(w,{style:
|
|
76
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l=e*.6,i={position:"absolute",width:l,height:l,borderWidth:n,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
|
|
77
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
77
78
|
/* @__PURE__ */H(w,{style:[i,{top:0,left:0}]}),
|
|
78
|
-
/* @__PURE__ */H(w,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=
|
|
79
|
-
return U(w,{style:[
|
|
79
|
+
/* @__PURE__ */H(w,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=ig(e,r),o=n?t:"transparent";/* @__PURE__ */
|
|
80
|
+
return U(w,{style:[lg(e),{transform:[{rotate:l}]}],...ng,children:[
|
|
80
81
|
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),
|
|
81
82
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),
|
|
82
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
83
|
-
return U(w,{style:[
|
|
83
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r);/* @__PURE__ */
|
|
84
|
+
return U(w,{style:[lg(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...ng,children:[
|
|
84
85
|
/* @__PURE__ */H(w,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),
|
|
85
|
-
/* @__PURE__ */H(w,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
86
|
-
return U(w,{style:
|
|
86
|
+
/* @__PURE__ */H(w,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l=e*.34;/* @__PURE__ */
|
|
87
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
87
88
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.06,width:l,height:l,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),
|
|
88
89
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),
|
|
89
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
90
|
-
return U(w,{style:[
|
|
90
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r);/* @__PURE__ */
|
|
91
|
+
return U(w,{style:[lg(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...ng,children:[
|
|
91
92
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),
|
|
92
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
93
|
-
return U(w,{style:
|
|
93
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r);/* @__PURE__ */
|
|
94
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
94
95
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),
|
|
95
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */H(w,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
96
|
-
return U(w,{style:
|
|
96
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */H(w,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l=e/24,i=16*l+n,o=11*l-i/2,a=11+8/Math.SQRT2,s=(21-a)*Math.SQRT2*l,u=(a+21)/2*l;/* @__PURE__ */
|
|
97
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
97
98
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:o,left:o,width:i,height:i,borderRadius:i,borderWidth:n,borderColor:t}}),
|
|
98
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
99
|
-
return U(w,{style:
|
|
99
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r);/* @__PURE__ */
|
|
100
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
100
101
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),
|
|
101
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
102
|
-
return U(w,{style:
|
|
102
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l=e*.62;/* @__PURE__ */
|
|
103
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
103
104
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:0,width:l,height:l,borderRadius:l,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */H(w,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),
|
|
104
105
|
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.04,width:l*.5,height:l*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:e,color:t,testID:r}){let n=e*.36;/* @__PURE__ */
|
|
105
|
-
return H(w,{style:
|
|
106
|
-
return H(w,{style:
|
|
107
|
-
return U(w,{style:
|
|
106
|
+
return H(w,{style:lg(e),testID:r,...ng,children:/* @__PURE__ */H(w,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:r}){/* @__PURE__ */
|
|
107
|
+
return H(w,{style:lg(e),testID:r,...ng,children:/* @__PURE__ */H(w,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=ig(e,r);/* @__PURE__ */
|
|
108
|
+
return U(w,{style:lg(e),testID:n,...ng,children:[
|
|
108
109
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.08,width:e*.26,height:e*.48,borderWidth:l,borderColor:t,borderRadius:e*.13}}),
|
|
109
110
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.38,width:e*.56,height:e*.36,borderBottomWidth:l,borderLeftWidth:l,borderRightWidth:l,borderColor:t,borderBottomLeftRadius:e*.28,borderBottomRightRadius:e*.28}}),
|
|
110
111
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.74,width:l,height:e*.18,backgroundColor:t}})]})}function Ring({size:e,strokeWidth:t,color:r,children:n}){/* @__PURE__ */
|
|
111
|
-
return H(w,{style:[
|
|
112
|
-
return U(w,{style:
|
|
112
|
+
return H(w,{style:[lg(e),{borderRadius:e/2,borderWidth:t??b.hairlineWidth,borderColor:r}],children:n})}function ArrowUpGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=ig(e,r),i=e*.46;/* @__PURE__ */
|
|
113
|
+
return U(w,{style:lg(e),testID:n,...ng,children:[
|
|
113
114
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,bottom:e*.12,width:l,borderRadius:l,backgroundColor:t}}),
|
|
114
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
115
|
-
return U(w,{style:
|
|
115
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r);/* @__PURE__ */
|
|
116
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
116
117
|
/* @__PURE__ */H(w,{style:{width:e*.8,height:e*.6,marginTop:-e*.12,borderWidth:n,borderColor:t,borderRadius:e*.14}}),
|
|
117
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
118
|
-
return U(w,{style:
|
|
118
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=ig(e,r),l=e*.72,i=e/2;/* @__PURE__ */
|
|
119
|
+
return U(w,{style:lg(e),...ng,children:[
|
|
119
120
|
/* @__PURE__ */H(w,{style:{width:l,height:l,borderRadius:l/2,borderWidth:n,borderColor:t,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
|
|
120
121
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,left:e*.12,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}}),
|
|
121
122
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:i-e*.2,left:i-n/2,width:n,height:e*.2+n/2,borderRadius:n,backgroundColor:t}}),
|
|
122
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var
|
|
123
|
-
return H(R,{...o,hitSlop:i??
|
|
124
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
125
|
-
/* @__PURE__ */H(w,{pointerEvents:"box-none",style:[
|
|
123
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var ag=/* @__PURE__ */Object.freeze({standard:ra.standard,emphasized:ra.emphasized,exit:ra.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var sg=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),ug=/* @__PURE__ */Object.freeze({...sg,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function cg(e){return e.motion.reducedMotion?ug:sg}function dg(e,t){return Math.max(0,t)*e.followUpStaggerMs}function fg(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}function hg(){let e=useEverfurTheme();return cg(e)}var pg=8;function gg(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function bg(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function mg(e){let[t,r,n,l]=e;return e=>{if(e<=0)return 0;if(e>=1)return 1;let i=e;for(let r=0;r<pg;r+=1){let r=bg(i,t,n);if(r===0)break;i-=(gg(i,t,n)-e)/r}return gg(Math.min(1,Math.max(0,i)),r,l)}}var yg=mg(ag.standard),vg=mg(ag.outQuad),kg=mg(ag.out);function wg(e){let t=u(null);return t.current===null&&(t.current=new F.Value(e)),t.current}function Cg(e,t={}){let r=t.risePx??0,l=t.delayMs??0,i=wg(e>0?0:1);return n(()=>{if(e<=0){i.setValue(1);return}let t=F.timing(i,{toValue:1,duration:e,easing:vg,useNativeDriver:true}),r=l>0?F.sequence([F.delay(l),t]):t;return r.start(),()=>r.stop()},[i,e,l]),a(()=>({opacity:i,transform:[{translateY:i.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[i,r])}function FadePresence({visible:e,inMs:t,outMs:r,style:i,children:o}){let[a,s]=l(e),u=wg(e&&t<=0?1:0);return n(()=>{if(e){s(true);let e=F.timing(u,{toValue:1,duration:Math.max(0,t),easing:yg,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(r<=0){s(false);return}let n=F.timing(u,{toValue:0,duration:r,easing:yg,useNativeDriver:true});return n.start(({finished:e})=>{e&&s(false)}),()=>n.stop()},[e,a,t,r,u]),!a&&!e?null:/* @__PURE__ */H(F.View,{style:[i,{opacity:u}],children:o})}var Sg=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function xg(e,t){let[r]=l(()=>e?t.bubbleInMs:0),i=r>0,o=wg(i?0:1);n(()=>{if(r<=0)return;let e=F.timing(o,{toValue:1,duration:r,easing:kg,useNativeDriver:true});return e.start(),()=>e.stop()},[r,o]);let s=t.bubbleFromScale,u=t.bubbleRisePx;return a(()=>i?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[u,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:Sg,[i,o,u,s])}function _g(e){let t=u(null),r=u(null),n=e[0]?.id??null;if(t.current===null||r.current!==n){let l=t.current===null;t.current=new Map(e.map(e=>[e.id,l&&e.pending===true])),r.current=n}let l=t.current;for(let t of e)l.has(t.id)||l.set(t.id,true);return s(e=>l.get(e)===true,[l])}var Rg=12;function PressScale({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:l,hitSlop:i,...o}){let a=hg(),u=wg(1),c=s(e=>{a.pressMs<=0||a.pressScale===1||F.timing(u,{toValue:e,duration:a.pressMs,easing:yg,useNativeDriver:true}).start()},[u,a.pressMs,a.pressScale]);/* @__PURE__ */
|
|
124
|
+
return H(R,{...o,hitSlop:i??Rg,style:t,onPressIn:e=>{c(a.pressScale),n?.(e)},onPressOut:e=>{c(1),l?.(e)},children:/* @__PURE__ */H(F.View,{style:[e,{transform:[{scale:u}]}],children:r})})}function Tg(e,t,r){let i=t&&r.revealTickMs>0,[o,a]=l(0),s=u(e);return s.current=e,n(()=>{if(!i)return;let e=setInterval(()=>{a(e=>fg(r,e,s.current.length))},r.revealTickMs);return()=>clearInterval(e)},[i,r]),i?e.slice(0,Math.min(o,e.length)):e}var Ig=false;function zg(e){e.layoutMs<=0||(Ig||(Ig=true,p.OS==="android"&&typeof E.setLayoutAnimationEnabledExperimental=="function"&&E.setLayoutAnimationEnabledExperimental(true)),j.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function Pg(e,t){let r=u(e);r.current!==e&&(r.current=e,zg(t))}var Og=36,Eg=22,jg=12,Fg=12,Ag=16,Dg="#000",Mg="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:r}){let n=useEverfurTheme(),l=L();return e===null?null:/* @__PURE__ */U(I,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[
|
|
125
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:If.closePreview,style:Lg.backdrop,onPress:r,children:/* @__PURE__ */H(O,{source:{uri:e},style:Lg.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
|
|
126
|
+
/* @__PURE__ */H(w,{pointerEvents:"box-none",style:[Lg.closeWrap,{top:l.top+Fg}],children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:If.closePreview,hitSlop:jg,style:Lg.closeButton,onPress:r,children:/* @__PURE__ */H(CloseGlyph,{size:Eg,color:n.color.surface,strokeWidth:2})})})]})}var Lg=b.create({backdrop:{flex:1,backgroundColor:Dg,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:Ag},closeButton:{width:Og,height:Og,borderRadius:Og/2,backgroundColor:Mg,alignItems:"center",justifyContent:"center"}});var Bg=()=>{};function Hg(){try{return C.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let r=C.currentState==="background";t=C.addEventListener("change",t=>{t==="background"?r=!0:t==="active"&&r&&(r=!1,e())})}catch{return Bg}return()=>t.remove()},isVisible:Hg}}function Ug(e,t){if(e===void 0)return{};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}function Ng(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function $g(e){return e?.textColor===void 0?{}:{color:e.textColor}}function Wg(e){switch(e.code){case"too_large":return zf(If.attachmentTooLarge,{max:formatBytes(dl),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return zf(If.attachmentTooMany,{max:fl});case"unsupported_type":return zf(If.attachmentUnsupported,{filename:e.filename});case"network":return If.attachmentNetwork;case"server":return zf(If.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case"cancelled":return If.attachmentCancelled;case"rate_limited":return If.attachmentRateLimited;case"quota_exceeded":return If.attachmentQuota;case"idempotency_conflict":return If.attachmentConflict;case"unknown":return If.attachmentUnknown}}function Vg(e,t){return zf(e>=t?If.attachmentsFull:If.addAttachment,{used:e,total:t})}var qg=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:t,userRef:r,scopeEpoch:o}=bd(),c=e.maxPerMessage??fl,d=s(()=>{let{services:n}=t.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:n.authFor(r),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}),transport:e.transport??n.uploadTransport,maxPerMessage:c})},[t,r,o,c,e.transport]),f=a(()=>e.queue??d(),[e.queue,d]),h=u(/* @__PURE__ */new WeakSet),[p,g]=l(null),b=p!==null&&p.of===f?p.queue:f;n(()=>{if(b!==e.queue){if(h.current.has(b)){g({of:f,queue:d()});return}return()=>{b.dispose(),h.current.add(b)}}},[b,f,d,e.queue]);let m=i(b.subscribe,b.getSnapshot,()=>qg),[y,v]=l(null),k=s(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>b.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&v(r.error),t},[b,v]),w=s(e=>b.retry(e),[b]),C=s(e=>b.remove(e),[b]),S=s(()=>b.clear(),[b]),x=s(()=>v(null),[v]),_=m.attachments.some(e=>e.status==="uploading"),R=m.attachments.some(e=>e.status==="failed");return a(()=>({available:b.available,attachments:m.attachments,maxPerMessage:c,uploading:_,failed:R,blocked:_||R,s3Keys:m.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:y,add:k,retry:w,remove:C,clear:S,dismissRejected:x}),[b.available,m,c,_,R,y,k,w,C,S,x])}var Gg=6e3;function Kg(e,t,r){let n=t.trim();if(!n)return e;let l=e===""||/\s$/.test(e)?"":" ",i=`${e}${l}${n}`;return typeof r=="number"&&r>0?i.slice(0,r):i}function Yg(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${r}:${n.toString().padStart(2,"0")}`}function Qg(e){switch(e){case"permissionDenied":return If.micBlocked;case"noSpeech":return If.noSpeech;case"unavailable":return If.dictationUnavailable}}function Jg(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var Xg=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function Zg(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...Xg]){let e=(n??"").trim();if(!e)continue;let l=e.toLowerCase();if(!t.has(l)&&(t.add(l),r.push(e),r.length>=100))break}return r}function eb(e,t,r){let[i,o]=l({send:e,conversationId:t,text:r??"",seeded:r??null}),a=i.send===e&&(i.conversationId===null||i.conversationId===t);n(()=>{o(n=>{let l=n.send===e&&(n.conversationId===null||n.conversationId===t),i=l?n.text:"",o=l?n.seeded:null,a=r!=null&&r!==o&&i.length===0;return{send:e,conversationId:t,text:a?r:i,seeded:a?r:o}})},[e,t,r]);let u=s(r=>o(n=>({send:e,conversationId:t,text:r,seeded:n.seeded})),[e,t]);return[a?i.text:"",u]}function tb(e,t,r,i,o=false){let a=u({draft:r,setDraft:i});a.current={draft:r,setDraft:i};let s=u(null),[c,d]=l(null);n(()=>{if(e===void 0)return;let r=`${t??""}`;if(s.current===r)return;s.current=r;let n=true;return(async()=>{let l=await Ch(()=>e.read(t));if(!n)return;let i=l.ok&&typeof l.value=="string"?l.value:"";i.length>0&&a.current.draft.length===0&&a.current.setDraft(i),d(r)})(),()=>{n=false}},[e,t]),n(()=>{e===void 0||o||c!==`${t??""}`||vh(()=>e.write(t,r))},[e,t,r,c,o])}function rb(e){if(!(p.OS!=="ios"||e===""))try{let t=m?.announceForAccessibility;typeof t=="function"&&t.call(m,e)}catch{}}function AnnounceLine({line:e}){return n(()=>{rb(e)},[e]),null}var nb=12,lb=80,ib=44,ob=22,ab=.14,sb=18,ub=8,cb=/* @__PURE__ */Object.freeze({photo:If.attachmentPhoto,camera:If.attachmentCamera});function AttachmentPickerPopover({sources:e,full:t,onPick:r,onClose:n}){let l=useEverfurTheme(),i=a(()=>db(l),[l]);/* @__PURE__ */
|
|
126
127
|
return U(w,{style:i.anchor,pointerEvents:"box-none",children:[
|
|
127
|
-
/* @__PURE__ */H(R,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:
|
|
128
|
+
/* @__PURE__ */H(R,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:If.closeAttachmentPicker,onPress:n}),
|
|
128
129
|
/* @__PURE__ */U(w,{style:i.bubble,children:[
|
|
129
|
-
/* @__PURE__ */H(w,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
130
|
-
/* @__PURE__ */H(w,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */H(PhotoGlyph,{size:
|
|
131
|
-
/* @__PURE__ */H(Text,{tier:"control",style:i.tileLabel,children:
|
|
130
|
+
/* @__PURE__ */H(w,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:cb[e],accessibilityState:{disabled:t},disabled:t,containerStyle:i.tile,style:i.tileInner,onPress:()=>r(e),children:[
|
|
131
|
+
/* @__PURE__ */H(w,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */H(PhotoGlyph,{size:ob,color:l.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */H(CameraGlyph,{size:ob,color:l.color.brandInk,strokeWidth:1.5})}),
|
|
132
|
+
/* @__PURE__ */H(Text,{tier:"control",style:i.tileLabel,children:cb[e]})]},e))}),
|
|
132
133
|
/* @__PURE__ */H(w,{style:i.tail}),
|
|
133
|
-
/* @__PURE__ */H(w,{style:i.tailFill})]})]})}function
|
|
134
|
-
/* @__PURE__ */H(R,{accessibilityRole:d?"button":"image",accessibilityLabel:d?
|
|
135
|
-
/* @__PURE__ */H(O,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */H(w,{style:t.uploadingOverlay,children:/* @__PURE__ */H(P,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */H(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
136
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
137
|
-
return H(w,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
138
|
-
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(
|
|
139
|
-
/* @__PURE__ */H(R,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?
|
|
134
|
+
/* @__PURE__ */H(w,{style:i.tailFill})]})]})}function db(e){let t=e.color,r=e.radius;return b.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:ab,shadowRadius:sb,shadowOffset:{width:0,height:ub},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:lb,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:ib,height:ib,borderRadius:ib/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-nb/2,width:nb,height:nb,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:nb+4,height:2,backgroundColor:t.surfaceCream}})}var fb=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var hb=56,pb=12,gb=14,bb=10,mb=.45,yb="rgba(7,193,104,0.55)",vb="rgba(185,28,28,0.55)",kb=200,wb=300,Cb=20,Sb=22,xb=12,_b="rgba(0,0,0,0.78)",Rb=220,Tb=100,Ib="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:l,onPreview:i,style:o}){let s=useEverfurTheme(),u=a(()=>zb(s),[s]);return e.length===0&&t===null?null:/* @__PURE__ */U(w,{style:[u.strip,o],children:[e.length>0?/* @__PURE__ */H(w,{style:u.cards,children:e.map(e=>/* @__PURE__ */H(PreviewCard,{row:e,styles:u,onRetry:n,onRemove:l,onPreview:i},e.id))}):null,r?/* @__PURE__ */H(Text,{style:u.rejected,accessibilityRole:"alert",children:If.attachmentsFailedBlocked}):null,t!==null?/* @__PURE__ */H(Text,{style:u.rejected,accessibilityRole:"alert",children:Wg(t)}):null]})}function PreviewCard({row:e,styles:t,onRetry:r,onRemove:i,onPreview:o}){let a=useEverfurTheme(),s=e.status==="uploading",c=e.status==="failed",d=e.status==="uploaded",f=u(e.status),[h,p]=l(false);return n(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */U(w,{style:t.card,children:[
|
|
135
|
+
/* @__PURE__ */H(R,{accessibilityRole:d?"button":"image",accessibilityLabel:d?zf(If.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:s,disabled:!d},disabled:!d,style:t.thumbHit,onPress:()=>o(e),children:/* @__PURE__ */U(w,{style:t.thumb,children:[
|
|
136
|
+
/* @__PURE__ */H(O,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */H(w,{style:t.uploadingOverlay,children:/* @__PURE__ */H(P,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */H(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:zf(If.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:/* @__PURE__ */H(w,{style:t.failedInner,children:/* @__PURE__ */H(CloseGlyph,{size:Cb,color:a.color.surface,strokeWidth:2})})}):null,
|
|
137
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:zf(If.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>i(e.id),children:/* @__PURE__ */H(CloseGlyph,{size:xb,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:t}){let r=useEverfurTheme(),l=hg(),i=u(null);i.current===null&&(i.current=new F.Value(0));let o=i.current;return n(()=>{let e=F.sequence([F.timing(o,{toValue:1,duration:kb,useNativeDriver:true}),F.delay(l.uploadFlashMs),F.timing(o,{toValue:0,duration:wb,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&t()}),()=>e.stop()},[o,l.uploadFlashMs,t]),/* @__PURE__ */H(F.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:o}],children:/* @__PURE__ */H(CheckGlyph,{size:Cb,color:r.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:t}){let r=useEverfurTheme(),n=a(()=>zb(r),[r]);if(e.length===0)return null;let l=e.length===1;/* @__PURE__ */
|
|
138
|
+
return H(w,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:zf(If.attachedImage,{filename:e.filename}),onPress:()=>t(e),children:/* @__PURE__ */H(O,{source:{uri:e.uri},style:l?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${r}`))})}function zb(e){let t=e.color,r=e.type;return b.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:hb,height:hb,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:pb,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:b.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...fb,alignItems:"center",justifyContent:"center",backgroundColor:co(e.color.brandInk,mb)??e.color.brandSofter},successOverlay:{...fb,alignItems:"center",justifyContent:"center",backgroundColor:yb},failedOverlay:{...fb,borderRadius:pb,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:vb},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:Sb,height:Sb,borderRadius:Sb/2,backgroundColor:_b,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:Rb,height:Rb,borderRadius:gb,backgroundColor:Ib},gridImage:{width:Tb,height:Tb,borderRadius:bb,backgroundColor:Ib}})}var Pb="chat attachment upload: the file handle has no uri",Ob="chat attachment upload failed";function Eb(e){return{uri:e.uri,name:sanitizeFilename(e.name),type:e.mimeType}}function createRnChatAttachmentTransport(e={}){/* @__PURE__ */
|
|
139
|
+
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Pb));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(Ob));return l?.aborted===true?o():je({url:t.upload_url,fields:t.upload_fields,file:Eb(r),signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}var jb=300,Fb=3e3,Ab=120,Db=44,Mb=120,Lb="88%",Bb=520,Hb=2,Ub=.5,Nb=1.5,$b=1.6,Wb=.6,Vb=56,qb=1.5,Gb=5,Kb=5,Yb=36,Qb=20,Jb=14,Xb=Db,Zb=4,em=24,tm=22,rm=.4,nm=Db,lm=20,im=.4,om=480,am=12,sm=.72,um=48,cm=1.5,dm=1.3,fm=1,hm=1,pm="12%",gm=14,bm=16,mm=28,ym=18,vm="84%",km=10,wm=15,Cm=1.42,Sm=4,xm=3,_m=14,Rm=20;function Tm(){let e=useEverfurTheme(),t=a(()=>Im(e),[e]);return{theme:e,styles:t}}function Im(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=Math.round(l.size.body*Nb),o=Math.round(l.size.body*$b),a=Math.round(Qb*l.size.body/Jb),s=t.borderRingCream,u=e.slots;return b.create({container:{flex:1,minHeight:Ab,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Ab,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:pm,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:om,gap:r.lg},errorText:{...face(e,"regular"),fontSize:l.size.subtitle,lineHeight:l.size.subtitle*l.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Db,minWidth:Db,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...Ug(u.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,...$g(u.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.md,backgroundColor:t.surfaceCream,borderWidth:hm,borderColor:t.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal},turnNoticeAction:{minHeight:Db,justifyContent:"center"},turnNoticeActionLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight},setupNoticeAction:{...face(e,"medium"),color:t.brandInk,fontSize:l.size.caption},reconnectingCaption:{...face(e,"medium"),color:t.text.secondary,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:r.xs,paddingVertical:r.md,paddingHorizontal:r.md+r.xs/2,backgroundColor:t.surfaceSubtle,borderRadius:n.md},readingDot:{width:6,height:6,borderRadius:n.pill,backgroundColor:t.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:xm,minHeight:_m},readingDotInline:{width:Sm,height:Sm,borderRadius:n.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:Db,justifyContent:"center",paddingHorizontal:r.md+r.xs/2},earlierLabel:{...face(e,"monoBold"),color:t.linkInk,fontSize:l.size.caption},listContent:{padding:r.lg,gap:r.xl},listContentCards:{paddingTop:gm,paddingHorizontal:bm,paddingBottom:mm,gap:ym},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:Lb,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:Bb,paddingVertical:r.md,paddingHorizontal:r.lg+Hb,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:Ub,borderColor:t.primaryEdge}:{},borderRadius:n.lg,borderBottomRightRadius:n.xs,...Ug(u.userBubble,Ub)},bubbleAssistant:u.assistantBubble?.backgroundColor===void 0?{...Ug(u.assistantBubble,Ub)}:{paddingVertical:r.md,paddingHorizontal:r.lg+Hb,borderRadius:n.lg,...Ug(u.assistantBubble,Ub)},bubbleVet:{maxWidth:Bb,paddingVertical:r.md,paddingHorizontal:r.lg+Hb,backgroundColor:t.bubbleVet,borderRadius:n.lg,borderTopLeftRadius:n.xs,...Ug(u.vetBubble,Ub)},bubbleCards:{maxWidth:vm},bubbleUserCards:{paddingVertical:km,paddingHorizontal:wm},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*Cm)},bubblePending:{opacity:Wb},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:l.size.body,lineHeight:i,...$g(u.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:o,...$g(u.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:l.size.body,lineHeight:i,...$g(u.vetBubble)},assistantName:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,marginBottom:r.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:r.sm,marginBottom:r.xs},assistantAvatar:{width:Rm,height:Rm,borderRadius:Rm/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:r.sm,marginBottom:r.xs},vetSender:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},vetTime:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption},bubbleBold:face(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.md},followUpsHeading:{...face(e,"monoBold"),color:t.text.muted,fontSize:am,textTransform:"uppercase",letterSpacing:sm,paddingBottom:r.sm,borderBottomWidth:fm,borderBottomColor:s},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:fm,borderTopColor:s},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,minHeight:um,paddingVertical:r.sm+Hb,...u.chip?.backgroundColor!==void 0||u.chip?.borderColor!==void 0?{paddingHorizontal:r.md}:{},...Ug(u.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:l.size.bodyTight,...$g(u.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,marginTop:r.md},askChip:{minHeight:Db,maxWidth:"100%",justifyContent:"center",paddingVertical:r.sm,paddingHorizontal:r.lg,borderRadius:n.pill,borderWidth:cm,borderColor:t.brandInk,backgroundColor:t.chatGround,...Ug(u.chip,cm)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*dm),...$g(u.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:r.md,marginTop:r.xs},composer:{marginHorizontal:r.md,marginTop:r.xs,minHeight:Vb,justifyContent:"center",paddingLeft:r.sm,paddingRight:Gb,paddingVertical:Kb,backgroundColor:t.composerFill,borderWidth:qb,borderColor:t.composerBorder,borderRadius:n.pill,...Ug(u.composerInput,qb)},composerRow:{flexDirection:"row",alignItems:"center",gap:r.xs,minHeight:Yb},dictationError:{...face(e,"regular"),fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,color:t.danger,paddingHorizontal:r.xs},attachControl:{width:nm,height:nm,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:im},input:{flex:1,minHeight:Yb,maxHeight:Mb,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:l.size.body,lineHeight:a,color:t.text.primary,...$g(u.composerInput)},sendControl:{minHeight:Xb,minWidth:Xb,alignItems:"center",justifyContent:"center"},sendDisc:{width:Xb,height:Xb,borderRadius:Xb/2,alignItems:"center",justifyContent:"center",...Ug(u.sendButton)},sendControlDisabled:{opacity:rm},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.micro,textAlign:"center",paddingBottom:r.xs}})}var zm=18,Pm=28,Om=6,Em=1200,jm=.4,Fm=.4;function DictationButton({active:e,listening:t,elapsedMs:r,disabled:l=false,onToggle:i}){let o=useEverfurTheme(),s=a(()=>Am(o),[o]);return n(()=>{if(t)try{m.announceForAccessibility(If.listening)}catch{}},[t]),/* @__PURE__ */U(w,{style:s.wrap,children:[t?/* @__PURE__ */H(Text,{style:s.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:Yg(r)}):null,
|
|
140
|
+
/* @__PURE__ */H(R,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?If.stopDictation:If.dictate,accessibilityState:{selected:e,disabled:l},style:[s.button,l?s.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */U(N,{children:[
|
|
140
141
|
/* @__PURE__ */H(Pulse,{style:s.pulse,reduced:o.motion.reducedMotion}),
|
|
141
|
-
/* @__PURE__ */H(StopGlyph,{size:wm,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */H(MicGlyph,{size:km,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=u(new F.Value(1)).current;return n(()=>{if(t)return;let e=F.loop(F.sequence([F.timing(r,{toValue:xm,duration:Sm/2,useNativeDriver:true}),F.timing(r,{toValue:1,duration:Sm/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */H(F.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function Rm(e){let t=e.color,r=e.type.tierSizes.compact.micro;return b.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:xb,height:xb,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:_m},pulse:{position:"absolute",top:Cm,right:Cm,bottom:Cm,left:Cm,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var Tm=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function Im(){let e=globalThis,t=e[Tm];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[Tm]=r,r}function registerEverfurDictation(e){let t=Im();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function zm(){return Im().version??0}function Pm(e){let t=Im(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function Om(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function Em(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function jm(){let e=Im();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||p.OS!=="ios"&&p.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:Em(t())}),e=>typeof e=="object"&&e!==null&&Om(e.box));return r.available&&(e.memo=r.module.box),e.memo}function Fm(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function Am(){try{return Intl.DateTimeFormat().resolvedOptions().locale||Mm}catch{return Mm}}function Dm(e){return e.replace(/_/g,"-").toLowerCase()}var Mm="en-US";function Lm(e=Am()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return Mm;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:Mm}function Bm(e,t){if(t.length===0)return null;let r=e=>t.find(t=>Dm(t)===Dm(e));return r(e)??r(Mm)??t.find(e=>Dm(e).startsWith("en-"))??null}async function Hm(e,t){if(p.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return Bm(t,r??[])??t}catch{return t}}async function Um(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(p.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=Dm(t);return(r??[]).some(e=>Dm(e)===n)?"on_device":"network"}catch{return"network"}}function Nm(){return p.OS!=="android"?true:Number(p.Version)>=$m}var $m=33;function Wm(e,t,r){return{lang:t,interimResults:true,continuous:Nm(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var Vm=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),qm=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Gm(e){return qm.has(e)}var Km=600,Ym=3;function Qm(e,t,r){if(Vm.has(r))return null;let n=Gm(r)?Km:0;return r==="language-not-supported"&&Dm(t)!==Dm(Mm)?{mode:"network",lang:Mm,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Jm(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Xm(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Zm=55e3,ey=3e3,ty=1e3;function ry(e){return ny.has(e)||Gm(e)}var ny=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),ly=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function iy(e){return e.replace(/\s+/g," ").trim()}function oy(e,t,r){let n=iy(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function ay(e){return iy([...e.committed,e.interim].join(" "))}function sy(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,a=e=>i!==null&&i.token===e?i:null;function s(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){s(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&ay(e.transcript)===""&&e.launchedAt-o<ty}function d(e){return e.mode??"none"}function f(e,t){Bg(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){Bg(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(a(e.token)===null)return;u(e);let r=ay(e.transcript),n=e.errorCode;if(n!==null&&!(r&&ry(n))){h(e,Jm(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{a(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),Bg(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(a(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=oy(l.transcript,r,e?.isFinal===true),t.onText(ay(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||Gm(t)))return;let r=ay(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<Ym?Qm(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(a(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){b(l,e.mode);return}s(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(a(l.token)===null||l.userStopped)&&b(l,e.mode)},e.delayMs);return}p(l)}})]}function b(t,r){s(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=ly,t.errorCode=null,g(t);try{e.start(Wm(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function m(t){let r=await Xm(e);if(a(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await Hm(e,t.lang),a(t.token)===null)return;let n=await Um(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Zm),b(t,n))}function y(r){if(!(a(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),ey);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:Lm(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:ly,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),m(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,a=ay(r.transcript);if(u(r),t.onStatus("idle"),!!l){a&&f(r,a),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function uy({enabled:e,input:t,setInput:r,phrases:o,maxLength:c,telemetry:d}){let f=i(Pm,zm,zm),h=a(()=>e?jm():null,[e,f]),p=a(()=>Fm(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=u(t);w.current=t;let S=u(r);S.current=r;let x=u(d);x.current=d;let _=u(""),R=u(c);R.current=c;let T=u(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:sy(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>S.current(Dg(_.current,e,R.current)),onError:e=>{y(e),b("error")}},()=>x.current)});let I=h===null?null:T.current?.controller??null,z=s(()=>{I?.cancel()},[I]),P=s(()=>{if(I!==null){if(I.isActive()){I.stop();return}y(null),k(0),_.current=w.current,I.start(o)}},[I,o]);n(()=>{if(g!=="listening")return;let e=Date.now();k(0);let t=setInterval(()=>k(Date.now()-e),1e3);return()=>clearInterval(t)},[g]),n(()=>{if(g!=="error")return;let e=setTimeout(()=>{y(null),b("idle")},Ag);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=C.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var cy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function dy(){let e=globalThis,t=e[cy];if(t!==void 0)return t;let r=createContext(true);return e[cy]=r,r}var fy=dy();function hy(){return o(fy)}var py=/* @__PURE__ */Object.freeze(["photo"]),gy=52,by=1.5,my=10,yy=14,vy=10,ky=40,wy=20,Cy=.3,Sy=2.5,xy=1,_y=1.5,Ry=38,Ty=22,Iy=3;function zy(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?xf(wf.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):xf(wf.placeholder,t):n==="urgent"?wf.placeholderUrgentWeb:n==="followUp"?wf.placeholderFollowUpWeb:xf(wf.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??sl,transport:r}),l=a(()=>({state:n,sources:e.sources??py,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
|
|
142
|
-
return H(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:c,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:C=false}){let{theme:S,styles:x}=
|
|
143
|
-
return U(w,{style:x.composerOuter,children:[o!==null&&O?/* @__PURE__ */H(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */H(AttachmentStrip,{attachments:X,rejected:M
|
|
142
|
+
/* @__PURE__ */H(StopGlyph,{size:Pm,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */H(MicGlyph,{size:zm,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=u(new F.Value(1)).current;return n(()=>{if(t)return;let e=F.loop(F.sequence([F.timing(r,{toValue:jm,duration:Em/2,useNativeDriver:true}),F.timing(r,{toValue:1,duration:Em/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */H(F.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function Am(e){let t=e.color,r=e.type.tierSizes.compact.micro;return b.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:Db,height:Db,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:Fm},pulse:{position:"absolute",top:Om,right:Om,bottom:Om,left:Om,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var Dm=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function Mm(){let e=globalThis,t=e[Dm];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[Dm]=r,r}function registerEverfurDictation(e){let t=Mm();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function Lm(){return Mm().version??0}function Bm(e){let t=Mm(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function Hm(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function Um(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function Nm(){let e=Mm();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||p.OS!=="ios"&&p.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:Um(t())}),e=>typeof e=="object"&&e!==null&&Hm(e.box));return r.available&&(e.memo=r.module.box),e.memo}function $m(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function Wm(){try{return Intl.DateTimeFormat().resolvedOptions().locale||qm}catch{return qm}}function Vm(e){return e.replace(/_/g,"-").toLowerCase()}var qm="en-US";function Gm(e=Wm()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return qm;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:qm}function Km(e,t){if(t.length===0)return null;let r=e=>t.find(t=>Vm(t)===Vm(e));return r(e)??r(qm)??t.find(e=>Vm(e).startsWith("en-"))??null}async function Ym(e,t){if(p.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return Km(t,r??[])??t}catch{return t}}async function Qm(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(p.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=Vm(t);return(r??[]).some(e=>Vm(e)===n)?"on_device":"network"}catch{return"network"}}function Jm(){return p.OS!=="android"?true:Number(p.Version)>=Xm}var Xm=33;function Zm(e,t,r){return{lang:t,interimResults:true,continuous:Jm(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var ey=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),ty=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function ry(e){return ty.has(e)}var ny=600,ly=3;function iy(e,t,r){if(ey.has(r))return null;let n=ry(r)?ny:0;return r==="language-not-supported"&&Vm(t)!==Vm(qm)?{mode:"network",lang:qm,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function oy(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function ay(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var sy=55e3,uy=3e3,cy=1e3;function dy(e){return fy.has(e)||ry(e)}var fy=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),hy=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function py(e){return e.replace(/\s+/g," ").trim()}function gy(e,t,r){let n=py(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function by(e){return py([...e.committed,e.interim].join(" "))}function my(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,a=e=>i!==null&&i.token===e?i:null;function s(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){s(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&by(e.transcript)===""&&e.launchedAt-o<cy}function d(e){return e.mode??"none"}function f(e,t){Jg(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){Jg(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(a(e.token)===null)return;u(e);let r=by(e.transcript),n=e.errorCode;if(n!==null&&!(r&&dy(n))){h(e,oy(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{a(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),Jg(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(a(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=gy(l.transcript,r,e?.isFinal===true),t.onText(by(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||ry(t)))return;let r=by(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<ly?iy(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(a(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){b(l,e.mode);return}s(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(a(l.token)===null||l.userStopped)&&b(l,e.mode)},e.delayMs);return}p(l)}})]}function b(t,r){s(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=hy,t.errorCode=null,g(t);try{e.start(Zm(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function m(t){let r=await ay(e);if(a(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await Ym(e,t.lang),a(t.token)===null)return;let n=await Qm(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),sy),b(t,n))}function y(r){if(!(a(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),uy);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:Gm(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:hy,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),m(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,a=by(r.transcript);if(u(r),t.onStatus("idle"),!!l){a&&f(r,a),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function yy({enabled:e,input:t,setInput:r,phrases:o,maxLength:c,telemetry:d}){let f=i(Bm,Lm,Lm),h=a(()=>e?Nm():null,[e,f]),p=a(()=>$m(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=u(t);w.current=t;let S=u(r);S.current=r;let x=u(d);x.current=d;let _=u(""),R=u(c);R.current=c;let T=u(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:my(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>S.current(Kg(_.current,e,R.current)),onError:e=>{y(e),b("error")}},()=>x.current)});let I=h===null?null:T.current?.controller??null,z=s(()=>{I?.cancel()},[I]),P=s(()=>{if(I!==null){if(I.isActive()){I.stop();return}y(null),k(0),_.current=w.current,I.start(o)}},[I,o]);n(()=>{if(g!=="listening")return;let e=Date.now();k(0);let t=setInterval(()=>k(Date.now()-e),1e3);return()=>clearInterval(t)},[g]),n(()=>{if(g!=="error")return;let e=setTimeout(()=>{y(null),b("idle")},Gg);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=C.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var vy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function ky(){let e=globalThis,t=e[vy];if(t!==void 0)return t;let r=createContext(true);return e[vy]=r,r}var wy=ky();function Cy(){return o(wy)}var Sy=/* @__PURE__ */Object.freeze(["photo"]),xy=52,_y=1.5,Ry=10,Ty=14,Iy=10,zy=40,Py=20,Oy=.3,Ey=2.5,jy=1,Fy=1.5,Ay=38,Dy=22,My=3;function Ly(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?Of(If.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):Of(If.placeholder,t):n==="urgent"?If.placeholderUrgentWeb:n==="followUp"?If.placeholderFollowUpWeb:Of(If.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??fl,transport:r}),l=a(()=>({state:n,sources:e.sources??Sy,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
|
|
143
|
+
return H(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:c,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:C=false}){let{theme:S,styles:x}=Tm(),_=a(()=>Wy(S),[S]),T=a(()=>Vy(S),[S]),I=hg(),[z,P]=eb(e,i,c),[O,E]=l(false),[j,F]=l(false),A=s(()=>F(true),[]),D=s(()=>F(false),[]),[M,L]=l(false);n(()=>{L(false)},[i]);let B=Ly(S.meta.placeholder,p,k,b,S.meta.placeholderFillsPet===true),$=a(()=>Zg({name:p,breed:g}),[p,g]),W=yy({enabled:m,input:z,setInput:P,phrases:$,maxLength:Wn,telemetry:y}),V=W.cancel,q=W.active;tb(d,i===null?null:String(i),z,P,q);let G=u(i);n(()=>{G.current!==i&&(G.current=i,V())},[i,V]);let K=Cy();n(()=>{K||V()},[K,V]);let Y=o?.state.uploading??false,Q=o?.state.failed??false,J=Y||Q,X=o?.state.attachments??By;Pg(X.length,I);let Z=s(()=>{let t=z.trim();if(t.length===0||J||[...t].length>Wn)return;q&&V();let r=o?.state.s3Keys??Hy;o!==null&&r.length>0?(f(o.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),o.state.clear()):e(t),P(""),L(false)},[z,e,J,q,V,o,f]),ee=s(e=>{q&&V(),P(e)},[q,V,P]),te=s(()=>{t()},[t]),re=s(e=>{E(false),o!==null&&(L(false),o.state.dismissRejected(),Ch(o.pick,e).then(e=>{if(!e.ok){L(true);return}e.value!==null&&o.state.add(e.value)}))},[o]),ne=a(()=>[...z.trim()].length>Wn,[z]),le=ne||J||z.trim().length===0,ie=ne||J||C&&z.trim().length===0,oe=o!==null&&X.length>=o.state.maxPerMessage,ae=S.slots.sendButton?.textColor??S.color.brandInk,se=S.slots.sendButton?.textColor??S.color.surface;/* @__PURE__ */
|
|
144
|
+
return U(w,{style:x.composerOuter,children:[o!==null&&O?/* @__PURE__ */H(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */H(AttachmentStrip,{attachments:X,rejected:M?$y:o.state.rejected,uploadFailed:Q,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:e=>h({uri:e.previewUri,label:e.filename}),style:v?_.tray:T.tray}):null,
|
|
144
145
|
/* @__PURE__ */U(w,{style:v?[x.composer,_.bar,j?_.barFocused:null]:x.composer,children:[W.supported&&W.error!==null?/* @__PURE__ */U(N,{children:[
|
|
145
|
-
/* @__PURE__ */H(Text,{style:x.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:
|
|
146
|
-
/* @__PURE__ */H(AnnounceLine,{line:
|
|
147
|
-
/* @__PURE__ */U(w,{style:x.composerRow,children:[o!==null?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:oe?
|
|
148
|
-
/* @__PURE__ */H(Zd,{style:v?[x.input,_.input]:x.input,onFocus:A,onBlur:D,value:z,onChangeText:ee,placeholder:B,placeholderTextColor:S.slots.composerInput?.textColor??S.color.text.placeholder,accessibilityLabel:wf.composerLabel,onSubmitEditing:Z,returnKeyType:"send",...Ey,...v?jy:null,blurOnSubmit:false,multiline:true,editable:true}),W.supported?/* @__PURE__ */H(DictationButton,{active:W.active,listening:W.status==="listening",elapsedMs:W.elapsedMs,onToggle:W.toggle}):null,r?/* @__PURE__ */H(R,{onPress:te,accessibilityRole:"button",accessibilityLabel:wf.stop,style:x.sendControl,children:/* @__PURE__ */H(w,{style:v?_.disc:x.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */H(StopGlyph,{size:v?wy:$b,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */H(R,{onPress:Z,disabled:le,accessibilityRole:"button",accessibilityLabel:wf.send,accessibilityState:{disabled:le,busy:Y},style:[x.sendControl,ie?v?_.dimmed:x.sendControlDisabled:null],children:v?/* @__PURE__ */H(w,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */H(ArrowUpGlyph,{size:wy,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */H(w,{style:x.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */H(SendGlyph,{size:Nb,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var Py=/* @__PURE__ */Object.freeze([]),Oy=/* @__PURE__ */Object.freeze([]),Ey=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),jy=/* @__PURE__ */Object.freeze(p.OS==="web"?{rows:1}:{}),Fy=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function Ay(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+xy;return b.create({bar:{marginTop:my,marginHorizontal:yy,marginBottom:vy,minHeight:gy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:by,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Sy,paddingLeft:8-(Sy-by),paddingRight:6-(Sy-by)},input:{fontSize:n,lineHeight:Math.round(n*_y),minHeight:Math.round(n*_y),...p.OS==="web"?{outlineStyle:"none"}:null},add:{width:Ry,height:Ry,borderRadius:Ry/2},disc:{width:ky,height:ky,borderRadius:ky/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...zg(r)},dimmed:{opacity:Cy},tray:{marginHorizontal:yy,marginTop:my,paddingBottom:0}})}function Dy(e){return b.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=ud(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[c,d]=l({repository:o,pets:[],loading:true,error:null}),f=c.repository===o?c:{pets:[],loading:true,error:null},h=u(0),p=s(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>Di(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function My(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Ly=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var By=false;function Hy(e,t){return t!==void 0?(fh(t,e),"onStartInApp"):uf(e)==="presented"?"presenter":hf(e)?"experience":(By||(By=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Uy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&Uy.includes(e)}var Ny="/widget/v1/televet/handoffs",$y="/widget/v1/televet/availability",Wy="/widget/v1/televet/chat-entry",Vy=/^[a-z0-9][a-z0-9_-]{0,39}$/,qy=/^[A-Za-z0-9_-]{22}$/;var Gy=32,Ky=128,Yy=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function Qy(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Jy(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Xy(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Vy.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>Yy)return{ok:false,message:`visitRef must be 1..${Yy} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${Uy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Zy(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function ev(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(ov(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>Ky)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Ky} characters`}));i=e}let o=Xy(i,l);if(!o.ok){let e=Qy(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:Ny,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=tv(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!qy.test(d))){let e=Jy("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,h=f?Zy(s.value?.visit):null;if(f&&h===null){let e=Jy("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(ov(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Gy)return Qy(`state must be at most ${Gy} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:$y,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Jy("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:Wy},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function tv(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!iv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var rv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),nv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,lv=/[\s\u0000-\u001f\u007f]/;function iv(e){if(lv.test(e))return false;let t=nv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&rv.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function ov(e,t,r){if(e)try{e.track(t,r)}catch{}}var av=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function sv(e,t,r){let{usState:i,chat:o,scope:a}=r,s=t&&(i!==null||o),u=`${i??""}|${o?"chat":""}`,[c,d]=l(null);if(n(()=>{if(!s)return;let t=true,r=e.current;return d(null),(async()=>{try{if(o&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&d({key:u,open:e})}),()=>{t=false}},[s,u,i,o,a,e]),!s)return null;let f=c!==null&&c.key===u;return{open:f&&c.open,pending:!f}}var uv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function cv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=ud(),o=useCapability("televet"),c=o.enabled&&n!==null,d=t.usState??null,f=t.entry==="chat",h=t.petRef??null,p=t.prefer==="redirect",g=a(()=>{if(t.controller)return t.controller;let{services:e}=r.registry;return ev({auth:e.authFor(n),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[r,n,i,t.controller]),b=u(g);b.current=g;let m=a(()=>({runtime:r,userRef:n,scopeEpoch:i}),[r,n,i]),y=sv(b,c,{usState:d,chat:f,scope:m}),v=c&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(av),S=u(null),x=u({runtime:r,userRef:n,scopeEpoch:i});x.current={runtime:r,userRef:n,scopeEpoch:i};let _=u(g);_.current=g;let R=u(v);R.current=v;let T=s((t,r)=>{if(S.current)return S.current;let n=(e,t)=>(C({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!R.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=x.current,o=_.current;C(uv);let a=(async()=>{let a,s={...k!==null?{returnTo:k}:{},...f?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},u=Object.keys(s).length===0?void 0:s,c=t===void 0?h:t;try{a=await(u===void 0?o.createHandoff(c):o.createHandoff(c,u))}catch{return e.abandon(l.value),n("unknown",null)}let d=x.current;if(d.runtime!==i.runtime||d.userRef!==i.userRef||d.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!a.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let p=await e.finish(l.value,a.value);return p!==null?n(p,null):(C(av),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{S.current===a&&(S.current=null)});return S.current=a,a},[e,h,k,f]),I=s((e,t)=>{if(!R.current)return C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?h:e,n={...r!==null?{petRef:r}:{},...d!==null?{usState:d}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return Hy(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(av),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[h,d]),z=s(e=>p?T(e,null):I(e,null),[p,T,I]),P=s((e,t)=>p?T(void 0,{visitRef:e,intent:t??null}):I(void 0,{visitRef:e,intent:t??null}),[p,T,I]),O=s(e=>p?T(void 0,null):I(void 0,{consultId:e.trim()}),[p,T,I]);return{available:v,isPending:o.isPending||(y?.pending??false),status:w.status,error:w.error,errorReason:w.errorReason,open:z,openVisit:P,joinVisit:O}}var dv=e=>x.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??dv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return cv(n,r)}var fv=44,hv=.6;function VetVisitButtonCore(e){let{petRef:t,label:r,openUrl:n,onOpened:l,onError:i,style:o,labelStyle:s,controller:c,returnTo:d,usState:f,entry:h,visitRef:p,intent:g,onStartInApp:b,prefer:m}=e,y=m==="redirect",v=useVetVisit({...d!==void 0?{returnTo:d}:{},...f!==void 0?{usState:f}:{},...h!==void 0?{entry:h}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...c!==void 0?{controller:c}:{},prefer:y?"redirect":"in-app"}),k=useEverfurTheme(),w=a(()=>pv(k),[k]),C=u(false);if(!v.available)/* @__PURE__ */
|
|
146
|
+
/* @__PURE__ */H(Text,{style:x.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:Qg(W.error)}),
|
|
147
|
+
/* @__PURE__ */H(AnnounceLine,{line:Qg(W.error)})]}):null,
|
|
148
|
+
/* @__PURE__ */U(w,{style:x.composerRow,children:[o!==null?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:oe?Vg(X.length,o.state.maxPerMessage):If.attachPhotoOrFileNative,accessibilityState:{disabled:oe,expanded:O},disabled:oe,style:[x.attachControl,v?_.add:null,oe?x.attachControlDisabled:null],hitSlop:v?My:void 0,onPress:()=>E(e=>!e),children:/* @__PURE__ */H(UploadGlyph,{size:v?Dy:lm,color:oe?S.color.text.muted:v?S.color.text.primary:S.color.brandInk,strokeWidth:1.75})}):null,
|
|
149
|
+
/* @__PURE__ */H(af,{style:v?[x.input,_.input]:x.input,onFocus:A,onBlur:D,value:z,onChangeText:ee,placeholder:B,placeholderTextColor:S.slots.composerInput?.textColor??S.color.text.placeholder,accessibilityLabel:If.composerLabel,onSubmitEditing:Z,returnKeyType:"send",...Uy,...v?Ny:null,blurOnSubmit:false,multiline:true,editable:true}),W.supported?/* @__PURE__ */H(DictationButton,{active:W.active,listening:W.status==="listening",elapsedMs:W.elapsedMs,onToggle:W.toggle}):null,r?/* @__PURE__ */H(R,{onPress:te,accessibilityRole:"button",accessibilityLabel:If.stop,style:x.sendControl,children:/* @__PURE__ */H(w,{style:v?_.disc:x.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */H(StopGlyph,{size:v?Py:tm,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */H(R,{onPress:Z,disabled:le,accessibilityRole:"button",accessibilityLabel:If.send,accessibilityState:{disabled:le,busy:Y},style:[x.sendControl,ie?v?_.dimmed:x.sendControlDisabled:null],children:v?/* @__PURE__ */H(w,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */H(ArrowUpGlyph,{size:Py,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */H(w,{style:x.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */H(SendGlyph,{size:em,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var By=/* @__PURE__ */Object.freeze([]),Hy=/* @__PURE__ */Object.freeze([]),Uy=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),Ny=/* @__PURE__ */Object.freeze(p.OS==="web"?{rows:1}:{}),$y=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function Wy(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+jy;return b.create({bar:{marginTop:Ry,marginHorizontal:Ty,marginBottom:Iy,minHeight:xy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:_y,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Ey,paddingLeft:8-(Ey-_y),paddingRight:6-(Ey-_y)},input:{fontSize:n,lineHeight:Math.round(n*Fy),minHeight:Math.round(n*Fy),...p.OS==="web"?{outlineStyle:"none"}:null},add:{width:Ay,height:Ay,borderRadius:Ay/2},disc:{width:zy,height:zy,borderRadius:zy/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...Ug(r)},dimmed:{opacity:Oy},tray:{marginHorizontal:Ty,marginTop:Ry,paddingBottom:0}})}function Vy(e){return b.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=bd(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[c,d]=l({repository:o,pets:[],loading:true,error:null}),f=c.repository===o?c:{pets:[],loading:true,error:null},h=u(0),p=s(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>Hi(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function qy(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Gy=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var Ky=false;function Yy(e,t){return t!==void 0?(vh(t,e),"onStartInApp"):bf(e)==="presented"?"presenter":kf(e)?"experience":(Ky||(Ky=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Qy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&Qy.includes(e)}var Jy="/widget/v1/televet/handoffs",Xy="/widget/v1/televet/availability",Zy="/widget/v1/televet/chat-entry",ev=/^[a-z0-9][a-z0-9_-]{0,39}$/,tv=/^[A-Za-z0-9_-]{22}$/;var rv=32,nv=128,lv=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function iv(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function ov(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function av(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!ev.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>lv)return{ok:false,message:`visitRef must be 1..${lv} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${Qy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function sv(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function uv(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(gv(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>nv)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${nv} characters`}));i=e}let o=av(i,l);if(!o.ok){let e=iv(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:Jy,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=cv(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!tv.test(d))){let e=ov("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,h=f?sv(s.value?.visit):null;if(f&&h===null){let e=ov("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(gv(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>rv)return iv(`state must be at most ${rv} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:Xy,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?ov("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:Zy},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function cv(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!pv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var dv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),fv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,hv=/[\s\u0000-\u001f\u007f]/;function pv(e){if(hv.test(e))return false;let t=fv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&dv.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function gv(e,t,r){if(e)try{e.track(t,r)}catch{}}var bv=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function mv(e,t,r){let{usState:i,chat:o,scope:a}=r,s=t&&(i!==null||o),u=`${i??""}|${o?"chat":""}`,[c,d]=l(null);if(n(()=>{if(!s)return;let t=true,r=e.current;return d(null),(async()=>{try{if(o&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&d({key:u,open:e})}),()=>{t=false}},[s,u,i,o,a,e]),!s)return null;let f=c!==null&&c.key===u;return{open:f&&c.open,pending:!f}}var yv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function vv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=bd(),o=useCapability("televet"),c=o.enabled&&n!==null,d=t.usState??null,f=t.entry==="chat",h=t.petRef??null,p=t.prefer==="redirect",g=a(()=>{if(t.controller)return t.controller;let{services:e}=r.registry;return uv({auth:e.authFor(n),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[r,n,i,t.controller]),b=u(g);b.current=g;let m=a(()=>({runtime:r,userRef:n,scopeEpoch:i}),[r,n,i]),y=mv(b,c,{usState:d,chat:f,scope:m}),v=c&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(bv),S=u(null),x=u({runtime:r,userRef:n,scopeEpoch:i});x.current={runtime:r,userRef:n,scopeEpoch:i};let _=u(g);_.current=g;let R=u(v);R.current=v;let T=s((t,r)=>{if(S.current)return S.current;let n=(e,t)=>(C({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!R.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=x.current,o=_.current;C(yv);let a=(async()=>{let a,s={...k!==null?{returnTo:k}:{},...f?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},u=Object.keys(s).length===0?void 0:s,c=t===void 0?h:t;try{a=await(u===void 0?o.createHandoff(c):o.createHandoff(c,u))}catch{return e.abandon(l.value),n("unknown",null)}let d=x.current;if(d.runtime!==i.runtime||d.userRef!==i.userRef||d.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!a.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let p=await e.finish(l.value,a.value);return p!==null?n(p,null):(C(bv),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{S.current===a&&(S.current=null)});return S.current=a,a},[e,h,k,f]),I=s((e,t)=>{if(!R.current)return C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?h:e,n={...r!==null?{petRef:r}:{},...d!==null?{usState:d}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return Yy(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(bv),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[h,d]),z=s(e=>p?T(e,null):I(e,null),[p,T,I]),P=s((e,t)=>p?T(void 0,{visitRef:e,intent:t??null}):I(void 0,{visitRef:e,intent:t??null}),[p,T,I]),O=s(e=>p?T(void 0,null):I(void 0,{consultId:e.trim()}),[p,T,I]);return{available:v,isPending:o.isPending||(y?.pending??false),status:w.status,error:w.error,errorReason:w.errorReason,open:z,openVisit:P,joinVisit:O}}var kv=e=>x.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??kv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return vv(n,r)}var wv=44,Cv=.6;function VetVisitButtonCore(e){let{petRef:t,label:r,openUrl:n,onOpened:l,onError:i,style:o,labelStyle:s,controller:c,returnTo:d,usState:f,entry:h,visitRef:p,intent:g,onStartInApp:b,prefer:m}=e,y=m==="redirect",v=useVetVisit({...d!==void 0?{returnTo:d}:{},...f!==void 0?{usState:f}:{},...h!==void 0?{entry:h}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...c!==void 0?{controller:c}:{},prefer:y?"redirect":"in-app"}),k=useEverfurTheme(),w=a(()=>Sv(k),[k]),C=u(false);if(!v.available)/* @__PURE__ */
|
|
149
150
|
return U(N,{children:[null,
|
|
150
|
-
/* @__PURE__ */H(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??
|
|
151
|
+
/* @__PURE__ */H(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??Gy.visitButton;/* @__PURE__ */
|
|
151
152
|
return U(N,{children:[
|
|
152
|
-
/* @__PURE__ */H(R,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}};
|
|
153
|
-
/* @__PURE__ */H(TelevetHostOutlet,{})]})}function
|
|
154
|
-
return H(O,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=
|
|
153
|
+
/* @__PURE__ */H(R,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}};Yy(e,b)===null&&vh(i,"unavailable",null);return}C.current=true,(p==null?v.open():v.openVisit(p,g??null)).then(e=>{e.opened?vh(l,e.flowId??null):e.reason!=="cancelled"&&vh(i,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:x,accessibilityState:{busy:S,disabled:S},style:[w.button,S?w.busy:null,o],children:/* @__PURE__ */H(Text,{style:[w.label,s],children:x})}),
|
|
154
|
+
/* @__PURE__ */H(TelevetHostOutlet,{})]})}function Sv(e){let{color:t,space:r,radius:n,type:l,slots:i}=e;return b.create({button:{minHeight:wv,minWidth:wv,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...Ug(i.vetVisitButton)},busy:{opacity:Cv},label:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.snug,...$g(i.vetVisitButton)}})}function xv(e){let[t,r]=l(null);return{shown:e!==null&&t!==e,onError:()=>r(e)}}function BrandImage({uri:e,label:t,decorative:r=false,style:n,resizeMode:l="contain",fallback:i=null,onError:o,testID:a}){let s=xv(e);if(e===null||!s.shown)return i;let u=r?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...t===void 0?{}:{accessibilityLabel:t}};/* @__PURE__ */
|
|
155
|
+
return H(O,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=xv(e);return e===null||!i.shown?null:/* @__PURE__ */H(w,{style:r,...l===void 0?{}:{testID:l},children:/* @__PURE__ */H(O,{source:{uri:e},style:n,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:i.onError})})}var _v=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),Rv=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function Tv(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return Rv;let n=Math.abs(e.leading-e.trailing);if(n<.5)return Rv;let l=e.row-t-e.leading-e.trailing,i=Math.min(n,Math.max(0,l-r));return i<.5?Rv:e.leading<e.trailing?{leading:e.leading+i,trailing:void 0}:{leading:void 0,trailing:e.trailing+i}}function Iv(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function zv(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function Pv(e){if(e.brightness!=="light")return false;let t=ia.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),l=new Set(zv(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&zv(r).every(e=>l.has(e))}function Ov(e){let t=(e.brightness==="dark"?aa:ia).color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t);return{success:!n(r.success,t.success),warning:!n(r.warningStrong,t.warningStrong)||!n(r.cautionAccent,t.cautionAccent),info:!(n(r.info,r.brandInk)&&n(r.badgeBgInfo,r.brandSoft)&&n(r.infoEdge,r.structureEdge))}}function Ev(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function jv(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function Fv(e){let t=jv(e.ageYears),r=Ev(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var Av=/* @__PURE__ */Object.freeze([
|
|
155
156
|
/* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
|
|
156
157
|
/* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
|
|
157
158
|
/* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
|
|
158
159
|
/* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
|
|
159
160
|
/* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
|
|
160
|
-
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function
|
|
161
|
-
return H(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */H(w,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */H(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?
|
|
162
|
-
/* @__PURE__ */H(R,{style:
|
|
161
|
+
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function Dv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Av[t%Av.length]}function Mv(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function Lv(e){return{...Dv(e.petRef),initial:Mv(e.name)}}function Bv(e,t,r){let n=Lv(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function Hv(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:t,ringStroke:r}){let n=useEverfurTheme(),l=a(()=>Uv(n),[n]),i=t-r*2,o=e===null?null:Bv(e,Pv(n),{fill:n.color.highlight,ink:n.color.onHighlight}),s=Hv(i);/* @__PURE__ */
|
|
162
|
+
return H(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */H(w,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */H(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?Mv(null):o.initial})})})}function Uv(e){return b.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function Nv(e,t){let{borderRadius:r,...n}=Ug(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function $v(e,t){let{backgroundColor:r,borderColor:n,borderWidth:l,borderRadius:i}=Ug(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:l??1},...i===void 0?{}:{borderTopRightRadius:i,borderBottomRightRadius:i}}}var Wv=48,Vv=2,qv=320,Gv="80%",Kv="rgba(17,17,17,0.45)",Yv=18,Qv=22,Jv=12,Xv=.4,Zv=44;function ek(e){return e?.name?.trim()||If.yourPet}function PetSwitcherSheet({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:l=null,onClose:i}){let o=useEverfurTheme(),s=a(()=>tk(o),[o]);return e?/* @__PURE__ */H(I,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"fade",onRequestClose:i,children:/* @__PURE__ */U(w,{style:s.root,children:[
|
|
163
|
+
/* @__PURE__ */H(R,{style:fb,onPress:i,accessibilityRole:"button",accessibilityLabel:If.close,children:/* @__PURE__ */H(w,{style:s.backdrop})}),
|
|
163
164
|
/* @__PURE__ */U(w,{style:s.panel,accessibilityViewIsModal:true,children:[
|
|
164
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:
|
|
165
|
-
/* @__PURE__ */H(z,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=
|
|
166
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
167
|
-
/* @__PURE__ */H(PetDisc,{pet:e,size:
|
|
165
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:If.yourPets}),
|
|
166
|
+
/* @__PURE__ */H(z,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=ek(e),i=Fv(e);/* @__PURE__ */
|
|
167
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:zf(t?If.petCurrentlyActive:If.switchToPet,{name:l}),accessibilityState:{selected:t},style:[s.row,t?s.rowActive:null],onPress:()=>n(e.petRef),children:[
|
|
168
|
+
/* @__PURE__ */H(PetDisc,{pet:e,size:Wv,ringStroke:Vv}),
|
|
168
169
|
/* @__PURE__ */U(w,{style:s.copy,children:[
|
|
169
170
|
/* @__PURE__ */H(Text,{style:s.name,numberOfLines:1,children:l}),
|
|
170
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${
|
|
171
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${If.activePrefix}${i}`:i})]}),t?/* @__PURE__ */H(CheckGlyph,{size:Yv,color:o.color.brandInk}):null]},e.petRef)})}),l!==null?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:If.addAnotherPet,style:s.addRow,onPress:l,children:[
|
|
171
172
|
/* @__PURE__ */H(w,{style:s.addDisc,children:/* @__PURE__ */H(Text,{tier:"control",style:s.addPlus,children:"+"})}),
|
|
172
|
-
/* @__PURE__ */H(Text,{style:s.addLabel,children:
|
|
173
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
173
|
+
/* @__PURE__ */H(Text,{style:s.addLabel,children:If.addAnotherPet})]}):null,
|
|
174
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:If.close,containerStyle:s.closeSlot,style:s.closeButton,onPress:i,children:/* @__PURE__ */H(Text,{tier:"control",style:s.closeText,children:If.close})})]})]})}):null}function tk(e){let t=e.color,r=e.radius,n=$g(e.slots.dialog);return b.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:Kv},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Qv,borderTopRightRadius:Qv,gap:14,maxHeight:Gv,...Nv(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...n},list:{maxHeight:qv,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:Zv,paddingHorizontal:8},addDisc:{width:Wv,height:Wv,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Vv,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...face(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...face(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary,...n},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...face(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...face(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Xv},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:Jv,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Xv}})}var rk=44,nk=36,lk=22,ik=20,ak=9,sk=1.5,uk=6,ck=35,dk=1.75,fk=12.4,hk=.5,pk=8,gk=28,bk=160,mk=16,yk=8;function vk(e,t){return qy(e,t)}function ChatHeader({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onNewChat:i,onPetChange:o,onAddPet:u,vet:c,textingEntry:d=null}){let f=useEverfurTheme(),h=a(()=>kk(f),[f]),[p,g]=l(false),b=vk(e.pets,t),m=b!==null&&(e.pets.length>=2||u!==void 0),y=t??b?.petRef??null,v=ek(b),[k,C]=l(_v),S=s(e=>t=>{let r=t.nativeEvent.layout.width;C(t=>Iv(t,e,r))},[]),x=a(()=>S("row"),[S]),_=a(()=>S("leading"),[S]),R=a(()=>S("trailing"),[S]),T=2*mk+2*(f.slots.header?.borderColor!==void 0?1:0)+2*yk,I=Tv(k,T,bk),z=t=>{g(false),e.setActivePet(t),vh(o,t)},P=u===void 0?null:()=>{g(false),vh(u)};/* @__PURE__ */
|
|
174
175
|
return U(N,{children:[
|
|
175
176
|
/* @__PURE__ */U(w,{style:h.row,onLayout:x,children:[
|
|
176
|
-
/* @__PURE__ */H(w,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */U(w,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
177
|
-
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${
|
|
178
|
-
/* @__PURE__ */H(MenuGlyph,{size:
|
|
177
|
+
/* @__PURE__ */H(w,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */U(w,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Pp.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:i,children:/* @__PURE__ */H(EditGlyph,{size:ik,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
|
|
178
|
+
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${If.openHistoryNative}${If.newReplySuffix}`:If.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:n,children:[
|
|
179
|
+
/* @__PURE__ */H(MenuGlyph,{size:lk,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),r?/* @__PURE__ */H(w,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
|
|
179
180
|
/* @__PURE__ */H(w,{style:h.centre,pointerEvents:"box-none",children:/* @__PURE__ */H(BrandLogo,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,barStyle:h.logoBar,logoStyle:h.logo})}),
|
|
180
181
|
/* @__PURE__ */H(w,{style:[h.trailing,I.trailing===void 0?null:{minWidth:I.trailing}],children:/* @__PURE__ */U(w,{style:h.trailingContent,onLayout:R,children:[y===null?null:/* @__PURE__ */H(VetVisitButtonCore,{entry:"chat",petRef:y,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:h.vetEntry,labelStyle:h.vetEntryLabel}),
|
|
181
|
-
/* @__PURE__ */H(w,{style:h.right,children:m?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
182
|
-
/* @__PURE__ */H(PetDisc,{pet:b,size:
|
|
183
|
-
/* @__PURE__ */H(w,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */H(PlusGlyph,{size:
|
|
184
|
-
/* @__PURE__ */H(w,{style:h.avatarWrap,accessible:true,accessibilityLabel:
|
|
185
|
-
/* @__PURE__ */H(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */H(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>
|
|
186
|
-
return H(w,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */H(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function
|
|
187
|
-
/* @__PURE__ */Object.freeze({key:"inaccurate",label:
|
|
188
|
-
/* @__PURE__ */Object.freeze({key:"outdated",label:
|
|
189
|
-
/* @__PURE__ */Object.freeze({key:"unsafe",label:
|
|
190
|
-
/* @__PURE__ */Object.freeze({key:"unclear",label:
|
|
191
|
-
/* @__PURE__ */Object.freeze({key:"other",label:
|
|
192
|
-
/* @__PURE__ */Object.freeze({sentiment:"up",label:
|
|
193
|
-
/* @__PURE__ */Object.freeze({sentiment:"down",label:
|
|
182
|
+
/* @__PURE__ */H(w,{style:h.right,children:m?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:zf(If.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
|
|
183
|
+
/* @__PURE__ */H(PetDisc,{pet:b,size:ck,ringStroke:dk}),
|
|
184
|
+
/* @__PURE__ */H(w,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */H(PlusGlyph,{size:pk,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&b===null?
|
|
185
|
+
/* @__PURE__ */H(w,{style:h.avatarWrap,accessible:true,accessibilityLabel:If.yourPet,children:/* @__PURE__ */H(Ring,{size:ck,strokeWidth:dk,color:f.color.mark,children:/* @__PURE__ */H(w,{style:h.placeholderDisc})})}):/* @__PURE__ */H(w,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:b===null?If.yourPet:v,children:/* @__PURE__ */H(PetDisc,{pet:b,size:ck,ringStroke:dk})})})]})}),
|
|
186
|
+
/* @__PURE__ */H(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */H(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>kk(r),[r]);/* @__PURE__ */
|
|
187
|
+
return H(w,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */H(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function kk(e){let t=e.color,r=ck-dk*2,n=e.slots.header;return b.create({vetEntry:{minHeight:rk,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:b.hairlineWidth,borderColor:t.controlEdge},vetEntryLabel:{...face(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},textingEntrySlot:{borderRadius:e.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:mk,paddingBottom:10,backgroundColor:n?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:mk,paddingTop:e.space.sm},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:mk,paddingVertical:10,backgroundColor:t.surface,...Ug(n)},iconSlot:{borderRadius:nk/2},iconButton:{width:nk,height:nk,borderRadius:nk/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:uk,right:uk,width:ak,height:ak,borderRadius:ak,backgroundColor:t.danger,borderWidth:sk,borderColor:n?.backgroundColor??t.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:e.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:yk,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:gk,width:bk,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:ck/2},avatarWrap:{width:ck,height:ck,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:fk,height:fk,borderRadius:fk/2,borderWidth:hk,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var wk=/* @__PURE__ */Object.freeze([
|
|
188
|
+
/* @__PURE__ */Object.freeze({key:"inaccurate",label:If.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
189
|
+
/* @__PURE__ */Object.freeze({key:"outdated",label:If.feedbackReasonOutdated,feedbackType:"outdated"}),
|
|
190
|
+
/* @__PURE__ */Object.freeze({key:"unsafe",label:If.feedbackReasonUnsafe,feedbackType:"dangerous"}),
|
|
191
|
+
/* @__PURE__ */Object.freeze({key:"unclear",label:If.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
192
|
+
/* @__PURE__ */Object.freeze({key:"other",label:If.feedbackReasonOther,feedbackType:"not_helpful"})]),Ck=/* @__PURE__ */Object.freeze([
|
|
193
|
+
/* @__PURE__ */Object.freeze({sentiment:"up",label:If.feedbackHelpful}),
|
|
194
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:If.feedbackNotHelpful})]);function Sk(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function xk(e,t){if(e==="down"&&t!==null){let e=wk.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return Sk(e)}var _k=44,Rk="rgba(17,17,17,0.55)",Tk=26,Ik=36,zk=4,Pk=20,Ok=38,Ek=18,jk=12;function FeedbackReasons({visible:e,onSubmit:t,onSkip:r}){let n=useEverfurTheme(),i=a(()=>Fk(n),[n]),[o,s]=l(null),[u,c]=l(""),[d,f]=l(false),[h,g]=l(false),b=()=>{s(null),c(""),f(false),g(false)},m=()=>{d||(b(),r())},y=async()=>{if(d)return;f(true),g(false);let e=u.trim();await t(o,e.length>0?e:null)?b():(f(false),g(true))};if(!e)return null;let v=[...u].length>$n;/* @__PURE__ */
|
|
194
195
|
return H(I,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:m,children:/* @__PURE__ */U(_,{behavior:p.OS==="ios"?"padding":void 0,style:i.root,children:[
|
|
195
|
-
/* @__PURE__ */H(R,{style:i.scrim,onPress:m,accessibilityRole:"button",accessibilityLabel:
|
|
196
|
+
/* @__PURE__ */H(R,{style:i.scrim,onPress:m,accessibilityRole:"button",accessibilityLabel:If.feedbackSkipA11y}),
|
|
196
197
|
/* @__PURE__ */U(w,{style:i.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
|
|
197
198
|
/* @__PURE__ */H(w,{style:i.handle}),
|
|
198
199
|
/* @__PURE__ */U(w,{style:i.header,children:[
|
|
199
|
-
/* @__PURE__ */H(w,{style:i.iconBadge,children:/* @__PURE__ */H(ThumbGlyph,{size:
|
|
200
|
+
/* @__PURE__ */H(w,{style:i.iconBadge,children:/* @__PURE__ */H(ThumbGlyph,{size:Ek,color:n.color.brandInk,active:false,rotate:"180deg"})}),
|
|
200
201
|
/* @__PURE__ */U(w,{style:i.headerText,children:[
|
|
201
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:
|
|
202
|
-
/* @__PURE__ */H(Text,{style:i.subtitle,children:
|
|
203
|
-
/* @__PURE__ */H(w,{style:i.options,children:
|
|
202
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:If.feedbackTitle}),
|
|
203
|
+
/* @__PURE__ */H(Text,{style:i.subtitle,children:If.feedbackSubtitle})]})]}),
|
|
204
|
+
/* @__PURE__ */H(w,{style:i.options,children:wk.map(e=>{let t=o===e.key;/* @__PURE__ */
|
|
204
205
|
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[i.option,t?i.optionSelected:null],onPress:()=>s(t=>t===e.key?null:e.key),children:[
|
|
205
206
|
/* @__PURE__ */H(Text,{style:[i.optionLabel,t?i.optionLabelSelected:null],children:e.label}),
|
|
206
|
-
/* @__PURE__ */H(w,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */H(CheckGlyph,{size:
|
|
207
|
+
/* @__PURE__ */H(w,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */H(CheckGlyph,{size:jk,color:n.color.surface,strokeWidth:2}):null})]},e.key)})}),
|
|
207
208
|
/* @__PURE__ */U(w,{style:i.inputWrap,children:[
|
|
208
|
-
/* @__PURE__ */H(
|
|
209
|
+
/* @__PURE__ */H(af,{style:i.input,placeholder:If.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:If.feedbackNotesPlaceholder,value:u,onChangeText:c,multiline:true,editable:!d}),u.length>0?/* @__PURE__ */H(Text,{tier:"compact",style:[i.counter,v?i.counterOver:null],children:`${[...u].length}/${$n}`}):null]}),h?/* @__PURE__ */H(Text,{style:i.failed,accessibilityRole:"alert",children:If.feedbackFailed}):null,
|
|
209
210
|
/* @__PURE__ */U(w,{style:i.actions,children:[
|
|
210
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
211
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
211
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:If.feedbackSubmit,accessibilityState:{busy:d,disabled:d||v},disabled:d||v,style:[i.submit,d||v?i.submitDisabled:null],onPress:()=>{y()},children:/* @__PURE__ */H(Text,{tier:"control",style:i.submitLabel,children:If.feedbackSubmit})}),
|
|
212
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:If.feedbackSkipA11y,hitSlop:8,onPress:m,style:i.skip,children:/* @__PURE__ */H(Text,{tier:"control",style:i.skipLabel,children:If.feedbackSkip})})]})]})]})})}function Fk(e){let t=e.color,r=e.type,n=e.radius,l=e.slots,i=$g(l.dialog);return b.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...fb,backgroundColor:Rk},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Tk,borderTopRightRadius:Tk,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...Nv(l.dialog)},handle:{alignSelf:"center",width:Ik,height:zk,borderRadius:zk/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Ok,height:Ok,borderRadius:Ok/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight,...i},subtitle:{...face(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted,...i},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:b.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...Ug(l.chip,b.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.primary,...$g(l.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:Pk,height:Pk,borderRadius:Pk/2,borderWidth:2,borderColor:t.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top",...Ug(l.input,1),...$g(l.input)},counter:{...face(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:_k,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...Ug(l.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...$g(l.primaryButton)},skip:{minHeight:_k,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}var Ak=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function Dk(){let e=globalThis,t=e[Ak];if(t!==void 0)return t;let r={factory:createContext(null),home:createContext(null)};return e[Ak]=r,r}var Mk=Dk().factory,Lk=Dk().home;function Bk(){return o(Mk)}function Hk(){return o(Lk)?.kit??null}function Uk(){return o(Lk)}var Nk=15,$k=8;function HistoryBar({bar:e,history:t,empty:r,unread:n,extra:l}){let i=useEverfurTheme(),o=Hk(),s=a(()=>o!==null?qk(i,o):Gk(i),[i,o]),u=t.cursor===null?t.rows.length:0,c=t=>{let r=e.renderIcon;if(r!==void 0)/* @__PURE__ */return H(HostRender,{render:()=>r(t),fallback:null});if(o===null)return null;let n=String(b.flatten(s.label).color??i.color.linkInk);return t==="history"?/* @__PURE__ */H(HistoryGlyph,{size:Vk,color:n,strokeWidth:1.8}):/* @__PURE__ */H(EditGlyph,{size:Vk,color:n,strokeWidth:1.8})};/* @__PURE__ */
|
|
212
213
|
return U(w,{style:s.bar,testID:"everfur-history-bar",children:[
|
|
213
|
-
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?
|
|
214
|
+
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?Wk:void 0,children:[c("history"),
|
|
214
215
|
/* @__PURE__ */H(Text,{tier:"control",style:s.label,children:e.chats}),u>0?/* @__PURE__ */H(w,{style:s.count,children:/* @__PURE__ */H(Text,{tier:"badge",style:s.countText,children:String(u)})}):null,n?/* @__PURE__ */H(w,{style:s.dot,testID:"everfur-chat-history-bar-unread"}):null]}),e.extra??null,l??null,
|
|
215
|
-
/* @__PURE__ */H(w,{style:s.spacer}),r?null:/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?
|
|
216
|
-
/* @__PURE__ */H(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var
|
|
216
|
+
/* @__PURE__ */H(w,{style:s.spacer}),r?null:/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?Wk:void 0,children:[c("edit"),
|
|
217
|
+
/* @__PURE__ */H(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var Wk=4,Vk=18;function qk(e,t){return{...Gk(e),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:e.space.sm},control:t.view(".thread__hist"),label:t.text(".thread__hist"),count:t.view(".thread__count"),countText:t.text(".thread__count")}}function Gk(e){let t=e.color,r=e.space;return b.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:Db},label:{...face(e,"bold"),fontSize:Nk,color:t.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,alignItems:"center"},countText:{...face(e,"bold"),fontSize:e.type.size.caption,color:t.text.primary},dot:{width:$k,height:$k,borderRadius:$k/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var Kk=.88,Yk=420,Qk=58,Jk="rgba(17,17,17,0.28)",Xk=.15,Zk=14,ew=12,tw=44,rw=16,nw=14,lw=12,iw=14,ow=8,aw=2,sw=.5,uw=mg(ag.standard);function cw(e){return Math.min(Math.round(e*Kk),Yk)}function HistoryDrawer({chat:e,history:t}){let[r,n]=l(t.open),i=s(()=>n(false),[]);return t.open&&!r&&n(true),r?/* @__PURE__ */H(DrawerModal,{chat:e,history:t,onHidden:i}):null}function DrawerModal({chat:e,history:t,onHidden:r}){let l=useEverfurTheme(),i=a(()=>dw(l),[l]),o=hg(),s=L(),{width:c}=A(),d=cw(c),f=t.open,h=u(null);h.current===null&&(h.current=new F.Value(o.drawerMs<=0&&f?1:0));let g=h.current;n(()=>{if(!f&&o.drawerMs<=0){r();return}let e=F.timing(g,{toValue:f?1:0,duration:o.drawerMs,easing:uw,useNativeDriver:true});return e.start(({finished:e})=>{e&&!f&&r()}),()=>e.stop()},[f,g,o.drawerMs,r]);let b=g.interpolate({inputRange:[0,1],outputRange:[-d,0]}),m=t.filtered,y=t.rows.length===0,v=t.cursor===null&&!t.loading&&t.error===null,k=y&&t.loading?/* @__PURE__ */U(w,{style:i.emptyCard,accessibilityLabel:Pp.loading,accessibilityState:{busy:true},children:[
|
|
217
218
|
/* @__PURE__ */H(P,{color:i.emptyTitle.color}),
|
|
218
|
-
/* @__PURE__ */H(Text,{style:i.emptyBody,children:
|
|
219
|
-
/* @__PURE__ */H(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:
|
|
219
|
+
/* @__PURE__ */H(Text,{style:i.emptyBody,children:Pp.loading})]}):y&&t.error!==null?/* @__PURE__ */U(w,{style:i.emptyCard,children:[
|
|
220
|
+
/* @__PURE__ */H(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:Pp.loadFailed}),
|
|
220
221
|
/* @__PURE__ */H(Text,{style:i.emptyBody,children:t.error}),
|
|
221
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
222
|
-
/* @__PURE__ */H(Text,{style:i.emptyTitle,children:
|
|
223
|
-
/* @__PURE__ */H(Text,{style:i.emptyBody,children:
|
|
224
|
-
/* @__PURE__ */H(Text,{style:i.noMatch,children:
|
|
222
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Pp.retry,containerStyle:i.retrySlot,style:i.retryButton,onPress:()=>{t.load()},children:/* @__PURE__ */H(Text,{tier:"control",style:i.retryText,children:Pp.retry})})]}):t.emptyKind==="empty"?/* @__PURE__ */U(w,{style:i.emptyCard,children:[
|
|
223
|
+
/* @__PURE__ */H(Text,{style:i.emptyTitle,children:Pp.empty}),
|
|
224
|
+
/* @__PURE__ */H(Text,{style:i.emptyBody,children:Pp.emptyBody})]}):
|
|
225
|
+
/* @__PURE__ */H(Text,{style:i.noMatch,children:Pp.noMatch}),C=!t.searching&&t.loadingMore?/* @__PURE__ */H(w,{style:i.loadMoreFooter,children:/* @__PURE__ */H(Text,{style:i.loadMoreLabel,children:Pp.loadingMore})}):null;/* @__PURE__ */
|
|
225
226
|
return H(I,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:/* @__PURE__ */U(w,{style:i.root,children:[
|
|
226
|
-
/* @__PURE__ */H(R,{style:
|
|
227
|
-
/* @__PURE__ */H(F.View,{style:[i.panel,{width:d,paddingTop:Math.max(
|
|
227
|
+
/* @__PURE__ */H(R,{style:fb,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Pp.closeA11y,children:/* @__PURE__ */H(F.View,{style:[i.backdrop,{opacity:g}]})}),
|
|
228
|
+
/* @__PURE__ */H(F.View,{style:[i.panel,{width:d,paddingTop:Math.max(Qk,s.top+l.space.md),transform:[{translateX:b}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */U(_,{style:i.keyboardAvoider,behavior:p.OS==="ios"?"padding":"height",children:[
|
|
228
229
|
/* @__PURE__ */U(w,{style:i.header,children:[
|
|
229
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:
|
|
230
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
231
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
230
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:Pp.heading}),
|
|
231
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Pp.newChat,style:i.newChat,onPress:t.newConversation,children:/* @__PURE__ */H(Text,{tier:"control",style:i.newChatLabel,children:Pp.newChat})}),
|
|
232
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Pp.close,hitSlop:0,style:i.closeButton,onPress:t.close,children:/* @__PURE__ */H(CloseGlyph,{size:rw,color:l.color.text.muted,strokeWidth:1.75})})]}),
|
|
232
233
|
/* @__PURE__ */U(w,{style:i.searchPill,children:[
|
|
233
|
-
/* @__PURE__ */H(SearchGlyph,{size:
|
|
234
|
-
/* @__PURE__ */H(
|
|
235
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:i.countLabel,children:
|
|
236
|
-
/* @__PURE__ */H(D,{data:m,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */H(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:m.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:C,onEndReached:t.loadMore,onEndReachedThreshold:
|
|
237
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
234
|
+
/* @__PURE__ */H(SearchGlyph,{size:iw,color:l.color.text.muted,strokeWidth:1.5}),
|
|
235
|
+
/* @__PURE__ */H(af,{value:t.query,onChangeText:e=>t.setQuery(e.replace(/^\s+/,"")),style:i.searchInput,placeholder:Pp.searchPlaceholder,placeholderTextColor:l.color.text.placeholder,accessibilityLabel:Pp.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
|
|
236
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:i.countLabel,children:Fp(t.rows.length,v)}),t.error!==null&&!y?/* @__PURE__ */H(w,{style:i.errorCard,children:/* @__PURE__ */H(Text,{style:i.errorText,accessibilityRole:"alert",children:t.error})}):null,
|
|
237
|
+
/* @__PURE__ */H(D,{data:m,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */H(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:m.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:C,onEndReached:t.loadMore,onEndReachedThreshold:sw})]})})]})})}function Row({row:e,active:t,disabled:r,styles:n,onPress:l}){let i=e.unreadCount!==null&&e.unreadCount>0,o=jp(e);/* @__PURE__ */
|
|
238
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:Ap(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:l,children:[
|
|
238
239
|
/* @__PURE__ */U(w,{style:n.itemRow,children:[
|
|
239
|
-
/* @__PURE__ */H(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:
|
|
240
|
+
/* @__PURE__ */H(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:Op(e.title)}),i?/* @__PURE__ */H(w,{style:n.unreadDot}):null]}),o!==null?/* @__PURE__ */H(Text,{tier:"compact",style:n.itemMeta,numberOfLines:1,children:o}):null]})}function dw(e){let t=e.color,r=e.space,n=e.type,l=e.slots,i=t.text.primary,o=$g(l.card);return b.create({root:{flex:1},backdrop:{flex:1,backgroundColor:Jk},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:r.lg,borderRightWidth:b.hairlineWidth,borderRightColor:t.borderRingCream,gap:r.md,...$v(l.dialog,b.hairlineWidth)},keyboardAvoider:{flex:1,gap:r.md},header:{flexDirection:"row",alignItems:"center",gap:r.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:n.size.subtitle,color:i,...$g(l.dialog)},newChat:{minHeight:tw,justifyContent:"center",paddingHorizontal:r.xs},newChatLabel:{...face(e,"bold"),fontSize:Zk,color:t.brandInk},closeButton:{width:tw,height:tw,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:r.md+aw,paddingVertical:r.sm+aw,borderWidth:1,borderColor:t.borderRingCream,...Ug(l.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:n.size.bodyTight,color:t.text.primary,padding:0,...$g(l.input)},countLabel:{...face(e,"mono"),fontSize:ew,color:t.text.muted},list:{gap:r.xs,paddingBottom:r.xl},listEmpty:{flexGrow:1},item:{paddingVertical:r.sm+aw,paddingHorizontal:r.sm,borderRadius:e.radius.md,gap:aw},itemActive:{backgroundColor:co(t.highlight,Xk)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:r.sm},itemTitle:{...face(e,"bold"),flex:1,fontSize:n.size.bodyTight,color:i},itemMeta:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted},unreadDot:{width:ow,height:ow,borderRadius:ow/2,backgroundColor:t.danger},errorCard:{borderRadius:lw,borderWidth:b.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:r.md},errorText:{...face(e,"regular"),fontSize:n.size.caption,color:t.danger},emptyCard:{borderRadius:nw,padding:r.md+aw,gap:r.xs+aw,backgroundColor:t.surfaceSubtle,borderWidth:b.hairlineWidth,borderColor:t.borderRingCream,...Ug(l.card,b.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:n.size.bodyTight,color:i,...o},emptyBody:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.secondary,...o},noMatch:{...face(e,"regular"),fontSize:n.size.bodyTight,color:t.text.muted,paddingVertical:r.sm},retrySlot:{marginTop:r.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:r.md+aw,paddingVertical:r.sm,borderWidth:1,borderColor:t.brandInk,...Ug(l.primaryButton)},retryText:{...face(e,"bold"),fontSize:n.size.caption,color:t.brandInk,...$g(l.primaryButton)},loadMoreFooter:{paddingVertical:r.md+aw,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted}})}function fw(e,t=/* @__PURE__ */new Date,r){let n=new Date(e);if(Number.isNaN(n.getTime()))return null;let l=new Date(t);l.setHours(0,0,0,0);let i=new Date(n);i.setHours(0,0,0,0);let o=Math.round((l.getTime()-i.getTime())/864e5);if(o===0||o===1)try{let e=new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day");return e.charAt(0).toLocaleUpperCase(r)+e.slice(1)}catch{}return n.toLocaleDateString(r,{month:"short",day:"numeric"})}function hw(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function pw(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=fw(n.updatedAt,t)??"",l=r[r.length-1];l!==void 0&&l.day===e?l.rows.push(n):r.push({day:e,rows:[n]})}return r}var gw="rgba(38,37,35,0.38)",bw=28,mw=40,yw=5,vw=11,kw=10.5,ww=36,Cw=11,Sw=14,xw=15,_w=13.5,Rw=48,Tw=2,Iw=1.3,zw=.12,Pw=16,Ow=8,Ew="80%";function jw(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */H(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:t,sheet:r}){let n=useEverfurTheme(),l=a(()=>Fw(n),[n]),i=L(),o=a(()=>pw(t.rows),[t.rows]);if(!t.open)return null;let s=n.color,u=r?.title?.trim(),c=u!==void 0&&u!==""?u:Pp.heading;/* @__PURE__ */
|
|
240
241
|
return H(I,{visible:true,transparent:true,animationType:"slide",onRequestClose:t.close,children:/* @__PURE__ */U(w,{style:l.root,children:[
|
|
241
|
-
/* @__PURE__ */H(R,{style:[
|
|
242
|
+
/* @__PURE__ */H(R,{style:[fb,l.scrim],onPress:t.close,accessibilityRole:"button",accessibilityLabel:Pp.closeA11y}),
|
|
242
243
|
/* @__PURE__ */U(w,{style:[l.sheet,{paddingBottom:Math.max(40,i.bottom+n.space.lg)}],accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
|
|
243
244
|
/* @__PURE__ */H(w,{style:l.grab}),
|
|
244
245
|
/* @__PURE__ */U(w,{style:l.top,children:[
|
|
245
246
|
/* @__PURE__ */H(Text,{tier:"compact",style:l.kicker,accessibilityRole:"header",children:c}),
|
|
246
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
247
|
-
/* @__PURE__ */U(z,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */U(w,{style:l.state,accessibilityLabel:
|
|
247
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Pp.closeA11y,onPress:t.close,style:l.close,children:jw(r,"close",/* @__PURE__ */H(CloseGlyph,{size:22,color:s.text.primary,strokeWidth:2}))})]}),
|
|
248
|
+
/* @__PURE__ */U(z,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */U(w,{style:l.state,accessibilityLabel:Pp.loading,accessibilityState:{busy:true},children:[
|
|
248
249
|
/* @__PURE__ */H(P,{color:s.brandInk}),
|
|
249
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:l.mono,children:
|
|
250
|
-
/* @__PURE__ */H(Text,{style:l.stateText,accessibilityRole:"alert",children:
|
|
251
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
252
|
-
return U(R,{accessibilityRole:"button",accessibilityLabel:
|
|
253
|
-
/* @__PURE__ */H(w,{style:l.icon,children:
|
|
250
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:l.mono,children:Pp.loading})]}):null,t.error!==null?/* @__PURE__ */U(w,{style:l.state,children:[
|
|
251
|
+
/* @__PURE__ */H(Text,{style:l.stateText,accessibilityRole:"alert",children:Pp.loadFailed}),
|
|
252
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Pp.retry,onPress:()=>{t.load()},style:l.link,children:/* @__PURE__ */H(Text,{tier:"control",style:l.linkText,children:Pp.retry})})]}):null,!t.loading&&t.error===null&&t.rows.length===0?/* @__PURE__ */H(Text,{style:[l.stateText,l.state],children:Pp.empty}):null,o.map((n,i)=>/* @__PURE__ */U(h,{children:[n.day?/* @__PURE__ */H(Text,{tier:"compact",style:[l.mono,l.day,i===0?l.dayFirst:null],children:n.day}):null,n.rows.map(n=>{let i=n.id===e.conversationId,o=n.unreadCount!==null&&n.unreadCount>0,a=hw(n.updatedAt);/* @__PURE__ */
|
|
253
|
+
return U(R,{accessibilityRole:"button",accessibilityLabel:Ap(n),accessibilityState:{selected:i},onPress:()=>{t.resume(n.id)},style:[l.row,i?l.rowCurrent:null],children:[
|
|
254
|
+
/* @__PURE__ */H(w,{style:l.icon,children:jw(r,"chat",/* @__PURE__ */H(ChatBubbleGlyph,{size:19,color:s.linkInk,strokeWidth:1.75}))}),
|
|
254
255
|
/* @__PURE__ */U(w,{style:l.rowWords,children:[
|
|
255
|
-
/* @__PURE__ */H(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:
|
|
256
|
-
/* @__PURE__ */U(w,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */H(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */H(w,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
257
|
-
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:
|
|
258
|
-
/* @__PURE__ */H(Text,{tier:"control",style:l.newChatText,children:
|
|
256
|
+
/* @__PURE__ */H(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:Op(n.title)}),n.preview!==void 0?/* @__PURE__ */H(Text,{tier:"compact",style:l.preview,numberOfLines:1,children:n.preview}):null]}),
|
|
257
|
+
/* @__PURE__ */U(w,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */H(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */H(w,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Pp.more,onPress:t.loadMore,style:l.link,children:/* @__PURE__ */H(Text,{tier:"control",style:l.linkText,children:Pp.more})}):null]}),
|
|
258
|
+
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:Pp.newChat,onPress:t.newConversation,style:l.newChat,children:[jw(r,"edit",/* @__PURE__ */H(EditGlyph,{size:18,color:n.slots.primaryButton?.textColor??s.onPrimary,strokeWidth:1.75})),
|
|
259
|
+
/* @__PURE__ */H(Text,{tier:"control",style:l.newChatText,children:Pp.newChat})]})]})]})})}function Fw(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:kw,letterSpacing:kw*.06,textTransform:"uppercase",color:t.text.muted};return b.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:gw},sheet:{maxHeight:Ew,backgroundColor:t.surface,borderTopLeftRadius:bw,borderTopRightRadius:bw,paddingTop:10,paddingHorizontal:20},grab:{width:mw,height:yw,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...n,fontSize:vw,letterSpacing:vw*.08,flexShrink:1},close:{width:Db,height:Db,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:Db/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:r.xs},mono:n,day:{marginTop:r.lg,marginBottom:r.xs},dayFirst:{marginTop:Tw},state:{marginVertical:r.md,gap:r.sm,alignItems:"flex-start"},stateText:{...face(e,"regular"),fontSize:e.type.size.body,color:t.text.primary},link:{minHeight:Db,justifyContent:"center"},linkText:{...face(e,"bold"),fontSize:e.type.size.body,color:t.brandInk},row:{flexDirection:"row",alignItems:"center",gap:r.md,paddingVertical:10,paddingHorizontal:r.sm,borderRadius:Sw,minHeight:Db},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:ww,height:ww,borderRadius:Cw,backgroundColor:co(t.linkInk,zw)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:xw,lineHeight:xw*Iw,color:t.text.primary},preview:{...face(e,"regular"),fontSize:_w,color:t.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:kw*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:Ow,height:Ow,borderRadius:Ow/2,backgroundColor:t.danger},newChat:{marginTop:r.lg,minHeight:Rw,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...Ug(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:Pw,color:t.onPrimary,...$g(e.slots.primaryButton)}})}var Aw="Close",Dw=/* @__PURE__ */Object.freeze({action:e=>e.possessive===null?null:`See ${e.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(e,t)=>e.risk?.lead?`${e.risk.lead} ${t}`:`${e.title}: ${t}`,close:e=>e.possessive===null?null:`Close ${e.possessive} focus`,resultsKicker:e=>e.possessive===null?null:`${Mw(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function Mw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function healthPlanPossessive(e){let t=typeof e.sex=="string"?e.sex.trim().toLowerCase():null;if(t==="female")return"her";if(t==="male")return"his";let r=typeof e.name=="string"?e.name.trim():"";return r!==""?`${r}'s`:null}function healthPlanTopCard(e,t={}){let r=e?.page?.focus;if(e===null||r===void 0||r.title.trim()===""||r.kicker.trim()==="")return;let n={...Dw,...t.copy},l={pet:e.pet,possessive:healthPlanPossessive(e.pet)},i=r.sources?.find(e=>e.label.trim()!=="")?.label,o=t.onOpenPlan,a=o===void 0?null:n.action(l),s=n.close(l),u=n.ask.trim(),c=t.results!==void 0&&r.report!==void 0?t.results:void 0;if(c!==void 0){let e=n.resultsKicker(l)?.trim()||r.kicker,s=n.resultsClose(l),d=c.onTopRisk??o,f={key:"top-risk",label:n.resultsTopRisk,title:r.title,...r.risk?.lead?{line:r.risk.lead}:{},tone:"risk",...d===void 0?{}:{onPress:d}};return{kicker:e,...i===void 0?{}:{badge:i},title:r.title,results:[f,...c.rows??[]],...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?Aw:s,pill:e,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}return{kicker:r.kicker,...i===void 0?{}:{badge:i},title:r.title,...r.risk?.lead?{lead:r.risk.lead}:{},...r.risk?.body?{body:r.risk.body}:{},...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?Aw:s,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function Lw(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function Bw(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var Hw=20,Uw=14,Nw=16,$w=18,Ww=22,Vw=15,qw=12,Gw=24,Kw=15,Yw=14.5,Qw=21,Jw=14.5,Xw=18,Zw=9,eC=36,tC=14,rC=15,nC=8,lC=40;function TopCard({card:e,open:t,onOpenChange:r,ask:n}){let l=useEverfurTheme(),i=Hk(),o=a(()=>i!==null?oC(i):aC(l),[l,i]),s=a(()=>Ug(l.slots.card),[l.slots.card]);if(!t)return null;let u=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:If.close,c=e.action,d=e.ask,f=/* @__PURE__ */H(CloseGlyph,{size:i!==null?HOME_CLOSE_GLYPH(i):Xw,color:i!==null?String(i.text(".ask-focus__x").color):l.color.text.primary,strokeWidth:2});/* @__PURE__ */
|
|
259
260
|
return U(w,{style:[o.card,s],testID:"everfur-top-card",children:[
|
|
260
261
|
/* @__PURE__ */U(w,{style:o.kickerRow,children:[
|
|
261
|
-
/* @__PURE__ */H(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */H(w,{style:o.badge,children:/* @__PURE__ */H(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */H(R,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?
|
|
262
|
+
/* @__PURE__ */H(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */H(w,{style:o.badge,children:/* @__PURE__ */H(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */H(R,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?iC:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */H(HostRender,{render:()=>e.renderIcon?.("close"),fallback:f}):f}):null]}),
|
|
262
263
|
/* @__PURE__ */H(Text,{tier:"heading",style:o.title,accessibilityRole:"header",children:e.title}),e.lead!==void 0||e.body!==void 0?/* @__PURE__ */U(w,{style:o.finding,children:[
|
|
263
264
|
/* @__PURE__ */H(w,{style:o.dot}),
|
|
264
|
-
/* @__PURE__ */U(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */H(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */U(w,{style:o.actions,children:[c!==void 0?/* @__PURE__ */H(R,{onPress:()=>{
|
|
265
|
-
return U(R,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?
|
|
265
|
+
/* @__PURE__ */U(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */H(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */U(w,{style:o.actions,children:[c!==void 0?/* @__PURE__ */H(R,{onPress:()=>{vh(c.onPress)},accessibilityRole:"button",accessibilityLabel:c.label,style:o.action,hitSlop:i!==null?iC:void 0,children:/* @__PURE__ */H(Text,{tier:"control",style:o.actionText,children:c.label})}):null,d!==void 0?/* @__PURE__ */H(R,{onPress:()=>n(d.prompt),accessibilityRole:"button",accessibilityLabel:d.label,style:o.ask,hitSlop:i!==null?iC:void 0,children:/* @__PURE__ */H(Text,{tier:"control",style:o.askText,children:d.label})}):null]}):null]})}function TopCardPill({card:e,open:t,onOpenChange:r}){let n=useEverfurTheme(),l=Hk(),i=a(()=>l!==null?oC(l):aC(n),[n,l]);if(t||e.closeLabel===void 0)return null;let o=e.pill??e.kicker;/* @__PURE__ */
|
|
266
|
+
return U(R,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?iC:void 0,testID:"everfur-top-card-pill",children:[
|
|
266
267
|
/* @__PURE__ */H(w,{style:i.pillDot}),
|
|
267
|
-
/* @__PURE__ */H(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var Qw=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:$w};function Jw(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),l=typeof n.height=="number"?n.height:Ww;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-l)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function Xw(e){let t=e.color,r=e.space;return b.create({card:{paddingTop:Ew,paddingHorizontal:jw,paddingBottom:jw,borderRadius:Ow,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:xb-8},kicker:{...Pw(e),fontSize:Dw,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:Lw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:Mw,color:t.text.secondary},close:{width:xb,height:xb,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:xb/2},title:{...Pw(e),fontSize:Fw,lineHeight:Aw,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:Ww,height:Ww,borderRadius:Ww/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:Hw,lineHeight:Uw,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(Yw,xb),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:Bw,color:t.onPrimary},ask:{minHeight:xb,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:Nw,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(Vw,xb),paddingHorizontal:qw,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:Kw,height:Kw,borderRadius:Kw/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:Gw,color:t.danger,flexShrink:1}})}var Zw=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),eC=/* @__PURE__ */new WeakMap;function tC(e){let t=eC.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...Zw},i=(e,t)=>so(e,t,eo(t),rC),o=(e,t)=>contrastRatio(e,t)>=rC?e:Zi(t,rC),a=[l.card,l.paper].map(e=>io(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return eC.set(e,u),u}var rC=4.5;function nC(e,t){for(let r of t)if(contrastRatio(r,e)>=rC)return r;return Zi(e,rC)}function lC(e,t,r){let n=oo(e,t);return(n===null?null:io(n,r))??r}function iC(e){let t=tC(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:nC(t.accent,[t.ink,t.onAccent]),accent2:lC(t.accent,.75,n),accent4:lC(t.accent,.17,n),accentChip:lC(t.accent,.47,n),link:t.link,linkChip:lC(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var oC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),aC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),sC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],uC=17,cC=1.5,dC=400,fC=700;function hC(e){return e<=450?"regular":e<=650?"medium":"bold"}function pC(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function gC(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:pC(r)}}let n=t==="$serif"?headingFace(e,hC(r)):face(e,hC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:pC(r)}}function bC(e,t,r={}){let n=iC(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},a=/* @__PURE__ */new Map,s=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),s=a.get(l);if(s!==void 0)return s;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return a.set(l,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=s(e),l={};for(let[e,t]of Object.entries(n))oC.has(e)||aC.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of sC){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let a=n.shadow;if(Array.isArray(a)){let[e,t,r,n]=a;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=s(r),a=typeof o.fontSize=="number"?o.fontSize:uC,u=typeof o.lh=="number"?o.lh:cC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...gC(e,f,c),fontSize:a,lineHeight:Math.round(a*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*a*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(dC,e),strong:(...e)=>f(fC,e),icon:(...e)=>{let t=s(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=s([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=s(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>s(t)[e]}}var mC={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},yC=16;var vC=4e3,kC=.5;function wC(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function CC(e,t,r){if(e.length===0)return r;let n=wC(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=kC*e.length+1;for(let o of l)if(wC(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=b.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=u({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[c,d]=l(null),f=c!==null&&c.key===o?c.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=CC(t,l,(e.ch+kC)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
268
|
-
return U(w,{style:
|
|
268
|
+
/* @__PURE__ */H(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var iC=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:Xw};function oC(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),l=typeof n.height=="number"?n.height:Zw;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-l)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function aC(e){let t=e.color,r=e.space;return b.create({card:{paddingTop:Uw,paddingHorizontal:Nw,paddingBottom:Nw,borderRadius:Hw,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Db-8},kicker:{...Bw(e),fontSize:Vw,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:Gw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:qw,color:t.text.secondary},close:{width:Db,height:Db,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:Db/2},title:{...Bw(e),fontSize:$w,lineHeight:Ww,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:Zw,height:Zw,borderRadius:Zw/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:Yw,lineHeight:Qw,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(lC,Db),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:Kw,color:t.onPrimary},ask:{minHeight:Db,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:Jw,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(eC,Db),paddingHorizontal:tC,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:nC,height:nC,borderRadius:nC/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:rC,color:t.danger,flexShrink:1}})}var sC=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),uC=/* @__PURE__ */new WeakMap;function cC(e){let t=uC.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...sC},i=(e,t)=>ho(e,t,lo(t),dC),o=(e,t)=>contrastRatio(e,t)>=dC?e:no(t,dC),a=[l.card,l.paper].map(e=>uo(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return uC.set(e,u),u}var dC=4.5;function fC(e,t){for(let r of t)if(contrastRatio(r,e)>=dC)return r;return no(e,dC)}function hC(e,t,r){let n=co(e,t);return(n===null?null:uo(n,r))??r}function pC(e){let t=cC(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:fC(t.accent,[t.ink,t.onAccent]),accent2:hC(t.accent,.75,n),accent4:hC(t.accent,.17,n),accentChip:hC(t.accent,.47,n),link:t.link,linkChip:hC(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var gC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),bC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),mC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],yC=17,vC=1.5,kC=400,wC=700;function CC(e){return e<=450?"regular":e<=650?"medium":"bold"}function SC(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function xC(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:SC(r)}}let n=t==="$serif"?headingFace(e,CC(r)):face(e,CC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:SC(r)}}function _C(e,t,r={}){let n=pC(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},a=/* @__PURE__ */new Map,s=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),s=a.get(l);if(s!==void 0)return s;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return a.set(l,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=s(e),l={};for(let[e,t]of Object.entries(n))gC.has(e)||bC.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of mC){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let a=n.shadow;if(Array.isArray(a)){let[e,t,r,n]=a;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=s(r),a=typeof o.fontSize=="number"?o.fontSize:yC,u=typeof o.lh=="number"?o.lh:vC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...xC(e,f,c),fontSize:a,lineHeight:Math.round(a*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*a*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(kC,e),strong:(...e)=>f(wC,e),icon:(...e)=>{let t=s(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=s([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=s(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>s(t)[e]}}var RC={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},TC=16;var IC=4e3,zC=.5;function PC(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function OC(e,t,r){if(e.length===0)return r;let n=PC(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=zC*e.length+1;for(let o of l)if(PC(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=b.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=u({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[c,d]=l(null),f=c!==null&&c.key===o?c.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=OC(t,l,(e.ch+zC)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
269
|
+
return U(w,{style:EC.wrap,children:[
|
|
269
270
|
/* @__PURE__ */H(Text,{tier:"heading",style:f===null?t:[t,{maxWidth:f}],accessibilityRole:"header",children:e}),
|
|
270
|
-
/* @__PURE__ */H(w,{style:
|
|
271
|
+
/* @__PURE__ */H(w,{style:EC.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */U(w,{style:EC.probeRow,children:[
|
|
271
272
|
/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.ch=t}),children:"0"}),
|
|
272
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var
|
|
273
|
-
return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:
|
|
273
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var EC=b.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:IC,flexDirection:"row",alignItems:"flex-start"}});function jC(e){return{kit:_C(e,RC),Title:BalancedTitle,titleCh:TC}}var FC=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function AC(){let e=globalThis,t=e[FC];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[FC]=r,r}var DC=e=>{let t=AC();return t.listeners.add(e),()=>t.listeners.delete(e)},MC=()=>AC().count>0;function useHostPoweredBy(){return i(DC,MC,MC)}var LC=/* @__PURE__ */Object.freeze({}),BC=100,HC=20;function UC(e,t,r,n){return![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}function NC(e,t){let r=typeof e=="number"&&Number.isFinite(e),i=u(null),[o,c]=l(null),d=u(null),f=u(null),h=u(true),p=s(()=>{f.current!==null&&clearTimeout(f.current),f.current=null},[]);n(()=>(h.current=true,()=>{h.current=false,p()}),[p]);let g=s(function e(t){i.current?.measureInWindow((r,n)=>{let l=d.current;if(!h.current||l===null)return;let i=UC(n,l.y,l.height,v.get("window").height);if(i!==null){c(e=>e!==null&&e.chatTop===i.chatTop&&e.parentTop===i.parentTop?e:i);return}t>=HC||(f.current=setTimeout(()=>{f.current=null,e(t+1)},BC))})},[]),b=s(e=>{let{y:t,height:r}=e.nativeEvent.layout;d.current={y:t,height:r},p(),g(0)},[g,p]);return a(()=>{if(!t)return{avoidingProps:r?{keyboardVerticalOffset:e}:LC,probeRef:null,topInWindow:null};let n=o?.parentTop??0;return{avoidingProps:r?{keyboardVerticalOffset:e,onLayout:b}:n>0?{keyboardVerticalOffset:n,onLayout:b}:{onLayout:b},probeRef:i,topInWindow:o?.chatTop??null}},[t,r,e,o,b])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */H(w,{ref:e,collapsable:false,pointerEvents:"none",style:$C})}var $C=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function WC(){let[e,t]=l(false);return n(()=>{let e=T;if(typeof e?.addListener!="function")return;let r=p.OS==="ios",n=e.addListener(r?"keyboardWillShow":"keyboardDidShow",()=>t(true)),l=e.addListener(r?"keyboardWillHide":"keyboardDidHide",()=>t(false));return()=>{n.remove(),l.remove()}},[]),e}function VC(e,t,r){return ho(e,t,lo(t),r)}function qC(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=Ov(t),l=r?n.warning:n.info,i=Pv(t)&&!l?e:GC(e,t,r);return KC(i,t.slots.banner)}function GC(e,t,r){let n=t.color,l=uo(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,i=r?n.cautionAccent:n.infoEdge,o=VC(uo(i,n.surface)??i,[n.surface,n.chatGround],Io),a=VC(r?n.warningStrong:n.info,[l,n.surface],ko);/* @__PURE__ */
|
|
274
|
+
return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:VC(n.text.primary,[l],ko),pillColor:n.surface})}function KC(e,t){if(t===void 0)return e;let r={...e};return t.backgroundColor!==void 0&&(r.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(r.borderColor=t.borderColor),t.textColor!==void 0&&(r.textColor=t.textColor,r.reasonColor=t.textColor),/* @__PURE__ */Object.freeze(r)}function YC(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}var QC=.75,JC=1.5,XC=.4,ZC=4,eS=1.5,tS=22,rS=14,nS=8,lS=20,iS=10,oS=13,aS=12,sS=15,uS=44,cS=14,dS=1.25,fS=14,hS=6,pS=2;function gS(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:co(r.danger,XC)??r.danger,borderWidth:JC},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}};let n=e.slots.banner?.borderRadius;return{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:QC,...n===void 0?{}:{borderRadius:n}},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}function UrgencyBanner({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,compact:i=false}){let o=useEverfurTheme(),s=a(()=>bS(o),[o]),u=hg(),c=e.tier===null?null:qC(e.tier,o),d=e.source;/* @__PURE__ */
|
|
274
275
|
return U(N,{children:[
|
|
275
276
|
/* @__PURE__ */H(FadePresence,{visible:e.showBanner&&c!==null,inMs:u.bannerInMs,outMs:u.bannerOutMs,style:s.pinned,children:c!==null&&d!==null?/* @__PURE__ */H(BannerCard,{tier:c,reason:d.reason,surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,styles:s,compact:i}):null}),
|
|
276
|
-
/* @__PURE__ */H(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
277
|
+
/* @__PURE__ */H(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:If.showLatestVetAlert,hitSlop:iS,onPress:e.expand,children:/* @__PURE__ */H(InfoGlyph,{size:lS,color:o.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:e,reason:t,surface:r,petRef:n,renderVetAction:l,onFindVet:i,vet:o,styles:a,compact:s}){let u=useEverfurTheme(),c=gS(u,e),d=/* @__PURE__ */H(VetAction,{tier:e,paint:c,petRef:n,onFindVet:i,vet:o,styles:a}),f=r.showVetAction?l!==void 0?/* @__PURE__ */H(HostRender,{render:()=>l(e.level),fallback:d,resetKey:e.level}):d:null,h=c.action!==null?/* @__PURE__ */H(PoisonControl,{paint:c.action,styles:a}):null,p=e.level==="emergency"&&i===void 0,g=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
|
|
277
278
|
return U(w,{...g?{accessibilityRole:"alert"}:{accessibilityLiveRegion:"polite"},style:[a.card,c.card,s?a.cardCompact:null],testID:s?"chat-urgency-compact":void 0,children:[
|
|
278
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */H(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?
|
|
279
|
-
return H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
280
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:u?
|
|
281
|
-
/* @__PURE__ */H(MapPinGlyph,{size:
|
|
282
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=
|
|
283
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
284
|
-
/* @__PURE__ */H(MapPinGlyph,{size:
|
|
285
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:
|
|
286
|
-
/* @__PURE__ */H(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */H(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:
|
|
287
|
-
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:
|
|
279
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */H(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?pS:void 0,accessibilityLabel:s?t:void 0,children:t}):null,p?/* @__PURE__ */H(Text,{style:[a.reason,a.erLine,{color:c.reason}],children:If.goToNearestEmergencyVet}):null,f!==null||h!==null?/* @__PURE__ */U(w,{style:a.actions,children:[f,h]}):null,r.dismissLabel!==null?/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:r.dismissLabel,hitSlop:nS,containerStyle:a.closeSlot,style:a.closeButton,onPress:r.dismiss,children:/* @__PURE__ */H(CloseGlyph,{size:rS,color:c.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let r=()=>{try{x.openURL(Ef).catch(()=>{})}catch{}};/* @__PURE__ */
|
|
280
|
+
return H(PressScale,{accessibilityRole:"button",accessibilityLabel:If.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:r,children:/* @__PURE__ */H(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:If.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:l,styles:i}){let o=useEverfurTheme(),a=useVetVisit(YC(r,l)),s=a.status==="opening",u=!a.available&&n!==void 0,c=a.available?()=>{a.open()}:n!==void 0?()=>{vh(n,e.level)}:null;if(c===null)return null;let d=t.action;if(d!==null){let e=u?If.nearestEmergencyVet:If.findVet,t=Ng(o.slots.vetVisitButton)?.textColor??d.ink;/* @__PURE__ */
|
|
281
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:u?If.nearestEmergencyVet:If.findVetA11y,accessibilityState:{busy:s},hitSlop:0,style:[i.action,{backgroundColor:d.fill,borderColor:d.edge},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
|
|
282
|
+
/* @__PURE__ */H(MapPinGlyph,{size:oS,color:t,strokeWidth:1.5}),
|
|
283
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=Ng(o.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
|
|
284
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:If.findVetA11y,accessibilityState:{busy:s},style:[i.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
|
|
285
|
+
/* @__PURE__ */H(MapPinGlyph,{size:oS,color:f,strokeWidth:1.5}),
|
|
286
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:If.findVet})]})}function bS(e){let t=Ng(e.slots.vetVisitButton),r=e.space,n=e.type;return b.create({pinned:{marginTop:0,marginBottom:r.xs,paddingHorizontal:r.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:r.lg+ZC,paddingVertical:r.lg,gap:r.sm},cardCompact:{paddingVertical:r.md,gap:r.xs},label:{...face(e,"bold"),fontSize:n.size.body,paddingRight:tS},reason:{...face(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*eS),paddingRight:tS},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm},action:{flexDirection:"row",alignItems:"center",gap:hS,minHeight:uS,paddingHorizontal:cS,borderRadius:e.radius.pill,borderWidth:dS},actionLabel:{...face(e,"bold"),fontSize:fS},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...Ug(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:aS,lineHeight:sS},closeSlot:{position:"absolute",top:r.md,right:r.md},closeButton:{width:tS,height:tS,borderRadius:tS/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:r.lg,paddingTop:2,paddingBottom:r.xs}})}function mS(e,t,r,i){let[o,a]=l({pet:r,user:t}),s=o.pet!==r||o.user===null&&t!==null;s&&a({pet:r,user:t});let u=s?{user:t}:o,c=r!==null&&u.user!==null&&u.user!==t;return n(()=>{if(!c||t===null||r===null)return;let n=true,l=createPetsRepository(e.registry.services.authFor(t)),i=async()=>{let e=await l.list();n&&e.ok&&e.value.some(e=>e.petRef===r)&&a({pet:r,user:t})};i();let o=Hi(e,()=>{i()});return()=>{n=false,o()}},[c,e,t,r,i]),c}var yS=/* @__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(e){let{runtime:t,userRef:r,activePet:o,scopeEpoch:c}=bd(),d=e?.petRef??o??null,f=e?.conversationId??null,h=mS(t,r,d,c),p=a(()=>({runtime:t,userRef:r,petRef:d,conversationId:f,scopeEpoch:c,held:h}),[t,r,d,f,c,h]),[g,b]=l(null),m=h?null:g?.scope===p?g.controller:t.registry.peekChat({userRef:r,petRef:d,conversationId:f}),y=u(null);n(()=>{if(h)return;let e=t.registry.acquireChat({userRef:r,petRef:d,conversationId:f});return y.current=e,b({scope:p,controller:e}),()=>{y.current=null,b(t=>t?.controller===e?null:t),t.registry.releaseChat(e)}},[t,r,d,f,c,h,p]);let v=s(e=>m?m.subscribe(e):NOOP_UNSUBSCRIBE,[m]),k=s(()=>m?m.getSnapshot():yS,[m]),w=i(v,k,k),C=s((e,t)=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?kS(m,m.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>y.current===m):Promise.resolve(CS()),[m]),S=s(e=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?kS(m,m.askEverfur(e),()=>y.current===m):Promise.resolve(CS()),[m]),x=s(()=>m&&y.current===m?kS(m,m.retryLast(),()=>y.current===m):Promise.resolve(CS()),[m]),_=s(()=>{m&&y.current===m&&m.stop()},[m]),R=s(()=>{m&&y.current===m&&m.newConversation()},[m]),[T,I]=l({controller:null,byMessage:{}}),z=T.controller===m?T.byMessage:vS,P=s(async(e,t,r,n)=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let l=String(e),i=T.controller===m?T.byMessage[l]:void 0;if(i===t&&r==null)return I(e=>{let t={...e.controller===m?e.byMessage:{}};return delete t[l],{controller:m,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));I(e=>({controller:m,byMessage:{...e.controller===m?e.byMessage:{},[l]:t}}));let o=await m.submitFeedback(e,xk(t,r??null),n??null);return y.current!==m?err(makeEverfurError("accessDenied")):(o.ok||I(e=>{let t={...e.controller===m?e.byMessage:{}};return i===void 0?delete t[l]:t[l]=i,{controller:m,byMessage:t}}),o)},[m,T]),O=a(()=>{let e=async e=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let t=await e(m);return y.current===m?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...d?{petRef:d}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[m,d]);return a(()=>({status:w.status,messages:w.messages,conversationId:w.conversationId,petRef:d,error:w.error,isStreaming:w.isStreaming,isBootstrapping:w.isBootstrapping,historyCursor:w.historyCursor??null,isLoadingHistory:w.isLoadingHistory??false,stopped:w.stopped??false,reconnecting:w.reconnecting??false,...O,suggestedPrompts:w.suggestedPrompts,unreadCount:w.unreadCount,hasUnreadThreads:w.hasUnreadThreads??false,pendingCheckin:w.pendingCheckin??null,newConversation:R,sentimentByMessage:z,feedback:P,send:C,askEverfur:S,retryLast:x,stop:_}),[w,d,C,S,x,_,O,R,z,P])}var NOOP_UNSUBSCRIBE=()=>{},vS=/* @__PURE__ */Object.freeze({});async function kS(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(wS(n.messages))}function wS(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}function CS(){return np()}function SS(){let e=useEverfurPets(),{handle:t}=bd(),r=s(e=>t.setActivePet(e),[t]);return a(()=>({...e,setActivePet:r}),[e,r])}function xS(){try{let e=m?.announceForAccessibility;typeof e=="function"&&e.call(m,If.answered)}catch{}}function _S(e){let t=u(false),r=u({send:e.send,id:e.conversationId});n(()=>{let n=r.current;if((n.send!==e.send||n.id!==null&&n.id!==e.conversationId)&&(t.current=false),r.current={send:e.send,id:e.conversationId},t.current&&!e.isStreaming){let t=e.messages[e.messages.length-1];t!==void 0&&t.role==="assistant"&&xS()}t.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var RS=/* @__PURE__ */Object.freeze({kind:"live"}),TS=/* @__PURE__ */Object.freeze({kind:"folded"});function IS(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=In(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function zS(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=IS(t);if(e===null)continue;let n=r.get(e.caseId);(n===void 0||e.dueDay>=n.dueDay)&&r.set(e.caseId,{messageId:t.id,dueDay:e.dueDay})}if(r.size===0)return t;let n=null;for(let l of e){let e=IS(l);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===l.id){t.set(l.id,RS),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(l.id,TS);continue}let i=[e.dueDay];n={id:l.id,caseId:e.caseId,days:i},t.set(l.id,{kind:"past",runDueDays:i})}return t}function PS(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var OS=864e5,ES=365;function jS(e,t){if(typeof e!="string"||typeof t!="string")return null;let r=Date.parse(e),n=Date.parse(t);if(Number.isNaN(r)||Number.isNaN(n))return null;let l=Math.floor(n/OS)-Math.floor(r/OS);return l<1||l>ES?null:l}function FS(e){return IS(e)?.dueDay||null}function AS(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:e,named:t,styles:r}){let n=xv(e);return n.shown?/* @__PURE__ */U(w,{style:r.assistantSender,testID:"everfur-assistant-sender",children:[
|
|
287
|
+
/* @__PURE__ */H(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */H(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:If.assistantName}):null]}):t?/* @__PURE__ */H(Text,{tier:"control",style:r.assistantName,children:If.assistantName}):null}var DS=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),MS="#C8BEB4";function LS(e){return e?DS[e.toUpperCase()]??MS:MS}function BS(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function HS(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function US(e){let t=HS(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function NS(e,t){let r=HS(e.source_name)??HS(e.sourceName),n=HS(e.section),l=HS(e.authority_tier)??HS(e.authorityTier),i=BS(l),o=r??HS(e.title)??`Source ${t+1}`,a=HS(e.monograph_chunk_id)??HS(e.chunkId),s=[n,i].filter(e=>e!==null).join(" · ");/* @__PURE__ */
|
|
288
|
+
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:US(e.url),excerpt:HS(e.excerpt),tierColor:LS(l),key:`${o}-${a??"none"}-${t}`})}function $S(e){return e===void 0||e.length===0?WS:/* @__PURE__ */Object.freeze(e.map((e,t)=>NS(e,t)))}var WS=/* @__PURE__ */Object.freeze([]);function VS(e){return e===1?`1 ${If.sourceSingular}`:`${e} ${If.sourcePlural}`}function qS(e,t){return`${t?If.hideSources:If.showSources} ${VS(e)}`}function GS(e){return[e.url!==null?`${If.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function KS(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var YS=/^\s*[-*]\s+(\S.*)$/,QS=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function JS(e){let t=[],r=[],n=null,l=()=>{r.length>0&&t.push({kind:"text",text:r.join(`\n`)}),r=[]},i=()=>{n!==null&&t.push(n.ordered?{kind:"list",ordered:true,start:n.start,items:n.items}:{kind:"list",ordered:false,items:n.items}),n=null};for(let t of e.split(`\n`)){let e=YS.exec(t),o=e===null?QS.exec(t):null,a=e?.[1]??o?.[2];if(a===void 0){i(),r.push(t);continue}let s=o!==null;l(),n!==null&&n.ordered!==s&&i(),n===null&&(n={ordered:s,start:o===null?1:Number(o[1]),items:[]}),n.items.push(a.trim())}return l(),i(),t}function XS(e,t){let r=e.findIndex(e=>e.id===t);for(let t=r-1;t>=0;t-=1){let r=e[t];if(r!==void 0&&r.role==="user")return r.text}return null}function ZS(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function ex(e){return hardenHttpsUrl(e.trim())}function tx(e,t){if(t?.followUpActions===void 0||e.isStreaming||e.status==="error")return[];let r=e.messages[e.messages.length-1];return r===void 0||r.role!=="assistant"||r.pending===true?[]:ZS(t.followUpActions,{answer:r.text,question:XS(e.messages,r.id),messageId:r.id})}var rx=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,nx=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${Yp}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${Yp}})`,"gi"),lx=/https:\/\//i,ix=`.,;:!?'"`;function ox(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&lx.test(e)}function ax(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):cx(r,e,t)},l=0;rx.lastIndex=0;for(let t=rx.exec(e);t!==null;t=rx.exec(e)){t.index>l&&n(e.slice(l,t.index));let i=t[1],o=t[2],a=t[3];i!==void 0?r.push({kind:"bold",text:i}):o!==void 0?r.push({kind:"italic",text:o}):a!==void 0&&r.push({kind:"code",text:a}),l=t.index+t[0].length}return l<e.length&&n(e.slice(l)),r}function sx(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(ix.includes(r))t-=1;else if(r===")"&&ux(e,"(",t)<ux(e,")",t))t-=1;else break}return e.slice(0,t)}function ux(e,t,r){let n=0;for(let l=0;l<r;l+=1)e[l]===t&&(n+=1);return n}function cx(e,t,r){if(!lx.test(t)){e.push({kind:"text",text:t});return}let n=0;nx.lastIndex=0;for(let l=nx.exec(t);l!==null;l=nx.exec(t)){let i=l[1],o=l[2],a=l[3],s,u,c;if(i!==void 0&&o!==void 0)s=i.trim(),u=s.length>0?Zp(o,r):null,c=l[0].length;else if(a!==void 0)s=sx(a),u=Zp(s,r),c=s.length;else continue;u!==null&&(l.index>n&&e.push({kind:"text",text:t.slice(n,l.index)}),e.push({kind:"link",text:s,href:u}),n=l.index+c,nx.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var dx=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function fx(e,t){return t===void 0||!ox(e,t.hosts)?false:ax(e,t.hosts).some(e=>e.kind==="link")}function hx(e,t,r){let n=r?.hosts;return ox(e,n)?ax(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
|
|
288
289
|
return H(Text,{style:t.bold,children:e.text},n);case"italic":return t.italic?/* @__PURE__ */H(Text,{style:t.italic,children:e.text},n):e.text;case"code":return t.code?/* @__PURE__ */H(Text,{style:t.code,children:e.text},n):e.text;case"link":{if(r===void 0)return e.text;let{href:t}=e;/* @__PURE__ */
|
|
289
|
-
return H(Text,{style:
|
|
290
|
-
return H(w,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */H(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?
|
|
290
|
+
return H(Text,{style:dx,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var px=10.5,gx=16,bx=12,mx=38,yx=11,vx=15,kx=22,wx=32,Cx=13.5,Sx=14,xx=15,_x=16,Rx=13,Tx=13,Ix=26,zx=21,Px=42,Ox=1,Ex=.06,jx=.07,Fx=.12,Ax="45%";function Dx(){let e=useEverfurTheme(),t=a(()=>Mx(e),[e]);return{theme:e,styles:t}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */H(ChevronGlyph,{size:_x,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */H(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:r,styles:n}=Dx();if(e.render!==void 0){let r=e.render;/* @__PURE__ */
|
|
291
|
+
return H(w,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */H(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?ex(e.tile.imageUrl):null,c=/* @__PURE__ */U(N,{children:[l?null:/* @__PURE__ */H(w,{style:[n.tile,a!==void 0?i?.tileTone?.[a]:null],children:u!==null?/* @__PURE__ */H(O,{source:{uri:u},style:n.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
|
|
291
292
|
/* @__PURE__ */U(w,{style:n.cardWords,children:[
|
|
292
293
|
/* @__PURE__ */H(Text,{tier:"control",style:n.cardTitle,children:e.title}),e.meta!==void 0?/* @__PURE__ */H(Text,{tier:"compact",style:n.cardMeta,children:e.meta}):null]}),l?/* @__PURE__ */U(Text,{tier:"control",style:n.stat,children:[e.value?.amount,e.value?.unit!==void 0?/* @__PURE__ */H(Text,{style:n.statUnit,children:e.value.unit}):null]}):/* @__PURE__ */U(N,{children:[e.pill!==void 0?/* @__PURE__ */H(w,{style:[n.pill,s!==void 0?i?.pillTone?.[s]:null],children:/* @__PURE__ */H(Text,{tier:"badge",style:[n.pillText,s!==void 0?i?.pillToneText?.[s]:null],numberOfLines:1,ellipsizeMode:"tail",children:e.pill.label})}):null,e.onPress!==void 0?/* @__PURE__ */H(Chevron,{options:t,color:r.color.text.muted}):null]})]});if(e.onPress!==void 0){let t=e.onPress;/* @__PURE__ */
|
|
293
|
-
return H(R,{onPress:()=>{
|
|
294
|
-
return H(w,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=
|
|
294
|
+
return H(R,{onPress:()=>{vh(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:o,children:c})}/* @__PURE__ */
|
|
295
|
+
return H(w,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=Dx(),f=a(()=>({answer:e.text,question:XS(n,e.id),messageId:e.id}),[e.text,e.id,n]),h=!r&&e.pending!==true,p=h?ZS(l?.cards,f):[],g=a(()=>h?$S(e.citations):[],[h,e.citations]),b=l?.byline,m=l?.feedback!==void 0&&e.responseId!==void 0&&o!==void 0?l.feedback:null,y={bold:d.bold,italic:d.italic,code:d.code},v=rg(),k=h?v:void 0;/* @__PURE__ */
|
|
295
296
|
return U(w,{style:d.answer,testID:"everfur-answer-cards",children:[b!==void 0?/* @__PURE__ */U(w,{style:d.byline,children:[b.icon??null,
|
|
296
297
|
/* @__PURE__ */H(Text,{tier:"compact",style:d.bylineText,children:b.label})]}):s,
|
|
297
|
-
/* @__PURE__ */H(w,{style:d.body,children:
|
|
298
|
+
/* @__PURE__ */H(w,{style:d.body,children:KS(t).flatMap((e,t)=>JS(e).map((e,r)=>{let n=`${t}-${r}`;return e.kind==="text"?/* @__PURE__ */H(Text,{style:d.paragraph,children:hx(e.text,y,k)},n):/* @__PURE__ */H(w,{style:d.list,children:e.items.map((t,r)=>/* @__PURE__ */U(w,{style:d.listItem,children:[
|
|
298
299
|
/* @__PURE__ */H(Text,{style:d.paragraph,children:e.ordered?`${e.start+r}.`:"•"}),
|
|
299
|
-
/* @__PURE__ */H(Text,{style:[d.paragraph,d.listText],children:
|
|
300
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:d.label,children:
|
|
300
|
+
/* @__PURE__ */H(Text,{style:[d.paragraph,d.listText],children:hx(t,y,k)})]},r))},n)}))}),p.length>0?/* @__PURE__ */H(w,{style:d.cards,children:p.map(e=>/* @__PURE__ */H(AnswerCard,{card:e,options:l},e.key))}):null,g.length>0?/* @__PURE__ */U(w,{style:d.cards,accessibilityLabel:VS(g.length),children:[
|
|
301
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:d.label,children:If.sourcesHeading}),g.map(e=>{let t=e.url;/* @__PURE__ */
|
|
301
302
|
return H(AnswerCard,{card:{key:e.key,title:e.title,...e.meta!==null?{meta:e.meta}:{},tile:{icon:/* @__PURE__ */H(SourceTileGlyph,{})},...c!==void 0&&t!==null?{onPress:()=>c(t)}:{}},options:l},e.key)})]}):null,h&&m!==null&&o!==void 0?/* @__PURE__ */U(w,{style:[d.feedback,l?.styles?.feedback],children:[
|
|
302
303
|
/* @__PURE__ */H(FeedbackChip,{label:m.helpful,on:i==="up",onPress:()=>o("up"),styles:d,host:l?.styles}),
|
|
303
304
|
/* @__PURE__ */H(FeedbackChip,{label:m.notHelpful,on:i==="down",onPress:()=>o("down"),styles:d,host:l?.styles})]}):null,h?u(m===null):null]})}function SourceTileGlyph(){let e=useEverfurTheme();/* @__PURE__ */
|
|
304
|
-
return H(BookGlyph,{size:
|
|
305
|
-
return H(R,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(
|
|
305
|
+
return H(BookGlyph,{size:zx,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:r,styles:n,host:l}){/* @__PURE__ */
|
|
306
|
+
return H(R,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(Db-wx)/2,children:/* @__PURE__ */H(Text,{tier:"control",style:[n.chipText,l?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:t,label:r,actions:n,options:l}){let{theme:i,styles:o}=Dx();if(e.length===0&&n.length===0)return null;let a=l?.styles,s=r??If.followUpsHeadingNative;/* @__PURE__ */
|
|
306
307
|
return U(w,{style:[o.followUps,a?.followUps],accessibilityLabel:s,testID:"everfur-cards-follow-ups",children:[
|
|
307
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */U(R,{onPress:()=>{
|
|
308
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */U(R,{onPress:()=>{vh(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:Ox,style:[o.row,o.rowAction,a?.followUp,a?.followUpAction],children:[e.icon??null,
|
|
308
309
|
/* @__PURE__ */H(Text,{tier:"control",style:[o.rowText,o.rowTextAction,a?.followUpText,a?.followUpActionText],children:e.label}),
|
|
309
|
-
/* @__PURE__ */H(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */U(R,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:
|
|
310
|
+
/* @__PURE__ */H(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */U(R,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:Ox,style:[o.row,a?.followUp],children:[
|
|
310
311
|
/* @__PURE__ */H(Text,{tier:"control",style:[o.rowText,a?.followUpText],children:e}),
|
|
311
|
-
/* @__PURE__ */H(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=
|
|
312
|
-
return H(w,{style:t.byline,children:/* @__PURE__ */H(Text,{tier:"compact",style:t.bylineText,children:e})})}function
|
|
313
|
-
return U(w,{style:c.card,accessibilityLabel:
|
|
312
|
+
/* @__PURE__ */H(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=Dx();/* @__PURE__ */
|
|
313
|
+
return H(w,{style:t.byline,children:/* @__PURE__ */H(Text,{tier:"compact",style:t.bylineText,children:e})})}function Mx(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:px,textTransform:"uppercase",color:t.text.muted},l={borderWidth:1,borderColor:t.borderRingCream},i={borderWidth:1,borderColor:co(t.text.primary,Ex)??t.borderRingCream},o={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:jx,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=$g(e.slots.chip);return b.create({answer:{gap:r.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...n,letterSpacing:px*.06,flexShrink:1},body:{gap:10},paragraph:{...face(e,"regular"),fontSize:a.fontSize,lineHeight:Math.round(a.lineHeight),color:t.text.primary},list:{gap:4},listItem:{flexDirection:"row",gap:r.sm,paddingLeft:r.xs},listText:{flex:1},bold:face(e,"bold"),italic:{fontStyle:"italic"},code:face(e,"mono"),cards:{gap:r.sm},card:{flexDirection:"row",alignItems:"center",gap:r.md,padding:bx,borderRadius:gx,backgroundColor:t.surface,...i,...o,minHeight:Db,...Ug(e.slots.card)},tile:{width:mx,height:mx,borderRadius:yx,backgroundColor:co(t.linkInk,Fx)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:mx,height:mx},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:vx,lineHeight:Math.round(vx*1.25),color:t.text.primary,...$g(e.slots.card)},cardMeta:{...n,letterSpacing:px*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:kx,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:px+2,color:t.text.muted},pill:{minHeight:Ix,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:Ax},pillText:{...face(e,"bold"),fontSize:Tx,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,alignItems:"center"},chip:{minHeight:wx,paddingHorizontal:12,borderRadius:e.radius.pill,...l,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...Lw(e),fontSize:Cx,color:t.text.primary,...chipInk},followUps:{gap:r.sm,alignSelf:"stretch",marginTop:r.xs},label:{...face(e,"bold"),fontSize:Rx,lineHeight:Math.round(Rx*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:Px,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:Sx,backgroundColor:t.surface,...i},rowAction:{},rowText:{...Lw(e),flex:1,fontSize:xx,lineHeight:Math.round(xx*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var Lx=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),Bx=/* @__PURE__ */Object.freeze(Dr.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:Lx.answers[e]})));function Hx(e,t){let[r,n]=l(null),[i,o]=l(null),[a,u]=l(null),c=s(r=>{t!==null&&(n(r),o(null),t(e.caseId,r).then(e=>{n(null),e.ok?u(r):o(e.error)}))},[t,e.caseId]),d=a??e.answer;return{answer:d,answerable:!isCheckinSettled(e),escalated:d==="worse",pending:r,error:i,choose:c}}var Ux=44,Nx=.6,$x=/* @__PURE__ */Object.freeze({caseId:"",answer:null,resolutionText:null,status:null});function CheckinCard({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:l,vet:i,onLayout:o,onOpen:s}){let u=useEverfurTheme(),c=a(()=>Wx(u),[u]),d=Hx(t??$x,t===null?null:r),f=d.answer!==null||d.pending!==null,h=t!==null&&r!==null&&d.answerable,p=t===null?null:jS(t.openedAt,FS(e));/* @__PURE__ */
|
|
314
|
+
return U(w,{style:c.card,accessibilityLabel:Lx.eyebrow,onLayout:o,children:[
|
|
314
315
|
/* @__PURE__ */U(w,{style:c.head,children:[
|
|
315
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:c.eyebrow,children:
|
|
316
|
-
return H(R,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */H(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */H(Text,{style:c.logged,children:
|
|
316
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:c.eyebrow,children:Lx.eyebrow}),p!==null?/* @__PURE__ */H(Text,{tier:"compact",style:c.headDay,children:zf(Lx.day,{day:p})}):null]}),s?/* @__PURE__ */H(R,{onPress:s,accessibilityRole:"button",accessibilityLabel:e.text,style:c.open,children:/* @__PURE__ */H(Text,{style:[c.question,c.openText],children:e.text})}):/* @__PURE__ */H(Text,{style:c.question,accessibilityRole:"text",children:e.text}),h?/* @__PURE__ */H(w,{style:[c.row,d.pending?c.rowPending:null],children:Bx.map(({answer:e,label:t})=>{let r=(d.pending??d.answer)===e;/* @__PURE__ */
|
|
317
|
+
return H(R,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */H(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */H(Text,{style:c.logged,children:Lx.logged}):null,d.escalated?/* @__PURE__ */H(CheckinFindVet,{petRef:n??null,onFindVet:l,vet:i,styles:c}):null,t?.resolutionText?/* @__PURE__ */H(Text,{style:c.resolution,children:t.resolutionText}):null,d.error?/* @__PURE__ */H(Text,{style:c.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:r,styles:n}){return useVetVisit(YC(e,r)).available&&e!==null?/* @__PURE__ */H(VetVisitButtonCore,{entry:"chat",petRef:e,label:Lx.findVet,...r?.returnTo!==void 0?{returnTo:r.returnTo}:{},...r?.usState!==void 0?{usState:r.usState}:{},...r?.prefer!==void 0?{prefer:r.prefer}:{},style:n.findVet,labelStyle:n.findVetLabel}):t===void 0?null:/* @__PURE__ */H(R,{onPress:t,accessibilityRole:"button",accessibilityLabel:Lx.findVet,style:n.findVet,children:/* @__PURE__ */H(Text,{tier:"control",style:n.findVetLabel,children:Lx.findVet})})}function Wx(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=Ng(e.slots.card),o=$g(i);return b.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:b.hairlineWidth,borderColor:t.brandBorder,...Ug(i,b.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},question:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},open:{minHeight:Ux,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:Nx},pill:{flex:1,minHeight:Ux,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.controlEdge,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,...o},resolution:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},error:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption},findVet:{alignSelf:"stretch",minHeight:Ux,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.controlEdge,backgroundColor:t.surface},findVetLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.body}})}var Vx=244,qx=8,Gx=13,Kx=14,Yx=.3,Qx=-.24,Jx=22,Xx=10,Zx=15;function CitationCards({citations:e,onOpenUrl:t}){let r=useEverfurTheme(),n=a(()=>e_(r),[r]),i=a(()=>$S(e),[e]),[o,s]=l(false);if(i.length===0)return null;let u=i.length;/* @__PURE__ */
|
|
317
318
|
return U(w,{style:n.block,children:[
|
|
318
|
-
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
319
|
-
/* @__PURE__ */H(BookGlyph,{size:
|
|
320
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:n.toggleLabel,children:
|
|
321
|
-
/* @__PURE__ */H(ChevronGlyph,{size:
|
|
322
|
-
return H(F.View,{style:l,children:/* @__PURE__ */H(z,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */H(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=
|
|
319
|
+
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:qS(u,o),accessibilityState:{expanded:o},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>s(e=>!e),children:[
|
|
320
|
+
/* @__PURE__ */H(BookGlyph,{size:Gx,color:r.color.brandInk,strokeWidth:1.5}),
|
|
321
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:n.toggleLabel,children:VS(u)}),
|
|
322
|
+
/* @__PURE__ */H(ChevronGlyph,{size:Gx,color:r.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?/* @__PURE__ */H(Deck,{cards:i,styles:n,open:t}):null]})}function Deck({cards:e,styles:t,open:r}){let n=hg(),l=Cg(n.citationsInMs,{risePx:n.citationsRisePx});/* @__PURE__ */
|
|
323
|
+
return H(F.View,{style:l,children:/* @__PURE__ */H(z,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */H(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=GS(l?e:{...e,url:null}),o=/* @__PURE__ */U(N,{children:[
|
|
323
324
|
/* @__PURE__ */U(w,{style:t.cardHeader,children:[
|
|
324
325
|
/* @__PURE__ */H(w,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),
|
|
325
|
-
/* @__PURE__ */H(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */H(ArrowUpRightGlyph,{size:
|
|
326
|
+
/* @__PURE__ */H(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */H(ArrowUpRightGlyph,{size:Kx,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */H(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */H(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let n=e.url;/* @__PURE__ */
|
|
326
327
|
return H(PressScale,{accessibilityRole:"link",accessibilityLabel:i,style:t.card,onPress:()=>r(n),children:o})}/* @__PURE__ */
|
|
327
|
-
return H(w,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function
|
|
328
|
-
/* @__PURE__ */U(w,{style:[c.row,f?c.rowUser:c.rowAssistant],children:[h!==null?/* @__PURE__ */H(Text,{tier:"compact",style:c.timestamp,children:h}):null,p?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:b?
|
|
329
|
-
/* @__PURE__ */H(Text,{style:c.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:
|
|
330
|
-
/* @__PURE__ */H(AnnounceLine,{line:
|
|
328
|
+
return H(w,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function e_(e){let t=e.color,r=e.space,n=e.radius,l=e.type.size,i=$g(e.slots.card);return b.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:l.micro,lineHeight:l.micro,letterSpacing:Yx,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:Vx,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2,...Ug(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:qx,height:qx,borderRadius:n.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:l.bodyTight,lineHeight:Jx,color:t.text.primary,letterSpacing:Qx,...i},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:l.nano,lineHeight:Xx,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...i},cardExcerpt:{...face(e,"regular"),fontSize:l.tiny,lineHeight:Zx,color:t.text.muted,...i}})}var t_=15,r_=44,n_=16,l_=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:e,onCopy:t,sentiment:r=null,onSentiment:i,note:o=null}){let s=useEverfurTheme(),c=a(()=>i_(s),[s]),d=hg(),f=e.role==="user",h=a(()=>AS(e.createdAt),[e.createdAt]),p=t!==void 0&&e.role!=="vet"&&e.text.length>0,g=e.role==="assistant"&&i!==void 0&&e.responseId!==void 0,[b,m]=l(false),y=u(null);n(()=>()=>{y.current&&clearTimeout(y.current)},[]);let v=()=>{t!==void 0&&(Ch(t,e.text),m(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null},d.copiedMs))};return h===null&&!p&&!g?null:/* @__PURE__ */U(w,{style:c.wrap,children:[
|
|
329
|
+
/* @__PURE__ */U(w,{style:[c.row,f?c.rowUser:c.rowAssistant],children:[h!==null?/* @__PURE__ */H(Text,{tier:"compact",style:c.timestamp,children:h}):null,p?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:b?If.copied:f?If.copyUserMessage:If.copyAssistantMessage,onPress:v,style:c.iconHit,children:b?/* @__PURE__ */H(CheckGlyph,{size:t_,color:s.color.success,strokeWidth:2}):/* @__PURE__ */H(CopyGlyph,{size:t_,color:s.color.text.timestamp,strokeWidth:1.5})}):null,g?Ck.map(({sentiment:e,label:t})=>/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r===e},onPress:()=>i?.(e),style:c.iconHit,children:/* @__PURE__ */H(ThumbGlyph,{size:t_,color:r===e?s.color.sentiment[e]:s.color.text.timestamp,active:r===e,rotate:l_[e],strokeWidth:1.5})},e)):null]}),o==="thanks"?/* @__PURE__ */H(Text,{style:c.thanks,accessibilityLiveRegion:"polite",children:If.feedbackThanks}):null,o==="failed"?/* @__PURE__ */U(N,{children:[
|
|
330
|
+
/* @__PURE__ */H(Text,{style:c.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:If.feedbackFailed}),
|
|
331
|
+
/* @__PURE__ */H(AnnounceLine,{line:If.feedbackFailed})]}):null]})}function i_(e){let t=e.type;return b.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:n_,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:r_,height:r_,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary},failed:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.danger}})}var o_=16,a_=10,s_=12,u_=10,c_=2,d_=.06,f_=34,h_=9,p_=10.5,g_=.06,b_=15,m_=19.5,y_=14,v_=19.6;function OpeningCard({card:e,onLayout:t}){let r=useEverfurTheme(),n=a(()=>k_(r),[r]),l=e.styles;/* @__PURE__ */
|
|
331
332
|
return U(w,{testID:"everfur-opening-card",onLayout:t,accessible:true,accessibilityLabel:[e.kicker,e.title,e.body].filter(e=>e!==void 0).join(", "),style:[n.card,l?.card],children:[e.icon!==void 0?/* @__PURE__ */H(w,{style:[n.icon,l?.icon],children:e.icon}):null,
|
|
332
333
|
/* @__PURE__ */U(w,{style:n.words,children:[
|
|
333
334
|
/* @__PURE__ */H(Text,{tier:"compact",style:[n.kicker,l?.kicker],children:e.kicker}),
|
|
334
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */H(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function
|
|
335
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */H(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function k_(e){let t=e.color;return b.create({card:{flexDirection:"row",alignItems:"flex-start",gap:u_,paddingVertical:a_,paddingHorizontal:s_,alignSelf:"stretch",borderRadius:o_,backgroundColor:t.surface,borderWidth:1,borderColor:co(t.text.primary,d_)??t.borderRingCream},icon:{flexShrink:0,width:f_,height:f_,borderRadius:h_,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:c_},kicker:{...face(e,"mono"),fontSize:p_,letterSpacing:p_*g_,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:b_,lineHeight:m_,color:t.text.primary},body:{...face(e,"regular"),fontSize:y_,lineHeight:v_,color:t.text.secondary}})}var w_="#10462E",C_="Book a video visit",S_="#000000",x_="#83E0B4",__=/* @__PURE__ */Object.freeze([
|
|
335
336
|
/* @__PURE__ */Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
336
|
-
/* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:
|
|
337
|
-
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:
|
|
338
|
-
/* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function
|
|
339
|
-
return Object.freeze(
|
|
337
|
+
/* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:x_,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
338
|
+
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:w_,brandEdge:true,borderWidth:1}),
|
|
339
|
+
/* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function R_(e,t){return e?null:{fill:t.fill,ink:t.ink}}var T_=8;function I_(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function z_(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=T_)break;if(r===null||typeof r!="object"||typeof r.label!="string")continue;let e=r.label.trim();if(e.length===0)continue;let n=typeof r.prompt=="string"&&r.prompt.trim().length>0?r.prompt.trim():e,l=I_(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:l,ink:l===null?null:I_(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var P_=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function O_(e){return e==null?e:e.replace(P_,"").trim()}var E_=/* @__PURE__ */new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function j_(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return E_.has(t)}function F_(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function A_(e,t){let r=e?.trim();if(r===void 0||r==="")return D_(t);let n=t?.name?.trim()||If.emptyTitlePetFallback,l=n.charAt(0).toUpperCase()+n.slice(1);return r.replace(/\{(pet|petName)\}/g,(e,t,r)=>r===0?l:n)}function D_(e){let t=e?.name?.trim()||If.emptyTitlePetFallback;return zf(If.emptyTitle,{petName:t})}function M_(e){let t=e.toLowerCase();return t===F_("dog").toLowerCase()||t===F_("cat").toLowerCase()}function L_(e){let t=O_(e);if(j_(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return M_(r)?null:r}function B_(e,t=w_,r){let n=canonicalPetSpecies(e?.species),l=e?.name?.trim()||null,i=L_(e?.breed),o=jv(e?.ageYears),a=o===null?null:String(o),s=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
|
|
340
|
+
return Object.freeze(__.flatMap(e=>{let r=e.intent==="vet_report"&&s!==null?s:e.label,o=r.includes("{breed}"),u=r.includes("{ageYears}"),c=e.fallbackLabel!==void 0&&(o&&!i||u&&!a)&&e.fallbackLabel?e.fallbackLabel:r;if(c.includes("{breed}")&&i===null||c.includes("{ageYears}")&&a===null||n===null&&(c.includes("{species}")||c.includes("{petName}")&&l===null))return[];let d=zf(c,{petName:l??(n==="cat"?"my cat":"my dog"),breed:i??"",species:n??"",ageYears:a??""}),f=!l&&c.startsWith("{petName}")?d.charAt(0).toUpperCase()+d.slice(1):d;return[/* @__PURE__ */Object.freeze({id:e.id,intent:e.intent,label:f,background:e.background,borderColor:e.brandEdge===true?t:e.borderColor,borderWidth:e.borderWidth})]}))}var H_=44,U_=0,N_={top:3,bottom:3},$_=1,W_=.28,V_=2,q_=2,G_=1.3,K_=-.015,Y_=/* @__PURE__ */Object.freeze([
|
|
340
341
|
/* @__PURE__ */Object.freeze({tint:"#FFE7A1",ink:"#262523"}),
|
|
341
342
|
/* @__PURE__ */Object.freeze({tint:"#C8F4F8",ink:"#262523"}),
|
|
342
343
|
/* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
|
|
343
|
-
/* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()=>
|
|
344
|
-
return U(w,{style:
|
|
345
|
-
/* @__PURE__ */H(w,{style:
|
|
346
|
-
return H(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,
|
|
344
|
+
/* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()=>Q_(u),[u]),d=a(()=>z_(i),[i]),f=a(()=>d!==null?d.map(e=>({prompt:{id:e.id,intent:"send",label:e.label,background:e.tint??u.color.highlight,borderColor:"transparent",borderWidth:1},send:e.prompt,paint:e.tint===null?null:{fill:e.tint,ink:e.ink??u.color.text.primary}})):B_(e,u.color.brandInk,{vetPrepLabel:C_}).map(e=>({prompt:e,send:e.label,paint:null})),[d,e,u.color.brandInk,u.color.highlight,u.color.text.primary]),h=o?.chipTints!==void 0,p=a(()=>(o?.chipTints??(u.brightness==="light"?Y_:[])).filter(e=>typeof e.tint=="string"&&e.tint.trim()!==""),[o?.chipTints,u.brightness]),g=a(()=>p.length===0?f:f.map((e,t)=>{if(e.paint!==null)return e;let r=p[t%p.length];return{...e,paint:{fill:r.tint,ink:r.ink??u.color.text.primary},...h?{}:{cycleDefault:true}}}),[f,p,h,u.color.text.primary]),b=a(()=>R_(Pv(u),{fill:u.color.highlight,ink:u.color.onHighlight}),[u]),m=a(()=>({fill:u.color.highlight,ink:u.color.onHighlight}),[u.color.highlight,u.color.onHighlight]),y=A_(o?.title,e),v=Hk(),k=Uk(),C=v!==null&&k!==null?/* @__PURE__ */H(k.Title,{text:y,style:[c.title,v.text(".serif",".ask-empty h2"),c.centerText],measureCh:k.titleCh}):/* @__PURE__ */H(Text,{tier:"heading",style:s?[c.title,c.centerText]:c.title,accessibilityRole:"header",children:y});/* @__PURE__ */
|
|
345
|
+
return U(w,{style:v!==null?c.homeBlock:c.block,children:[C,
|
|
346
|
+
/* @__PURE__ */H(w,{style:v!==null?[c.list,c.listCentered,v.view(".ask-chips",".ask-empty .ask-chips")]:s?[c.list,c.listCentered]:c.list,accessibilityLabel:If.suggestions,children:g.map(({prompt:i,send:o,paint:a,cycleDefault:u},f)=>/* @__PURE__ */H(Chip,{prompt:i,send:o,themed:a??(d!==null?m:b),index:f,petRef:t,onSend:r,onVetPrep:n,vet:l,pet:e,styles:c,tinted:a!==null&&u!==true,soft:a!==null,centered:s},i.id))})]})}function Chip({prompt:e,send:t,themed:r,index:n,pet:l,petRef:i,onSend:o,onVetPrep:a,vet:s,styles:u,tinted:c,soft:d,centered:f}){let h=hg(),p=Cg(h.followUpInMs,{delayMs:dg(h,n),risePx:h.promptRisePx}),g=Hk(),b=g!==null?[u.chipHome,g.view(".chip")]:f&&d?u.chipNoEdge:u.chipEdge,m={backgroundColor:r?.fill??e.background},y=u.chipSlot===null?m:c?{...u.chipSlot,...m}:{...m,...u.chipSlot},v=g!==null?[u.chipLabel,g.text(".chip")]:f?[u.chipLabel,u.centerText]:[u.chipLabel],k=g!==null?N_:U_,w=r===null?u.chipSlotLabel===null?v:[...v,u.chipSlotLabel]:c?[...v,...u.chipSlotLabel===null?[]:[u.chipSlotLabel],{color:r.ink}]:[...v,{color:r.ink},...u.chipSlotLabel===null?[]:[u.chipSlotLabel]];return e.intent==="vet_report"?a!==void 0?/* @__PURE__ */H(F.View,{style:p,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>{vh(a,l)},children:/* @__PURE__ */H(Text,{tier:"compact",style:w,children:e.label})})}):i===null?null:/* @__PURE__ */H(F.View,{style:p,children:/* @__PURE__ */H(VetVisitButtonCore,{entry:"chat",petRef:i,label:e.label,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:[u.chip,b,y],labelStyle:w})}):/* @__PURE__ */H(F.View,{style:p,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>o(t),children:/* @__PURE__ */H(Text,{tier:"compact",style:w,children:e.label})})})}function Q_(e){let t=Ng(e.slots.chip),r=$g(t);return{chipSlot:t===void 0?null:Ug(t,$_),chipSlotLabel:r.color===void 0?null:r,...J_(e)}}function J_(e){let t=e.color,r=e.space,n=e.type;return b.create({block:{gap:r.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:n.size.heading,lineHeight:Math.round(n.size.heading*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.size.heading*K_,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:r.sm+V_},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:$_,borderColor:"transparent"},chip:{borderRadius:e.radius.pill,paddingHorizontal:r.lg+q_,paddingVertical:r.sm,minHeight:H_,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:$_,borderColor:co(t.brandInk,W_)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*G_),color:S_,textAlign:"left"}})}var X_=1e3,Z_=150,eR=.25,tR=.5,rR=3;function TypingIndicator({petName:e=null,inline:t=false}){let{theme:r,styles:l}=Tm(),i=r.motion.reducedMotion,o=Of(If.reading,e),a=u(Array.from({length:rR},()=>new F.Value(0))).current;return n(()=>{if(i)return;let e=a.map((e,t)=>F.loop(F.sequence([F.delay(t*Z_),F.timing(e,{toValue:1,duration:X_*.4,useNativeDriver:true}),F.timing(e,{toValue:0,duration:X_*.6,useNativeDriver:true}),F.delay((rR-t-1)*Z_)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[i,a]),/* @__PURE__ */H(w,{style:t?l.readingInline:l.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:o,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:a.map((e,r)=>/* @__PURE__ */H(F.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[t?l.readingDotInline:l.readingDot,i?{opacity:tR}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[eR,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},r))})}function nR(e,t,r){let n=e-r,l=t!=null?Math.min(n,t):n;return Math.max(0,l)}function lR(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return{assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}function iR(e,t,r){let n=Math.max(0,r),l=e===null?n:Math.min(Math.max(0,e),n);return l>t+1?l:null}var oR=16;function aR(e,t,r=null){let l=u(null),i=u(true),o=u(t),a=u(0),c=u(0),d=u(0),f=u(/* @__PURE__ */new Map),h=u(null),p=u(false),g=e[0]?.id??null,b=u(g),m=u(null);n(()=>{let t=b.current;if(b.current=g,t===null||t===g||(m.current=null,i.current||!e.some(e=>e.id===t)))return;let r=f.current.get(t);r!==void 0&&(m.current={id:t,top:r,offset:a.current})},[g,e]);let y=lR(e),v=y===null?null:e[y.assistantIndex]?.id??null,k=y===null||y.userIndex===null?null:e[y.userIndex]?.id??null,w=s(()=>{let e=l.current;if(e===null||!i.current||c.current===0)return;let t=null;if(v!==null){let e=f.current.get(v);if(e===void 0)return;let r=k===null?null:f.current.get(k)??null;t=nR(e,r,96)}let r=iR(t,a.current,d.current-c.current);if(r!==null&&(a.current=r,e.scrollTo({y:r,animated:false})),!p.current||h.current===null)return;let n=iR(h.current+oR-c.current,a.current,d.current-c.current);n!==null&&(a.current=n,e.scrollTo({y:n,animated:false}))},[v,k]);n(()=>{p.current=r!==null,r===null&&(h.current=null),w()},[r,w]),n(()=>{t&&!o.current&&(i.current=true,p.current=false),o.current=t,w()},[e,t,w]);let C=s(e=>{c.current=e.nativeEvent.layout.height,w()},[w]),S=s((e,t)=>{d.current=t,c.current>0&&(a.current=Math.min(a.current,Math.max(0,t-c.current))),w()},[w]),x=s(e=>{a.current=e.nativeEvent.contentOffset.y},[]),_=s(()=>{i.current=false,p.current=false},[]),R=s(e=>{let{contentOffset:t,contentSize:r,layoutMeasurement:n}=e.nativeEvent;a.current=t.y,i.current=r.height-t.y-n.height<=24},[]),T=s(e=>t=>{let r=t.nativeEvent.layout.y;f.current.set(e,r);let n=m.current;if(n!==null&&n.id===e&&r!==n.top){m.current=null;let e=Math.max(0,n.offset+r-n.top);a.current=e,l.current?.scrollTo({y:e,animated:false})}(e===v||e===k)&&w()},[v,k,w]),I=s(e=>{let{y:t,height:r}=e.nativeEvent.layout;h.current=t+r,w()},[w]);return{ref:l,onLayout:C,onContentSizeChange:S,onScroll:x,onScrollBeginDrag:_,onScrollEnd:R,rowLayout:T,asideLayout:I}}function sR(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */H(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */H(LoadingState,{})}):/* @__PURE__ */H(LoadingState,{});case"empty":/* @__PURE__ */
|
|
347
|
+
return H(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,renderEmptyHeader:r.renderEmptyHeader});case"error":/* @__PURE__ */
|
|
347
348
|
return H(ErrorState,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case"populated":/* @__PURE__ */
|
|
348
|
-
return H(PopulatedState,{messages:t.messages,prompts:
|
|
349
|
-
return U(z,{contentContainerStyle:[f
|
|
350
|
-
/* @__PURE__ */H(w,{style:
|
|
349
|
+
return H(PopulatedState,{messages:t.messages,prompts:Wh(t,r.followUpPolicy),actions:r.answerCards?tx(t,r.answerCards):cR,answerCards:r.answerCards??null,threadTop:r.threadTop,pendingCheckin:r.pendingCheckin??null,threadAside:r.threadAside,threadAsideKey:r.threadAsideKey??null,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,feedbackNote:r.feedbackNote,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl,petName:r.shownPet?.name??null,followUpLabel:r.followUpPolicy?.label,openingCard:r.openingCard,earlier:t.historyCursor?{loading:t.isLoadingHistory,load:t.loadOlderMessages}:null});default:return assertNever(e)}}function LoadingState(){let{theme:e,styles:t}=Tm(),[r,i]=l(false);return n(()=>{let e=setTimeout(()=>i(true),jb);return()=>clearTimeout(e)},[]),/* @__PURE__ */H(w,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:If.loading,children:r?/* @__PURE__ */H(P,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:l,top:i,topCard:o,pendingCheckin:a,starterPrompts:s,emptyState:u,centered:c,renderEmptyHeader:d}){let{styles:f}=Tm(),h=Hk(),p=d===void 0?null:/* @__PURE__ */H(w,{testID:"everfur-empty-header",children:/* @__PURE__ */H(HostRender,{render:()=>d({ask:r}),fallback:null})});if(h!==null){let{minHeight:c,...d}=h.view(".ask-empty");/* @__PURE__ */
|
|
350
|
+
return U(z,{contentContainerStyle:[d,f.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:fR,nestedScrollEnabled:true,accessibilityLabel:If.empty,children:[i!=null?/* @__PURE__ */H(w,{style:h.view(".ask-top"),children:i}):null,a,o??null,p,
|
|
351
|
+
/* @__PURE__ */H(w,{style:h.view(".ask-start"),children:/* @__PURE__ */H(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:true})})]})}
|
|
351
352
|
/* @__PURE__ */
|
|
352
|
-
return U(z,{contentContainerStyle:
|
|
353
|
-
/* @__PURE__ */H(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})
|
|
354
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??
|
|
353
|
+
return U(z,{contentContainerStyle:f.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:fR,nestedScrollEnabled:true,accessibilityLabel:If.empty,children:[i??null,a,o??null,p,
|
|
354
|
+
/* @__PURE__ */H(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:r}){let{styles:n}=Tm();return e.length===0?null:/* @__PURE__ */U(w,{style:n.followUps,children:[
|
|
355
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??If.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */H(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:l}=Tm(),i=hg(),o=Cg(i.followUpInMs,{delayMs:dg(i,t)});/* @__PURE__ */
|
|
355
356
|
return H(F.View,{style:o,children:/* @__PURE__ */U(PressScale,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[l.followUpSlot,t>0?l.followUpSlotRuled:null],style:l.followUpRow,children:[
|
|
356
357
|
/* @__PURE__ */H(Text,{tier:"control",style:l.followUpText,children:e}),
|
|
357
|
-
/* @__PURE__ */H(PlusGlyph,{size:
|
|
358
|
+
/* @__PURE__ */H(PlusGlyph,{size:hR,color:n.slots.chip?.textColor??n.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Tm(),l=Jh(e)?wh(r):void 0,i=Ah(e);/* @__PURE__ */
|
|
358
359
|
return U(w,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[i!==null?/* @__PURE__ */H(Text,{style:n.errorText,testID:"everfur-chat-cap-reached",children:i.reached}):null,
|
|
359
|
-
/* @__PURE__ */H(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */H(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */H(R,{onPress:l,accessibilityRole:"button",accessibilityLabel:
|
|
360
|
-
return U(z,{ref:
|
|
360
|
+
/* @__PURE__ */H(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */H(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */H(R,{onPress:l,accessibilityRole:"button",accessibilityLabel:If.addPet,style:n.retryButton,children:/* @__PURE__ */H(Text,{tier:"control",style:n.retryLabel,children:If.addPet})}):null,e.retryable?/* @__PURE__ */H(R,{onPress:t,accessibilityRole:"button",accessibilityLabel:If.retry,style:n.retryButton,children:/* @__PURE__ */H(Text,{tier:"control",style:n.retryLabel,children:If.retry})}):null]})}function PopulatedState({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:l,onCopy:i,sentimentByMessage:o,onSentiment:s,feedbackNote:u,imagesByMessage:c,onPreview:d,notice:f,reconnecting:h,onRetry:p,onStartNew:g,petRef:b,onFindVet:m,vet:y,onOpenUrl:v,petName:k,actions:C,answerCards:S,threadTop:x,pendingCheckin:_,threadAside:T,threadAsideKey:I,followUpLabel:P,openingCard:O,earlier:E}){let{styles:j}=Tm(),F=hg();Pg(e.length,F);let A=a(()=>PS(zS(e)),[e]),D=Lh(e,n),M=e[e.length-1],L=T??null,B=aR(e,n,L===null?null:I??"shown"),N=_g(e),$=e[0],W=O!==void 0&&$!==void 0&&$.role==="user"&&$.text.trim()===O.prompt?$.id:null;/* @__PURE__ */
|
|
361
|
+
return U(z,{ref:B.ref,style:j.list,contentContainerStyle:S!==null?j.listContentCards:j.listContent,accessibilityLabel:If.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:fR,nestedScrollEnabled:true,onLayout:B.onLayout,onContentSizeChange:B.onContentSizeChange,onScroll:B.onScroll,scrollEventThrottle:dR,onScrollBeginDrag:B.onScrollBeginDrag,onScrollEndDrag:B.onScrollEnd,onMomentumScrollEnd:B.onScrollEnd,children:[x??null,_,E!==null?/* @__PURE__ */H(R,{onPress:()=>{E.load()},disabled:E.loading,accessibilityRole:"button",accessibilityLabel:E.loading?Pp.loadingEarlier:Pp.earlier,accessibilityState:{disabled:E.loading,busy:E.loading},hitSlop:Zb,style:j.earlierButton,children:/* @__PURE__ */H(Text,{tier:"compact",style:j.earlierLabel,children:E.loading?Pp.loadingEarlier:Pp.earlier})}):null,e.map(t=>t.id===W&&O!==void 0?/* @__PURE__ */H(OpeningCard,{card:O.card,onLayout:B.rowLayout(t.id)},t.id):t.checkin&&A.has(t.id)?/* @__PURE__ */H(CheckinCard,{message:t,checkin:t.checkin,onAnswer:l,petRef:b,onFindVet:m,vet:y,onLayout:B.rowLayout(t.id)},t.id):/* @__PURE__ */H(MessageRow,{onLayout:B.rowLayout(t.id),message:t,revealing:n&&t===M&&t.role==="assistant",onCopy:i,sentiment:t.responseId===void 0?null:o[String(t.responseId)]??null,onSentiment:s,note:t.responseId!==void 0&&u?.responseId===String(t.responseId)?u.kind:null,images:c[t.id]??uR,onPreview:d,onOpenUrl:v,entering:N(t.id),answerCards:S,messages:e},t.id)),h?/* @__PURE__ */H(Text,{tier:"compact",style:j.reconnectingCaption,accessibilityRole:"text",children:If.reconnecting}):null,D?/* @__PURE__ */H(TypingIndicator,{petName:k,inline:S!==null}):null,f!==null?/* @__PURE__ */H(TurnNoticeCard,{notice:f,onRetry:p,onStartNew:g}):null,S!==null?/* @__PURE__ */H(CardsFollowUps,{prompts:t,onSelectPrompt:r,label:P,actions:C,options:S}):/* @__PURE__ */H(FollowUps,{prompts:t,onSelectPrompt:r,label:P}),L!==null?/* @__PURE__ */H(w,{onLayout:B.asideLayout,children:L}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Tm(),l=e.tone==="error";/* @__PURE__ */
|
|
361
362
|
return U(w,{style:[n.turnNotice,l?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
|
|
362
363
|
/* @__PURE__ */H(Text,{tier:"control",style:[n.turnNoticeTitle,l?n.turnNoticeTitleError:null],children:e.title}),
|
|
363
364
|
/* @__PURE__ */H(Text,{tier:"compact",style:n.turnNoticeBody,children:e.body}),e.guidance!==void 0?/* @__PURE__ */H(Text,{tier:"compact",style:n.turnNoticeBody,testID:"everfur-chat-cap-guidance",children:e.guidance}):null,
|
|
364
|
-
/* @__PURE__ */H(R,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:
|
|
365
|
+
/* @__PURE__ */H(R,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Zb,style:n.turnNoticeAction,children:/* @__PURE__ */H(Text,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}var uR=/* @__PURE__ */Object.freeze([]),cR=/* @__PURE__ */Object.freeze([]),dR=16,fR=p.OS==="ios"?"interactive":"on-drag",hR=18;function MessageRow({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:l,note:i,images:o,onPreview:a,onOpenUrl:u,onLayout:c,entering:d,answerCards:f,messages:h}){let{theme:p,styles:g}=Tm(),b=hg(),m=xg(d,b),y=Tg(e.text,t,b),v=e.role==="user",k=e.role==="vet",C=e.role==="assistant",S=rg(),x=C&&!t?S:void 0,_=x!==void 0&&fx(e.text,x),R=C&&!p.meta.hidePoweredBy,T=v?If.senderUser:k?Vh(e):R?If.assistantName:If.senderAssistant,I=k?AS(e.createdAt):null,z=s(t=>l(e,t),[l,e]),P=e.pending!==true,O=C&&p.meta.assistantAvatarUrl!==null?/* @__PURE__ */H(AssistantSender,{avatarUrl:p.meta.assistantAvatarUrl,named:R,styles:g}):R?f!==null?/* @__PURE__ */H(CardsByline,{label:If.assistantName}):/* @__PURE__ */H(Text,{tier:"control",style:g.assistantName,children:If.assistantName}):null,E=f!==null;return C&&f!==null?/* @__PURE__ */H(F.View,{style:[g.rowBlock,m],onLayout:c,accessibilityLabel:`${T}: ${e.text}`,children:/* @__PURE__ */H(CardsAnswer,{message:e,text:y,streaming:t,messages:h,options:f,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,sender:O,onOpenUrl:u,footer:t=>/* @__PURE__ */H(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:t&&e.responseId!==void 0?z:void 0,note:i})})}):/* @__PURE__ */U(w,{style:[g.rowBlock,v?g.rowBlockUser:g.rowBlockAssistant],onLayout:c,children:[
|
|
365
366
|
/* @__PURE__ */H(w,{style:[g.row,v?g.rowUser:g.rowAssistant],accessible:!_,accessibilityRole:_?void 0:"text",accessibilityLabel:_?void 0:`${T}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:/* @__PURE__ */U(F.View,{style:[g.bubble,E?g.bubbleCards:null,v?g.bubbleSideUser:null,m],children:[O,k?/* @__PURE__ */U(w,{style:g.vetHeader,children:[
|
|
366
367
|
/* @__PURE__ */H(Text,{tier:"control",style:g.vetSender,children:T}),I!==null?/* @__PURE__ */H(Text,{tier:"compact",style:g.vetTime,children:I}):null]}):null,
|
|
367
368
|
/* @__PURE__ */U(w,{style:[v?g.bubbleUser:k?g.bubbleVet:g.bubbleAssistant,v&&E?g.bubbleUserCards:null,e.pending?g.bubblePending:null],children:[v&&o.length>0?/* @__PURE__ */H(SentImages,{images:o,onPreview:e=>a({uri:e.uri,label:e.filename})}):null,
|
|
368
|
-
/* @__PURE__ */H(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:C?
|
|
369
|
+
/* @__PURE__ */H(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:C?hx(y,{bold:g.bubbleBold,italic:g.bubbleItalic,code:g.bubbleCode},x):e.text})]})]})}),C&&!t?/* @__PURE__ */H(CitationCards,{citations:e.citations,onOpenUrl:u}):null,P&&!(v&&f!==null)?/* @__PURE__ */H(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,note:i}):null]})}var pR=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(e){if(e.isBootstrapping===true||e.isLoadingHistory===true||e.isStreaming===true||e.status==="error"||e.stopped===true)return false;let t=e.messages[e.messages.length-1];return t===void 0||t.role!=="assistant"||t.pending===true||t.checkin!==void 0||t.text.trim().length===0?false:!(typeof t.urgencyLevel=="string"&&pR.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function gR(){let{runtime:e}=bd(),t=e.entitlements??null,r=s(e=>t===null?()=>{}:t.subscribe(e),[t]),n=t===null?NO_SNAPSHOT2:t.getSnapshot,l=i(r,n,n);return a(()=>l!==null&&decideCapability("texting",l.decisions,{isPending:l.isPending}).enabled,[l])}var bR=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function mR(e,t,r=false){let[n,i]=l(null);if(!e)return bR;let o=/* @__PURE__ */H(AskRunner,{ready:textingAskThreadReady(t),onAsk:i,entry:r}),a=r&&n!==null&&n.canOpen?{label:W.textingAskLines(n).accept,onOpen:n.open}:null;if(n===null||n.stage==="hidden"||n.stage==="dismissed")return{runner:o,line:null,entry:null,stage:null,headerEntry:a};let s=W.textingAskLines(n),u=/* @__PURE__ */H(AskLine,{stage:n.stage,text:n.stage==="verified"?s.verified:s.line,accept:s.accept,dismiss:s.dismiss,onAccept:n.accept,onDismiss:n.dismiss}),c=n.stage==="enrolling"?/* @__PURE__ */H(W.ChatTextingAskComposer,{ask:n}):null;return{runner:o,line:u,entry:c,stage:n.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:t,entry:r}){let{userRef:l}=bd(),i=gR(),o=l!==null&&i;return n(()=>{o||t(null)},[o,t]),o?/* @__PURE__ */H(W.ChatTextingAskController,{enabled:true,ready:e,onAsk:t,entry:r}):null}function AskLine({stage:e,text:t,accept:r,dismiss:n,onAccept:l,onDismiss:i}){let{theme:o,styles:a}=Tm(),s=!o.meta.hidePoweredBy,u=s?If.assistantName:If.senderAssistant,c=o.meta.assistantAvatarUrl!==null?/* @__PURE__ */H(AssistantSender,{avatarUrl:o.meta.assistantAvatarUrl,named:s,styles:a}):s?/* @__PURE__ */H(Text,{tier:"control",style:a.assistantName,children:If.assistantName}):null;/* @__PURE__ */
|
|
369
370
|
return U(w,{style:[a.rowBlock,a.rowBlockAssistant],testID:`everfur-texting-ask-${e}`,children:[
|
|
370
371
|
/* @__PURE__ */H(w,{style:[a.row,a.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${u}: ${t}`,children:/* @__PURE__ */U(w,{style:a.bubble,children:[c,
|
|
371
|
-
/* @__PURE__ */H(w,{style:a.bubbleAssistant,children:/* @__PURE__ */H(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */H(w,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */H(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */H(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function
|
|
372
|
-
return H(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */H(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */H(ChatBody,{...e})})})}function
|
|
373
|
-
return H(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=
|
|
374
|
-
return H(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:c,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:g,attachments:b,pet:m,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:C,initialAskKey:S,composerSeed:x,lifecycle:R,refreshIntervalMs:T,refreshesBlankThread:I,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:B,historySheet:$,historyBar:W,starterPrompts:V,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:J}){let{presentation:X,isLocked:isLocked,planPage:Z,planPetRef:ee}=e,{theme:te,styles:re}=
|
|
375
|
-
/* @__PURE__ */H(TopCard,{card:Je,open:Xe,onOpenChange:Ze,ask:et}),at===void 0?ot:null]}),dt=at!==void 0,ft=he.load,ht=he.open;n(()=>{dt&&!ht&&ft()},[dt,ht,ce.conversationId,ft]);let pt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:Se,draftStore:P,onStage:Pe.stage,onPreview:Ee,petName:ye?.name??null,petBreed:ye?.breed??null,compact:X.chatComposerStyle==="compact",petPlaceholder:X.chatComposerPlaceholder==="pet_name",dimEmptySend:X.chatSendButton==="dim_when_empty",mood:
|
|
372
|
+
/* @__PURE__ */H(w,{style:a.bubbleAssistant,children:/* @__PURE__ */H(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */H(w,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */H(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */H(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function yR(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),t=globalThis;return t[e]??(t[e]=createContext(null))}var vR=/* @__PURE__ */yR();function kR(e){return typeof e=="object"&&e!==null&&e.ok===true}function wR(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:ut(t.error)}function CR(e){let t=o(vR),r=t?.onMessageSent,n=t?.onFreeCapReached,l=s((...t)=>{let l=e(...t);return Promise.resolve(l).then(e=>{try{if(kR(e)){r?.();return}let t=n===void 0?null:wR(e);t!==null&&n?.(t)}catch{}},()=>{}),l},[e,r,n]);return r===void 0&&n===void 0?e:l}function EverfurChatCore(e){let{style:t,renderPending:r}=e;/* @__PURE__ */
|
|
373
|
+
return H(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */H(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */H(ChatBody,{...e})})})}function SR(){try{return bd()}catch{return null}}function xR(e){return jh({...e.presentation,chatComposerMic:e.presentation?.chatComposerMic??(e.dictation===void 0?void 0:e.dictation!==false),chatComposerUpload:e.presentation?.chatComposerUpload??(e.attachments===void 0?void 0:true)})}function ChatBody(e){let t=SR();return t===null?/* @__PURE__ */H(ChatBodyAlone,{...e}):/* @__PURE__ */H(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let t=xR(e),r=JSON.stringify(t),n=e.petRef??null,l=a(()=>({presentation:resolvePresentation({server:null,locked:null,client:t}),isLocked:()=>false,planPage:null,planPetRef:n,inProvider:false,telemetry:null}),[r,n]);/* @__PURE__ */
|
|
374
|
+
return H(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=Eh(xR(r)),l=Zd("healthPlan"),i=n.chatTopCard==="focus"&&r.topCard===void 0&&l,o=r.petRef??e??null,s=useHealthPlanPage({petRef:o,enabled:i}),u=i&&s.phase==="ready"?s.page:null,c=a(()=>({presentation:n,isLocked:isLocked,planPage:u,planPetRef:o,inProvider:true,telemetry:t}),[n,isLocked,u,o,t]);/* @__PURE__ */
|
|
375
|
+
return H(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:c,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:g,attachments:b,pet:m,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:C,initialAskKey:S,composerSeed:x,lifecycle:R,refreshIntervalMs:T,refreshesBlankThread:I,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:B,historySheet:$,historyBar:W,starterPrompts:V,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:J}){let{presentation:X,isLocked:isLocked,planPage:Z,planPetRef:ee}=e,{theme:te,styles:re}=Tm(),ne=Bk()??(X.chatAnswerStyle==="cards"?jC:null),le=a(()=>ne===null?null:ne(te),[ne,te]),ie=useHostPoweredBy(),oe=hg(),ae=a(()=>qh(t,r),[t,r]),se=useEverfurChat(ae),ue=CR(se.send),ce=a(()=>ue===se.send?se:{...se,send:ue},[se,ue]),de=Fh(ce),fe=SS(),he=Bp(ce),pe=L(),ge=Mh(ce,"web"),be=a(()=>h===void 0?void 0:()=>{vh(h,"emergency")},[h]),me=a(()=>O===void 0&&E===void 0&&j===void 0?void 0:{returnTo:O,usState:E,prefer:j},[O,E,j]),ye=vk(fe.pets,ce.petRef),ve=a(()=>Vp(ce.messages,ye?.name??null),[ce.messages,ye?.name]),ke=Gp(ve);_S(ce),Pg(ke.showBanner,oe);let we=SR(),Ce=Tp(k,we);zp(ce.openCheckin,v??Ce,{petRef:ce.petRef,pinned:t!==void 0,ready:!ce.isBootstrapping,selectPet:e=>{fe.setActivePet(e),vh(d,e)}}),ap(ce.askEverfur,ce.isBootstrapping,C,S);let Se=a(()=>op(x),[x]),xe=a(()=>op(C),[C]),_e=a(()=>J!==void 0&&xe!==null?{card:J,prompt:xe}:void 0,[J,xe]),Re=a(()=>R===void 0?createAppStateLifecycle():R??void 0,[R]);mp(Re,{conversationId:ce.conversationId===null?null:String(ce.conversationId),isTurnInFlight:ce.isStreaming,refreshesBlankThread:I===true||z===true,refresh:ce.refreshActiveThread===void 0?void 0:()=>ce.refreshActiveThread?.(fp(z===true,hp(Re,Hg)))??Promise.resolve()},{intervalMs:T===void 0?3e4:T,isVisibleFallback:Hg}),pp({isStreaming:ce.isStreaming,status:ce.status,conversationId:ce.conversationId===null?null:String(ce.conversationId),unreadCount:ce.unreadCount,markRead:ce.markRead},()=>hp(Re,Hg));let Te=ce.pendingCheckin??null,Ie=Te===null?null:/* @__PURE__ */H(w,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */H(CheckinCard,{message:Te.message,checkin:Te.checkin,onAnswer:ce.petRef?ce.answerCheckin:null,petRef:ce.petRef,onFindVet:be,vet:me,onOpen:()=>{ce.resumeConversation(Te.conversationId)}})}),ze=(ce.hasUnreadThreads??false)||he.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(ce.unreadCount??0)>0,Pe=tp(ce.messages),[Oe,Ee]=l(null),je=s(()=>Ee(null),[]),[Fe,Ae]=l(null),[De,Me]=l(null),Le=u(null);n(()=>()=>{Le.current&&clearTimeout(Le.current)},[]);let Be=s((e,t)=>{Me({responseId:String(e),kind:t}),Le.current&&clearTimeout(Le.current),Le.current=t==="thanks"?setTimeout(()=>{Me(null),Le.current=null},Fb):null},[]),He=s((e,t)=>{let r=e.responseId;if(r===void 0)return;let n=ce.sentimentByMessage[String(r)];Me(e=>e?.responseId===String(r)?null:e),ce.feedback(r,t).then(e=>{e.ok||Be(r,"failed")}),t==="down"&&n!=="down"&&Ae(r)},[ce,Be]),Ue=s(async(e,t)=>Fe===null||!(e==null&&t===null?{ok:true}:await ce.feedback(Fe,"down",e??"other",t)).ok?false:(Ae(null),Be(Fe,"thanks"),true),[ce,Fe,Be]),Ne=s(()=>Ae(null),[]),$e=s(e=>{ce.send(e)},[ce.send]),We=a(()=>F===void 0?void 0:e=>{vh(F,e,"citation")},[F]),Ve=p.OS==="ios"?"padding":void 0,qe=NC(A,Ve!==void 0),Ge=qe.topInWindow===null?pe.top:Math.max(0,pe.top-qe.topInWindow),Ke=WC(),Ye=a(()=>M===void 0?void 0:()=>{vh(M,ee)},[M,ee]),Qe=a(()=>D===void 0?healthPlanTopCard(Z,{onOpenPlan:Ye}):void 0,[D,Z,Ye]),Je=X.chatTopCard==="focus"?D??Qe:void 0,[Xe,Ze]=l(true),et=s(e=>{ce.send(e)},[ce.send]),tt=a(()=>Yh(Q,X,isLocked("chatFollowUpCount")),[Q,X,isLocked]),rt=X.chatAnswerStyle==="cards",nt=a(()=>rt&&ce.messages.length===0?TR(ce.suggestedPrompts):void 0,[rt,ce.messages.length,ce.suggestedPrompts]),lt=X.chatHistoryStyle==="sheet",it=ce.messages.length===0,ot=Je!==void 0?/* @__PURE__ */H(TopCardPill,{card:Je,open:Xe,onOpenChange:Ze}):null,at=W??(G?void 0:IR),st=at!==void 0?/* @__PURE__ */H(HistoryBar,{bar:at,history:he,empty:it,unread:ze,extra:ot}):null,ut=X.chatHistoryBar==="scroll"&&(de==="empty"||de==="populated"),ct=Je===void 0?null:/* @__PURE__ */U(N,{children:[
|
|
376
|
+
/* @__PURE__ */H(TopCard,{card:Je,open:Xe,onOpenChange:Ze,ask:et}),at===void 0?ot:null]}),dt=at!==void 0,ft=he.load,ht=he.open;n(()=>{dt&&!ht&&ft()},[dt,ht,ce.conversationId,ft]);let pt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:Se,draftStore:P,onStage:Pe.stage,onPreview:Ee,petName:ye?.name??null,petBreed:ye?.breed??null,compact:X.chatComposerStyle==="compact",petPlaceholder:X.chatComposerPlaceholder==="pet_name",dimEmptySend:X.chatSendButton==="dim_when_empty",mood:zR(de,ke.source?.level??null),dictation:X.chatComposerMic,telemetry:e.telemetry},gt=mR(X.chatTextingAsk&&e.inProvider,ce,K),bt=b!==void 0&&X.chatComposerUpload,mt=!X.chatGeneralBanner&&ke.source?.level==="general";
|
|
376
377
|
/* @__PURE__ */
|
|
377
|
-
return H(
|
|
378
|
+
return H(Lk.Provider,{value:le,children:/* @__PURE__ */U(_,{style:[re.container,{paddingTop:Ge},i],behavior:Ve,...qe.avoidingProps,children:[
|
|
378
379
|
/* @__PURE__ */H(KeyboardOffsetProbe,{probeRef:qe.probeRef}),G?/* @__PURE__ */H(ChatHeader,{pets:fe,petRef:ce.petRef,historyUnread:ze,onOpenHistory:he.show,onNewChat:he.newConversation,onPetChange:d,onAddPet:y,vet:me,textingEntry:gt.headerEntry}):null,m!==void 0?/* @__PURE__ */H(PetSetupNotice,{petRef:t??null,pet:m,onRegistered:fe.refresh}):null,!G&>.headerEntry!==null?/* @__PURE__ */H(TextingEntryRow,{entry:gt.headerEntry,place:"thread"}):null,ut?null:st,mt?null:/* @__PURE__ */H(UrgencyBanner,{surface:ke,petRef:ce.petRef,renderVetAction:g,onFindVet:h,vet:me,compact:Ke}),
|
|
379
|
-
/* @__PURE__ */H(w,{style:re.body,children:
|
|
380
|
+
/* @__PURE__ */H(w,{style:re.body,children:sR(de,ce,{notice:ge,vet:me,onCheckinFindVet:be,onSelectPrompt:$e,renderPending:o,shownPet:ye,onVetPrep:f,onCopy:c,onSentiment:He,feedbackNote:De,imagesByMessage:Pe.byMessage,onPreview:Ee,onAddPet:y,onOpenUrl:We,threadTop:ut?st:null,pendingCheckin:Ie,topCard:ct,starterPrompts:V??nt,emptyState:q,emptyCentered:X.chatAnswerStyle==="cards",followUpPolicy:tt,answerCards:X.chatAnswerStyle==="cards"?B??_R:null,threadAside:gt.line,threadAsideKey:gt.stage,renderEmptyHeader:Y,openingCard:_e})}),gt.runner,gt.entry!==null?/* @__PURE__ */H(w,{style:re.composerOuter,children:/* @__PURE__ */H(w,{style:re.askEntry,children:gt.entry})}):bt&&b!==void 0?/* @__PURE__ */H(ComposerWithAttachments,{...pt,attachments:b}):/* @__PURE__ */H(Composer,{...pt,attachments:null}),te.meta.hidePoweredBy||ie?null:/* @__PURE__ */H(Text,{tier:"compact",style:re.poweredBy,accessibilityRole:"text",accessibilityLabel:If.poweredBy,children:If.poweredBy}),lt?/* @__PURE__ */H(HistorySheet,{chat:ce,history:he,sheet:$}):/* @__PURE__ */H(HistoryDrawer,{chat:ce,history:he}),
|
|
380
381
|
/* @__PURE__ */H(FeedbackReasons,{visible:Fe!==null,onSubmit:Ue,onSkip:Ne}),
|
|
381
382
|
/* @__PURE__ */H(AttachmentImageLightbox,{uri:Oe?.uri??null,label:Oe?.label??"",onClose:je}),
|
|
382
|
-
/* @__PURE__ */H(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=
|
|
383
|
+
/* @__PURE__ */H(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Tm(),l=Zh(e,t,r);return l.status!=="failed"||l.error===null?null:/* @__PURE__ */U(w,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[
|
|
383
384
|
/* @__PURE__ */H(Text,{tier:"compact",style:n.setupNoticeText,children:l.error.displayMessage}),
|
|
384
|
-
/* @__PURE__ */H(R,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:
|
|
385
|
-
return H(
|
|
385
|
+
/* @__PURE__ */H(R,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:If.retry,hitSlop:Zb,children:/* @__PURE__ */H(Text,{tier:"control",style:n.setupNoticeAction,children:If.retry})})]})}var _R=/* @__PURE__ */Object.freeze({}),RR=3;function TR(e){let t=[];for(let r of e){let e=r.trim();if(e.length>0&&!t.some(t=>t.label===e)&&t.push(/* @__PURE__ */Object.freeze({label:e})),t.length===RR)break}return t.length>0?/* @__PURE__ */Object.freeze(t):void 0}var IR=/* @__PURE__ */Object.freeze({chats:Pp.heading,newChat:Pp.newChat});function zR(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
|
|
386
|
+
return H(ff.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */H(EverfurChatCore,{...e})})}var PR=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function OR(e,t){let{runtime:r,userRef:l,activePet:o,scopeEpoch:u}=bd(),c=r.unread??null,d=e===void 0?o:e,f=s(e=>c===null?NO_SUBSCRIPTION():c.subscribe(e),[c]),h=s(()=>c===null||l===null?PR:c.get(d),[c,l,d]),p=i(f,h,h),g=s(()=>c===null||l===null?Promise.resolve():c.refresh(d),[c,l,d]);return n(()=>{g()},[g,u]),mp(t,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:g}),a(()=>({...p,refresh:g}),[p,g])}function useEverfurUnread(e={}){let{lifecycle:t}=e,r=a(()=>t===void 0?createAppStateLifecycle():t??void 0,[t]);return OR(e.petRef,r)}function useEverfurPetProfile(e){let{runtime:t,userRef:r,scopeEpoch:i}=bd(),o=a(()=>createPetsRepository(t.registry.services.authFor(r)),[t,r,i]),c=a(()=>({repository:o,petRef:e}),[o,e]),[d,f]=l({key:c,profile:null,loading:e!==null,error:null}),h=d.key===c?d:{profile:null,loading:e!==null,error:null},p=u(0),g=s(async()=>{let e=++p.current;if(c.petRef===null){f({key:c,profile:null,loading:false,error:null});return}f(e=>({key:c,profile:e.key===c?e.profile:null,loading:true,error:null}));let t=await c.repository.getPetProfile(c.petRef);e===p.current&&f(t.ok?{key:c,profile:t.value,loading:false,error:null}:{key:c,profile:null,loading:false,error:t.error})},[c]);return n(()=>(g(),()=>{p.current+=1}),[g]),a(()=>({profile:h.profile,loading:h.loading,error:h.error,refresh:g}),[h.profile,h.loading,h.error,g])}function EverfurThemeProvider(e){return r(EverfurThemeProviderCore,{clientTheme:e.clientTheme??null,seams:Qd,children:e.children})}export{hs as APPEARANCE_PRESETS,fs as APPEARANCE_PRESET_NAMES,ps as APPEARANCE_SIZE_RANGES,CapabilityGate,EverfurChat,K as EverfurConfigError,EverfurProvider,EverfurThemeProvider,G as EverfurThrownError,Uo as PHONE_TEXT_SCALE_CAPS,yo as THEME_SLOT_KEYS,vo as THEME_SLOT_KEYS_BY_SLOT,mo as THEME_SLOT_NAMES,Lo as TYPE_ROLE_DEFAULTS,Mo as TYPE_ROLE_NAMES,canonicalPetSpecies,categoryFor,chatHandoffTokenFromUrl,conversationId,createAppStateLifecycle,createRnRecordsUploadTransport,expandAppearance,face,headingFace,isErr,isOk,isRetryableCode,petRef,previewTheme,registerEverfurDictation,textRole,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurTheme,useEverfurUnread,userFacingError,userRef};
|