@everfur/sdk 0.7.0 → 0.8.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/CHANGELOG.md +326 -0
- package/README.md +24 -16
- package/dist/{Chat-DZpYH8Uh.d.ts → Chat-Cv9EYMYA.d.ts} +3 -3
- package/dist/{Chat-bATY4atj.d.cts → Chat-s2vcPbw3.d.cts} +3 -3
- package/dist/{DepthViews-qBIoA48w.d.ts → DepthViews-CVxUHOJ-.d.ts} +1 -1
- package/dist/{DepthViews-C4DC4Kom.d.cts → DepthViews-Cz7mSW7p.d.cts} +1 -1
- package/dist/{DepthViews-dLTizxjr.d.ts → DepthViews-DNRY0Ugm.d.ts} +1 -1
- package/dist/{DepthViews-BpHUbjSY.d.cts → DepthViews-DvNixbxg.d.cts} +1 -1
- package/dist/{ErrorPolicyPort-D22LUVrK.d.ts → ErrorPolicyPort-DwSnmGcX.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-D6CybiqJ.d.cts → ErrorPolicyPort-NFDPe-5w.d.cts} +1 -1
- package/dist/{EverfurError-DmELDpXp.d.cts → EverfurError-pEXDbUJ1.d.cts} +9 -1
- package/dist/{EverfurError-DmELDpXp.d.ts → EverfurError-pEXDbUJ1.d.ts} +9 -1
- package/dist/{EverfurResult-ZtH-YV1h.d.cts → EverfurResult-dtl8ERAw.d.cts} +1 -1
- package/dist/{EverfurResult-SGvHKsCB.d.ts → EverfurResult-sKkoXew0.d.ts} +1 -1
- package/dist/IntakeMedia-BFZfBLjB.d.cts +116 -0
- package/dist/{BookedScreen-DFJcgf1e.d.ts → IntakeMedia-BH0fYDT2.d.cts} +58 -2
- package/dist/{BookedScreen-R5X_Zrlh.d.cts → IntakeMedia-Bavl7E4Z.d.ts} +58 -2
- package/dist/IntakeMedia-C8GlN_GK.d.ts +116 -0
- package/dist/animations/index.cjs +109 -1
- package/dist/animations/index.d.cts +6 -6
- package/dist/animations/index.d.ts +6 -6
- package/dist/animations/index.js +109 -1
- package/dist/{attachments-CPRFfoHT.d.ts → attachments-BaslXMdS.d.ts} +3 -3
- package/dist/{attachments-CUOGILir.d.cts → attachments-DbFwz4iq.d.cts} +7 -7
- package/dist/{attachments-Ce06TWqe.d.cts → attachments-y3EcOX_w.d.cts} +3 -3
- package/dist/{attachments-CXAnZcEg.d.ts → attachments-y_aO4hlk.d.ts} +7 -7
- package/dist/{bookingCopy-BwVopcoV.d.cts → bookingCopy-4i1R7klo.d.cts} +15 -7
- package/dist/{bookingCopy-DFTv9w6J.d.ts → bookingCopy-B3UMITD-.d.ts} +15 -7
- package/dist/{branding-ytH4jJq1.d.ts → branding-BYEqU855.d.ts} +1 -1
- package/dist/{branding-Bio5MM6g.d.cts → branding-BwEu68C8.d.cts} +1 -1
- package/dist/{callRoom-7wrE3RP2.d.ts → callRoom-B1qq_D-4.d.ts} +1 -1
- package/dist/{callRoom-B_EqaUzx.d.cts → callRoom-DfZTWFXh.d.cts} +1 -1
- package/dist/{casesRepository-CJchNp3x.d.cts → casesRepository-B6Z0XBIb.d.cts} +2 -2
- package/dist/{casesRepository-DAVcY3jC.d.ts → casesRepository-SI0zp5YH.d.ts} +2 -2
- package/dist/chat/index.cjs +333 -1
- package/dist/chat/index.d.cts +12 -12
- package/dist/chat/index.d.ts +12 -12
- package/dist/chat/index.js +333 -1
- package/dist/client/index.cjs +115 -11
- package/dist/client/index.d.cts +14 -14
- package/dist/client/index.d.ts +14 -14
- package/dist/client/index.js +115 -11
- package/dist/{config-ZxwCylac.d.ts → config-Cvo47voG.d.ts} +3 -3
- package/dist/{config-h5h6TsHL.d.cts → config-v5k6NsK_.d.cts} +3 -3
- package/dist/consent/index.cjs +112 -1
- package/dist/consent/index.d.cts +9 -9
- package/dist/consent/index.d.ts +9 -9
- package/dist/consent/index.js +112 -1
- package/dist/{context-CtsAgJnc.d.cts → context-BZOtJbBO.d.cts} +9 -9
- package/dist/{context-DtPIshVA.d.ts → context-cZ7NZ0sG.d.ts} +9 -9
- package/dist/{copy-Cg89Qoal.d.ts → copy-CZBUHbyS.d.ts} +5 -5
- package/dist/{copy-CaWaplQc.d.cts → copy-ChJupm1p.d.cts} +5 -5
- package/dist/core/index.cjs +140 -13
- package/dist/core/index.d.cts +19 -19
- package/dist/core/index.d.ts +19 -19
- package/dist/core/index.js +140 -13
- package/dist/{depth-EXZYEO70.d.cts → depth-CRyU7-pf.d.cts} +8 -7
- package/dist/{depth-Bo4bAwcn.d.ts → depth-vNpwOkZ8.d.ts} +8 -7
- package/dist/{entitlementRepository-BYtVb1oU.d.cts → entitlementRepository-Bv8nSYRd.d.cts} +4 -4
- package/dist/{entitlementRepository-DcbIx8yV.d.ts → entitlementRepository-CUdxbQrP.d.ts} +4 -4
- package/dist/{identity-EC5-apbY.d.ts → identity-B8GkH53J.d.ts} +2 -2
- package/dist/{identity-b5Vp32Vp.d.cts → identity-BHaMJ3KK.d.cts} +2 -2
- package/dist/index.cjs +363 -12
- package/dist/index.d.cts +19 -19
- package/dist/index.d.ts +19 -19
- package/dist/index.js +363 -12
- package/dist/{models-DSqA5Ahs.d.ts → models-CrbUwbuS.d.ts} +1 -1
- package/dist/{models-Bn2z0NNo.d.cts → models-DzvqEjMm.d.cts} +1 -1
- package/dist/notifications/index.cjs +94 -2
- package/dist/notifications/index.d.cts +5 -5
- package/dist/notifications/index.d.ts +5 -5
- package/dist/notifications/index.js +94 -2
- package/dist/{pets-DM8QvKLo.d.cts → pets-BI7Ji8hi.d.cts} +2 -2
- package/dist/{pets-B_27_agU.d.ts → pets-Dnn-DK1T.d.ts} +2 -2
- package/dist/{petsRepository-CuYZZaI5.d.ts → petsRepository-B2lO1sKS.d.ts} +2 -2
- package/dist/{petsRepository-BJsJ4cju.d.cts → petsRepository-BP9nhM1R.d.cts} +2 -2
- package/dist/photo/index.cjs +131 -1
- package/dist/photo/index.d.cts +3 -3
- package/dist/photo/index.d.ts +3 -3
- package/dist/photo/index.js +131 -1
- package/dist/{ports-nXHf50_X.d.ts → ports-BUXF0Rp3.d.ts} +7 -7
- package/dist/{ports-ZmJYgd5I.d.cts → ports-C40S2V14.d.cts} +7 -7
- package/dist/records/depth/index.cjs +200 -2
- package/dist/records/depth/index.d.cts +11 -11
- package/dist/records/depth/index.d.ts +11 -11
- package/dist/records/depth/index.js +200 -2
- package/dist/records/index.cjs +742 -4
- package/dist/records/index.d.cts +22 -14
- package/dist/records/index.d.ts +22 -14
- package/dist/records/index.js +742 -4
- package/dist/{requestFunnel-Ve9BshTB.d.ts → requestFunnel-BrOijMcw.d.ts} +5 -5
- package/dist/{requestFunnel-C_cZXhIA.d.cts → requestFunnel-BxNVGyGm.d.cts} +5 -5
- package/dist/{runtimeTypes-ByKsp8hm.d.ts → runtimeTypes-CvI1ZH8j.d.ts} +7 -7
- package/dist/{runtimeTypes-D155OlBW.d.cts → runtimeTypes-DOO3f-W-.d.cts} +7 -7
- package/dist/server/events/index.cjs +92 -2
- package/dist/server/events/index.d.cts +4 -4
- package/dist/server/events/index.d.ts +4 -4
- package/dist/server/events/index.js +92 -2
- package/dist/server/index.cjs +95 -2
- package/dist/server/index.d.cts +5 -5
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +95 -2
- package/dist/televet/booking/index.cjs +394 -4
- package/dist/televet/booking/index.d.cts +24 -127
- package/dist/televet/booking/index.d.ts +24 -127
- package/dist/televet/booking/index.js +394 -4
- package/dist/televet/call/index.cjs +71 -1
- package/dist/televet/call/index.d.cts +3 -3
- package/dist/televet/call/index.d.ts +3 -3
- package/dist/televet/call/index.js +71 -1
- package/dist/televet/index.cjs +101 -1
- package/dist/televet/index.d.cts +25 -8
- package/dist/televet/index.d.ts +25 -8
- package/dist/televet/index.js +101 -1
- package/dist/{bookingTypes-D4pD3tHs.d.ts → televetGlobal-C5dTUACe.d.cts} +34 -1
- package/dist/{bookingTypes-D4pD3tHs.d.cts → televetGlobal-CnjrfhT4.d.ts} +34 -1
- package/dist/testing/index.cjs +98 -7
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +98 -7
- package/dist/testing/rn/index.cjs +101 -1
- package/dist/testing/rn/index.d.cts +13 -13
- package/dist/testing/rn/index.d.ts +13 -13
- package/dist/testing/rn/index.js +101 -1
- package/dist/testing/web/index.cjs +95 -1
- package/dist/testing/web/index.d.cts +14 -14
- package/dist/testing/web/index.d.ts +14 -14
- package/dist/testing/web/index.js +95 -1
- package/dist/{timelineRows-DXpjECfA.d.ts → timelineRows-CEx2TzYB.d.ts} +1 -1
- package/dist/{timelineRows-BNF43SXK.d.cts → timelineRows-Dffceql_.d.cts} +1 -1
- package/dist/{tokens-BYtbKwFh.d.cts → tokens-Tzo1KBND.d.cts} +43 -2
- package/dist/{tokens-BYtbKwFh.d.ts → tokens-Tzo1KBND.d.ts} +43 -2
- package/dist/{typeStyle-BqfwxZH4.d.cts → typeStyle-C3IG9Sft.d.ts} +22 -3
- package/dist/{typeStyle-DKz02DGU.d.ts → typeStyle-CZ3Tj60N.d.cts} +22 -3
- package/dist/{useRecordsDepth-CARTuHKh.d.cts → useRecordsDepth-D6a6-_u_.d.cts} +7 -6
- package/dist/{useRecordsDepth-fPSv-GXU.d.ts → useRecordsDepth-DuPUJFDQ.d.ts} +7 -6
- package/dist/{useVetVisit-Ds8f1peV.d.cts → useVetVisit-BQX_aTJs.d.cts} +2 -2
- package/dist/{useVetVisit-BsjoDO-n.d.ts → useVetVisit-RPBOabl8.d.ts} +2 -2
- package/dist/video/index.cjs +122 -1
- package/dist/video/index.d.cts +3 -3
- package/dist/video/index.d.ts +3 -3
- package/dist/video/index.js +122 -1
- package/dist/{view-Dc-JlFkf.d.ts → view-BSmN5RWf.d.ts} +5 -5
- package/dist/{view-DGPaVno8.d.cts → view-UFwCG1Pn.d.cts} +5 -5
- package/dist/web/consent/index.cjs +111 -1
- package/dist/web/consent/index.d.cts +9 -9
- package/dist/web/consent/index.d.ts +9 -9
- package/dist/web/consent/index.js +111 -1
- package/dist/web/index.cjs +325 -14
- package/dist/web/index.d.cts +22 -22
- package/dist/web/index.d.ts +22 -22
- package/dist/web/index.js +325 -14
- package/dist/web/notifications/index.cjs +95 -2
- package/dist/web/notifications/index.d.cts +7 -7
- package/dist/web/notifications/index.d.ts +7 -7
- package/dist/web/notifications/index.js +95 -2
- package/dist/web/records/depth/index.cjs +169 -2
- package/dist/web/records/depth/index.d.cts +11 -11
- package/dist/web/records/depth/index.d.ts +11 -11
- package/dist/web/records/depth/index.js +169 -2
- package/dist/web/records/index.cjs +689 -4
- package/dist/web/records/index.d.cts +34 -37
- package/dist/web/records/index.d.ts +34 -37
- package/dist/web/records/index.js +689 -4
- package/dist/web/records/upload/index.cjs +3 -0
- package/dist/web/records/upload/index.d.cts +23 -0
- package/dist/web/records/upload/index.d.ts +23 -0
- package/dist/web/records/upload/index.js +3 -0
- package/dist/web/televet/booking/index.cjs +423 -4
- package/dist/web/televet/booking/index.d.cts +26 -74
- package/dist/web/televet/booking/index.d.ts +26 -74
- package/dist/web/televet/booking/index.js +423 -4
- package/dist/web/televet/call/index.cjs +28 -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 +28 -1
- package/dist/web/televet/index.cjs +102 -4
- package/dist/web/televet/index.d.cts +29 -10
- package/dist/web/televet/index.d.ts +29 -10
- package/dist/web/televet/index.js +102 -4
- package/package.json +20 -4
- package/web/records/upload/native-blocked.cjs +12 -0
- package/web/records/upload/package.json +8 -0
- package/dist/televetGlobal-CEk0_cW9.d.cts +0 -34
- package/dist/televetGlobal-Cs9Wbqsy.d.ts +0 -34
package/dist/chat/index.js
CHANGED
|
@@ -1 +1,333 @@
|
|
|
1
|
-
import {createContext,forwardRef,useMemo,useState,useRef,useEffect,useCallback,useSyncExternalStore,createElement,useContext,Component}from'react';import {StyleSheet,TextInput,Linking,Platform,KeyboardAvoidingView,View,Pressable,Text,Animated,UIManager,LayoutAnimation,Modal,Image,ActivityIndicator,ScrollView,useWindowDimensions,FlatList,Dimensions,AccessibilityInfo}from'react-native';import {useSafeAreaInsets}from'react-native-safe-area-context';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var xd=Object.defineProperty;var i=(e,t)=>xd(e,"name",{value:t,configurable:true});var Br=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Br.map(e=>e.wireCode));var wd=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",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),Ro=Object.freeze(Br.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:wd[e.wireCode]}))),kd=new Map(Ro.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),_d=Object.freeze(["http_envelope",...[...new Set(Ro.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Bt(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",..._d]){let o=kd.get(n+r);if(o)return o}}i(Bt,"contractErrorFor");function Id(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Id,"contractDocUrl");function So(e){return null}i(So,"publishedDocUrl");var Ad=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"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 To(e){return Ad[e]}i(To,"categoryFor");function Po(e){let t=Bt(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 "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"}}i(Po,"fromWire");var Od=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function jr(e){return Od.has(e)}i(jr,"isAutoRetryable");var Fd=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function xo(e){return jr(e)||Fd.has(e)}i(xo,"isRetryableCode");var Md=500,Wr=8e3,wo=4;function ko(e,t=Math.random){let r=Math.max(0,e),n=Math.min(Md*2**r,Wr);return Math.floor(t()*n)}i(ko,"backoffDelayMs");var Ld=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:"This feature isn't available on your account right now.",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:"Something in that request was not right. Check the details and try again.",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.",unknown:"Something went wrong. Please try again."});function Gr(e){return Ld[e]}i(Gr,"userFacingError");function _o(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(_o,"defineHidden");var Vd=/^[a-z][a-z0-9_]{0,63}$/;function Y(e,t){let r=Bt(t?.wireCode,t?.wireEnvelope),n={code:e,category:To(e),retryable:t?.retryable??xo(e),displayMessage:Gr(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Vd.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&_o(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&_o(n,"raw",t.raw),Object.freeze(n)}i(Y,"makeEverfurError");function ce(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(ce,"ok");function D(e){return Object.freeze({ok:false,error:e})}i(D,"err");var jt=class jt extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,jt.prototype);}};i(jt,"EverfurConfigError");var mt=jt;var f=Object.freeze({placeholder:"Ask anything about {petName}\u2026",placeholderFollowUpWeb:"Ask a follow-up\u2026",placeholderUrgentWeb:"Tell us what\u2019s happening\u2026",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur\u2019s assistant isn\u2019t a vet and doesn\u2019t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}\u2019s records\u2026",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn\u2019t 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\u2026",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",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 \xB7 ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function B(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(B,"fillCopy");function Nd(e){return e?.trim()||f.emptyTitlePetFallback}i(Nd,"petNameSlot");function Wt(e,t){return B(e,{petName:Nd(t)})}i(Wt,"forPet");var Io="tel:+18884264435";var qr=Object.freeze([Object.freeze({key:"inaccurate",label:f.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:f.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:f.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:f.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:f.feedbackReasonOther,feedbackType:"not_helpful"})]),Ao=Object.freeze([Object.freeze({sentiment:"up",label:f.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:f.feedbackNeutral}),Object.freeze({sentiment:"down",label:f.feedbackNotHelpful})]);function Dd(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Dd,"sentimentToFeedbackType");function Oo(e,t){if(e==="down"&&t!==null){let r=qr.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Dd(e)}i(Oo,"feedbackTypeFor");var Fo=Symbol.for("@everfur/sdk#EverfurContext@v1"),Mo=globalThis,Lo=Mo[Fo]??(Mo[Fo]=createContext(null));Lo.displayName??="EverfurContext";function ae(){let e=useContext(Lo);if(e===null)throw new mt("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ae,"useEverfurContext");var Wd=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function Gt(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=ae(),s=e?.petRef??n??null,a=e?.conversationId??null,l=useMemo(()=>({runtime:t,userRef:r,petRef:s,conversationId:a,scopeEpoch:o}),[t,r,s,a,o]),[d,u]=useState(null),c=d?.scope===l?d.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=useRef(null);useEffect(()=>{let O=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=O,u({scope:l,controller:O}),()=>{p.current=null,u(C=>C?.controller===O?null:C),t.registry.releaseChat(O);}},[t,r,s,a,o,l]);let y=useCallback(O=>c?c.subscribe(O):Gd,[c]),g=useCallback(()=>c?c.getSnapshot():Wd,[c]),h=useSyncExternalStore(y,g,g),k=useCallback((O,C)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Yr(c,c.send(O,C?.imageS3Keys===void 0?{}:{imageS3Keys:C.imageS3Keys}),()=>p.current===c):Promise.resolve($r()),[c]),E=useCallback(O=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Yr(c,c.askEverfur(O),()=>p.current===c):Promise.resolve($r()),[c]),P=useCallback(()=>c&&p.current===c?Yr(c,c.retryLast(),()=>p.current===c):Promise.resolve($r()),[c]),T=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),S=useCallback(()=>{c&&p.current===c&&c.newConversation();},[c]),[w,m]=useState({controller:null,byMessage:{}}),R=w.controller===c?w.byMessage:qd,_=useCallback(async(O,C,M,x)=>{if(!c||p.current!==c)return D(Y("accessDenied"));let N=String(O),q=w.controller===c?w.byMessage[N]:void 0;if(q===C&&M==null)return m(G=>{let be={...G.controller===c?G.byMessage:{}};return delete be[N],{controller:c,byMessage:be}}),ce(Object.freeze({feedbackId:""}));m(G=>({controller:c,byMessage:{...G.controller===c?G.byMessage:{},[N]:C}}));let X=await c.submitFeedback(O,Oo(C,M??null),x??null);return p.current!==c?D(Y("accessDenied")):(X.ok||m(G=>{let be={...G.controller===c?G.byMessage:{}};return q===void 0?delete be[N]:be[N]=q,{controller:c,byMessage:be}}),X)},[c,w]),A=useMemo(()=>{let O=i(async C=>{if(!c||p.current!==c)return D(Y("accessDenied"));let M=await C(c);return p.current===c?M:D(Y("accessDenied"))},"run");return {listConversations:i(C=>O(M=>M.listConversations({...s?{petRef:s}:{},...C})),"listConversations"),getMessages:i((C,M)=>O(x=>x.getMessages(C,M)),"getMessages"),resumeConversation:i(C=>O(M=>M.resumeConversation(C)),"resumeConversation"),loadOlderMessages:i(()=>O(C=>C.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>O(C=>C.markRead()),"markRead"),refreshActiveThread:i(()=>O(C=>C.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((C,M)=>O(x=>x.answerCheckin(C,M)),"answerCheckin"),openCheckin:i(C=>O(M=>M.openCheckin(C)),"openCheckin")}},[c,s]);return useMemo(()=>({status:h.status,messages:h.messages,conversationId:h.conversationId,petRef:s,error:h.error,isStreaming:h.isStreaming,isBootstrapping:h.isBootstrapping,historyCursor:h.historyCursor??null,isLoadingHistory:h.isLoadingHistory??false,stopped:h.stopped??false,reconnecting:h.reconnecting??false,...A,suggestedPrompts:h.suggestedPrompts,unreadCount:h.unreadCount,hasUnreadThreads:h.hasUnreadThreads??false,newConversation:S,sentimentByMessage:R,feedback:_,send:k,askEverfur:E,retryLast:P,stop:T}),[h,s,k,E,P,T,A,S,R,_])}i(Gt,"useEverfurChat");var Gd=i(()=>{},"NOOP_UNSUBSCRIBE"),qd=Object.freeze({});async function Yr(e,t,r){for await(let o of t);if(!r())return D(Y("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?D(n.error):ce(Kd(n.messages))}i(Yr,"driveToResult");function Kd(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}i(Kd,"lastAssistantResponseId");function $r(){return D(Y("internalError",{retryable:true}))}i($r,"notReadyError");function Xr(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))Xr(e[t]);}return e}i(Xr,"deepFreeze");var Yd=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Do={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Ho={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},No={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},$d={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Xd={regular:"400",medium:"500",bold:"700"},Qd={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Zd=0,qt="System",Kt="monospace",Jd=["content","heading","control","compact","badge"];function eu(e){let t={};for(let r of Jd)t[r]=e;return t}i(eu,"authoredTierSizes");function zo(){return {family:qt,mono:Kt,fontUrl:null,families:{regular:qt,medium:qt,bold:qt,mono:Kt,monoMedium:Kt,monoBold:Kt},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:No,tierSizes:eu(No),lineHeight:$d,weight:Xd,letterSpacing:Qd,scale:1,maxScale:Zd,scaleCaps:Yd}}i(zo,"baseType");var Uo={},We=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function Yt(e){return `cubic-bezier(${e.join(", ")})`}i(Yt,"cssCubicBezier");var Bo={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:Yt(We.standard),emphasized:Yt(We.emphasized),exit:Yt(We.exit)},reducedMotion:false},tu={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",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},jo=Xr({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:tu,space:Do,radius:Ho,type:zo(),motion:Bo,slots:Uo}),ru={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",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};Xr({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:ru,space:Do,radius:Ho,type:zo(),motion:Bo,slots:Uo});var Wo=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Go=globalThis,Qr=Go[Wo]??(Go[Wo]=createContext(jo));Qr.displayName??="EverfurThemeContext";function F(){return useContext(Qr)}i(F,"useEverfurTheme");function lu(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(lu,"tierMultiplier");function b({tier:e="content",...t}){let{type:r}=F(),n=lu(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(b,"Text");var ot=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));function $t(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i($t,"assertNever");function Ko(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(Ko,"errorFrame");function cu(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(cu,"authHeaders");function gt(e,t){return {...e,headers:{...pu(e.headers),...cu(t)}}}i(gt,"withAuthHeaders");function pu(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(pu,"stripAuthHeaders");async function Yo(e,t){if(t.mode==="anonymous")return t.transport.request(gt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return D(Zr())}let n=await t.transport.request(gt(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return D(Zr())}let s=await t.transport.request(gt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?D(Zr(s.error.httpStatus)):s}i(Yo,"authedSend");function Zr(e){return Y("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(Zr,"authRejectedError");function $o(e){return Y("internalError",{retryable:true,wireMessage:fu(e)})}i($o,"networkError");function fu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(fu,"describeCause");var yu=3e4,mu=Wr*2,gu="idempotency-key",hu=new Set(["POST","PUT","PATCH","DELETE"]),bu=Object.freeze({onEvent(){}}),vu=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Cu(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Cu,"seededIdempotencyKey");function Ge(e){let t=e.observer??bu,r=e.timers??vu,n=e.rng??Math.random,o=e.sleep??((y,g)=>Mu(y,r,g)),s=e.maxAttempts??wo,a=e.unaryTimeoutMs??yu,l=e.newIdempotencyKey??Ru(),d=i(y=>{try{t.onEvent(y);}catch{}},"emit");async function u(y,g,h){let k=h?.maxAttempts,E=Math.max(1,k??s),P=h?.idempotent??hu.has(g.method),T=h?.idempotencyKey===void 0?null:Cu(h.idempotencyKey),S=P?T??l():null,w=Eu(g,S),m=0;for(;;){let R=i(N=>Object.freeze({call:y,method:g.method,path:g.path,attempt:m,...S?{idempotencyKey:S}:{},...N}),"stamp");d(R({phase:"attempt"}));let _=Ou(a,r),A=Fu(_.signal,g.signal),O;try{O=await Yo({...w,signal:A.signal},e.auth);}catch(N){O=D($o(N));}finally{A.dispose(),_.cancel();}if(O.ok)return d(R({phase:"settled",ok:true,reason:"ok"})),O;let C=O.error,M=Tu(C,m,{maxAttempts:E,rng:n,now:r.now(),aborted:g.signal?.aborted===true,...k!==void 0?{perCallMaxAttempts:k}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),x={ok:false,code:C.code,reason:M.reason,...C.httpStatus!==void 0?{httpStatus:C.httpStatus}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};if(!M.retry)return d(R({phase:"settled",...x})),D(C);if(d(R({phase:"retry",...x,delayMs:M.delayMs})),await o(M.delayMs,g.signal),g.signal?.aborted===true)return d(R({phase:"settled",...x,reason:"aborted"})),D(C);m+=1;}}i(u,"send");async function c(y){return gt(y,await Au(e.auth))}i(c,"authorize");async function*p(y,g,h){d(Object.freeze({call:y,phase:"stream.open",method:g.method,path:g.path,attempt:0}));try{yield*e.auth.transport.stream(g,h);}catch{yield Ko({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:u,authorize:c,stream:p})}i(Ge,"createRequestFunnel");function Eu(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==gu&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Eu,"assembleHeaders");function Ru(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Ru,"defaultIdempotencyKeyFactory");var Su=10;function Tu(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Pu(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!jr(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(r.policy===void 0)return null;let u;try{u=r.policy.maxAttempts(e.code);}catch{return null}return typeof u!="number"||!Number.isFinite(u)?null:Math.max(1,Math.min(Su,Math.floor(u)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let d=xu(e,r.now);return d!==null?d>mu?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:d}:{retry:true,reason:o,delayMs:ko(t,r.rng)}}i(Tu,"decideRetry");function Pu(e){let t=e.code==="unknown"?Po(Iu(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Pu,"throttleKind");function xu(e,t){let r=ku(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=wu(e.raw);return n===null?null:Math.round(n*1e3)}i(xu,"retryOverrideMs");function wu(e){for(let t of Jr(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(wu,"findRetryAfterSeconds");function ku(e){for(let t of Jr(e)){let r=t.resets_at,n=_u(r);if(n!==null)return n}return null}i(ku,"findResetsAt");function Jr(e){if(!Xo(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Xo(n)&&t.push(n);}return t}i(Jr,"candidateScopes");function _u(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}i(_u,"parseInstantMs");function Iu(e){for(let t of Jr(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Iu,"rawWireCode");function Xo(e){return typeof e=="object"&&e!==null}i(Xo,"isRecord");async function Au(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Au,"resolveDeviceAuth");function Ou(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Ou,"boundedSignal");function Fu(e,t){let r=i(()=>{},"noop");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 o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(Fu,"mergeSignals");function Mu(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(Mu,"delayAbortable");function Xt(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(Xt,"hasLoneSurrogate");function Qt(e){return [...e].length}i(Qt,"serverLength");var Qo=Object.freeze(["better","same","worse"]),Zo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var Jo=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ei(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(ei,"delayAbortable");var Lu="checkin",Vu=/^\d{4}-\d{2}-\d{2}$/,Nu="watching";function ti(e){return e.status!=null&&e.status!==Nu}i(ti,"isCheckinSettled");function ri(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Lu||n===void 0||o===void 0||!Zo.test(n)||!Vu.test(o)?null:{caseId:n,dueDay:o}}i(ri,"parseCheckinOrigin");var Zt=4e3;var Jt=4e3;var zu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function ni(e){return e!==zu}i(ni,"isUploadTransportAvailable");var Uu=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var er=10*1024*1024,tr=5,ht=120,Bu="/widget/v1/uploads/initiate";function ju(e){return typeof e=="string"&&Uu.includes(e.trim().toLowerCase())}i(ju,"isAttachmentMime");function en(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<=ht)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,ht);let n=t.slice(r);return n.length>=ht?t.slice(0,ht):`${t.slice(0,r).slice(0,ht-n.length)}${n}`}i(en,"sanitizeFilename");function tn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(tn,"formatBytes");var bt=i(e=>Object.freeze({ok:true,value:e}),"ok"),ve=i(e=>Object.freeze({ok:false,error:e}),"err");function ee(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(ee,"failure");function Wu(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}i(Wu,"attachmentSize");function Gu(e){let t=en(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!ju(r))return ve(ee("unsupported_type",false,t));let n=Wu(e);return n===null?ve(ee("unknown",false,t)):n>er?ve(ee("too_large",false,t,{sizeBytes:n})):bt(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Gu,"validateAttachment");function qu(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(u=>typeof u=="string"&&u.length>0?u:null,"str"),n=i(u=>typeof u=="number"&&Number.isFinite(u)?u:null,"num"),o=r(t.upload_id),s=r(t.upload_url),a=r(t.s3_key);if(o===null||s===null||a===null)return null;let l={},d=t.upload_fields;if(typeof d=="object"&&d!==null)for(let[u,c]of Object.entries(d))typeof c=="string"&&(l[u]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(l),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??er,s3_key:a,purpose:r(t.purpose)})}i(qu,"parsePolicy");function Ku(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return ee("quota_exceeded",false,t,{cause:e});case "rateLimited":return ee("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return ee("idempotency_conflict",true,t,{cause:e});case "validationFailed":return ee("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return ee("network",true,t,{cause:e});default:return r===429?ee("rate_limited",true,t,{cause:e}):r===503?ee("network",true,t,{cause:e}):r===void 0?ee("network",true,t,{cause:e}):ee("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Ku,"initiateFailure");async function Yu(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Bu,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return ve(Ku(n.error,t.filename));let o=qu(n.value);return o===null?ve(ee("server",false,t.filename)):bt(o)}i(Yu,"initiateAttachmentUpload");async function $u(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return ve(ee("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),bt(void 0)}catch{return o()?ve(ee("cancelled",true,r.filename)):ve(ee("server",true,r.filename))}}i($u,"uploadAttachmentBytes");var Xu=2,Qu=3,Zu=Object.freeze([1e3,2e3,4e3]),oi=0;function Ju(){return oi+=1,`attachment-${oi}`}i(Ju,"defaultNewId");function ii(e){let t=Math.max(1,e.concurrency??Xu),r=Math.max(1,e.maxAttempts??Qu),n=e.backoffMs??Zu,o=Math.max(1,e.maxPerMessage??tr),s=e.timers??Jo,a=e.newId??Ju,l=ni(e.transport),d=new Map,u=[],c=[],p=new Set,y=new Set,g=Object.freeze({attachments:Object.freeze([])}),h=false,k=i(()=>{g=Object.freeze({attachments:Object.freeze(u.flatMap(m=>{let R=d.get(m);return R===void 0?[]:[R.state]}))});for(let m of y)m();},"publish"),E=i((m,R)=>{m.state=Object.freeze({...m.state,...R}),k();},"patch"),P=i(()=>{for(;!h&&p.size<t&&c.length>0;){let m=c.shift(),R=d.get(m);R!==void 0&&(p.add(m),T(R).finally(()=>{p.delete(m),P();}));}},"pump"),T=i(async m=>{let{attachment:R}=m;for(;m.attempts<r;){if(h||m.controller.signal.aborted)return;m.attempts+=1;let _=m.controller.signal;E(m,{status:"uploading",error:null,progress:0});let A=await Yu(e.funnel,R,{signal:_});if(h||_.aborted)return;let O;if(!A.ok)O=ve(A.error);else {let N=await $u(e.transport,A.value,R,{signal:_,onProgress:i(q=>{!_.aborted&&m.state.status==="uploading"&&E(m,{progress:ec(q)});},"onProgress")});if(h||_.aborted)return;O=N.ok?bt(A.value.s3_key):ve(N.error);}if(O.ok){E(m,{status:"uploaded",s3Key:O.value,error:null,progress:1});return}let C=O.error,M=C.retryable&&m.attempts<r;if(E(m,{status:M?"uploading":"failed",error:C,progress:0}),!M)return;let x=n[Math.min(m.attempts-1,n.length-1)]??0;await ei(x,_,s);}},"run"),S=i(m=>{c.push(m.state.id),P();},"enqueue"),w={available:l,subscribe(m){return y.add(m),()=>{y.delete(m);}},getSnapshot:i(()=>g,"getSnapshot"),get uploading(){return g.attachments.some(m=>m.status==="uploading")},get s3Keys(){return g.attachments.flatMap(m=>m.status==="uploaded"&&m.s3Key!==null?[m.s3Key]:[])},add(m){let R=Gu(m);if(!R.ok)return R;if(h||u.length>=o)return ve(ee("too_many",false,R.value.filename));let _=a(),A={attachment:R.value,controller:new AbortController,attempts:0,state:Object.freeze({id:_,filename:R.value.filename,previewUri:m.uri,contentType:R.value.contentType,sizeBytes:R.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return d.set(_,A),u.push(_),k(),S(A),bt(A.state)},retry(m){let R=d.get(m);R===void 0||h||R.state.status!=="failed"||(R.controller=new AbortController,R.attempts=0,E(R,{status:"uploading",error:null,progress:0,s3Key:null}),S(R));},remove(m){let R=d.get(m);if(R===void 0)return;R.controller.abort(),d.delete(m);let _=u.indexOf(m);_>=0&&u.splice(_,1);let A=c.indexOf(m);A>=0&&c.splice(A,1),k();},clear(){for(let m of [...u])w.remove(m);},dispose(){h=true;for(let m of d.values())m.controller.abort();d.clear(),u.length=0,c.length=0,y.clear(),g=Object.freeze({attachments:Object.freeze([])});}};return w}i(ii,"createAttachmentQueue");function ec(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(ec,"clamp");function li(e){switch(e.code){case "too_large":return B(f.attachmentTooLarge,{max:tn(er),filename:e.filename,size:tn(e.sizeBytes??0)});case "too_many":return B(f.attachmentTooMany,{max:tr});case "unsupported_type":return B(f.attachmentUnsupported,{filename:e.filename});case "network":return f.attachmentNetwork;case "server":return B(f.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return f.attachmentCancelled;case "rate_limited":return f.attachmentRateLimited;case "quota_exceeded":return f.attachmentQuota;case "idempotency_conflict":return f.attachmentConflict;case "unknown":return f.attachmentUnknown}}i(li,"attachmentErrorMessage");function di(e,t){return B(e>=t?f.attachmentsFull:f.addAttachment,{used:e,total:t})}i(di,"attachControlLabel");var oc=Object.freeze({attachments:Object.freeze([])});function rn(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=ae(),o=e.maxPerMessage??tr,s=useCallback(()=>{let{services:m}=t.registry;return ii({funnel:Ge({auth:m.authFor(r),...m.errorPolicy?{errorPolicy:m.errorPolicy}:{}}),transport:e.transport??m.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.transport]),a=useMemo(()=>e.queue??s(),[e.queue,s]),l=useRef(new WeakSet),[d,u]=useState(null),c=d!==null&&d.of===a?d.queue:a;useEffect(()=>{if(c!==e.queue){if(l.current.has(c)){u({of:a,queue:s()});return}return ()=>{c.dispose(),l.current.add(c);}}},[c,a,s,e.queue]);let p=useSyncExternalStore(c.subscribe,c.getSnapshot,()=>oc),[y,g]=useState(null),h=useCallback(m=>{let _=(Array.isArray(m)?m:[m]).map(O=>c.add(O)),A=_.find(O=>!O.ok);return A!==void 0&&!A.ok&&g(A.error),_},[c,g]),k=useCallback(m=>c.retry(m),[c]),E=useCallback(m=>c.remove(m),[c]),P=useCallback(()=>c.clear(),[c]),T=useCallback(()=>g(null),[g]),S=p.attachments.some(m=>m.status==="uploading"),w=p.attachments.some(m=>m.status==="failed");return useMemo(()=>({available:c.available,attachments:p.attachments,maxPerMessage:o,uploading:S,failed:w,blocked:S||w,s3Keys:p.attachments.flatMap(m=>m.status==="uploaded"&&m.s3Key!==null?[m.s3Key]:[]),rejected:y,add:h,retry:k,remove:E,clear:P,dismissRejected:T}),[c.available,p,o,S,w,y,h,k,E,P,T])}i(rn,"useChatAttachments");var ui=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function rr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(ui,t)?ui[t]:null}i(rr,"canonicalPetSpecies");var ci=50,ic=128,nn=120,pi=120,sc=2e3,fi=120,ac=80,gi=new Set(["male","female","unknown"]),hi=new Set(["day","month","year"]),bi=new Set(["low","medium","high","athletic"]),vi=new Set(["indoor","outdoor","both"]),Ci=new Set(["mild","moderate","severe"]),lc=/^(\d{4})-(\d{2})-(\d{2})$/,Ei=[["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"]],Ri=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Ei,...Ri].map(([e])=>e));function dc(e){let t=lc.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(dc,"isRealDate");var Ct=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),uc=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),or=i((e,t)=>typeof t=="string"&&dc(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Ee=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Xt(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=Qt(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),cc={sex:Ct(gi),spayedNeutered:uc,birthDate:or,birthDatePrecision:Ct(hi),activityLevel:Ct(bi),indoorOutdoor:Ct(vi),foodBrand:Ee(fi),foodType:Ee(fi),microchipId:Ee(ac)},on=["ref","ref",false,Ee(ic,{required:true,trimmed:true})],sn=["notes","notes",false,Ee(sc,{trimmed:true})],yi=[on,["name","name",true,Ee(nn,{required:true,trimmed:true})],["dose","dose",false,Ee(pi,{trimmed:true})],["frequency","frequency",false,Ee(pi,{trimmed:true})],["startDate","start_date",false,or],["endDate","end_date",false,or],sn],pc={allergies:[on,["allergen","allergen",true,Ee(nn,{required:true,trimmed:true})],["severity","severity",false,Ct(Ci)],sn],medications:yi,supplements:yi,conditions:[on,["conditionName","condition_name",true,Ee(nn,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,or],sn]};function fc(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[d,u,c,p]of pc[e]){let y=o[d];if(y==null){if(c)return {error:`${n}.${d} is required`};y===null&&(s[u]=null);continue}let g=p(`${n}.${d}`,y);if(g!==null)return {error:g};s[u]=y;}let a=s.start_date,l=s.end_date;return typeof a=="string"&&typeof l=="string"&&l<a?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(fc,"itemToWire");function yc(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>ci)return {error:`${e} has ${t.length} items; the server accepts at most ${ci}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=fc(e,o,t[o]);if("error"in s)return s;let a=s.item.ref;if(typeof a=="string"){let l=a.trim();if(n.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};n.add(l);}r.push(s.item);}return {items:r}}i(yc,"listToWire");function Si(e,t){let r=e,n={};for(let[a,l]of Ei){let d=r[a];if(d!==void 0){if(d!==null){let u=cc[a](a,d);if(u!==null)return {error:u}}n[l]=d;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[a,l]of Ri){let d=r[a];if(d===void 0)continue;let u=yc(a,d);if("error"in u)return u;n[l]=u.items;}return Object.keys(n).length>0&&t!==void 0&&rr(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}}i(Si,"petHealthToWire");var Q=i(e=>typeof e=="string"?e:null,"str"),vt=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),mc=i(e=>typeof e=="boolean"?e:null,"bool");function nr(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(nr,"itemsFromWire");function mi(e){let t=Q(e.name);return t===null||t.length===0?null:Object.freeze({ref:Q(e.ref),name:t,dose:Q(e.dose),frequency:Q(e.frequency),startDate:Q(e.start_date),endDate:Q(e.end_date),notes:Q(e.notes)})}i(mi,"medicationFromWire");function Ti(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:vt(gi,e.sex),spayedNeutered:mc(e.spayed_neutered),birthDate:Q(e.birth_date),birthDatePrecision:vt(hi,e.birth_date_precision),activityLevel:vt(bi,e.activity_level),indoorOutdoor:vt(vi,e.indoor_outdoor),foodBrand:Q(e.food_brand),foodType:Q(e.food_type),microchipId:Q(e.microchip_id),allergies:nr(e.allergies,r=>{let n=Q(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:Q(r.ref),allergen:n,severity:vt(Ci,r.severity),notes:Q(r.notes)})}),medications:nr(e.medications,mi),supplements:nr(e.supplements,mi),conditions:nr(e.conditions,r=>{let n=Q(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:Q(r.ref),conditionName:n,diagnosedDate:Q(r.diagnosed_date),notes:Q(r.notes)})})})}i(Ti,"petHealthFromWire");var wi=100,ki=50,_i=100,Ii=50,Ai=500,gc=128,hc=6e4;function Se(e){return Y("validationFailed",{retryable:false,wireMessage:e})}i(Se,"invalid");function qe(e,t,r){if(typeof t!="string")return Se(`${e} must be a string`);let n=Qt(t);return n<=r?null:Se(`${e} is ${n} characters; the server accepts at most ${r}`)}i(qe,"checkString");function ir(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Se(`${e} must be a finite number between 0 and ${r}`)}i(ir,"outOfRange");function Pi(e,t){if(typeof e!="string")return Se("pet_ref must be a string");if(e.trim().length===0)return Se("pet_ref must not be blank");if(Xt(e))return Se("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Se("profile must be an object");let r=[qe("pet_ref",e,gc)];return t?.name!==void 0&&r.push(qe("name",t.name,wi)),t?.species!==void 0&&r.push(qe("species",t.species,ki)),t?.breed!==void 0&&r.push(qe("breed",t.breed,_i)),t?.ageYears!==void 0&&r.push(ir("age_years",t.ageYears,Ii)),t?.weightKg!==void 0&&r.push(ir("weight_kg",t.weightKg,Ai)),r.find(n=>n!==null)??null}i(Pi,"validate");function Oi(e,t){let r=Si(e,t);return "error"in r?{error:Se(r.error)}:r}i(Oi,"healthToWire");function bc(e){if(typeof e!="object"||e===null)return {error:Se("patch must be an object")};let t=e,r=[["name","name",s=>qe("name",s,wi)],["species","species",s=>qe("species",s,ki)],["breed","breed",s=>qe("breed",s,_i)],["ageYears","age_years",s=>ir("age_years",s,Ii)],["weightKg","weight_kg",s=>ir("weight_kg",s,Ai)]],n={};for(let[s,a,l]of r){let d=t[s];if(d!==void 0){if(d!==null){let u=l(d);if(u!==null)return {error:u}}n[a]=d;}}let o=Oi(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Se("patch must change at least one field")}:{body:n})}i(bc,"patchToWire");function vc(e){if(e==null)return {body:{}};let t=Oi(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}}}i(vc,"toWire");var Re=i(e=>typeof e=="string"?e:null,"str"),sr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function xi(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Re(r.pet_ref)??t,name:Re(r.name),species:Re(r.species),breed:Re(r.breed),ageYears:sr(r.age_years),weightKg:sr(r.weight_kg)})}i(xi,"fromWire");function Fi(e){if(typeof e!="object"||e===null)return null;let t=e,r=Re(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Re(t.pet_id),petRef:r,name:Re(t.name),species:Re(t.species),breed:Re(t.breed),ageYears:sr(t.age_years),weightKg:sr(t.weight_kg),updatedAt:Re(t.updated_at)})}i(Fi,"widgetPetFromWire");function Cc(e){let t=Fi(e);return t===null?null:Object.freeze({...t,...Ti(e)})}i(Cc,"widgetPetProfileFromWire");function Ec(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=Fi(r);return n===null?[]:[n]}))}i(Ec,"petListFromWire");function ar(e){return Rc(Ge({auth:e}),Ge({auth:e,unaryTimeoutMs:hc}))}i(ar,"createPetsRepository");function Rc(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Pi(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?ce(Ec(s.value)):D(s.error)},async registerPet(o,s,a){let l=Pi(o,s);if(l!==null)return D(l);let d=vc(s);if("error"in d)return D(d.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:d.body},p=await e.send("pets.registerPet",a?.signal?{...c,signal:a.signal}:c);return p.ok?ce(xi(p.value,o)):D(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return D(l);let d=bc(s);if("error"in d)return D(d.error);let u=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:d.body},a?.signal));return u.ok?ce(xi(u.value,o)):D(u.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return D(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return D(l.error);let d=Cc(l.value);return d===null?D(Y("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ce(d)},async deletePet(o,s){let a=n(o);if(typeof a!="string")return D(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?ce(void 0):D(l.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?ce(void 0):D(s.error)}}}i(Rc,"createPetsRepositoryOver");var Pc="pet_not_registered";function Vi(e){return e!=null&&e.reasonCode===Pc}i(Vi,"isPetNotRegistered");var xc=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function Ni(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=ae(),a=useCallback(()=>ar(n.registry.services.authFor(o)),[n,o,s]),l=useMemo(()=>t===void 0?null:ln(t),[t]),[d,u]=useState({key:null,status:"idle",error:null,registered:null}),c=useRef(0),p=useRef(r);p.current=r;let y=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,g=useCallback(()=>{if(e===null||t===void 0||y===null)return;let k=++c.current;u({key:y,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(E=>{k===c.current&&(E.ok?(u({key:y,status:"registered",error:null,registered:E.value}),p.current?.()):u({key:y,status:"failed",error:E.error,registered:null}));});},[a,e,y]);useEffect(()=>{if(y===null){c.current+=1;return}return g(),()=>{c.current+=1;}},[y,g]);let h=useCallback(()=>{d.status==="failed"&&g();},[d.status,g]);return useMemo(()=>y===null?xc:d.key!==y?{status:"registering",error:null,registered:null,retry:h}:{status:d.status,error:d.error,registered:d.registered,retry:h},[y,d,h])}i(Ni,"useChatPetRegistration");function ln(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ln).join(",")}]`:`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>`${JSON.stringify(r)}:${ln(n)}`).join(",")}}`}i(ln,"stableKey");var dn=Object.freeze({});function Hi(e){let[t,r]=useState(dn),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(d=>d===dn?d:dn);return}let a=n.current;if(a===null)return;let l=e.find(d=>d.role==="user"&&!a.known.has(d.id));l!==void 0&&(n.current=null,r(d=>({...d,[l.id]:a.images})));},[e]);let s=useCallback(a=>{n.current=a.length===0?null:{images:a,known:new Set(o.current)};},[]);return useMemo(()=>({byMessage:t,stage:s}),[t,s])}i(Hi,"useSentImages");var Oc=500;function un(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,Oc):null}i(un,"sanitizeSeedPrompt");function Ui(e,t,r){let n=un(r),o=useRef(e);o.current=e;let s=useRef(null);useEffect(()=>{if(n===null||t||s.current===n)return;let a=o.current;a!==void 0&&(s.current=n,Promise.resolve(a(n)).catch(()=>{}));},[n,t]);}i(Ui,"useInitialAsk");function Fc(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}i(Fc,"isCoalesced");function Bi(e,t){let r=t.activeConversationId;return r===null||r.length===0?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:Fc(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Bi,"decideChatRefresh");function cn(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(cn,"reportHostFailure");function Mc(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Mc,"isThenable");function W(e,...t){if(typeof e=="function")try{let r=e(...t);return Mc(r)&&Promise.resolve(r).then(void 0,cn),r}catch(r){cn(r);return}}i(W,"callHost");var ji=new WeakMap;function Wi(e){if(typeof e!="function")return;let t=ji.get(e);if(t!==void 0)return t;let r=i((...n)=>{W(e,...n);},"guarded");return ji.set(e,r),r}i(Wi,"guardHost");function st(e,...t){let r;try{r=e(...t);}catch(n){return cn(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(st,"callHostAsync");function qi(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),s=e?.isOffline===void 0?false:W(()=>e.isOffline?.()===!0)===true,a=useRef(()=>{});a.current=l=>{let{conversationId:d,isTurnInFlight:u,refresh:c}=r.current,p=Bi(l,{activeConversationId:d,isTurnInFlight:u,isOffline:s,lastRefresh:n.current,now:Date.now()});if(p.action!=="skip"){if(p.action==="defer"){o.current!=="announced"&&(o.current=l);return}o.current=null,n.current={conversationId:p.conversationId,at:Date.now()},c!==void 0&&Promise.resolve(c()).catch(()=>{});}},useEffect(()=>{if(t.isTurnInFlight||s)return;let l=o.current;l!==null&&a.current(l);},[t.isTurnInFlight,s]),useEffect(()=>{if(e===void 0)return;let l=[],d=i((u,c)=>{if(u===void 0)return;let p=W(()=>u(()=>{a.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return d(e.onForeground?.bind(e),"foreground"),d(e.onOnline?.bind(e),"foreground"),d(e.onAnnounced?.bind(e),"announced"),()=>{for(let u of l)W(u);}},[e]);}i(qi,"useChatLifecycle");function Vc(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(Vc,"targetKey");function Yi(e,t){let r=Vc(t),n=useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=useRef(null);useEffect(()=>{if(r===null||o.current===r)return;o.current=r;let{openCheckin:s,target:a}=n.current;s===void 0||a===void 0||Promise.resolve(s(a)).catch(()=>{});},[r]);}i(Yi,"useCheckinTarget");function Qi(e,t,r){let[n,o]=useState({send:e,conversationId:t,text:r??"",seeded:r??null}),s=n.send===e&&(n.conversationId===null||n.conversationId===t);useEffect(()=>{o(l=>{let d=l.send===e&&(l.conversationId===null||l.conversationId===t),u=d?l.text:"",c=d?l.seeded:null,p=r!=null&&r!==c&&u.length===0;return {send:e,conversationId:t,text:p?r:u,seeded:p?r:c}});},[e,t,r]);let a=useCallback(l=>o(d=>({send:e,conversationId:t,text:l,seeded:d.seeded})),[e,t]);return [s?n.text:"",a]}i(Qi,"useChatDraft");function Zi(e,t,r,n){let o=useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let s=useRef(null),[a,l]=useState(null);useEffect(()=>{if(e===void 0)return;let d=`${t??""}`;if(s.current===d)return;s.current=d;let u=true;return (async()=>{let c=await st(()=>e.read(t));if(!u)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(d);})(),()=>{u=false;}},[e,t]),useEffect(()=>{e===void 0||a!==`${t??""}`||W(()=>e.write(t,r));},[e,t,r,a]);}i(Zi,"usePersistedDraft");var j=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\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats\u2026",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" \xB7 ",newReply:"New reply \xB7 {date}",retry:"Try again",retryA11y:"Retry loading chats",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages\u2026",openConversation:"Open conversation",unreadPrefix:"Unread. "});function dr(e){let t=e?.replace(/\s+/g," ").trim();return t||j.untitled}i(dr,"conversationTitle");function Bc(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}i(Bc,"conversationDate");function es(e){let t=Bc(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?j.newReply.replace("{date}",t):t}i(es,"conversationMeta");function ts(e,t){return t?`${j.countLabel}${j.countSeparator}${e}`:j.countLabel}i(ts,"historyCountLabel");function rs(e){return `${e.unreadCount!==null&&e.unreadCount>0?j.unreadPrefix:""}${j.openConversation} ${dr(e.title)}`}i(rs,"openConversationLabel");function Ji(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Ji,"normalizeForSearch");function jc(e,t){let r=Ji(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=Ji(dr(o.title)),a=s.indexOf(r);if(a<0)continue;let l=a===0?0:s.charAt(a-1)===" "?1:2;n[l]?.push(o);}return n.flat()}i(jc,"filterConversations");function yn(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(yn,"fresh");function ns(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,d]=useState(()=>yn(s)),u=l.scope===s?l:yn(s);useEffect(()=>(a.current+=1,r(false),o(""),d(yn(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async S=>{let w=++a.current,m=S!==void 0;d(_=>({..._,scope:s,loading:!m,loadingMore:m,error:null}));let R=await e.listConversations(S?{cursor:S}:void 0);if(w===a.current){if(!R.ok){d(_=>({..._,loading:false,loadingMore:false,error:R.error.displayMessage}));return}d(_=>{let A=S&&_.scope===s?_.rows:[],O=new Set(A.map(C=>C.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...A,...R.value.conversations.filter(C=>!O.has(C.id))],cursor:R.value.nextCursor===S?null:R.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),y=i(()=>{a.current+=1,r(false);},"close"),g=i(async S=>{let w=++a.current;d(R=>({...R,loading:true,error:null}));let m=await e.resumeConversation(S);w===a.current&&(d(R=>({...R,loading:false,error:m.ok?null:m.error.displayMessage})),m.ok&&r(false));},"resume"),h=i(async()=>{let S=a.current,w=await e.loadOlderMessages();S===a.current&&!w.ok&&d(m=>({...m,error:w.error.displayMessage}));},"earlier"),k=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),E=i(()=>{u.cursor===null||u.loading||u.loadingMore||n.trim().length>0||c(u.cursor);},"loadMore"),P=useMemo(()=>jc(u.rows,n),[u.rows,n]),T=n.trim().length>0;return {...u,open:t,show:p,close:y,load:c,resume:g,earlier:h,newConversation:k,loadMore:E,query:n,setQuery:o,searching:T,filtered:P,emptyKind:u.rows.length===0?"empty":"noMatch"}}i(ns,"useHistoryPanel");var ur="#111111",cr="#FFFFFF",qc=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:ur,pillColor:cr,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:ur,pillColor:cr,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ur,pillColor:cr,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ur,pillColor:cr,showsVetAction:false})});function Kc(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(Kc,"urgencySignature");function Yc(e){return B(f.urgencyGeneralReason,{petName:e?.trim()||f.emptyTitlePetFallback})}i(Yc,"generalUrgencyReason");function ss(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 o=n.urgencyLevel;return o?{messageId:n.id,level:o,reason:$c(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Yc(t)}:null}return null}i(ss,"latestUrgencySource");function $c(e){return typeof e=="string"&&e.trim().length>0?e:null}i($c,"shownReason");function as(e){let t=e===null?null:Kc(e),[r,n]=useState(null),[o,s]=useState(false);useEffect(()=>s(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:qc[e.level],u=e!==null&&!l&&e.level!=="general",c=useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=useCallback(()=>s(true),[]);return useMemo(()=>({source:e,tier:d,signature:t,showBanner:l,showCompactIcon:u,showVetAction:l&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:B(f.dismissBanner,{label:d.label}),dismiss:c,expand:p}),[e,d,t,l,u,c,p])}i(as,"useUrgencySurface");function ls(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(ls,"selectView");function Xc(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Xc,"needsNewConversation");function ds(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let n=Xc(r),o=t==="web";return {tone:"error",title:n?f.turnUnreachableTitle:o?f.turnFailedTitleWeb:f.turnFailedTitle,body:r.displayMessage,actionLabel:n?f.turnStartNewChat:o?f.retry:f.turnRetry,action:n?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:f.turnStoppedTitle,body:f.turnStoppedBody,actionLabel:f.turnRetry,action:"retry"}:null}i(ds,"turnNotice");function us(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(us,"awaitingAssistant");var Qc=3,Zc=Object.freeze([]);function cs(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Zc;let r=new Set,n=[];for(let o of e.suggestedPrompts){let s=o.trim(),a=s.replace(/\s+/g," ").toLowerCase();if(!(a.length===0||r.has(a))&&(r.add(a),n.push(s),n.length===Qc))break}return Object.freeze(n)}i(cs,"visibleFollowUps");function ps(e){return e.sender?.displayName??f.senderVet}i(ps,"vetSenderLabel");function fs(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(fs,"buildChatOpts");var Jc=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function v(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Jc[t]]}}i(v,"face");var gn=class gn extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,n){return Object.is(r.resetKey,n.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(gn,"HostRenderBoundary");var mn=gn;function tp({render:e}){return e()}i(tp,"RenderHost");function Ke({render:e,fallback:t,resetKey:r}){return createElement(mn,{fallback:t,resetKey:r,children:createElement(tp,{render:e})})}i(Ke,"HostRender");var rp=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function np(e){return rp[e]}i(np,"requires");function ms(e,t,r){let n=np(e),o=new Map;for(let l of t)o.set(l.resource,l);if(r?.isPending===true&&n.some(l=>!o.has(l)))return hn({name:e,enabled:false,isPending:true,limits:{}});let s=op(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?hn({name:e,enabled:true,isPending:false,limits:s}):hn({name:e,enabled:false,isPending:false,limits:s,disabled:ip(n,o)})}i(ms,"decideCapability");function op(e,t){let r={};for(let n of e){let o=t.get(n)?.limits;if(o)for(let[s,a]of Object.entries(o)){let l=r[s];r[s]=l===void 0?a:Math.min(l,a);}}return r}i(op,"mergeLimits");function ip(e,t){for(let r of e){let n=t.get(r)?.disabled;if(n)return Object.freeze({reason:n.reason,level:n.level,recoverable:n.recoverable})}return Object.freeze({reason:Gr("accessDenied"),level:"user_entitlement",recoverable:false})}i(ip,"disabledFor");function hn(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(hn,"freezeDecision");function Et(e){let{runtime:t}=ae(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>ms(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Et,"useCapability");var lp=48;function dp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(dp,"selectView");function vs(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Et(t),l=useMemo(()=>dp(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(Ke,{render:o,fallback:jsx(hs,{capability:t,style:s})}):jsx(hs,{capability:t,style:s});case "disabled":return n?jsx(Ke,{render:()=>n(a),fallback:jsx(bs,{decision:a,style:s}),resetKey:a}):jsx(bs,{decision:a,style:s});default:return $t(l)}}i(vs,"CapabilityGate");function hs({capability:e,style:t}){let r=F(),n=useMemo(()=>Cs(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(hs,"PendingSkeleton");function bs({decision:e,style:t}){let r=F(),n=useMemo(()=>Cs(r),[r]),o=e.disabled?.reason??"";return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsx(b,{style:n.offstateText,children:o}):null})}i(bs,"OffState");function Cs(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:lp,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...v(e,"regular"),fontSize:o.size.body,lineHeight:Math.round(o.size.body*o.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}i(Cs,"makeStyles");var ne={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function te(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(te,"box");function le(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(le,"stroke");function Es({size:e,color:t,strokeWidth:r}){let n=le(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxs(View,{style:[te(e),{gap:e*.22}],...ne,children:[jsx(View,{style:o}),jsx(View,{style:o}),jsx(View,{style:o})]})}i(Es,"MenuGlyph");function Rs({size:e,color:t,strokeWidth:r,rotate:n}){let o=le(e,r),s=e*.78;return jsxs(View,{style:[te(e),{transform:[{rotate:n}]}],...ne,children:[jsx(View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),jsx(View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}i(Rs,"Cross");function pr(e){return jsx(Rs,{...e,rotate:"0deg"})}i(pr,"PlusGlyph");function ke(e){return jsx(Rs,{...e,rotate:"45deg"})}i(ke,"CloseGlyph");function He({size:e,color:t,strokeWidth:r}){let n=le(e,r);return jsx(View,{style:te(e),...ne,children:jsx(View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(He,"CheckGlyph");var cp={down:{rotate:"45deg",marginTop:-0.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-0.4}};function Ss({size:e,color:t,strokeWidth:r,direction:n}){let o=le(e,r),s=e*.46,a=cp[n];return jsx(View,{style:te(e),...ne,children:jsx(View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:s*a.marginTop,marginLeft:s*a.marginLeft,transform:[{rotate:a.rotate}]}})})}i(Ss,"ChevronGlyph");function Ts({size:e,color:t,strokeWidth:r}){let n=le(e,r),o={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};return jsxs(View,{style:[te(e),{flexDirection:"row",gap:1}],...ne,children:[jsx(View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsx(View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(Ts,"BookGlyph");function Ps({size:e,color:t,strokeWidth:r}){let n=le(e,r),o=e*.5;return jsxs(View,{style:te(e),...ne,children:[jsx(View,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),jsx(View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}i(Ps,"ArrowUpRightGlyph");function xs({size:e,color:t,strokeWidth:r}){let n=le(e,r),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:n,borderColor:t,borderRadius:e*.14};return jsxs(View,{style:te(e),...ne,children:[jsx(View,{style:[s,{top:0,left:0}]}),jsx(View,{style:[s,{bottom:0,right:0}]})]})}i(xs,"CopyGlyph");function fr({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=le(e,r),a=n?t:"transparent";return jsxs(View,{style:[te(e),{transform:[{rotate:o}]}],...ne,children:[jsx(View,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),jsx(View,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),jsx(View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}i(fr,"ThumbGlyph");function ws({size:e,color:t,strokeWidth:r}){let n=le(e,r);return jsxs(View,{style:[te(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...ne,children:[jsx(View,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),jsx(View,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}i(ws,"InfoGlyph");function ks({size:e,color:t,strokeWidth:r}){let n=le(e,r),o=e*.34;return jsxs(View,{style:te(e),...ne,children:[jsx(View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),jsx(View,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),jsx(View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}i(ks,"UploadGlyph");function _s({size:e,color:t,strokeWidth:r}){let n=le(e,r);return jsxs(View,{style:[te(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...ne,children:[jsx(View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),jsx(View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(_s,"PhotoGlyph");function Is({size:e,color:t,strokeWidth:r}){let n=le(e,r);return jsxs(View,{style:te(e),...ne,children:[jsx(View,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),jsx(View,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:jsx(View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}i(Is,"CameraGlyph");function As({size:e,color:t,strokeWidth:r}){let n=le(e,r),o=e*.66;return jsxs(View,{style:te(e),...ne,children:[jsx(View,{style:{position:"absolute",top:0,left:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t}}),jsx(View,{style:{position:"absolute",bottom:e*.02,right:e*.02,width:n,height:e*.4,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}})]})}i(As,"SearchGlyph");function Cn({size:e,color:t,strokeWidth:r}){let n=le(e,r),o=e*.62;return jsxs(View,{style:te(e),...ne,children:[jsx(View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:jsx(View,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),jsx(View,{style:{position:"absolute",bottom:e*.04,width:o*.5,height:o*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(Cn,"MapPinGlyph");function Os({size:e,color:t,testID:r}){let n=e*.36;return jsx(View,{style:te(e),testID:r,...ne,children:jsx(View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}i(Os,"SendGlyph");function Fs({size:e,color:t,testID:r}){return jsx(View,{style:te(e),testID:r,...ne,children:jsx(View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(Fs,"StopGlyph");function yr({size:e,strokeWidth:t,color:r,children:n}){return jsx(View,{style:[te(e),{borderRadius:e/2,borderWidth:t??StyleSheet.hairlineWidth,borderColor:r}],children:n})}i(yr,"Ring");var at=Object.freeze({standard:We.standard,emphasized:We.emphasized,exit:We.exit,outQuad:Object.freeze([.25,.46,.45,.94]),out:Object.freeze([.23,1,.32,1])});var Ms=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:Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),pp=Object.freeze({...Ms,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 Ls(e){return e.motion.reducedMotion?pp:Ms}i(Ls,"chatMotion");function mr(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(mr,"followUpDelayMs");function Vs(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)}i(Vs,"nextRevealLength");function K(){let e=F();return Ls(e)}i(K,"useChatMotion");var gp=8;function Ds(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(Ds,"bezierComponent");function hp(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(hp,"bezierSlope");function St(e){let[t,r,n,o]=e;return s=>{if(s<=0)return 0;if(s>=1)return 1;let a=s;for(let l=0;l<gp;l+=1){let d=hp(a,t,n);if(d===0)break;a-=(Ds(a,t,n)-s)/d;}return Ds(Math.min(1,Math.max(0,a)),r,o)}}i(St,"bezierEasing");var En=St(at.standard),bp=St(at.outQuad),vp=St(at.out);function hr(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(hr,"useAnimatedValue");function lt(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=hr(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:bp,useNativeDriver:true}),a=n>0?Animated.sequence([Animated.delay(n),s]):s;return a.start(),()=>a.stop()},[o,e,n]),useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[o,r])}i(lt,"useFadeIn");function Tn({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=hr(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let u=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:En,useNativeDriver:true});return u.start(),()=>u.stop()}if(!s)return;if(r<=0){a(false);return}let d=Animated.timing(l,{toValue:0,duration:r,easing:En,useNativeDriver:true});return d.start(({finished:u})=>{u&&a(false);}),()=>d.stop()},[e,s,t,r,l]),!s&&!e?null:jsx(Animated.View,{style:[n,{opacity:l}],children:o})}i(Tn,"FadePresence");var Cp=Object.freeze({opacity:1,transform:Object.freeze([{translateY:0},{scale:1}])});function Bs(e,t){let[r]=useState(()=>e?t.bubbleInMs:0),n=r>0,o=hr(n?0:1);useEffect(()=>{if(r<=0)return;let l=Animated.timing(o,{toValue:1,duration:r,easing:vp,useNativeDriver:true});return l.start(),()=>l.stop()},[r,o]);let s=t.bubbleFromScale,a=t.bubbleRisePx;return useMemo(()=>n?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[a,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:Cp,[n,o,a,s])}i(Bs,"useBubbleEnter");function js(e){let t=useRef(null),r=useRef(null),n=e[0]?.id??null;if(t.current===null||r.current!==n){let s=t.current===null;t.current=new Map(e.map(a=>[a.id,s&&a.pending===true])),r.current=n;}let o=t.current;for(let s of e)o.has(s.id)||o.set(s.id,true);return useCallback(s=>o.get(s)===true,[o])}i(js,"useEnteringRows");var Ep=12;function H({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=K(),d=hr(1),u=useCallback(c=>{l.pressMs<=0||l.pressScale===1||Animated.timing(d,{toValue:c,duration:l.pressMs,easing:En,useNativeDriver:true}).start();},[d,l.pressMs,l.pressScale]);return jsx(Pressable,{...a,hitSlop:s??Ep,style:t,onPressIn:c=>{u(l.pressScale),n?.(c);},onPressOut:c=>{u(1),o?.(c);},children:jsx(Animated.View,{style:[e,{transform:[{scale:d}]}],children:r})})}i(H,"PressScale");function Ws(e,t,r){let n=t&&r.revealTickMs>0,[o,s]=useState(0),a=useRef(e);return a.current=e,useEffect(()=>{if(!n)return;let l=setInterval(()=>{s(d=>Vs(r,d,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(Ws,"useRevealedText");var Hs=false;function Rp(e){e.layoutMs<=0||(Hs||(Hs=true,Platform.OS==="android"&&typeof UIManager.setLayoutAnimationEnabledExperimental=="function"&&UIManager.setLayoutAnimationEnabledExperimental(true)),LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}));}i(Rp,"animateLayout");function Tt(e,t){let r=useRef(e);r.current!==e&&(r.current=e,Rp(t));}i(Tt,"useAnimateLayoutOn");var Pn=36,_p=22,Ip=12,Ap=12,Op=16,Fp="#000",Mp="rgba(0,0,0,0.45)";function Gs({uri:e,label:t,onClose:r}){let n=F(),o=useSafeAreaInsets();return e===null?null:jsxs(Modal,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f.closePreview,style:br.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:br.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[br.closeWrap,{top:o.top+Ap}],children:jsx(H,{accessibilityRole:"button",accessibilityLabel:f.closePreview,hitSlop:Ip,style:br.closeButton,onPress:r,children:jsx(ke,{size:_p,color:n.color.surface,strokeWidth:2})})})]})}i(Gs,"AttachmentImageLightbox");var br=StyleSheet.create({backdrop:{flex:1,backgroundColor:Fp,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:Op},closeButton:{width:Pn,height:Pn,borderRadius:Pn/2,backgroundColor:Mp,alignItems:"center",justifyContent:"center"}});var vr=12,Hp=80,xn=44,qs=22,zp=.14,Up=18,Bp=8,Ks=Object.freeze({photo:f.attachmentPhoto,camera:f.attachmentCamera});function Ys({sources:e,full:t,onPick:r,onClose:n}){let o=F(),s=useMemo(()=>jp(o),[o]);return jsxs(View,{style:s.anchor,pointerEvents:"box-none",children:[jsx(Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:f.closeAttachmentPicker,onPress:n}),jsxs(View,{style:s.bubble,children:[jsx(View,{style:s.tilesRow,children:e.map(a=>jsxs(H,{accessibilityRole:"button",accessibilityLabel:Ks[a],accessibilityState:{disabled:t},disabled:t,containerStyle:s.tile,style:s.tileInner,onPress:()=>r(a),children:[jsx(View,{style:s.tileIconWrap,children:a==="photo"?jsx(_s,{size:qs,color:o.color.brandInk,strokeWidth:1.5}):jsx(Is,{size:qs,color:o.color.brandInk,strokeWidth:1.5})}),jsx(b,{tier:"control",style:s.tileLabel,children:Ks[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(Ys,"AttachmentPickerPopover");function jp(e){let t=e.color,r=e.radius;return StyleSheet.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:zp,shadowRadius:Up,shadowOffset:{width:0,height:Bp},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:Hp,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:xn,height:xn,borderRadius:xn/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...v(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-vr/2,width:vr,height:vr,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:vr+4,height:2,backgroundColor:t.surfaceCream}})}i(jp,"makeStyles");function Wp(e){if(typeof e=="number")return $s(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return kn(t.slice(1));if(t.toLowerCase().startsWith("0x"))return kn(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Gp(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=kn(t);if(r!==null)return r}return /^\d+$/.test(t)?$s(Number.parseInt(t,10)):null}i(Wp,"toRgba");function kn(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:_n(t[0]),g:_n(t[1]),b:_n(t[2]),a:1};if(t.length===6)return {r:Ye(t,0),g:Ye(t,2),b:Ye(t,4),a:1};if(t.length===8){let r=Ye(t,0);return {r:Ye(t,2),g:Ye(t,4),b:Ye(t,6),a:r/255}}return null}i(kn,"fromHex");function Gp(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(d=>d.trim());if(n.length<3)return null;let o=In(Number(n[0])),s=In(Number(n[1])),a=In(Number(n[2]));if(o===null||s===null||a===null)return null;let l=1;if(n.length>=4){let d=Number(n[3]);if(!Number.isFinite(d))return null;l=Math.min(1,Math.max(0,d));}return {r:o,g:s,b:a,a:l}}i(Gp,"fromRgbFunc");function $s(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}}i($s,"argbIntToRgba");function Ye(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(Ye,"byte");function _n(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(_n,"dup");function In(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(In,"clampByte");function Ue(e,t){let r=Wp(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return `rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}i(Ue,"withAlpha");var ye=Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var Qs=56,Zs=12,Yp=14,$p=10,Xp=.45,Qp="rgba(7,193,104,0.55)",Zp="rgba(185,28,28,0.55)",Jp=200,ef=300,sa=20,An=22,tf=12,rf="rgba(0,0,0,0.78)",Js=220,ea=100,ta="rgba(255,255,255,0.15)";function aa({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=F(),l=useMemo(()=>da(a),[a]);return e.length===0&&t===null?null:jsxs(View,{style:l.strip,children:[e.length>0?jsx(View,{style:l.cards,children:e.map(d=>jsx(nf,{row:d,styles:l,onRetry:n,onRemove:o,onPreview:s},d.id))}):null,r?jsx(b,{style:l.rejected,accessibilityRole:"alert",children:f.attachmentsFailedBlocked}):null,t!==null?jsx(b,{style:l.rejected,accessibilityRole:"alert",children:li(t)}):null]})}i(aa,"AttachmentStrip");function nf({row:e,styles:t,onRetry:r,onRemove:n,onPreview:o}){let s=F(),a=e.status==="uploading",l=e.status==="failed",d=e.status==="uploaded",u=useRef(e.status),[c,p]=useState(false);return useEffect(()=>{let y=u.current;u.current=e.status,e.status==="uploaded"&&y==="uploading"&&p(true);},[e.status]),jsxs(View,{style:t.card,children:[jsx(Pressable,{accessibilityRole:d?"button":"image",accessibilityLabel:d?B(f.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:a,disabled:!d},disabled:!d,style:t.thumbHit,onPress:()=>o(e),children:jsxs(View,{style:t.thumb,children:[jsx(Image,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),a?jsx(View,{style:t.uploadingOverlay,children:jsx(ActivityIndicator,{size:"small",color:s.color.surface})}):null,c?jsx(of,{styles:t,onDone:()=>p(false)}):null]})}),l?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:B(f.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsx(View,{style:t.failedInner,children:jsx(ke,{size:sa,color:s.color.surface,strokeWidth:2})})}):null,jsx(H,{accessibilityRole:"button",accessibilityLabel:B(f.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsx(ke,{size:tf,color:s.color.surface,strokeWidth:1.5})})]})}i(nf,"PreviewCard");function of({styles:e,onDone:t}){let r=F(),n=K(),o=useRef(null);o.current===null&&(o.current=new Animated.Value(0));let s=o.current;return useEffect(()=>{let a=Animated.sequence([Animated.timing(s,{toValue:1,duration:Jp,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:ef,useNativeDriver:true})]);return a.start(({finished:l})=>{l&&t();}),()=>a.stop()},[s,n.uploadFlashMs,t]),jsx(Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:s}],children:jsx(He,{size:sa,color:r.color.surface,strokeWidth:2})})}i(of,"SuccessFlash");function la({images:e,onPreview:t}){let r=F(),n=useMemo(()=>da(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsx(View,{style:o?n.sentSingle:n.sentGrid,children:e.map((s,a)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:B(f.attachedImage,{filename:s.filename}),onPress:()=>t(s),children:jsx(Image,{source:{uri:s.uri},style:o?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${s.uri}-${a}`))})}i(la,"SentImages");function da(e){let t=e.color,r=e.type;return StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:Qs,height:Qs,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Zs,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...ye,alignItems:"center",justifyContent:"center",backgroundColor:Ue(e.color.brandInk,Xp)??e.color.brandSofter},successOverlay:{...ye,alignItems:"center",justifyContent:"center",backgroundColor:Qp},failedOverlay:{...ye,borderRadius:Zs,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:Zp},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:An,height:An,borderRadius:An/2,backgroundColor:rf,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...v(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:Js,height:Js,borderRadius:Yp,backgroundColor:ta},gridImage:{width:ea,height:ea,borderRadius:$p,backgroundColor:ta}})}i(da,"makeStyles");var sf="file",Mn="multipart upload failed";function ua(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(sf,e.file);}catch{return Promise.reject(new Error(Mn))}return e.fetch!==void 0?df(e.fetch,e.url,t,e.signal):lf(e.url,t,e.signal)}i(ua,"postRnMultipart");function af(e){return e>=200&&e<300}i(af,"stored");function lf(e,t,r){return new Promise((n,o)=>{let s=globalThis.XMLHttpRequest;if(typeof s!="function"||r?.aborted===true){o(new Error(Mn));return}let a=null,l=i(()=>{a!==null&&r?.removeEventListener("abort",a);},"release"),d=i(()=>{l(),o(new Error(Mn));},"fail");try{let u=new s;u.open("POST",e),u.withCredentials=!1,u.onload=()=>{l(),n(af(u.status));},u.onerror=d,u.ontimeout=d,u.onabort=d,r!==void 0&&(a=i(()=>{try{u.abort();}finally{d();}},"onAbort"),r.addEventListener("abort",a,{once:!0})),u.send(t);}catch{d();}})}i(lf,"postWithXhr");function df(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(o=>o.ok)}i(df,"postWithFetch");var uf="chat attachment upload: the file handle has no uri",cf="chat attachment upload failed";function pf(e){return {uri:e.uri,name:en(e.name),type:e.mimeType}}i(pf,"filePartOf");function Ln(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(uf));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(cf)),"failed");return o?.aborted===true?a():ua({url:t.upload_url,fields:t.upload_fields,file:pf(r),signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(Ln,"createRnChatAttachmentTransport");function Nn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=ae(),o=useMemo(()=>ar(e.registry.services.authFor(t)),[e,t,n]),[s,a]=useState({repository:o,pets:[],loading:true,error:null}),l=s.repository===o?s:{pets:[],loading:true,error:null},d=useRef(0),u=useCallback(async()=>{let p=++d.current;a(g=>({...g,repository:o,loading:true,error:null,pets:g.repository===o?g.pets:[]}));let y=await o.list();p===d.current&&a(y.ok?{repository:o,pets:y.value,loading:false,error:null}:g=>({repository:o,pets:g.repository===o?g.pets:[],loading:false,error:y.error}));},[o]);useEffect(()=>(u(),()=>{d.current+=1;}),[u]);let c=useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return useMemo(()=>({pets:l.pets,activePet:c,loading:l.loading,error:l.error,refresh:u}),[l.pets,l.loading,l.error,c,u])}i(Nn,"useEverfurPets");function ca(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(ca,"headerPetOf");function oe(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}i(oe,"slotBox");function Cr(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(Cr,"ownGroundSlot");function me(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(me,"slotText");var pa=Object.freeze({visitButton:"Vet"});var fa=Symbol.for("@everfur/sdk/televet");function _e(){let e=globalThis,t=e[fa];if(t!==void 0)return t;let r={presenter:null,snapshot:Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:new Set,dailyRegistered:false};return e[fa]=r,r}i(_e,"televetGlobal");function Er(e){let t=_e();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Er,"publish");function ya(e){let t=_e().presenter;if(t===null)return "absent";try{return t(e)===!1?"declined":"presented"}catch(r){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",r),"threw"}}i(ya,"callTelevetPresenter");function ma(e){let t=_e();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(ma,"subscribeTelevetExperience");function Dn(){return _e().snapshot}i(Dn,"televetExperienceSnapshot");function hf(){return _e().hosts.length>0}i(hf,"hasTelevetHost");function ga(e){if(!hf())return false;let t=Object.freeze({...e});return Er({request:t,serial:_e().snapshot.serial+1}),true}i(ga,"presentTelevetExperience");function Hn(){_e().snapshot.request!==null&&Er({request:null});}i(Hn,"dismissTelevetExperience");function ha(){let e=_e(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Er({activeHost:e.hosts[0]??null}),t}i(ha,"claimTelevetHost");function ba(e){let t=_e();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Er(r===null?{activeHost:r,request:null}:{activeHost:r});}i(ba,"releaseTelevetHost");var va=false;function Rr(e,t){return t!==void 0?(W(t,e),"onStartInApp"):ya(e)==="presented"?"presenter":ga(e)?"experience":(va||(va=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(Rr,"openVetVisitInApp");function Ra(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}}i(Ra,"memoizeTelevetLoader");function Sa(e){let[t,r]=useState(null);useEffect(()=>{let u=ha();return r(u),()=>{ba(u);}},[]);let n=useSyncExternalStore(ma,Dn,Dn),s=t!==null&&n.activeHost===t?n.request:null,[a,l]=useState(null),d=s!==null&&a===null;return useEffect(()=>{if(!d)return;let u=true;return e().then(c=>{u&&l(()=>c);},c=>{u&&(console.warn("[everfur] The in-app vet visit could not load its screens.",c),Hn());}),()=>{u=false;}},[d,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:Hn}}i(Sa,"useTelevetExperienceHost");var vf=Ra(()=>import('@everfur/sdk/televet/booking'));function xt(){let e=Sa(vf);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(xt,"EverfurTelevetHost");var zn=Object.freeze(["visit","join","summary","messages"]);function Un(e){return typeof e=="string"&&zn.includes(e)}i(Un,"isVetVisitIntent");var Ef="/widget/v1/televet/handoffs",Rf="/widget/v1/televet/availability",Sf="/widget/v1/televet/chat-entry",Tf=/^[a-z0-9][a-z0-9_-]{0,39}$/,Pf=/^[A-Za-z0-9_-]{22}$/;var Ta=32,Pa=128,xa=64;function jn(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"}i(jn,"vetVisitErrorReasonOf");function wa(e){return D(Y("validationFailed",{retryable:false,wireMessage:e}))}i(wa,"invalid");function Bn(e){return D(Y("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Bn,"unusable");function xf(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Tf.test(n))return {ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n;}let o=t?.entry;if(o!=null){if(o!=="chat"||e===void 0)return {ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=o;}let s=t?.visitRef,a=t?.intent,l=s!=null;if(l){let d=typeof s=="string"?s.trim():"";if(d.length<1||[...d].length>xa)return {ok:false,message:`visitRef must be 1..${xa} characters`};r.visit_ref=d;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Un(a))return {ok:false,message:`intent must be one of ${zn.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(xf,"handoffBody");function wf(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Un(r)?null:Object.freeze({visitRef:t,intent:r})}i(wf,"parseVisitEcho");function _a(e){let t=e.funnel??Ge({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(ka(r,"televet.visit.handoff_failed",{reason:jn(o)}),D(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let E=typeof o=="string"?[...o].length:0;if(E<1||E>Pa)return n(Y("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Pa} characters`}));a=o;}let l=xf(a,s);if(!l.ok){let E=wa(l.message);return E.ok?E:n(E.error)}let d=l.body,u=await t.send("televet.visit.handoff",{method:"POST",path:Ef,body:d},{idempotent:false,maxAttempts:1});if(!u.ok)return n(u.error);let c=kf(u.value),p=d.return_to!==void 0,y=p?u.value?.flow_id:void 0;if(p&&(typeof y!="string"||!Pf.test(y))){let E=Bn("the handoff response carried no usable return flow id");return E.ok?E:n(E.error)}let g=d.visit_ref!==void 0,h=g?wf(u.value?.visit):null;if(g&&h===null){let E=Bn("the handoff response did not confirm the visit it opens");return E.ok?E:n(E.error)}let k=c===null?null:Object.freeze({...c,...p?{flowId:y}:{},...h!==null?{visit:h}:{}});return k===null?n(Y("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(ka(r,"televet.visit.handoff_created",{pet_scoped:d.pet_ref!==void 0}),ce(k))},async checkAvailability(o){if(typeof o!="string"||o.length>Ta)return wa(`state must be at most ${Ta} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:Rf,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return D(s.error);let a=s.value?.available;return typeof a!="boolean"?Bn("the availability response carried no usable answer"):ce(Object.freeze({available:a}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:Sf},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(_a,"createVetVisitController");function kf(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||!Of(t)?null:Object.freeze({url:t,expiresAt:r})}i(kf,"parseHandoff");var _f=new Set(["localhost","127.0.0.1","[::1]"]),If=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Af=/[\s\u0000-\u001f\u007f]/;function Of(e){if(Af.test(e))return false;let t=If.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let o=n.replace(/:\d+$/,"").toLowerCase(),s=r==="https",a=r==="http"&&_f.has(o);if(!s&&!a)return false;let l=e.indexOf("#");if(l<0)return false;let d=e.slice(l);return d.startsWith("#h=")&&d.length>3}i(Of,"isOpenableVisitUrl");function ka(e,t,r){if(e)try{e.track(t,r);}catch{}}i(ka,"safeTrack");var Wn=Object.freeze({status:"idle",error:null,errorReason:null});function Mf(e,t,r){let{usState:n,chat:o,scope:s}=r,a=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[d,u]=useState(null);if(useEffect(()=>{if(!a)return;let p=true,y=e.current;return u(null),i(async()=>{try{if(o&&!(y.chatEntryOpen&&await y.chatEntryOpen()))return !1;if(n===null)return !0;if(!y.checkAvailability)return !1;let h=await y.checkAvailability(n);return h.ok&&h.value.available}catch{return false}},"ask")().then(h=>{p&&u({key:l,open:h});}),()=>{p=false;}},[a,l,n,o,s,e]),!a)return null;let c=d!==null&&d.key===l;return {open:c&&d.open,pending:!c}}i(Mf,"usePreflight");var Lf=Object.freeze({status:"opening",error:null,errorReason:null});function Oa(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=ae(),s=Et("televet"),a=s.enabled&&n!==null,l=t.usState??null,d=t.entry==="chat",u=t.petRef??null,c=t.prefer==="redirect",p=useMemo(()=>{if(t.controller)return t.controller;let{services:M}=r.registry;return _a({auth:M.authFor(n),telemetry:M.telemetry,...M.errorPolicy?{errorPolicy:M.errorPolicy}:{}})},[r,n,o,t.controller]),y=useRef(p);y.current=p;let g=useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),h=Mf(y,a,{usState:l,chat:d,scope:g}),k=a&&(h===null||h.open)&&(!d||u!==null),E=t.returnTo??null,[P,T]=useState(Wn),S=useRef(null),w=useRef({runtime:r,userRef:n,scopeEpoch:o});w.current={runtime:r,userRef:n,scopeEpoch:o};let m=useRef(p);m.current=p;let R=useRef(k);R.current=k;let _=useCallback((M,x)=>{if(S.current)return S.current;let N=i((se,Ne)=>(T({status:se==="cancelled"?"idle":"error",error:Ne,errorReason:se==="cancelled"?null:se}),Object.freeze({opened:false,reason:se,error:Ne})),"fail");if(!R.current)return Promise.resolve(N("unavailable",null));let q=e.prepare();if(!q.ok)return Promise.resolve(N(q.reason,null));let X=w.current,G=m.current;T(Lf);let Ve=(async()=>{let se,Ne={...E!==null?{returnTo:E}:{},...d?{entry:"chat"}:{},...x!==null?{visitRef:x.visitRef}:{},...x!==null&&x.intent!==null&&x.intent!==void 0?{intent:x.intent}:{}},Dt=Object.keys(Ne).length===0?void 0:Ne,Ht=M===void 0?u:M;try{se=await(Dt===void 0?G.createHandoff(Ht):G.createHandoff(Ht,Dt));}catch{return e.abandon(q.value),N("unknown",null)}let rt=w.current;if(rt.runtime!==X.runtime||rt.userRef!==X.userRef||rt.scopeEpoch!==X.scopeEpoch)return e.abandon(q.value),N("cancelled",null);if(!se.ok)return e.abandon(q.value),N(jn(se.error),se.error);let pt=await e.finish(q.value,se.value);return pt!==null?N(pt,null):(T(Wn),Object.freeze(se.value.flowId===void 0?{opened:true}:{opened:true,flowId:se.value.flowId}))})().finally(()=>{S.current===Ve&&(S.current=null);});return S.current=Ve,Ve},[e,u,E,d]),A=useCallback((M,x)=>{if(!R.current)return T({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let N=M===void 0?u:M,q={...N!==null?{petRef:N}:{},...l!==null?{usState:l}:{},...x!==null?{visitRef:x.visitRef,intent:x.intent}:{}};return Rr(q)===null?(T({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(T(Wn),Promise.resolve(Object.freeze({opened:true})))},[u,l]),O=useCallback(M=>c?_(M,null):A(M,null),[c,_,A]),C=useCallback((M,x)=>c?_(void 0,{visitRef:M,intent:x??null}):A(void 0,{visitRef:M,intent:x??null}),[c,_,A]);return {available:k,isPending:s.isPending||(h?.pending??false),status:P.status,error:P.error,errorReason:P.errorReason,open:O,openVisit:C}}i(Oa,"useVetVisitWith");var Df=i(e=>Linking.openURL(e),"defaultOpenUrl");function Tr(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??Df;return {prepare:i(()=>({ok:true,value:null}),"prepare"),async finish(s,a){try{return await o(a.url),null}catch{return "openFailed"}},abandon:i(()=>{},"abandon")}},[t]);return Oa(n,r)}i(Tr,"useVetVisit");var Fa=44,jf=.6;function ct(e){let{petRef:t,label:r,openUrl:n,onOpened:o,onError:s,style:a,labelStyle:l,controller:d,returnTo:u,usState:c,entry:p,visitRef:y,intent:g,onStartInApp:h,prefer:k}=e,E=k==="redirect",P=Tr({...u!==void 0?{returnTo:u}:{},...c!==void 0?{usState:c}:{},...p!==void 0?{entry:p}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...d!==void 0?{controller:d}:{},prefer:E?"redirect":"in-app"}),T=F(),S=useMemo(()=>Wf(T),[T]),w=useRef(false);if(!P.available)return jsxs(Fragment,{children:[null,jsx(xt,{})]});let m=P.status==="opening",R=r??pa.visitButton;return jsxs(Fragment,{children:[jsx(Pressable,{onPress:i(()=>{if(!(m||w.current)){if(!E){let A={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...y!=null?{visitRef:y,intent:g??null}:{}};Rr(A,h)===null&&W(s,"unavailable",null);return}w.current=true,(y==null?P.open():P.openVisit(y,g??null)).then(A=>{A.opened?W(o,A.flowId??null):A.reason!=="cancelled"&&W(s,A.reason,A.error);}).finally(()=>{w.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:R,accessibilityState:{busy:m,disabled:m},style:[S.button,m?S.busy:null,a],children:jsx(b,{style:[S.label,l],children:R})}),jsx(xt,{})]})}i(ct,"VetVisitButton");function Wf(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:Fa,minWidth:Fa,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...oe(s.vetVisitButton)},busy:{opacity:jf},label:{...v(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...me(s.vetVisitButton)}})}i(Wf,"makeStyles");function Gn(e){return rr(e)==="cat"?"cat":"dog"}i(Gn,"speciesOf");function qn(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(qn,"petAgeYears");function Na(e){let t=qn(e.ageYears),r=Gn(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(Na,"formatPetMeta");var Va=Object.freeze([Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),Object.freeze({background:"#fbc558",foreground:"#10462e"}),Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function Gf(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Va[t%Va.length]}i(Gf,"pickInitialsPalette");function Kn(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(Kn,"getInitial");function Da(e){return {...Gf(e.petRef),initial:Kn(e.name)}}i(Da,"petInitials");function $f(e){return Math.max(12,Math.round(e*.42))}i($f,"letterSize");function kt({pet:e,size:t,ringStroke:r}){let n=F(),o=useMemo(()=>Xf(n),[n]),s=t-r*2,a=e===null?null:Da(e),l=$f(s);return jsx(yr,{size:t,strokeWidth:r,color:n.color.success,children:jsx(View,{style:[o.disc,{width:s,height:s,borderRadius:s/2},a===null?o.discEmpty:{backgroundColor:a.background}],children:jsx(b,{tier:"badge",style:[o.letter,{fontSize:l,lineHeight:Math.round(l*1.2),color:a===null?n.color.text.muted:a.foreground}],children:a===null?Kn(null):a.initial})})})}i(kt,"PetDisc");function Xf(e){return StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...v(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(Xf,"makeStyles");var $n=48,Ua=2,ry=320,ny="80%",oy="rgba(17,17,17,0.45)",iy=18,Ha=22,sy=12,za=.4,ay=44;function Xn(e){return e?.name?.trim()||f.yourPet}i(Xn,"petDisplayName");function Ba({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=F(),l=useMemo(()=>ly(a),[a]);return e?jsx(Modal,{visible:true,transparent:true,animationType:a.motion.reducedMotion?"none":"fade",onRequestClose:s,children:jsxs(View,{style:l.root,children:[jsx(Pressable,{style:ye,onPress:s,accessibilityRole:"button",accessibilityLabel:f.close,children:jsx(View,{style:l.backdrop})}),jsxs(View,{style:l.panel,accessibilityViewIsModal:true,children:[jsx(b,{tier:"heading",style:l.title,accessibilityRole:"header",children:f.yourPets}),jsx(ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(d=>{let u=d.petRef===r,c=Xn(d),p=Na(d);return jsxs(H,{accessibilityRole:"button",accessibilityLabel:B(u?f.petCurrentlyActive:f.switchToPet,{name:c}),accessibilityState:{selected:u},style:[l.row,u?l.rowActive:null],onPress:()=>n(d.petRef),children:[jsx(kt,{pet:d,size:$n,ringStroke:Ua}),jsxs(View,{style:l.copy,children:[jsx(b,{style:l.name,numberOfLines:1,children:c}),jsx(b,{tier:"compact",style:l.meta,numberOfLines:1,children:u?`${f.activePrefix}${p}`:p})]}),u?jsx(He,{size:iy,color:a.color.brandInk}):null]},d.petRef)})}),o!==null?jsxs(H,{accessibilityRole:"button",accessibilityLabel:f.addAnotherPet,style:l.addRow,onPress:o,children:[jsx(View,{style:l.addDisc,children:jsx(b,{tier:"control",style:l.addPlus,children:"+"})}),jsx(b,{style:l.addLabel,children:f.addAnotherPet})]}):null,jsx(H,{accessibilityRole:"button",accessibilityLabel:f.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsx(b,{tier:"control",style:l.closeText,children:f.close})})]})]})}):null}i(Ba,"PetSwitcherSheet");function ly(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:oy},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Ha,borderTopRightRadius:Ha,gap:14,maxHeight:ny},title:{...v(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:ry,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:ay,paddingHorizontal:8},addDisc:{width:$n,height:$n,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Ua,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...v(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...v(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary},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:{...v(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...v(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:za},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:sy,backgroundColor:t.brandSoft},closeText:{...v(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:za}})}i(ly,"makeStyles");var cy=44,xr=36,py=22,Qn=9,fy=1.5,Wa=6,Xe=35,wr=1.75,Zn=12.4,yy=.5,my=8,gy=28,hy=160;function eo(e,t){return ca(e,t)}i(eo,"headerPet");function qa({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=F(),d=useMemo(()=>vy(l),[l]),[u,c]=useState(false),p=eo(e.pets,t),y=e.pets.length>=2,g=t??p?.petRef??null,h=Xn(p),k=i(P=>{c(false),e.setActivePet(P),W(o,P);},"select"),E=s===void 0?null:()=>{c(false),W(s);};return jsxs(View,{style:d.row,children:[jsxs(H,{accessibilityRole:"button",accessibilityLabel:r?`${f.openHistoryNative}${f.newReplySuffix}`:f.openHistoryNative,containerStyle:d.iconSlot,style:d.iconButton,onPress:n,children:[jsx(Es,{size:py,color:l.color.text.primary,strokeWidth:2}),r?jsx(View,{style:d.unreadDot,pointerEvents:"none"}):null]}),jsx(View,{style:d.center,pointerEvents:"box-none",children:jsx(by,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:d})}),g===null?null:jsx(ct,{entry:"chat",petRef:g,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:d.vetEntry,labelStyle:d.vetEntryLabel}),jsx(View,{style:d.right,children:y?jsxs(H,{accessibilityRole:"button",accessibilityLabel:B(f.switchActivePet,{name:h}),containerStyle:d.avatarSlot,style:d.avatarWrap,onPress:()=>c(true),children:[jsx(kt,{pet:p,size:Xe,ringStroke:wr}),jsx(View,{style:d.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(pr,{size:my,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:d.avatarWrap,accessible:true,accessibilityLabel:f.yourPet,children:jsx(yr,{size:Xe,strokeWidth:wr,color:l.color.success,children:jsx(View,{style:d.placeholderDisc})})}):jsx(View,{style:d.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?f.yourPet:h,children:jsx(kt,{pet:p,size:Xe,ringStroke:wr})})}),jsx(Ba,{visible:u,pets:e.pets,activePetRef:p?.petRef??null,onSelect:k,onAddPet:E,onClose:()=>c(false)})]})}i(qa,"ChatHeader");function by({logoUrl:e,name:t,styles:r}){let[n,o]=useState(null);return e===null||n===e?null:jsx(View,{style:r.logoBar,children:jsx(Image,{source:{uri:e},style:r.logo,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:()=>o(e)})})}i(by,"BrandLogo");function vy(e){let t=e.color,r=Xe-wr*2;return StyleSheet.create({vetEntry:{minHeight:cy,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...v(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:16,paddingVertical:10,backgroundColor:t.surface},iconSlot:{borderRadius:xr/2},iconButton:{width:xr,height:xr,borderRadius:xr/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Wa,right:Wa,width:Qn,height:Qn,borderRadius:Qn,backgroundColor:t.danger,borderWidth:fy,borderColor:t.surface},center:{...ye,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:gy,width:hy},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Xe/2},avatarWrap:{width:Xe,height:Xe,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Zn,height:Zn,borderRadius:Zn/2,borderWidth:yy,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(vy,"makeStyles");var $a=44,Ty="rgba(17,17,17,0.55)",Xa=26,Py=36,Qa=4,to=20,ro=38,xy=18,wy=12;function Za({visible:e,onSubmit:t,onSkip:r}){let n=F(),o=useMemo(()=>ky(n),[n]),[s,a]=useState(null),[l,d]=useState(""),[u,c]=useState(false),[p,y]=useState(false),g=i(()=>{a(null),d(""),c(false),y(false);},"reset"),h=i(()=>{u||(g(),r());},"skip"),k=i(async()=>{if(u)return;c(true),y(false);let P=l.trim();await t(s,P.length>0?P:null)?g():(c(false),y(true));},"submit");if(!e)return null;let E=[...l].length>Zt;return jsx(Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:h,children:jsxs(KeyboardAvoidingView,{behavior:Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsx(Pressable,{style:o.scrim,onPress:h,accessibilityRole:"button",accessibilityLabel:f.feedbackSkipA11y}),jsxs(View,{style:o.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[jsx(View,{style:o.handle}),jsxs(View,{style:o.header,children:[jsx(View,{style:o.iconBadge,children:jsx(fr,{size:xy,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxs(View,{style:o.headerText,children:[jsx(b,{tier:"heading",style:o.title,accessibilityRole:"header",children:f.feedbackTitle}),jsx(b,{style:o.subtitle,children:f.feedbackSubtitle})]})]}),jsx(View,{style:o.options,children:qr.map(P=>{let T=s===P.key;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:P.label,accessibilityState:{selected:T},style:[o.option,T?o.optionSelected:null],onPress:()=>a(S=>S===P.key?null:P.key),children:[jsx(b,{style:[o.optionLabel,T?o.optionLabelSelected:null],children:P.label}),jsx(View,{style:[o.radio,T?o.radioSelected:null],children:T?jsx(He,{size:wy,color:n.color.surface,strokeWidth:2}):null})]},P.key)})}),jsxs(View,{style:o.inputWrap,children:[jsx(ot,{style:o.input,placeholder:f.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:f.feedbackNotesPlaceholder,value:l,onChangeText:d,multiline:true,editable:!u}),l.length>0?jsx(b,{tier:"compact",style:[o.counter,E?o.counterOver:null],children:`${[...l].length}/${Zt}`}):null]}),p?jsx(b,{style:o.failed,accessibilityRole:"alert",children:f.feedbackFailed}):null,jsxs(View,{style:o.actions,children:[jsx(H,{accessibilityRole:"button",accessibilityLabel:f.feedbackSubmit,accessibilityState:{busy:u,disabled:u||E},disabled:u||E,style:[o.submit,u||E?o.submitDisabled:null],onPress:()=>{k();},children:jsx(b,{tier:"control",style:o.submitLabel,children:f.feedbackSubmit})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f.feedbackSkipA11y,hitSlop:8,onPress:h,style:o.skip,children:jsx(b,{tier:"control",style:o.skipLabel,children:f.feedbackSkip})})]})]})]})})}i(Za,"FeedbackReasons");function ky(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ye,backgroundColor:Ty},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Xa,borderTopRightRadius:Xa,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:Py,height:Qa,borderRadius:Qa/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:ro,height:ro,borderRadius:ro/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...v(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...v(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,backgroundColor:t.surface},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...v(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:to,height:to,borderRadius:to/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,...v(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...v(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...v(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:$a,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...oe(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...v(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...me(o.primaryButton)},skip:{minHeight:$a,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...v(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(ky,"makeStyles");var Uy=.88,By=420,jy=58,Wy="rgba(17,17,17,0.28)",Gy=.15,qy=14,Ky=12,no=44,Yy=16,$y=14,Xy=12,Qy=14,oo=8,Be=2,Zy=.5,Jy=St(at.standard);function em(e){return Math.min(Math.round(e*Uy),By)}i(em,"drawerPanelWidth");function el({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(tm,{chat:e,history:t,onHidden:o}):null}i(el,"HistoryDrawer");function tm({chat:e,history:t,onHidden:r}){let n=F(),o=useMemo(()=>nm(n),[n]),s=K(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),d=em(l),u=t.open,c=useRef(null);c.current===null&&(c.current=new Animated.Value(s.drawerMs<=0&&u?1:0));let p=c.current;useEffect(()=>{if(!u&&s.drawerMs<=0){r();return}let T=Animated.timing(p,{toValue:u?1:0,duration:s.drawerMs,easing:Jy,useNativeDriver:true});return T.start(({finished:S})=>{S&&!u&&r();}),()=>T.stop()},[u,p,s.drawerMs,r]);let y=p.interpolate({inputRange:[0,1],outputRange:[-d,0]}),g=t.filtered,h=t.rows.length===0,k=t.cursor===null&&!t.loading&&t.error===null,E=h&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:j.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:o.emptyTitle.color}),jsx(b,{style:o.emptyBody,children:j.loading})]}):h&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(b,{style:o.emptyTitle,accessibilityRole:"alert",children:j.loadFailed}),jsx(b,{style:o.emptyBody,children:t.error}),jsx(H,{accessibilityRole:"button",accessibilityLabel:j.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(b,{tier:"control",style:o.retryText,children:j.retry})})]}):t.emptyKind==="empty"?jsxs(View,{style:o.emptyCard,children:[jsx(b,{style:o.emptyTitle,children:j.empty}),jsx(b,{style:o.emptyBody,children:j.emptyBody})]}):jsx(b,{style:o.noMatch,children:j.noMatch}),P=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(b,{style:o.loadMoreLabel,children:j.loadingMore})}):null;return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxs(View,{style:o.root,children:[jsx(Pressable,{style:ye,onPress:t.close,accessibilityRole:"button",accessibilityLabel:j.closeA11y,children:jsx(Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsx(Animated.View,{style:[o.panel,{width:d,paddingTop:Math.max(jy,a.top+n.space.md),transform:[{translateX:y}]}],accessibilityViewIsModal:true,children:jsxs(KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:Platform.OS==="ios"?"padding":"height",children:[jsxs(View,{style:o.header,children:[jsx(b,{tier:"heading",style:o.heading,accessibilityRole:"header",children:j.heading}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:j.newChat,style:o.newChat,onPress:t.newConversation,children:jsx(b,{tier:"control",style:o.newChatLabel,children:j.newChat})}),jsx(H,{accessibilityRole:"button",accessibilityLabel:j.close,hitSlop:0,style:o.closeButton,onPress:t.close,children:jsx(ke,{size:Yy,color:n.color.text.muted,strokeWidth:1.75})})]}),jsxs(View,{style:o.searchPill,children:[jsx(As,{size:Qy,color:n.color.text.muted,strokeWidth:1.5}),jsx(ot,{value:t.query,onChangeText:T=>t.setQuery(T.replace(/^\s+/,"")),style:o.searchInput,placeholder:j.searchPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:j.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsx(b,{tier:"compact",style:o.countLabel,children:ts(t.rows.length,k)}),t.error!==null&&!h?jsx(View,{style:o.errorCard,children:jsx(b,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsx(FlatList,{data:g,keyExtractor:T=>T.id,renderItem:({item:T})=>jsx(rm,{row:T,active:T.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(T.id);}}),contentContainerStyle:g.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:E,ListFooterComponent:P,onEndReached:t.loadMore,onEndReachedThreshold:Zy})]})})]})})}i(tm,"DrawerModal");function rm({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0,a=es(e);return jsxs(H,{accessibilityRole:"button",accessibilityLabel:rs(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:o,children:[jsxs(View,{style:n.itemRow,children:[jsx(b,{tier:"control",style:n.itemTitle,numberOfLines:1,children:dr(e.title)}),s?jsx(View,{style:n.unreadDot}):null]}),a!==null?jsx(b,{tier:"compact",style:n.itemMeta,numberOfLines:1,children:a}):null]})}i(rm,"Row");function nm(e){let t=e.color,r=e.space,n=e.type,o=e.slots,s=t.text.primary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:Wy},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:r.lg,borderRightWidth:StyleSheet.hairlineWidth,borderRightColor:t.borderRingCream,gap:r.md},keyboardAvoider:{flex:1,gap:r.md},header:{flexDirection:"row",alignItems:"center",gap:r.sm},heading:{...v(e,"bold"),flex:1,fontSize:n.size.subtitle,color:s},newChat:{minHeight:no,justifyContent:"center",paddingHorizontal:r.xs},newChatLabel:{...v(e,"bold"),fontSize:qy,color:t.brandInk},closeButton:{width:no,height:no,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:r.md+Be,paddingVertical:r.sm+Be,borderWidth:1,borderColor:t.borderRingCream},searchInput:{...v(e,"regular"),flex:1,fontSize:n.size.bodyTight,color:t.text.primary,padding:0},countLabel:{...v(e,"mono"),fontSize:Ky,color:t.text.muted},list:{gap:r.xs,paddingBottom:r.xl},listEmpty:{flexGrow:1},item:{paddingVertical:r.sm+Be,paddingHorizontal:r.sm,borderRadius:e.radius.md,gap:Be},itemActive:{backgroundColor:Ue(t.scanButtonPink,Gy)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:r.sm},itemTitle:{...v(e,"bold"),flex:1,fontSize:n.size.bodyTight,color:s},itemMeta:{...v(e,"regular"),fontSize:n.size.caption,color:t.text.muted},unreadDot:{width:oo,height:oo,borderRadius:oo/2,backgroundColor:t.danger},errorCard:{borderRadius:Xy,borderWidth:StyleSheet.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:r.md},errorText:{...v(e,"regular"),fontSize:n.size.caption,color:t.danger},emptyCard:{borderRadius:$y,padding:r.md+Be,gap:r.xs+Be,backgroundColor:t.surfaceSubtle,borderWidth:StyleSheet.hairlineWidth,borderColor:t.borderRingCream},emptyTitle:{...v(e,"bold"),fontSize:n.size.bodyTight,color:s},emptyBody:{...v(e,"regular"),fontSize:n.size.caption,color:t.text.secondary},noMatch:{...v(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+Be,paddingVertical:r.sm,borderWidth:1,borderColor:t.brandInk,...oe(o.primaryButton)},retryText:{...v(e,"bold"),fontSize:n.size.caption,color:t.brandInk,...me(o.primaryButton)},loadMoreFooter:{paddingVertical:r.md+Be,alignItems:"center"},loadMoreLabel:{...v(e,"regular"),fontSize:n.size.caption,color:t.text.muted}})}i(nm,"makeStyles");var dm=Object.freeze({}),um=100,cm=20;function pm(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)}}i(pm,"readWindowTops");function tl(e,t){let r=typeof e=="number"&&Number.isFinite(e),n=useRef(null),[o,s]=useState(null),a=useRef(null),l=useRef(null),d=useRef(true),u=useCallback(()=>{l.current!==null&&clearTimeout(l.current),l.current=null;},[]);useEffect(()=>(d.current=true,()=>{d.current=false,u();}),[u]);let c=useCallback(i(function y(g){n.current?.measureInWindow((h,k)=>{let E=a.current;if(!d.current||E===null)return;let P=pm(k,E.y,E.height,Dimensions.get("window").height);if(P!==null){s(T=>T!==null&&T.chatTop===P.chatTop&&T.parentTop===P.parentTop?T:P);return}g>=cm||(l.current=setTimeout(()=>{l.current=null,y(g+1);},um));});},"measureAt"),[]),p=useCallback(y=>{let{y:g,height:h}=y.nativeEvent.layout;a.current={y:g,height:h},u(),c(0);},[c,u]);return useMemo(()=>{if(!t)return {avoidingProps:r?{keyboardVerticalOffset:e}:dm,probeRef:null,topInWindow:null};let y=o?.parentTop??0;return {avoidingProps:r?{keyboardVerticalOffset:e,onLayout:p}:y>0?{keyboardVerticalOffset:y,onLayout:p}:{onLayout:p},probeRef:n,topInWindow:o?.chatTop??null}},[t,r,e,o,p])}i(tl,"useChatKeyboardOffset");function rl({probeRef:e}){return e===null?null:jsx(View,{ref:e,collapsable:false,pointerEvents:"none",style:fm})}i(rl,"KeyboardOffsetProbe");var fm=Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function nl(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}i(nl,"chatVetVisitOptions");var bm=.75,vm=1.5,Cm=.4,Em=4,Rm=1.5,At=22,Sm=14,Tm=8,Pm=20,xm=10,il=13,wm=12,km=15,_m=44,Im=14,Am=1.25,Om=14,Fm=6;function Mm(e,t){let r=e.color;return t.level==="emergency"?{card:{backgroundColor:r.badgeBgCritical,borderColor:Ue(r.danger,Cm)??r.danger,borderWidth:vm},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}}:{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:bm},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}i(Mm,"tierPaint");function sl({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=F(),a=useMemo(()=>Dm(s),[s]),l=K(),d=e.tier,u=e.source;return jsxs(Fragment,{children:[jsx(Tn,{visible:e.showBanner&&d!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:d!==null&&u!==null?jsx(Lm,{tier:d,reason:u.reason,surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o,styles:a}):null}),jsx(Tn,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:f.showLatestVetAlert,hitSlop:xm,onPress:e.expand,children:jsx(ws,{size:Pm,color:s.color.text.muted,strokeWidth:2})})})]})}i(sl,"UrgencyBanner");function Lm({tier:e,reason:t,surface:r,petRef:n,renderVetAction:o,onFindVet:s,vet:a,styles:l}){let d=F(),u=Mm(d,e),c=jsx(Nm,{tier:e,paint:u,petRef:n,onFindVet:s,vet:a,styles:l}),p=r.showVetAction?o!==void 0?jsx(Ke,{render:()=>o(e.level),fallback:c,resetKey:e.level}):c:null,y=u.action!==null?jsx(Vm,{paint:u.action,styles:l}):null;return jsxs(View,{accessibilityRole:"alert",style:[l.card,u.card],children:[jsx(b,{tier:"control",style:[l.label,{color:u.label}],children:e.label}),t!==null?jsx(b,{style:[l.reason,{color:u.reason}],children:t}):null,p!==null||y!==null?jsxs(View,{style:l.actions,children:[p,y]}):null,r.dismissLabel!==null?jsx(H,{accessibilityRole:"button",accessibilityLabel:r.dismissLabel,hitSlop:Tm,containerStyle:l.closeSlot,style:l.closeButton,onPress:r.dismiss,children:jsx(ke,{size:Sm,color:u.close,strokeWidth:1.5})}):null]})}i(Lm,"BannerCard");function Vm({paint:e,styles:t}){let r=i(()=>{try{Linking.openURL(Io).catch(()=>{});}catch{}},"call");return jsx(H,{accessibilityRole:"button",accessibilityLabel:f.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:r,children:jsx(b,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:f.poisonControlNative})})}i(Vm,"PoisonControl");function Nm({tier:e,paint:t,petRef:r,onFindVet:n,vet:o,styles:s}){let a=F(),l=Tr(nl(r,o)),d=l.status==="opening",u=!l.available&&n!==void 0,c=l.available?()=>{l.open();}:n!==void 0?()=>{W(n,e.level);}:null;if(c===null)return null;let p=t.action;if(p!==null){let g=u?f.nearestEmergencyVet:f.findVet,h=Cr(a.slots.vetVisitButton)?.textColor??p.ink;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:u?f.nearestEmergencyVet:f.findVetA11y,accessibilityState:{busy:d},hitSlop:0,style:[s.action,{backgroundColor:p.fill,borderColor:p.edge},s.findVetSlotBox,d?s.findVetBusy:null],onPress:c,children:[jsx(Cn,{size:il,color:h,strokeWidth:1.5}),jsx(b,{tier:"control",style:[s.actionLabel,{color:h}],children:g})]})}let y=Cr(a.slots.vetVisitButton)?.textColor??e.textColor;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:f.findVetA11y,accessibilityState:{busy:d},style:[s.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},s.findVetSlotBox,d?s.findVetBusy:null],onPress:c,children:[jsx(Cn,{size:il,color:y,strokeWidth:1.5}),jsx(b,{tier:"control",style:[s.findVetLabel,{color:y}],children:f.findVet})]})}i(Nm,"VetAction");function Dm(e){let t=Cr(e.slots.vetVisitButton),r=e.space,n=e.type;return StyleSheet.create({pinned:{marginTop:0,marginBottom:r.xs,paddingHorizontal:r.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:r.lg+Em,paddingVertical:r.lg,gap:r.sm},label:{...v(e,"bold"),fontSize:n.size.body,paddingRight:At},reason:{...v(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*Rm),paddingRight:At},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm},action:{flexDirection:"row",alignItems:"center",gap:Fm,minHeight:_m,paddingHorizontal:Im,borderRadius:e.radius.pill,borderWidth:Am},actionLabel:{...v(e,"bold"),fontSize:Om},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...oe(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...v(e,"monoBold"),fontSize:wm,lineHeight:km},closeSlot:{position:"absolute",top:r.md,right:r.md},closeButton:{width:At,height:At,borderRadius:At/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:r.lg,paddingTop:2,paddingBottom:r.xs}})}i(Dm,"makeStyles");function al(){let e=Nn(),{handle:t}=ae(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(al,"useChatPets");function jm(){try{let e=AccessibilityInfo?.announceForAccessibility;typeof e=="function"&&e.call(AccessibilityInfo,f.answered);}catch{}}i(jm,"announceAnswered");function ul(e){let t=useRef(false),r=useRef({send:e.send,id:e.conversationId});useEffect(()=>{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 o=e.messages[e.messages.length-1];o!==void 0&&o.role==="assistant"&&jm();}t.current=e.isStreaming;},[e.isStreaming,e.messages,e.send,e.conversationId]);}i(ul,"useSettleAnnouncement");var bl=300,vl=3e3,pl=120,Mt=44,Gm=120,qm="88%",fl=520,Or=2,Fr=.5,Km=1.5,Ym=1.6,$m=.6,Xm=56,yl=1.5,Qm=5,Zm=5,ml=36,Jm=20,eg=14,Ft=Mt,Mr=4,Cl=24,El=22,tg=.4,gl=Mt,Rl=20,rg=.4,ng=480,og=12,ig=.72,sg=48,hl=1,ag=12,lg=18,dg="12%";function ie(){let e=F(),t=useMemo(()=>ug(e),[e]);return {theme:e,styles:t}}i(ie,"useChatTheme");function ug(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=Math.round(o.size.body*Km),a=Math.round(o.size.body*Ym),l=Math.round(Jm*o.size.body/eg),d=t.borderRingCream,u=e.slots;return StyleSheet.create({container:{flex:1,minHeight:pl,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:pl,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:dg,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:ng,gap:r.lg},errorText:{...v(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Mt,minWidth:Mt,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...oe(u.primaryButton)},retryLabel:{...v(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...me(u.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...v(e,"regular"),color:t.danger,fontSize:o.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.lg,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...v(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...v(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:Mt,justifyContent:"center"},turnNoticeActionLabel:{...v(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...v(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...v(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingLine:{...v(e,"regular"),color:t.text.muted,fontSize:o.size.bodyTight,lineHeight:Math.round(o.size.bodyTight*o.lineHeight.relaxed)},list:{flex:1},listContent:{padding:r.lg,gap:r.xl},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:qm,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:fl,paddingVertical:r.md,paddingHorizontal:r.lg+Or,backgroundColor:t.bubbleUser,borderRadius:n.lg,borderBottomRightRadius:n.xs,...oe(u.userBubble,Fr)},bubbleAssistant:u.assistantBubble?.backgroundColor===void 0?{...oe(u.assistantBubble,Fr)}:{paddingVertical:r.md,paddingHorizontal:r.lg+Or,borderRadius:n.lg,...oe(u.assistantBubble,Fr)},bubbleVet:{maxWidth:fl,paddingVertical:r.md,paddingHorizontal:r.lg+Or,backgroundColor:t.bubbleVet,borderRadius:n.lg,borderTopLeftRadius:n.xs,...oe(u.vetBubble,Fr)},bubblePending:{opacity:$m},bubbleTextUser:{...v(e,"regular"),color:t.onPrimary,fontSize:o.size.body,lineHeight:s,...me(u.userBubble)},bubbleTextAssistant:{...v(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:a,...me(u.assistantBubble)},bubbleTextVet:{...v(e,"regular"),color:t.onBubbleVet,fontSize:o.size.body,lineHeight:s,...me(u.vetBubble)},assistantName:{...v(e,"bold"),color:t.brandInk,fontSize:o.size.bodyTight,marginBottom:r.xs},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:r.sm,marginBottom:r.xs},vetSender:{...v(e,"bold"),color:t.text.primary,fontSize:o.size.bodyTight},vetTime:{...v(e,"regular"),color:t.text.muted,fontSize:o.size.caption},bubbleBold:v(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:v(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.md},followUpsHeading:{...v(e,"monoBold"),color:t.text.muted,fontSize:og,textTransform:"uppercase",letterSpacing:ig,paddingBottom:r.sm,borderBottomWidth:hl,borderBottomColor:d},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:hl,borderTopColor:d},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,minHeight:sg,paddingVertical:r.sm+Or},followUpText:{...v(e,"bold"),flex:1,color:t.brandInk,fontSize:o.size.bodyTight},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,minHeight:Xm,justifyContent:"center",paddingLeft:r.sm,paddingRight:Qm,paddingVertical:Zm,backgroundColor:t.composerFill,borderWidth:yl,borderColor:t.composerBorder,borderRadius:n.pill,...oe(u.composerInput,yl)},composerRow:{flexDirection:"row",alignItems:"center",gap:r.xs,minHeight:ml},attachControl:{width:gl,height:gl,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:rg},input:{flex:1,minHeight:ml,maxHeight:Gm,paddingHorizontal:0,paddingVertical:0,...v(e,"regular"),fontSize:o.size.body,lineHeight:l,color:t.text.primary,...me(u.composerInput)},sendControl:{minHeight:Ft,minWidth:Ft,alignItems:"center",justifyContent:"center"},sendDisc:{width:Ft,height:Ft,borderRadius:Ft/2,alignItems:"center",justifyContent:"center",...oe(u.sendButton)},sendControlDisabled:{opacity:tg},footnote:{...v(e,"regular"),color:t.text.muted,fontSize:ag,lineHeight:lg,textAlign:"center",marginTop:r.sm,marginBottom:r.xs,paddingHorizontal:r.lg},poweredBy:{...v(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(ug,"makeStyles");var cg=Object.freeze({kind:"live"}),pg=Object.freeze({kind:"folded"});function so(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=ri(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(so,"askOf");function Tl(e){let t=new Map,r=new Map;for(let o of e){let s=so(o);if(s===null)continue;let a=r.get(s.caseId);(a===void 0||s.dueDay>=a.dueDay)&&r.set(s.caseId,{messageId:o.id,dueDay:s.dueDay});}if(r.size===0)return t;let n=null;for(let o of e){let s=so(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,cg),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,pg);continue}let a=[s.dueDay];n={id:o.id,caseId:s.caseId,days:a},t.set(o.id,{kind:"past",runDueDays:a});}return t}i(Tl,"placeCheckins");var Sl=864e5,fg=365;function Lr(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 o=Math.floor(n/Sl)-Math.floor(r/Sl);return o<1||o>fg?null:o}i(Lr,"checkinDayNumber");function Pl(e){return so(e)?.dueDay||null}i(Pl,"checkinDueDay");function Vr(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(Vr,"formatMessageTime");var ge=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" \xB7 ",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),xl=Object.freeze(Qo.map(e=>Object.freeze({answer:e,label:ge.answers[e]})));function wl(e,t){let[r,n]=useState(null),[o,s]=useState(null),[a,l]=useState(null),d=useCallback(c=>{t!==null&&(n(c),s(null),t(e.caseId,c).then(p=>{n(null),p.ok?l(c):s(p.error);}));},[t,e.caseId]),u=a??e.answer;return {answer:u,answerable:!ti(e),escalated:u==="worse",pending:r,error:o,choose:d}}i(wl,"useCheckinCard");var Il=44,gg=.6;function Ol({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s,onLayout:a}){let l=F(),d=useMemo(()=>hg(l),[l]),u=wl(t,r),c=u.answer!==null||u.pending!==null,p=r!==null&&u.answerable,y=Lr(t.openedAt,Pl(e));return jsxs(View,{style:d.card,accessibilityLabel:ge.eyebrow,onLayout:a,children:[jsxs(View,{style:d.head,children:[jsx(b,{tier:"compact",style:d.eyebrow,children:ge.eyebrow}),y!==null?jsx(b,{tier:"compact",style:d.headDay,children:B(ge.day,{day:y})}):null]}),jsx(b,{style:d.question,accessibilityRole:"text",children:e.text}),p?jsx(View,{style:[d.row,u.pending?d.rowPending:null],children:xl.map(({answer:g,label:h})=>{let k=(u.pending??u.answer)===g;return jsx(Pressable,{onPress:()=>u.choose(g),disabled:c,accessibilityRole:"button",accessibilityLabel:h,accessibilityState:{selected:k,disabled:c,busy:u.pending===g},style:[d.pill,k?d.pillSelected:null],children:jsx(b,{tier:"control",style:[d.pillLabel,k?d.pillLabelSelected:null],children:h})},g)})}):null,u.answer!==null?jsx(b,{style:d.logged,children:ge.logged}):null,u.escalated?o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:ge.findVet,style:d.findVet,children:jsx(b,{tier:"control",style:d.findVetLabel,children:ge.findVet})}):n?jsx(ct,{entry:"chat",petRef:n,label:ge.findVet,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:d.findVet,labelStyle:d.findVetLabel}):null:null,t.resolutionText?jsx(b,{style:d.resolution,children:t.resolutionText}):null,u.error?jsx(b,{style:d.error,accessibilityRole:"alert",children:u.error.displayMessage}):null]})}i(Ol,"CheckinCard");function hg(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return StyleSheet.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...v(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...v(e,"bold"),color:t.text.primary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...v(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:gg},pill:{flex:1,minHeight:Il,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...v(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...v(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...v(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...v(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:Il,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...v(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(hg,"makeStyles");var Cg=1.5,Eg=3;function Ml({text:e,runDueDays:t,openedAt:r,onLayout:n}){let o=F(),s=useMemo(()=>Rg(o),[o]),a=t.map(d=>Lr(r,d)).filter(d=>d!==null),l=t.length>1;return l&&a.length===0?null:jsxs(View,{style:s.row,onLayout:n,children:[jsx(View,{style:s.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),jsxs(View,{style:s.body,children:[a.length>0?jsx(b,{tier:"compact",style:s.days,children:a.map(d=>B(ge.day,{day:d})).join(ge.daySeparator)}):null,l?null:jsx(b,{style:s.question,accessibilityRole:"text",children:e})]})]})}i(Ml,"CheckinPastAsk");function Rg(e){let t=e.color,r=e.space,n=e.type;return StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:Cg,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:Eg},days:{...v(e,"monoMedium"),fontSize:n.size.nano,letterSpacing:n.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},question:{...v(e,"regular"),fontSize:n.size.bodyTight,lineHeight:n.size.bodyTight*n.lineHeight.normal,color:t.text.muted}})}i(Rg,"makeStyles");var Sg=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),Ll="#C8BEB4";function Tg(e){return e?Sg[e.toUpperCase()]??Ll:Ll}i(Tg,"tierColor");function Pg(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(Pg,"tierLabel");function we(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(we,"text");function xg(e){let t=we(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(xg,"httpsUrl");function wg(e,t){let r=we(e.source_name)??we(e.sourceName),n=we(e.section),o=we(e.authority_tier)??we(e.authorityTier),s=Pg(o),a=r??we(e.title)??`Source ${t+1}`,l=we(e.monograph_chunk_id)??we(e.chunkId),d=[n,s].filter(u=>u!==null).join(" \xB7 ");return Object.freeze({title:a,sourceName:r,section:n,authorityTier:o,tierLabel:s,meta:d.length===0?null:d,url:xg(e.url),excerpt:we(e.excerpt),tierColor:Tg(o),key:`${a}-${l??"none"}-${t}`})}i(wg,"toCitationCard");function Vl(e){return e===void 0||e.length===0?kg:Object.freeze(e.map((t,r)=>wg(t,r)))}i(Vl,"toCitationCards");var kg=Object.freeze([]);function po(e){return e===1?`1 ${f.sourceSingular}`:`${e} ${f.sourcePlural}`}i(po,"sourcesLabel");function Nl(e,t){return `${t?f.hideSources:f.showSources} ${po(e)}`}i(Nl,"sourcesToggleLabel");function Dl(e){return [e.url!==null?`${f.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(Dl,"citationA11yLabel");var Fg=244,zl=8,Ul=13,Mg=14,Lg=.3,Vg=-0.24,Ng=22,Dg=10,Hg=15;function Bl({citations:e,onOpenUrl:t}){let r=F(),n=useMemo(()=>Bg(r),[r]),o=useMemo(()=>Vl(e),[e]),[s,a]=useState(false);if(o.length===0)return null;let l=o.length;return jsxs(View,{style:n.block,children:[jsxs(H,{accessibilityRole:"button",accessibilityLabel:Nl(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(d=>!d),children:[jsx(Ts,{size:Ul,color:r.color.brandInk,strokeWidth:1.5}),jsx(b,{tier:"compact",style:n.toggleLabel,children:po(l)}),jsx(Ss,{size:Ul,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsx(zg,{cards:o,styles:n,open:t}):null]})}i(Bl,"CitationCards");function zg({cards:e,styles:t,open:r}){let n=K(),o=lt(n.citationsInMs,{risePx:n.citationsRisePx});return jsx(Animated.View,{style:o,children:jsx(ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsx(Ug,{card:s,styles:t,open:r},s.key))})})}i(zg,"Deck");function Ug({card:e,styles:t,open:r}){let n=F(),o=e.url!==null&&r!==void 0,s=Dl(o?e:{...e,url:null}),a=jsxs(Fragment,{children:[jsxs(View,{style:t.cardHeader,children:[jsx(View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsx(b,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsx(Ps,{size:Mg,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsx(b,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsx(b,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let l=e.url;return jsx(H,{accessibilityRole:"link",accessibilityLabel:s,style:t.card,onPress:()=>r(l),children:a})}return jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}i(Ug,"Card");function Bg(e){let t=e.color,r=e.space,n=e.radius,o=e.type.size;return StyleSheet.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:{...v(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:Lg,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:Fg,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:zl,height:zl,borderRadius:n.pill},cardTitle:{...v(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:Ng,color:t.text.primary,letterSpacing:Vg},cardTitleLink:{color:t.linkInk},cardMeta:{...v(e,"monoMedium"),fontSize:o.nano,lineHeight:Dg,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...v(e,"regular"),fontSize:o.tiny,lineHeight:Hg,color:t.text.muted}})}i(Bg,"makeStyles");var Lt=15,Yg=15,$g=6,Xg=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function Kl({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=F(),a=useMemo(()=>Qg(s),[s]),l=K(),d=e.role==="user",u=useMemo(()=>Vr(e.createdAt),[e.createdAt]),c=t!==void 0&&e.role!=="vet"&&e.text.length>0,p=e.role==="assistant"&&n!==void 0&&e.responseId!==void 0,[y,g]=useState(false),h=useRef(null);useEffect(()=>()=>{h.current&&clearTimeout(h.current);},[]);let k=i(()=>{t!==void 0&&(st(t,e.text),g(true),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{g(false),h.current=null;},l.copiedMs));},"copy");return u===null&&!c&&!p?null:jsxs(View,{style:a.wrap,children:[jsxs(View,{style:[a.row,d?a.rowUser:a.rowAssistant],children:[u!==null?jsx(b,{tier:"compact",style:a.timestamp,children:u}):null,c?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:y?f.copied:d?f.copyUserMessage:f.copyAssistantMessage,hitSlop:Yg,onPress:k,style:a.iconHit,children:y?jsx(He,{size:Lt,color:s.color.success,strokeWidth:2}):jsx(xs,{size:Lt,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?Ao.map(({sentiment:E,label:P})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:P,accessibilityState:{selected:r===E},hitSlop:$g,onPress:()=>n?.(E),style:a.iconHit,children:jsx(fr,{size:Lt,color:s.color.sentiment[E],active:r===E,rotate:Xg[E],strokeWidth:1.5})},E)):null]}),o?jsx(b,{style:a.thanks,accessibilityLiveRegion:"polite",children:f.feedbackThanks}):null]})}i(Kl,"MessageFooter");function Qg(e){let t=e.type;return StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...v(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:Lt,height:Lt,alignItems:"center",justifyContent:"center"},thanks:{...v(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(Qg,"makeStyles");var Yl="#10462E";var $l="#000000",Zg="#83E0B4",Jg=Object.freeze([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}),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:Zg,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:Yl,brandEdge:true,borderWidth:1}),Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}\u2019s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]),eh=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function th(e){return e==null?e:e.replace(eh,"").trim()}i(th,"formatBreedForPrompt");var rh=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 nh(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return rh.has(t)}i(nh,"isUninformativeBreed");function oh(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(oh,"unspecifiedBreedLabel");function ih(e,t){return nh(e)?oh(t):String(e).replace(/\s+/gu," ").trim()}i(ih,"resolveBreedLabel");function Xl(e){let t=e?.name?.trim()||f.emptyTitlePetFallback;return B(f.emptyTitle,{petName:t})}i(Xl,"emptyStateTitle");function Ql(e,t=Yl){let r=Gn(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=ih(th(e?.breed),r)||null,l=qn(e?.ageYears),d=l===null?null:String(l);return Object.freeze(Jg.map(u=>{let c=u.label.includes("{breed}"),p=u.label.includes("{ageYears}"),g=u.fallbackLabel!==void 0&&(c&&!a||p&&!d)&&u.fallbackLabel?u.fallbackLabel:u.label,h=B(g,{petName:s,breed:a??n,species:r,ageYears:d??""}),k=!o&&g.startsWith("{petName}")?h.charAt(0).toUpperCase()+h.slice(1):h;return Object.freeze({id:u.id,intent:u.intent,label:k,background:u.background,borderColor:u.brandEdge===true?t:u.borderColor,borderWidth:u.borderWidth})}))}i(Ql,"resolveQuickPrompts");var ah=44,ed=0,lh=1,dh=.28,uh=2,ch=2,ph=1.3,fh=-0.015;function td({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=F(),a=useMemo(()=>mh(s),[s]),l=useMemo(()=>Ql(e,s.color.brandInk),[e,s.color.brandInk]),d=Xl(e);return jsxs(View,{style:a.block,children:[jsx(b,{tier:"heading",style:a.title,accessibilityRole:"header",children:d}),jsx(View,{style:a.list,accessibilityLabel:f.suggestions,children:l.map((u,c)=>jsx(yh,{prompt:u,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},u.id))})]})}i(td,"QuickPrompts");function yh({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let d=K(),u=lt(d.followUpInMs,{delayMs:mr(d,t),risePx:d.promptRisePx}),c={backgroundColor:e.background};return e.intent==="vet_report"?s!==void 0?jsx(Animated.View,{style:u,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:ed,style:[l.chip,l.chipEdge,c],onPress:()=>{W(s,r);},children:jsx(b,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsx(Animated.View,{style:u,children:jsx(ct,{entry:"chat",petRef:n,label:e.label,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:[l.chip,l.chipEdge,c],labelStyle:l.chipLabel})}):jsx(Animated.View,{style:u,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:ed,style:[l.chip,l.chipEdge,c],onPress:()=>o(e.label),children:jsx(b,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(yh,"Chip");function mh(e){let t=e.color,r=e.space,n=e.type;return StyleSheet.create({block:{gap:r.lg,alignItems:"stretch",width:"100%"},title:{...v(e,"medium"),fontSize:n.size.heading,lineHeight:Math.round(n.size.heading*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.size.heading*fh,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:r.sm+uh},chip:{borderRadius:e.radius.pill,paddingHorizontal:r.lg+ch,paddingVertical:r.sm,minHeight:ah,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:lh,borderColor:Ue(t.brandInk,dh)??t.borderRingCream},chipLabel:{...v(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*ph),color:$l,textAlign:"left"}})}i(mh,"makeStyles");var yo=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function rd(e){return e.includes("*")||e.includes("`")}i(rd,"hasInlineMarkup");function nd(e){let t=[],r=0;yo.lastIndex=0;for(let n=yo.exec(e);n!==null;n=yo.exec(e)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});let o=n[1],s=n[2],a=n[3];o!==void 0?t.push({kind:"bold",text:o}):s!==void 0?t.push({kind:"italic",text:s}):a!==void 0&&t.push({kind:"code",text:a}),r=n.index+n[0].length;}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}i(nd,"tokenizeInlineMarkdown");function od(e,t){return rd(e)?nd(e).map((r,n)=>{switch(r.kind){case "bold":return jsx(b,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx(b,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx(b,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(od,"renderInlineMarkdown");function id({petName:e=null}){let{styles:t}=ie(),r=Wt(f.reading,e);return jsx(b,{tier:"compact",style:t.readingLine,accessibilityRole:"text",accessibilityLabel:r,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:r})}i(id,"TypingIndicator");function sd(e,t,r){let n=e-r,o=t!=null?Math.min(n,t):n;return Math.max(0,o)}i(sd,"resolveTurnScrollTarget");function ad(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}}i(ad,"latestTurn");function ld(e,t,r){let n=Math.max(0,r),o=e===null?n:Math.min(Math.max(0,e),n);return o>t+1?o:null}i(ld,"nextFollowOffset");function dd(e,t){let r=useRef(null),n=useRef(true),o=useRef(t),s=useRef(0),a=useRef(0),l=useRef(0),d=useRef(new Map),u=ad(e),c=u===null?null:e[u.assistantIndex]?.id??null,p=u===null||u.userIndex===null?null:e[u.userIndex]?.id??null,y=useCallback(()=>{let S=r.current;if(S===null||!n.current||a.current===0)return;let w=null;if(c!==null){let R=d.current.get(c);if(R===void 0)return;let _=p===null?null:d.current.get(p)??null;w=sd(R,_,96);}let m=ld(w,s.current,l.current-a.current);m!==null&&(s.current=m,S.scrollTo({y:m,animated:false}));},[c,p]);useEffect(()=>{t&&!o.current&&(n.current=true),o.current=t,y();},[e,t,y]);let g=useCallback(S=>{a.current=S.nativeEvent.layout.height,y();},[y]),h=useCallback((S,w)=>{l.current=w,a.current>0&&(s.current=Math.min(s.current,Math.max(0,w-a.current))),y();},[y]),k=useCallback(S=>{s.current=S.nativeEvent.contentOffset.y;},[]),E=useCallback(()=>{n.current=false;},[]),P=useCallback(S=>{let{contentOffset:w,contentSize:m,layoutMeasurement:R}=S.nativeEvent;s.current=w.y,n.current=m.height-w.y-R.height<=24;},[]),T=useCallback(S=>w=>{d.current.set(S,w.nativeEvent.layout.y),(S===c||S===p)&&y();},[c,p,y]);return {ref:r,onLayout:g,onContentSizeChange:h,onScroll:k,onScrollBeginDrag:E,onScrollEnd:P,rowLayout:T}}i(dd,"useThreadFollow");function yd(e,t,r){switch(e){case "loading":return r.renderPending?jsx(Ke,{render:r.renderPending,fallback:jsx(cd,{})}):jsx(cd,{});case "empty":return jsx(Ph,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(kh,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx(_h,{messages:t.messages,prompts:cs(t),onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,thanksFor:r.thanksFor,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});default:return $t(e)}}i(yd,"renderView");function cd(){let{theme:e,styles:t}=ie(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),bl);return ()=>clearTimeout(o)},[]),jsx(View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:f.loading,children:r?jsx(ActivityIndicator,{color:e.color.brandInk}):null})}i(cd,"LoadingState");function Ph({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:o}){let{styles:s}=ie();return jsx(ScrollView,{contentContainerStyle:s.emptyContent,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,accessibilityLabel:f.empty,children:jsx(td,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o})})}i(Ph,"EmptyState");function xh({prompts:e,onSelectPrompt:t}){let{styles:r}=ie();return e.length===0?null:jsxs(View,{style:r.followUps,children:[jsx(b,{tier:"compact",style:r.followUpsHeading,accessibilityRole:"header",children:f.followUpsHeadingNative}),e.map((n,o)=>jsx(wh,{prompt:n,index:o,onSelectPrompt:t},n))]})}i(xh,"FollowUps");function wh({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=ie(),s=K(),a=lt(s.followUpInMs,{delayMs:mr(s,t)});return jsx(Animated.View,{style:a,children:jsxs(H,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[o.followUpSlot,t>0?o.followUpSlotRuled:null],style:o.followUpRow,children:[jsx(b,{tier:"control",style:o.followUpText,children:e}),jsx(pr,{size:Fh,color:n.color.text.muted,strokeWidth:1.75})]})})}i(wh,"FollowUpRow");function kh({error:e,onRetry:t,onAddPet:r}){let{styles:n}=ie(),o=Vi(e)?Wi(r):void 0;return jsxs(View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsx(b,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:f.addPet,style:n.retryButton,children:jsx(b,{tier:"control",style:n.retryLabel,children:f.addPet})}):null,e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:f.retry,style:n.retryButton,children:jsx(b,{tier:"control",style:n.retryLabel,children:f.retry})}):null]})}i(kh,"ErrorState");function _h({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:o,onCopy:s,sentimentByMessage:a,onSentiment:l,thanksFor:d,imagesByMessage:u,onPreview:c,notice:p,reconnecting:y,onRetry:g,onStartNew:h,petRef:k,onFindVet:E,vet:P,onOpenUrl:T,petName:S}){let{styles:w}=ie(),m=K();Tt(e.length,m);let R=useMemo(()=>Tl(e),[e]),_=us(e,n),A=e[e.length-1],O=useMemo(()=>e.filter(x=>!(x.checkin&&R.get(x.id)?.kind==="folded")),[e,R]),C=dd(O,n),M=js(O);return jsxs(ScrollView,{ref:C.ref,style:w.list,contentContainerStyle:w.listContent,accessibilityLabel:f.transcript,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,onLayout:C.onLayout,onContentSizeChange:C.onContentSizeChange,onScroll:C.onScroll,scrollEventThrottle:Oh,onScrollBeginDrag:C.onScrollBeginDrag,onScrollEndDrag:C.onScrollEnd,onMomentumScrollEnd:C.onScrollEnd,children:[e.map(x=>{let N=x.checkin?R.get(x.id):void 0;return N?.kind==="folded"?null:N?.kind==="past"?jsx(Ml,{text:x.text,runDueDays:N.runDueDays,openedAt:x.checkin?.openedAt,onLayout:C.rowLayout(x.id)},x.id):x.checkin&&N!==void 0?jsx(Ol,{message:x,checkin:x.checkin,onAnswer:o,petRef:k,onFindVet:E,vet:P,onLayout:C.rowLayout(x.id)},x.id):jsx(Mh,{onLayout:C.rowLayout(x.id),message:x,revealing:n&&x===A&&x.role==="assistant",onCopy:s,sentiment:x.responseId===void 0?null:a[String(x.responseId)]??null,onSentiment:l,thanks:d!==null&&x.responseId!==void 0&&String(x.responseId)===d,images:u[x.id]??Ah,onPreview:c,onOpenUrl:T,entering:M(x.id)},x.id)}),y?jsx(b,{tier:"compact",style:w.reconnectingCaption,accessibilityRole:"text",children:f.reconnecting}):null,_?jsx(id,{petName:S}):null,p!==null?jsx(Ih,{notice:p,onRetry:g,onStartNew:h}):null,jsx(xh,{prompts:t,onSelectPrompt:r})]})}i(_h,"PopulatedState");function Ih({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=ie(),o=e.tone==="error";return jsxs(View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsx(b,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsx(b,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsx(Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Mr,style:n.turnNoticeAction,children:jsx(b,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(Ih,"TurnNoticeCard");var Ah=Object.freeze([]),Oh=16,Fh=18;function Mh({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l,onOpenUrl:d,onLayout:u,entering:c}){let{theme:p,styles:y}=ie(),g=K(),h=Bs(c,g),k=Ws(e.text,t,g),E=e.role==="user",P=e.role==="vet",T=e.role==="assistant",S=T&&!p.meta.hidePoweredBy,w=E?f.senderUser:P?ps(e):S?f.assistantName:f.senderAssistant,m=P?Vr(e.createdAt):null,R=useCallback(A=>o(e,A),[o,e]),_=e.pending!==true;return jsxs(View,{style:[y.rowBlock,E?y.rowBlockUser:y.rowBlockAssistant],onLayout:u,children:[jsx(View,{style:[y.row,E?y.rowUser:y.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${w}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxs(Animated.View,{style:[y.bubble,E?y.bubbleSideUser:null,h],children:[S?jsx(b,{tier:"control",style:y.assistantName,children:f.assistantName}):null,P?jsxs(View,{style:y.vetHeader,children:[jsx(b,{tier:"control",style:y.vetSender,children:w}),m!==null?jsx(b,{tier:"compact",style:y.vetTime,children:m}):null]}):null,jsxs(View,{style:[E?y.bubbleUser:P?y.bubbleVet:y.bubbleAssistant,e.pending?y.bubblePending:null],children:[E&&a.length>0?jsx(la,{images:a,onPreview:A=>l({uri:A.uri,label:A.filename})}):null,jsx(b,{style:E?y.bubbleTextUser:P?y.bubbleTextVet:y.bubbleTextAssistant,children:T?od(k,{bold:y.bubbleBold,italic:y.bubbleItalic,code:y.bubbleCode}):e.text})]})]})}),T&&!t?jsx(Bl,{citations:e.citations,onOpenUrl:d}):null,_?jsx(Kl,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:R,thanks:s}):null]})}i(Mh,"MessageRow");var Hh=Object.freeze(["photo"]),zh=1;function Uh(e){let{style:t,renderPending:r}=e;return jsx(vs,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(Bh,{...e})})}i(Uh,"EverfurChat");function Bh({petRef:e,conversationId:t,style:r,renderPending:n,onCopy:o,onPetChange:s,onVetPrep:a,onFindVet:l,renderVetAction:d,attachments:u,pet:c,onAddPet:p,checkinTarget:y,initialAsk:g,composerSeed:h,lifecycle:k,draftStore:E,vetReturnTo:P,vetUsState:T,vetPrefer:S,onOpenUrl:w,keyboardVerticalOffset:m}){let{theme:R,styles:_}=ie(),A=K(),O=useMemo(()=>fs(e,t),[e,t]),C=Gt(O),M=ls(C),x=al(),N=ns(C),q=useSafeAreaInsets(),X=ds(C),G=useMemo(()=>l===void 0?void 0:()=>{W(l,"emergency");},[l]),be=useMemo(()=>P===void 0&&T===void 0&&S===void 0?void 0:{returnTo:P,usState:T,prefer:S},[P,T,S]),Ve=eo(x.pets,C.petRef),se=useMemo(()=>ss(C.messages,Ve?.name??null),[C.messages,Ve?.name]),Ne=as(se);ul(C),Tt(Ne.showBanner,A),Yi(C.openCheckin,y),Ui(C.askEverfur,C.isBootstrapping,g);let Dt=useMemo(()=>un(h),[h]);qi(k,{conversationId:C.conversationId===null?null:String(C.conversationId),isTurnInFlight:C.isStreaming,refresh:C.refreshActiveThread});let Ht=(C.hasUnreadThreads??false)||N.rows.some(pe=>pe.unreadCount!==null&&pe.unreadCount>0)||(C.unreadCount??0)>0,rt=Hi(C.messages),[pt,zr]=useState(null),hd=useCallback(()=>zr(null),[]),[ft,Ur]=useState(null),[bd,ho]=useState(null),nt=useRef(null);useEffect(()=>()=>{nt.current&&clearTimeout(nt.current);},[]);let bo=useCallback(pe=>{ho(String(pe)),nt.current&&clearTimeout(nt.current),nt.current=setTimeout(()=>{ho(null),nt.current=null;},vl);},[]),vd=useCallback((pe,Ut)=>{let yt=pe.responseId;if(yt===void 0)return;let Pd=C.sentimentByMessage[String(yt)];C.feedback(yt,Ut),Ut==="down"&&Pd!=="down"&&Ur(yt);},[C]),Cd=useCallback(async(pe,Ut)=>ft===null||!(await C.feedback(ft,"down",pe??"other",Ut)).ok?false:(Ur(null),bo(ft),true),[C,ft,bo]),Ed=useCallback(()=>Ur(null),[]),Rd=useCallback(pe=>{C.send(pe);},[C.send]),Sd=useMemo(()=>w===void 0?void 0:pe=>{W(w,pe,"citation");},[w]),vo=Platform.OS==="ios"?"padding":void 0,zt=tl(m,vo!==void 0),Td=zt.topInWindow===null?q.top:Math.max(0,q.top-zt.topInWindow),Co={send:C.send,stop:C.stop,isStreaming:C.isStreaming,conversationId:C.conversationId,seed:Dt,draftStore:E,onStage:rt.stage,onPreview:zr,petName:Ve?.name??null};return jsxs(KeyboardAvoidingView,{style:[_.container,{paddingTop:Td},r],behavior:vo,...zt.avoidingProps,children:[jsx(rl,{probeRef:zt.probeRef}),jsx(qa,{pets:x,petRef:C.petRef,historyUnread:Ht,onOpenHistory:N.show,onPetChange:s,onAddPet:p,vet:be}),c!==void 0?jsx(jh,{petRef:e??null,pet:c,onRegistered:x.refresh}):null,jsx(sl,{surface:Ne,petRef:C.petRef,renderVetAction:d,onFindVet:l,vet:be}),jsx(View,{style:_.body,children:yd(M,C,{notice:X,vet:be,onCheckinFindVet:G,onSelectPrompt:Rd,renderPending:n,shownPet:Ve,onVetPrep:a,onCopy:o,onSentiment:vd,thanksFor:bd,imagesByMessage:rt.byMessage,onPreview:zr,onAddPet:p,onOpenUrl:Sd})}),u!==void 0?jsx(Wh,{...Co,attachments:u}):jsx(gd,{...Co,attachments:null}),jsx(b,{tier:"compact",style:_.footnote,accessibilityRole:"text",children:f.footnoteNative}),R.meta.hidePoweredBy?null:jsx(b,{tier:"compact",style:_.poweredBy,accessibilityRole:"text",accessibilityLabel:f.poweredBy,children:f.poweredBy}),jsx(el,{chat:C,history:N}),jsx(Za,{visible:ft!==null,onSubmit:Cd,onSkip:Ed}),jsx(Gs,{uri:pt?.uri??null,label:pt?.label??"",onClose:hd}),jsx(xt,{})]})}i(Bh,"ChatBody");function jh({petRef:e,pet:t,onRegistered:r}){let{styles:n}=ie(),o=Ni(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs(View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsx(b,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsx(Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:f.retry,hitSlop:Mr,children:jsx(b,{tier:"control",style:n.setupNoticeAction,children:f.retry})})]})}i(jh,"PetSetupNotice");function Wh({attachments:e,...t}){let r=useMemo(()=>Ln(),[]),n=rn({maxPerMessage:e.maxPerMessage??zh,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??Hh,pick:e.pick}),[n,e.sources,e.pick]);return jsx(gd,{...t,attachments:o})}i(Wh,"ComposerWithAttachments");function gd({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:d,petName:u}){let{theme:c,styles:p}=ie(),y=K(),[g,h]=Qi(e,n,s);Zi(a,n===null?null:String(n),g,h);let[k,E]=useState(false),[P,T]=useState(false);useEffect(()=>{T(false);},[n]);let S=c.meta.placeholder??Wt(f.placeholder,u),w=o?.state.uploading??false,m=o?.state.failed??false,R=w||m,_=o?.state.attachments??Gh;Tt(_.length,y);let A=useCallback(()=>{if(g.trim().length===0||R||[...g].length>Jt)return;let X=o?.state.s3Keys??qh;o!==null&&X.length>0?(l(o.state.attachments.filter(G=>G.status==="uploaded").map(G=>({uri:G.previewUri,filename:G.filename}))),e(g,{imageS3Keys:X}),o.state.clear()):e(g),h(""),T(false);},[g,e,R,o,l]),O=useCallback(()=>{t();},[t]),C=useCallback(X=>{E(false),o!==null&&(T(false),o.state.dismissRejected(),st(o.pick,X).then(G=>{if(!G.ok){T(true);return}G.value!==null&&o.state.add(G.value);}));},[o]),x=useMemo(()=>[...g].length>Jt,[g])||R,N=o!==null&&_.length>=o.state.maxPerMessage,q=c.slots.sendButton?.textColor??c.color.brandInk;return jsxs(View,{style:p.composerOuter,children:[o!==null&&k?jsx(Ys,{sources:o.sources,full:N,onPick:C,onClose:()=>E(false)}):null,jsxs(View,{style:p.composer,children:[o!==null?jsx(aa,{attachments:_,rejected:P?Kh:o.state.rejected,uploadFailed:m,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:X=>d({uri:X.previewUri,label:X.filename})}):null,jsxs(View,{style:p.composerRow,children:[o!==null?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:N?di(_.length,o.state.maxPerMessage):f.attachPhotoOrFileNative,accessibilityState:{disabled:N,expanded:k},disabled:N,style:[p.attachControl,N?p.attachControlDisabled:null],onPress:()=>E(X=>!X),children:jsx(ks,{size:Rl,color:N?c.color.text.muted:c.color.brandInk,strokeWidth:1.75})}):null,jsx(ot,{style:p.input,value:g,onChangeText:h,placeholder:S,placeholderTextColor:c.slots.composerInput?.textColor??c.color.text.placeholder,accessibilityLabel:f.composerLabel,onSubmitEditing:A,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsx(Pressable,{onPress:O,accessibilityRole:"button",accessibilityLabel:f.stop,style:p.sendControl,children:jsx(View,{style:p.sendDisc,testID:"everfur-stop-disc",children:jsx(Fs,{size:El,color:q,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:A,disabled:x,accessibilityRole:"button",accessibilityLabel:f.send,accessibilityState:{disabled:x,busy:w},style:[p.sendControl,x?p.sendControlDisabled:null],children:jsx(View,{style:p.sendDisc,testID:"everfur-send-disc",children:jsx(Os,{size:Cl,color:q,testID:"everfur-send-glyph"})})})]})]})]})}i(gd,"Composer");var Gh=Object.freeze([]),qh=Object.freeze([]),Kh=Object.freeze({code:"unknown",retryable:true,filename:""});export{Uh as EverfurChat,Ln as createRnChatAttachmentTransport,rn as useChatAttachments,Gt as useEverfurChat,Nn as useEverfurPets};
|
|
1
|
+
import{createContext,forwardRef,createElement,useMemo,useState,useRef,useEffect,useCallback,useSyncExternalStore,useContext,Component}from"react";import{TextInput as TextInput$1,StyleSheet,Platform,KeyboardAvoidingView,View,Pressable,Dimensions,Keyboard,Text as Text$1,Modal,Image,AccessibilityInfo,UIManager,LayoutAnimation,Animated,ScrollView,ActivityIndicator,useWindowDimensions,FlatList,Linking}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx,jsxs,Fragment}from"react/jsx-runtime";var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
2
|
+
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
3
|
+
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
4
|
+
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
5
|
+
/* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
6
|
+
/* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
7
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
8
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
9
|
+
/* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
10
|
+
/* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
|
|
11
|
+
/* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
|
|
12
|
+
/* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
|
|
13
|
+
/* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
14
|
+
/* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
15
|
+
/* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
16
|
+
/* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
17
|
+
/* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
18
|
+
/* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
19
|
+
/* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
20
|
+
/* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
21
|
+
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
22
|
+
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
23
|
+
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
24
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
25
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
26
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
27
|
+
/* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
28
|
+
/* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
29
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
30
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
31
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
32
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
33
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
34
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
35
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
36
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
37
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
38
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
39
|
+
/* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
40
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
41
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
|
|
42
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
43
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
44
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
45
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
46
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
47
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
48
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
49
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
50
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
51
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
52
|
+
/* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
53
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
54
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
55
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
56
|
+
/* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
|
|
57
|
+
/* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
58
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
59
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
60
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
61
|
+
/* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
62
|
+
/* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
63
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
64
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
65
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
66
|
+
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
67
|
+
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
68
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
69
|
+
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
70
|
+
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
72
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
73
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
74
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
75
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
76
|
+
/* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
77
|
+
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
78
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
79
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
80
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
81
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
82
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
84
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
85
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
86
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
87
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
88
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
89
|
+
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
90
|
+
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
|
|
91
|
+
/* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
92
|
+
/* @__PURE__ */Object.freeze({key:"outdated",label:CHAT_COPY.feedbackReasonOutdated,feedbackType:"outdated"}),
|
|
93
|
+
/* @__PURE__ */Object.freeze({key:"unsafe",label:CHAT_COPY.feedbackReasonUnsafe,feedbackType:"dangerous"}),
|
|
94
|
+
/* @__PURE__ */Object.freeze({key:"unclear",label:CHAT_COPY.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
95
|
+
/* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
|
|
96
|
+
/* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
|
|
97
|
+
/* @__PURE__ */Object.freeze({sentiment:"neutral",label:CHAT_COPY.feedbackNeutral}),
|
|
98
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef=opts?.petRef??activePet??null,conversationId=opts?.conversationId??null,scope=useMemo(()=>({runtime:runtime,userRef:userRef,petRef:petRef,conversationId:conversationId,scopeEpoch:scopeEpoch}),[runtime,userRef,petRef,conversationId,scopeEpoch]),[binding,setBinding]=useState(null),controller=binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef,petRef:petRef,conversationId:conversationId}),active=useRef(null);useEffect(()=>{let acquired=runtime.registry.acquireChat({userRef:userRef,petRef:petRef,conversationId:conversationId});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef,petRef,conversationId,scopeEpoch,scope]);let subscribe=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot=useSyncExternalStore(subscribe,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef?{petRef:petRef}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef]);return useMemo(()=>({status:snapshot.status,messages:snapshot.messages,conversationId:snapshot.conversationId,petRef:petRef,error:snapshot.error,isStreaming:snapshot.isStreaming,isBootstrapping:snapshot.isBootstrapping,historyCursor:snapshot.historyCursor??null,isLoadingHistory:snapshot.isLoadingHistory??false,stopped:snapshot.stopped??false,reconnecting:snapshot.reconnecting??false,...history,suggestedPrompts:snapshot.suggestedPrompts,unreadCount:snapshot.unreadCount,hasUnreadThreads:snapshot.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot,petRef,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot=controller.getSnapshot();return snapshot.status==="error"&&snapshot.error!==null?err(snapshot.error):ok(lastAssistantResponseId(snapshot.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return err(makeEverfurError("internalError",{retryable:true}))}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
99
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
100
|
+
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
|
|
101
|
+
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var CHECKIN_ANSWERS=/* @__PURE__ */Object.freeze(["better","same","worse"]),CASE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}var FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var MAX_ATTACHMENT_BYTES=10*1024*1024,MAX_ATTACHMENTS_PER_MESSAGE=5,MAX_FILENAME_LENGTH=120,ATTACHMENT_INITIATE_PATH="/widget/v1/uploads/initiate";function isAttachmentMime(mime){return typeof mime=="string"&&ATTACHMENT_MIME_TYPES.includes(mime.trim().toLowerCase())}function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
|
|
102
|
+
return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str3=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str3(o.upload_id),uploadUrl=str3(o.upload_url),s3Key=str3(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
|
|
103
|
+
return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str3(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight2=/* @__PURE__ */new Set,listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed=false,publish2=()=>{snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners2)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed&&inFlight2.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight2.add(id),run(row).finally(()=>{inFlight2.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot:()=>snapshot,get uploading(){return snapshot.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners2.clear(),snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef,scopeEpoch,maxPerMessage,options.transport]),scoped=useMemo(()=>options.queue??build(),[options.queue,build]),disposed=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;useEffect(()=>{if(queue!==options.queue){if(disposed.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot.attachments.some(row=>row.status==="uploading"),failed=snapshot.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str(o.ref),name:name,dose:str(o.dose),frequency:str(o.frequency),startDate:str(o.start_date),endDate:str(o.end_date),notes:str(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
104
|
+
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str(o.food_brand),foodType:str(o.food_type),microchipId:str(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),conditionName:conditionName,diagnosedDate:str(row.diagnosed_date),notes:str(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid("pet_ref must be a string");if(petRef.trim().length===0)return invalid("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str2=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
|
|
105
|
+
return Object.freeze({petRef:str2(o.pet_ref)??petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str2(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str2(o.pet_id),petRef:petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str2(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
|
|
106
|
+
return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid3=validate(petRef,profile);if(invalid3!==null)return err(invalid3);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function petRegistrationKey(runtime,auth,petRef,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef,pet,onRegistered){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),register=useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef,scopeEpoch]),bodyKey=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef===null||bodyKey===null?null:`${String(userRef)}|${scopeEpoch}|${petRef}|${bodyKey}`,run=useCallback(()=>{if(petRef===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef,scopeKey]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var NONE=/* @__PURE__ */Object.freeze({});function useSentImages(messages){let[byMessage,setByMessage]=useState(NONE),pending=useRef(null),knownIds=useRef([]);knownIds.current=messages.map(message=>message.id),useEffect(()=>{if(messages.length===0){pending.current=null,setByMessage(current=>current===NONE?current:NONE);return}let staged=pending.current;if(staged===null)return;let bubble=messages.find(message=>message.role==="user"&&!staged.known.has(message.id));bubble!==void 0&&(pending.current=null,setByMessage(current=>({...current,[bubble.id]:staged.images})))},[messages]);let stage=useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt){let clean=sanitizeSeedPrompt(prompt),latest=useRef(askEverfur);latest.current=askEverfur;let asked=useRef(null);useEffect(()=>{if(clean===null||isBootstrapping||asked.current===clean)return;let ask=latest.current;ask!==void 0&&(asked.current=clean,Promise.resolve(ask(clean)).catch(()=>{}))},[clean,isBootstrapping])}function isCoalesced(trigger,conversationId,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId=state.activeConversationId;return conversationId===null||conversationId.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),isOffline=lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,isOffline:isOffline,lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId=target.conversationId??"",petRef=target.petRef??"";return conversationId===""&&petRef===""?null:`${String(conversationId)}|${String(petRef)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}function useChatDraft(send,conversationId,seed){let[state,setState]=useState({send:send,conversationId:conversationId,text:seed??"",seeded:seed??null}),belongs=state.send===send&&(state.conversationId===null||state.conversationId===conversationId);useEffect(()=>{setState(previous=>{let kept=previous.send===send&&(previous.conversationId===null||previous.conversationId===conversationId),text3=kept?previous.text:"",seeded=kept?previous.seeded:null,fresh2=seed!=null&&seed!==seeded&&text3.length===0;return{send:send,conversationId:conversationId,text:fresh2?seed:text3,seeded:fresh2?seed:seeded}})},[send,conversationId,seed]);let setDraft=useCallback(text3=>setState(previous=>({send:send,conversationId:conversationId,text:text3,seeded:previous.seeded})),[send,conversationId]);return[belongs?state.text:"",setDraft]}function usePersistedDraft(store,conversationId,draft,setDraft){let latest=useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=useRef(null),[settled,setSettled]=useState(null);useEffect(()=>{if(store===void 0)return;let key=`${conversationId??""}`;if(asked.current===key)return;asked.current=key;let live=true;return(async()=>{let outcome=await callHostAsync(()=>store.read(conversationId));if(!live)return;let stored2=outcome.ok&&typeof outcome.value=="string"?outcome.value:"";stored2.length>0&&latest.current.draft.length===0&&latest.current.setDraft(stored2),setSettled(key)})(),()=>{live=false}},[store,conversationId]),useEffect(()=>{store===void 0||settled!==`${conversationId??""}`||callHost(()=>store.write(conversationId,draft))},[store,conversationId,draft,settled])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=useCallback(async cursor=>{let request=++generation.current,more=cursor!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor?{cursor:cursor}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:petName?.trim()||CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason(petName)}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=useState(null),[expanded,setExpanded]=useState(false);useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
|
|
107
|
+
return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef,conversationId){let opts={};return petRef!==void 0&&(opts.petRef=petRef),conversationId!==void 0&&(opts.conversationId=conversationId),opts}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}var REQUIRES=/* @__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"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
108
|
+
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
109
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView2(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=useMemo(()=>selectView2(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
110
|
+
return jsx(View,{style:[styles2.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsx(View,{style:styles2.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
111
|
+
return jsx(View,{style:[styles2.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsx(Text,{style:styles2.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
|
|
112
|
+
return jsxs(View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
|
|
113
|
+
/* @__PURE__ */jsx(View,{style:bar}),
|
|
114
|
+
/* @__PURE__ */jsx(View,{style:bar}),
|
|
115
|
+
/* @__PURE__ */jsx(View,{style:bar})]})}function Cross({size:size,color:color,strokeWidth:strokeWidth,rotate:rotate}){let w=stroke(size,strokeWidth),length=size*.78;/* @__PURE__ */
|
|
116
|
+
return jsxs(View,{style:[box(size),{transform:[{rotate:rotate}]}],...HIDDEN,children:[
|
|
117
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",width:length,height:w,borderRadius:w,backgroundColor:color}}),
|
|
118
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",width:w,height:length,borderRadius:w,backgroundColor:color}})]})}function PlusGlyph(props){/* @__PURE__ */
|
|
119
|
+
return jsx(Cross,{...props,rotate:"0deg"})}function CloseGlyph(props){/* @__PURE__ */
|
|
120
|
+
return jsx(Cross,{...props,rotate:"45deg"})}function CheckGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
121
|
+
return jsx(View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:size*.36,height:size*.66,marginTop:-size*.14,borderBottomWidth:w,borderRightWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})})}var CHEVRON_POSE={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:size,color:color,strokeWidth:strokeWidth,direction:direction}){let w=stroke(size,strokeWidth),side=size*.46,pose=CHEVRON_POSE[direction];/* @__PURE__ */
|
|
122
|
+
return jsx(View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:side,height:side,borderRightWidth:w,borderBottomWidth:w,borderColor:color,marginTop:side*pose.marginTop,marginLeft:side*pose.marginLeft,transform:[{rotate:pose.rotate}]}})})}function BookGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),page={width:size*.42,height:size*.7,borderWidth:w,borderColor:color,borderRadius:w};/* @__PURE__ */
|
|
123
|
+
return jsxs(View,{style:[box(size),{flexDirection:"row",gap:1}],...HIDDEN,children:[
|
|
124
|
+
/* @__PURE__ */jsx(View,{style:[page,{borderTopLeftRadius:size*.2}]}),
|
|
125
|
+
/* @__PURE__ */jsx(View,{style:[page,{borderTopRightRadius:size*.2}]})]})}function ArrowUpRightGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),head=size*.5;/* @__PURE__ */
|
|
126
|
+
return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
127
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",width:size*.78,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"-45deg"}]}}),
|
|
128
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.16,right:size*.16,width:head,height:head,borderTopWidth:w,borderRightWidth:w,borderColor:color}})]})}function CopyGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),side=size*.6,square={position:"absolute",width:side,height:side,borderWidth:w,borderColor:color,borderRadius:size*.14};/* @__PURE__ */
|
|
129
|
+
return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
130
|
+
/* @__PURE__ */jsx(View,{style:[square,{top:0,left:0}]}),
|
|
131
|
+
/* @__PURE__ */jsx(View,{style:[square,{bottom:0,right:0}]})]})}function ThumbGlyph({size:size,color:color,strokeWidth:strokeWidth,active:active,rotate:rotate}){let w=stroke(size,strokeWidth),fill=active?color:"transparent";/* @__PURE__ */
|
|
132
|
+
return jsxs(View,{style:[box(size),{transform:[{rotate:rotate}]}],...HIDDEN,children:[
|
|
133
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",bottom:size*.08,left:size*.12,width:size*.62,height:size*.5,borderWidth:w,borderColor:color,backgroundColor:fill,borderRadius:size*.12,borderTopLeftRadius:size*.04}}),
|
|
134
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.04,left:size*.4,width:size*.3,height:size*.5,borderWidth:w,borderColor:color,backgroundColor:fill,borderRadius:size*.15,transform:[{rotate:"-20deg"}]}}),
|
|
135
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",bottom:size*.08,left:0,width:size*.2,height:size*.5,borderWidth:w,borderColor:color,backgroundColor:fill,borderRadius:size*.05}})]})}function InfoGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
136
|
+
return jsxs(View,{style:[box(size),{borderRadius:size/2,borderWidth:w,borderColor:color}],...HIDDEN,children:[
|
|
137
|
+
/* @__PURE__ */jsx(View,{style:{width:w,height:w,borderRadius:w,backgroundColor:color,marginBottom:size*.1}}),
|
|
138
|
+
/* @__PURE__ */jsx(View,{style:{width:w,height:size*.34,borderRadius:w,backgroundColor:color}})]})}function UploadGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),head=size*.34;/* @__PURE__ */
|
|
139
|
+
return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
140
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.06,width:head,height:head,borderTopWidth:w,borderLeftWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}}),
|
|
141
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.1,width:w,height:size*.56,borderRadius:w,backgroundColor:color}}),
|
|
142
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",bottom:0,width:size*.84,height:size*.3,borderBottomWidth:w,borderLeftWidth:w,borderRightWidth:w,borderColor:color,borderBottomLeftRadius:w,borderBottomRightRadius:w}})]})}function PhotoGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
143
|
+
return jsxs(View,{style:[box(size),{borderWidth:w,borderColor:color,borderRadius:size*.14,overflow:"hidden"}],...HIDDEN,children:[
|
|
144
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.16,left:size*.18,width:size*.16,height:size*.16,borderRadius:size,backgroundColor:color}}),
|
|
145
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",bottom:-size*.3,right:-size*.1,width:size*.7,height:size*.7,borderTopWidth:w,borderLeftWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
146
|
+
return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
147
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.08,width:size*.34,height:size*.2,borderTopWidth:w,borderLeftWidth:w,borderRightWidth:w,borderColor:color,borderTopLeftRadius:w,borderTopRightRadius:w}}),
|
|
148
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.22,width:size*.92,height:size*.66,borderWidth:w,borderColor:color,borderRadius:size*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsx(View,{style:{width:size*.3,height:size*.3,borderRadius:size,borderWidth:w,borderColor:color}})})]})}function SearchGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),unit=size/24,outer=16*unit+w,ringAt=11*unit-outer/2,start=11+8/Math.SQRT2,length=(21-start)*Math.SQRT2*unit,middle=(start+21)/2*unit;/* @__PURE__ */
|
|
149
|
+
return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
150
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:ringAt,left:ringAt,width:outer,height:outer,borderRadius:outer,borderWidth:w,borderColor:color}}),
|
|
151
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:middle-w/2,left:middle-(length+w)/2,width:length+w,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"45deg"}]}})]})}function MapPinGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),ring=size*.62;/* @__PURE__ */
|
|
152
|
+
return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
153
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:0,width:ring,height:ring,borderRadius:ring,borderWidth:w,borderColor:color,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsx(View,{style:{width:w*1.4,height:w*1.4,borderRadius:w,backgroundColor:color}})}),
|
|
154
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",bottom:size*.04,width:ring*.5,height:ring*.5,borderRightWidth:w,borderBottomWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:size,color:color,testID:testID}){let half=size*.36;/* @__PURE__ */
|
|
155
|
+
return jsx(View,{style:box(size),testID:testID,...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:0,height:0,marginLeft:size*.12,borderLeftWidth:size*.78,borderTopWidth:half,borderBottomWidth:half,borderLeftColor:color,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:size,color:color,testID:testID}){/* @__PURE__ */
|
|
156
|
+
return jsx(View,{style:box(size),testID:testID,...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:size*.5,height:size*.5,backgroundColor:color}})})}function Ring({size:size,strokeWidth:strokeWidth,color:color,children:children}){/* @__PURE__ */
|
|
157
|
+
return jsx(View,{style:[box(size),{borderRadius:size/2,borderWidth:strokeWidth??StyleSheet.hairlineWidth,borderColor:color}],children:children})}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var CHAT_MOTION=/* @__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}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,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 chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return chatMotion(theme)}var NEWTON_ITERATIONS=8;function bezierComponent(t,a1,a2){return((1-3*a2+3*a1)*t+(3*a2-6*a1))*t*t+3*a1*t}function bezierSlope(t,a1,a2){return 3*(1-3*a2+3*a1)*t*t+2*(3*a2-6*a1)*t+3*a1}function bezierEasing(curve){let[x1,y1,x2,y2]=curve;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<NEWTON_ITERATIONS;i+=1){let slope=bezierSlope(t,x1,x2);if(slope===0)break;t-=(bezierComponent(t,x1,x2)-x)/slope}return bezierComponent(Math.min(1,Math.max(0,t)),y1,y2)}}var STANDARD=bezierEasing(CHAT_EASING.standard),OUT_QUAD=bezierEasing(CHAT_EASING.outQuad),OUT=bezierEasing(CHAT_EASING.out);function useAnimatedValue(initial){let ref=useRef(null);return ref.current===null&&(ref.current=new Animated.Value(initial)),ref.current}function useFadeIn(durationMs,options={}){let risePx=options.risePx??0,delayMs=options.delayMs??0,value=useAnimatedValue(durationMs>0?0:1);return useEffect(()=>{if(durationMs<=0)return;let timing=Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT_QUAD,useNativeDriver:true}),animation=delayMs>0?Animated.sequence([Animated.delay(delayMs),timing]):timing;return animation.start(),()=>animation.stop()},[value,durationMs,delayMs]),useMemo(()=>({opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})}]}),[value,risePx])}function FadePresence({visible:visible,inMs:inMs,outMs:outMs,style:style,children:children}){let[mounted,setMounted]=useState(visible),opacity=useAnimatedValue(visible&&inMs<=0?1:0);return useEffect(()=>{if(visible){setMounted(true);let animation2=Animated.timing(opacity,{toValue:1,duration:Math.max(0,inMs),easing:STANDARD,useNativeDriver:true});return animation2.start(),()=>animation2.stop()}if(!mounted)return;if(outMs<=0){setMounted(false);return}let animation=Animated.timing(opacity,{toValue:0,duration:outMs,easing:STANDARD,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&setMounted(false)}),()=>animation.stop()},[visible,mounted,inMs,outMs,opacity]),!mounted&&!visible?null:/* @__PURE__ */jsx(Animated.View,{style:[style,{opacity:opacity}],children:children})}var AT_REST=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function useBubbleEnter(animate,motion){let[durationMs]=useState(()=>animate?motion.bubbleInMs:0),run=durationMs>0,value=useAnimatedValue(run?0:1);useEffect(()=>{if(durationMs<=0)return;let animation=Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT,useNativeDriver:true});return animation.start(),()=>animation.stop()},[durationMs,value]);let fromScale=motion.bubbleFromScale,risePx=motion.bubbleRisePx;return useMemo(()=>run?{opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})},{scale:value.interpolate({inputRange:[0,1],outputRange:[fromScale,1]})}]}:AT_REST,[run,value,risePx,fromScale])}function useEnteringRows(rows){let verdicts=useRef(null),head=useRef(null),first=rows[0]?.id??null;if(verdicts.current===null||head.current!==first){let opened=verdicts.current===null;verdicts.current=new Map(rows.map(row=>[row.id,opened&&row.pending===true])),head.current=first}let map=verdicts.current;for(let row of rows)map.has(row.id)||map.set(row.id,true);return useCallback(id=>map.get(id)===true,[map])}var PRESS_SCALE_HIT_SLOP=12;function PressScale({style:style,containerStyle:containerStyle,children:children,onPressIn:onPressIn,onPressOut:onPressOut,hitSlop:hitSlop,...pressable}){let motion=useChatMotion(),scale=useAnimatedValue(1),animate=useCallback(toValue=>{motion.pressMs<=0||motion.pressScale===1||Animated.timing(scale,{toValue:toValue,duration:motion.pressMs,easing:STANDARD,useNativeDriver:true}).start()},[scale,motion.pressMs,motion.pressScale]);/* @__PURE__ */
|
|
158
|
+
return jsx(Pressable,{...pressable,hitSlop:hitSlop??PRESS_SCALE_HIT_SLOP,style:containerStyle,onPressIn:event=>{animate(motion.pressScale),onPressIn?.(event)},onPressOut:event=>{animate(1),onPressOut?.(event)},children:/* @__PURE__ */jsx(Animated.View,{style:[style,{transform:[{scale:scale}]}],children:children})})}function useRevealedText(text3,revealing,motion){let ticking=revealing&&motion.revealTickMs>0,[visible,setVisible]=useState(0),latest=useRef(text3);return latest.current=text3,useEffect(()=>{if(!ticking)return;let id=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.length))},motion.revealTickMs);return()=>clearInterval(id)},[ticking,motion]),ticking?text3.slice(0,Math.min(visible,text3.length)):text3}var layoutAnimationEnabled=false;function animateLayout(motion){motion.layoutMs<=0||(layoutAnimationEnabled||(layoutAnimationEnabled=true,Platform.OS==="android"&&typeof UIManager.setLayoutAnimationEnabledExperimental=="function"&&UIManager.setLayoutAnimationEnabledExperimental(true)),LayoutAnimation.configureNext({duration:motion.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function useAnimateLayoutOn(key,motion){let previous=useRef(key);previous.current!==key&&(previous.current=key,animateLayout(motion))}var CLOSE_SIZE=36,CLOSE_GLYPH=22,CLOSE_HIT_SLOP=12,CLOSE_TOP_OFFSET=12,CLOSE_RIGHT=16,BACKDROP="#000",CLOSE_BG="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:uri,label:label,onClose:onClose}){let theme=useEverfurTheme(),insets=useSafeAreaInsets();return uri===null?null:/* @__PURE__ */jsxs(Modal,{visible:true,animationType:theme.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:onClose,children:[
|
|
159
|
+
/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,style:styles.backdrop,onPress:onClose,children:/* @__PURE__ */jsx(Image,{source:{uri:uri},style:styles.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:label,accessibilityIgnoresInvertColors:true})}),
|
|
160
|
+
/* @__PURE__ */jsx(View,{pointerEvents:"box-none",style:[styles.closeWrap,{top:insets.top+CLOSE_TOP_OFFSET}],children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,hitSlop:CLOSE_HIT_SLOP,style:styles.closeButton,onPress:onClose,children:/* @__PURE__ */jsx(CloseGlyph,{size:CLOSE_GLYPH,color:theme.color.surface,strokeWidth:2})})})]})}var styles=StyleSheet.create({backdrop:{flex:1,backgroundColor:BACKDROP,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:CLOSE_RIGHT},closeButton:{width:CLOSE_SIZE,height:CLOSE_SIZE,borderRadius:CLOSE_SIZE/2,backgroundColor:CLOSE_BG,alignItems:"center",justifyContent:"center"}});var TAIL_SIZE=12,TILE_MIN_WIDTH=80,TILE_ICON_SIZE=44,TILE_GLYPH=22,BUBBLE_SHADOW_OPACITY=.14,BUBBLE_SHADOW_RADIUS=18,BUBBLE_SHADOW_OFFSET_Y=8,TILE_LABEL=/* @__PURE__ */Object.freeze({photo:CHAT_COPY.attachmentPhoto,camera:CHAT_COPY.attachmentCamera});function AttachmentPickerPopover({sources:sources,full:full,onPick:onPick,onClose:onClose}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles2(theme),[theme]);/* @__PURE__ */
|
|
161
|
+
return jsxs(View,{style:styles2.anchor,pointerEvents:"box-none",children:[
|
|
162
|
+
/* @__PURE__ */jsx(Pressable,{style:styles2.dismissLayer,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closeAttachmentPicker,onPress:onClose}),
|
|
163
|
+
/* @__PURE__ */jsxs(View,{style:styles2.bubble,children:[
|
|
164
|
+
/* @__PURE__ */jsx(View,{style:styles2.tilesRow,children:sources.map(source=>/* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:TILE_LABEL[source],accessibilityState:{disabled:full},disabled:full,containerStyle:styles2.tile,style:styles2.tileInner,onPress:()=>onPick(source),children:[
|
|
165
|
+
/* @__PURE__ */jsx(View,{style:styles2.tileIconWrap,children:source==="photo"?/* @__PURE__ */jsx(PhotoGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */jsx(CameraGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5})}),
|
|
166
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.tileLabel,children:TILE_LABEL[source]})]},source))}),
|
|
167
|
+
/* @__PURE__ */jsx(View,{style:styles2.tail}),
|
|
168
|
+
/* @__PURE__ */jsx(View,{style:styles2.tailFill})]})]})}function makeStyles2(theme){let c=theme.color,r=theme.radius;return StyleSheet.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:c.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:c.shadow,shadowOpacity:BUBBLE_SHADOW_OPACITY,shadowRadius:BUBBLE_SHADOW_RADIUS,shadowOffset:{width:0,height:BUBBLE_SHADOW_OFFSET_Y},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:TILE_MIN_WIDTH,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:TILE_ICON_SIZE,height:TILE_ICON_SIZE,borderRadius:TILE_ICON_SIZE/2,backgroundColor:c.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(theme,"medium"),fontSize:12,lineHeight:14,color:c.text.primary},tail:{position:"absolute",left:24,bottom:-TAIL_SIZE/2,width:TAIL_SIZE,height:TAIL_SIZE,backgroundColor:c.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:c.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:TAIL_SIZE+4,height:2,backgroundColor:c.surfaceCream}})}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var WHITE="#FFFFFF",BLACK="#000000";function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix(from.r,to.r),mix(from.g,to.g),mix(from.b,to.b));if(reads(candidate))return candidate}return pole}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var THUMB_SIZE=56,CARD_RADIUS=12,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_RADIUS=10,UPLOADING_ALPHA=.45,SUCCESS_OVERLAY="rgba(7,193,104,0.55)",FAILED_OVERLAY="rgba(185,28,28,0.55)",SUCCESS_FLASH_FADE_IN_MS=200,SUCCESS_FLASH_FADE_OUT_MS=300,SUCCESS_GLYPH=20,REMOVE_SIZE=22,REMOVE_GLYPH=12,REMOVE_BG="rgba(0,0,0,0.78)",SINGLE_IMAGE=220,GRID_IMAGE=100,IMAGE_ON_BRAND="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:attachments,rejected:rejected,uploadFailed:uploadFailed=false,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles3(theme),[theme]);return attachments.length===0&&rejected===null?null:/* @__PURE__ */jsxs(View,{style:styles2.strip,children:[attachments.length>0?/* @__PURE__ */jsx(View,{style:styles2.cards,children:attachments.map(row=>/* @__PURE__ */jsx(PreviewCard,{row:row,styles:styles2,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview},row.id))}):null,uploadFailed?/* @__PURE__ */jsx(Text,{style:styles2.rejected,accessibilityRole:"alert",children:CHAT_COPY.attachmentsFailedBlocked}):null,rejected!==null?/* @__PURE__ */jsx(Text,{style:styles2.rejected,accessibilityRole:"alert",children:attachmentErrorMessage(rejected)}):null]})}function PreviewCard({row:row,styles:styles2,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),uploading=row.status==="uploading",failed=row.status==="failed",uploaded=row.status==="uploaded",previous=useRef(row.status),[flash,setFlash]=useState(false);return useEffect(()=>{let before=previous.current;previous.current=row.status,row.status==="uploaded"&&before==="uploading"&&setFlash(true)},[row.status]),/* @__PURE__ */jsxs(View,{style:styles2.card,children:[
|
|
169
|
+
/* @__PURE__ */jsx(Pressable,{accessibilityRole:uploaded?"button":"image",accessibilityLabel:uploaded?fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}):row.filename,accessibilityState:{busy:uploading,disabled:!uploaded},disabled:!uploaded,style:styles2.thumbHit,onPress:()=>onPreview(row),children:/* @__PURE__ */jsxs(View,{style:styles2.thumb,children:[
|
|
170
|
+
/* @__PURE__ */jsx(Image,{source:{uri:row.previewUri},style:styles2.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),uploading?/* @__PURE__ */jsx(View,{style:styles2.uploadingOverlay,children:/* @__PURE__ */jsx(ActivityIndicator,{size:"small",color:theme.color.surface})}):null,flash?/* @__PURE__ */jsx(SuccessFlash,{styles:styles2,onDone:()=>setFlash(false)}):null]})}),failed?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.retryUpload,{filename:row.filename}),style:styles2.failedOverlay,onPress:()=>onRetry(row.id),children:/* @__PURE__ */jsx(View,{style:styles2.failedInner,children:/* @__PURE__ */jsx(CloseGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}):null,
|
|
171
|
+
/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.removeAttachment,{filename:row.filename}),hitSlop:6,containerStyle:styles2.removeSlot,style:styles2.removeButton,onPress:()=>onRemove(row.id),children:/* @__PURE__ */jsx(CloseGlyph,{size:REMOVE_GLYPH,color:theme.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:styles2,onDone:onDone}){let theme=useEverfurTheme(),motion=useChatMotion(),opacity=useRef(null);opacity.current===null&&(opacity.current=new Animated.Value(0));let value=opacity.current;return useEffect(()=>{let animation=Animated.sequence([Animated.timing(value,{toValue:1,duration:SUCCESS_FLASH_FADE_IN_MS,useNativeDriver:true}),Animated.delay(motion.uploadFlashMs),Animated.timing(value,{toValue:0,duration:SUCCESS_FLASH_FADE_OUT_MS,useNativeDriver:true})]);return animation.start(({finished:finished})=>{finished&&onDone()}),()=>animation.stop()},[value,motion.uploadFlashMs,onDone]),/* @__PURE__ */jsx(Animated.View,{pointerEvents:"none",style:[styles2.successOverlay,{opacity:value}],children:/* @__PURE__ */jsx(CheckGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}function SentImages({images:images,onPreview:onPreview}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles3(theme),[theme]);if(images.length===0)return null;let single=images.length===1;/* @__PURE__ */
|
|
172
|
+
return jsx(View,{style:single?styles2.sentSingle:styles2.sentGrid,children:images.map((image,index)=>/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.attachedImage,{filename:image.filename}),onPress:()=>onPreview(image),children:/* @__PURE__ */jsx(Image,{source:{uri:image.uri},style:single?styles2.singleImage:styles2.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${image.uri}-${index}`))})}function makeStyles3(theme){let c=theme.color,t=theme.type;return StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:THUMB_SIZE,height:THUMB_SIZE,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:CARD_RADIUS,overflow:"hidden",backgroundColor:c.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:c.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center",backgroundColor:withAlpha(theme.color.brandInk,UPLOADING_ALPHA)??theme.color.brandSofter},successOverlay:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center",backgroundColor:SUCCESS_OVERLAY},failedOverlay:{...ABSOLUTE_FILL,borderRadius:CARD_RADIUS,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:FAILED_OVERLAY},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:REMOVE_SIZE,height:REMOVE_SIZE,borderRadius:REMOVE_SIZE/2,backgroundColor:REMOVE_BG,borderWidth:1.5,borderColor:c.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:SINGLE_IMAGE,height:SINGLE_IMAGE,borderRadius:SINGLE_IMAGE_RADIUS,backgroundColor:IMAGE_ON_BRAND},gridImage:{width:GRID_IMAGE,height:GRID_IMAGE,borderRadius:GRID_IMAGE_RADIUS,backgroundColor:IMAGE_ON_BRAND}})}var FILE_FIELD="file",NOT_SENT="multipart upload failed";function postRnMultipart(post){let form;try{form=new FormData;for(let[name,value]of Object.entries(post.fields))form.append(name,value);form.append(FILE_FIELD,post.file)}catch{return Promise.reject(new Error(NOT_SENT))}return post.fetch!==void 0?postWithFetch(post.fetch,post.url,form,post.signal):postWithXhr(post.url,form,post.signal)}function stored(status){return status>=200&&status<300}function postWithXhr(url,form,signal){return new Promise((resolve,reject)=>{let Xhr=globalThis.XMLHttpRequest;if(typeof Xhr!="function"||signal?.aborted===true){reject(new Error(NOT_SENT));return}let onAbort=null,release=()=>{onAbort!==null&&signal?.removeEventListener("abort",onAbort)},fail=()=>{release(),reject(new Error(NOT_SENT))};try{let xhr=new Xhr;xhr.open("POST",url),xhr.withCredentials=!1,xhr.onload=()=>{release(),resolve(stored(xhr.status))},xhr.onerror=fail,xhr.ontimeout=fail,xhr.onabort=fail,signal!==void 0&&(onAbort=()=>{try{xhr.abort()}finally{fail()}},signal.addEventListener("abort",onAbort,{once:!0})),xhr.send(form)}catch{fail()}})}function postWithFetch(send,url,form,signal){return Promise.resolve().then(()=>send(url,{method:"POST",body:form,credentials:"omit",...signal?{signal:signal}:{}})).then(res=>res.ok)}var NO_URI="chat attachment upload: the file handle has no uri",FAILED="chat attachment upload failed";function filePartOf(file){return{uri:file.uri,name:sanitizeFilename(file.name),type:file.mimeType}}function createRnChatAttachmentTransport(options={}){/* @__PURE__ */
|
|
173
|
+
return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:filePartOf(file),signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function ownGroundSlot(slot){return slot===void 0||slot.backgroundColor!==void 0?slot:slot.borderRadius===void 0?void 0:{borderRadius:slot.borderRadius}}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present=televetGlobal().presenter;if(present===null)return"absent";try{return present(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}var warned=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned||(warned=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=useState(null);useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot=useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot.activeHost===id?snapshot.request:null,[module,setModule]=useState(null),wanted=request!==null&&module===null;return useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>import("@everfur/sdk/televet/booking"));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}={}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetModal:EverfurTelevetModal}=host.module;/* @__PURE__ */
|
|
174
|
+
return jsx(EverfurTelevetModal,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.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 status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid2(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid2(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid2(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=useState(null);if(useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch,opts.controller]),preflightController=useRef(controller);preflightController.current=controller;let scope=useMemo(()=>({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}),[runtime,userRef,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=useState(IDLE2),inFlight2=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=useCallback((petRef,visit)=>{if(inFlight2.current)return inFlight2.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef===void 0?defaultPet:petRef;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight2.current===tracked&&(inFlight2.current=null)});return inFlight2.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=useCallback((petRef,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef===void 0?defaultPet:petRef,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=useCallback(petRef=>redirect?start(petRef,null):openInApp(petRef,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit}}var defaultOpenUrl=url=>Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=useMemo(()=>{let openImpl=openUrl??defaultOpenUrl;return{prepare:()=>({ok:true,value:null}),async finish(_prepared,handoff){try{return await openImpl(handoff.url),null}catch{return"openFailed"}},abandon:()=>{}}},[openUrl]);return useVetVisitWith(opener,rest)}var MIN_TOUCH_TARGET=44,BUSY_OPACITY=.6;function VetVisitButton(props){let{petRef:petRef,label:label,openUrl:openUrl,onOpened:onOpened,onError:onError,style:style,labelStyle:labelStyle,controller:controller,returnTo:returnTo,usState:usState,entry:entry,visitRef:visitRef,intent:intent,onStartInApp:onStartInApp,prefer:prefer}=props,redirecting=prefer==="redirect",visit=useVetVisit({...returnTo!==void 0?{returnTo:returnTo}:{},...usState!==void 0?{usState:usState}:{},...entry!==void 0?{entry:entry}:{},...petRef!==void 0?{petRef:petRef}:{},...openUrl!==void 0?{openUrl:openUrl}:{},...controller!==void 0?{controller:controller}:{},prefer:redirecting?"redirect":"in-app"}),theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles4(theme),[theme]),settling=useRef(false);if(!visit.available)/* @__PURE__ */
|
|
175
|
+
return jsxs(Fragment,{children:[null,
|
|
176
|
+
/* @__PURE__ */jsx(EverfurTelevetHost,{})]});let busy=visit.status==="opening",text3=label??TELEVET_COPY.visitButton;/* @__PURE__ */
|
|
177
|
+
return jsxs(Fragment,{children:[
|
|
178
|
+
/* @__PURE__ */jsx(Pressable,{onPress:()=>{if(!(busy||settling.current)){if(!redirecting){let request={...petRef!==void 0?{petRef:petRef}:{},...usState!==void 0?{usState:usState}:{},...visitRef!=null?{visitRef:visitRef,intent:intent??null}:{}};openVetVisitInApp(request,onStartInApp)===null&&callHost(onError,"unavailable",null);return}settling.current=true,(visitRef==null?visit.open():visit.openVisit(visitRef,intent??null)).then(result=>{result.opened?callHost(onOpened,result.flowId??null):result.reason!=="cancelled"&&callHost(onError,result.reason,result.error)}).finally(()=>{settling.current=false})}},accessibilityRole:"button",accessibilityLabel:text3,accessibilityState:{busy:busy,disabled:busy},style:[styles2.button,busy?styles2.busy:null,style],children:/* @__PURE__ */jsx(Text,{style:[styles2.label,labelStyle],children:text3})}),
|
|
179
|
+
/* @__PURE__ */jsx(EverfurTelevetHost,{})]})}function makeStyles4(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return StyleSheet.create({button:{minHeight:MIN_TOUCH_TARGET,minWidth:MIN_TOUCH_TARGET,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.sm,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.vetVisitButton)},busy:{opacity:BUSY_OPACITY},label:{...face(theme,"medium"),color:color.onPrimary,fontSize:type.size.body,lineHeight:type.size.body*type.lineHeight.snug,...slotText(slots.vetVisitButton)}})}function grounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function isEverfurLightLook(theme){if(theme.brightness!=="light")return false;let compiled=EVERFUR_LIGHT.color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b),own=new Set(grounds(compiled));return same(c.brand,compiled.brand)&&same(c.accent,compiled.accent)&&grounds(c).every(ground=>own.has(ground))}function speciesOf(species){return canonicalPetSpecies(species)==="cat"?"cat":"dog"}function petAgeYears(ageYears){return typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<0?null:Math.floor(ageYears)}function formatPetMeta(pet){let ageYears=petAgeYears(pet.ageYears),speciesLabel=speciesOf(pet.species)==="cat"?"Cat":"Dog";if(ageYears==null)return speciesLabel;let ageLabel=ageYears===1?"1 yr":`${ageYears} yrs`;return`${speciesLabel} · ${ageLabel}`}var INITIALS_PALETTE=/* @__PURE__ */Object.freeze([
|
|
180
|
+
/* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
|
|
181
|
+
/* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
|
|
182
|
+
/* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
|
|
183
|
+
/* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
|
|
184
|
+
/* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
|
|
185
|
+
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function pickInitialsPalette(key){let hash=0;for(let i=0;i<key.length;i+=1)hash=hash*31+key.charCodeAt(i)>>>0;return INITIALS_PALETTE[hash%INITIALS_PALETTE.length]}function getInitial(name){let trimmed=(name??"").trim();return(Array.from(trimmed)[0]??"?").toUpperCase()}function petInitials(pet){return{...pickInitialsPalette(pet.petRef),initial:getInitial(pet.name)}}function petDiscPaint(pet,everfurLook,highlight){let initials=petInitials(pet);return everfurLook?initials:{background:highlight.fill,foreground:highlight.ink,initial:initials.initial}}function letterSize(size){return Math.max(12,Math.round(size*.42))}function PetDisc({pet:pet,size:size,ringStroke:ringStroke}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles5(theme),[theme]),inner=size-ringStroke*2,palette=pet===null?null:petDiscPaint(pet,isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),fontSize=letterSize(inner);/* @__PURE__ */
|
|
186
|
+
return jsx(Ring,{size:size,strokeWidth:ringStroke,color:theme.color.mark,children:/* @__PURE__ */jsx(View,{style:[styles2.disc,{width:inner,height:inner,borderRadius:inner/2},palette===null?styles2.discEmpty:{backgroundColor:palette.background}],children:/* @__PURE__ */jsx(Text,{tier:"badge",style:[styles2.letter,{fontSize:fontSize,lineHeight:Math.round(fontSize*1.2),color:palette===null?theme.color.text.muted:palette.foreground}],children:palette===null?getInitial(null):palette.initial})})})}function makeStyles5(theme){return StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:theme.color.brandSoft},letter:{...face(theme,"bold"),textAlign:"center",includeFontPadding:false}})}var ROW_RING_SIZE=48,ROW_RING_STROKE=2,LIST_MAX_HEIGHT=320,PANEL_MAX_HEIGHT="80%",BACKDROP2="rgba(17,17,17,0.45)",CHECK_SIZE=18,PANEL_RADIUS=22,CLOSE_RADIUS=12,META_TRACKING=.4,MIN_TOUCH_TARGET2=44;function petDisplayName(pet){return pet?.name?.trim()||CHAT_COPY.yourPet}function PetSwitcherSheet({visible:visible,pets:pets,activePetRef:activePetRef,onSelect:onSelect,onAddPet:onAddPet=null,onClose:onClose}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles6(theme),[theme]);return visible?/* @__PURE__ */jsx(Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"fade",onRequestClose:onClose,children:/* @__PURE__ */jsxs(View,{style:styles2.root,children:[
|
|
187
|
+
/* @__PURE__ */jsx(Pressable,{style:ABSOLUTE_FILL,onPress:onClose,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.close,children:/* @__PURE__ */jsx(View,{style:styles2.backdrop})}),
|
|
188
|
+
/* @__PURE__ */jsxs(View,{style:styles2.panel,accessibilityViewIsModal:true,children:[
|
|
189
|
+
/* @__PURE__ */jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:CHAT_COPY.yourPets}),
|
|
190
|
+
/* @__PURE__ */jsx(ScrollView,{style:styles2.list,contentContainerStyle:styles2.listContent,showsVerticalScrollIndicator:true,children:pets.map(pet=>{let isActive=pet.petRef===activePetRef,name=petDisplayName(pet),meta=formatPetMeta(pet);/* @__PURE__ */
|
|
191
|
+
return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(isActive?CHAT_COPY.petCurrentlyActive:CHAT_COPY.switchToPet,{name:name}),accessibilityState:{selected:isActive},style:[styles2.row,isActive?styles2.rowActive:null],onPress:()=>onSelect(pet.petRef),children:[
|
|
192
|
+
/* @__PURE__ */jsx(PetDisc,{pet:pet,size:ROW_RING_SIZE,ringStroke:ROW_RING_STROKE}),
|
|
193
|
+
/* @__PURE__ */jsxs(View,{style:styles2.copy,children:[
|
|
194
|
+
/* @__PURE__ */jsx(Text,{style:styles2.name,numberOfLines:1,children:name}),
|
|
195
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.meta,numberOfLines:1,children:isActive?`${CHAT_COPY.activePrefix}${meta}`:meta})]}),isActive?/* @__PURE__ */jsx(CheckGlyph,{size:CHECK_SIZE,color:theme.color.brandInk}):null]},pet.petRef)})}),onAddPet!==null?/* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addAnotherPet,style:styles2.addRow,onPress:onAddPet,children:[
|
|
196
|
+
/* @__PURE__ */jsx(View,{style:styles2.addDisc,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.addPlus,children:"+"})}),
|
|
197
|
+
/* @__PURE__ */jsx(Text,{style:styles2.addLabel,children:CHAT_COPY.addAnotherPet})]}):null,
|
|
198
|
+
/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.close,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:onClose,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.closeText,children:CHAT_COPY.close})})]})]})}):null}function makeStyles6(theme){let c=theme.color,r=theme.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:BACKDROP2},panel:{backgroundColor:c.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:PANEL_RADIUS,borderTopRightRadius:PANEL_RADIUS,gap:14,maxHeight:PANEL_MAX_HEIGHT},title:{...face(theme,"bold"),fontSize:18,lineHeight:22,color:c.brandInk},list:{maxHeight:LIST_MAX_HEIGHT,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:MIN_TOUCH_TARGET2,paddingHorizontal:8},addDisc:{width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:ROW_RING_STROKE,borderStyle:"dashed",borderColor:c.brandBorder,backgroundColor:c.surfaceCream},addPlus:{...face(theme,"bold"),fontSize:20,lineHeight:22,color:c.brandInk},addLabel:{...face(theme,"bold"),fontSize:15,lineHeight:20,color:c.text.primary},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface},rowActive:{borderColor:c.brandInk,backgroundColor:c.brandSoft},copy:{flex:1,gap:2},name:{...face(theme,"bold"),fontSize:15,lineHeight:18,color:c.text.primary},meta:{...face(theme,"monoBold"),fontSize:11,lineHeight:13,color:c.text.muted,textTransform:"uppercase",letterSpacing:META_TRACKING},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:CLOSE_RADIUS,backgroundColor:c.brandSoft},closeText:{...face(theme,"bold"),color:c.brandInk,fontSize:13,lineHeight:16,letterSpacing:META_TRACKING}})}var MIN_TOUCH_TARGET3=44,ICON_BUTTON_SIZE=36,MENU_GLYPH_SIZE=22,UNREAD_DOT_SIZE=9,UNREAD_DOT_RING=1.5,UNREAD_DOT_INSET=6,HEADER_AVATAR_SIZE=35,HEADER_RING_STROKE=1.75,ADD_BADGE_SIZE=12.4,ADD_BADGE_BORDER=.5,ADD_BADGE_GLYPH=8,LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160;function headerPet(pets,petRef){return headerPetOf(pets,petRef)}function ChatHeader({pets:pets,petRef:petRef,historyUnread:historyUnread,onOpenHistory:onOpenHistory,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles7(theme),[theme]),[switcherOpen,setSwitcherOpen]=useState(false),shown=headerPet(pets.pets,petRef),canSwitch=pets.pets.length>=2,shownPetRef=petRef??shown?.petRef??null,name=petDisplayName(shown),select=next=>{setSwitcherOpen(false),pets.setActivePet(next),callHost(onPetChange,next)},addPet=onAddPet===void 0?null:()=>{setSwitcherOpen(false),callHost(onAddPet)};/* @__PURE__ */
|
|
199
|
+
return jsxs(View,{style:styles2.row,children:[
|
|
200
|
+
/* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:historyUnread?`${CHAT_COPY.openHistoryNative}${CHAT_COPY.newReplySuffix}`:CHAT_COPY.openHistoryNative,containerStyle:styles2.iconSlot,style:styles2.iconButton,onPress:onOpenHistory,children:[
|
|
201
|
+
/* @__PURE__ */jsx(MenuGlyph,{size:MENU_GLYPH_SIZE,color:theme.color.text.primary,strokeWidth:2}),historyUnread?/* @__PURE__ */jsx(View,{style:styles2.unreadDot,pointerEvents:"none"}):null]}),
|
|
202
|
+
/* @__PURE__ */jsx(View,{style:styles2.center,pointerEvents:"box-none",children:/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles2})}),shownPetRef===null?null:/* @__PURE__ */jsx(VetVisitButton,{entry:"chat",petRef:shownPetRef,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles2.vetEntry,labelStyle:styles2.vetEntryLabel}),
|
|
203
|
+
/* @__PURE__ */jsx(View,{style:styles2.right,children:canSwitch?/* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.switchActivePet,{name:name}),containerStyle:styles2.avatarSlot,style:styles2.avatarWrap,onPress:()=>setSwitcherOpen(true),children:[
|
|
204
|
+
/* @__PURE__ */jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE}),
|
|
205
|
+
/* @__PURE__ */jsx(View,{style:styles2.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsx(PlusGlyph,{size:ADD_BADGE_GLYPH,color:theme.color.brandInk,strokeWidth:2})})]}):pets.loading&&shown===null?
|
|
206
|
+
/* @__PURE__ */jsx(View,{style:styles2.avatarWrap,accessible:true,accessibilityLabel:CHAT_COPY.yourPet,children:/* @__PURE__ */jsx(Ring,{size:HEADER_AVATAR_SIZE,strokeWidth:HEADER_RING_STROKE,color:theme.color.mark,children:/* @__PURE__ */jsx(View,{style:styles2.placeholderDisc})})}):/* @__PURE__ */jsx(View,{style:styles2.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:shown===null?CHAT_COPY.yourPet:name,children:/* @__PURE__ */jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE})})}),
|
|
207
|
+
/* @__PURE__ */jsx(PetSwitcherSheet,{visible:switcherOpen,pets:pets.pets,activePetRef:shown?.petRef??null,onSelect:select,onAddPet:addPet,onClose:()=>setSwitcherOpen(false)})]})}function BrandLogo({logoUrl:logoUrl,name:name,styles:styles2}){let[failed,setFailed]=useState(null);return logoUrl===null||failed===logoUrl?null:/* @__PURE__ */jsx(View,{style:styles2.logoBar,children:/* @__PURE__ */jsx(Image,{source:{uri:logoUrl},style:styles2.logo,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:()=>setFailed(logoUrl)})})}function makeStyles7(theme){let c=theme.color,placeholderInner=HEADER_AVATAR_SIZE-HEADER_RING_STROKE*2;return StyleSheet.create({vetEntry:{minHeight:MIN_TOUCH_TARGET3,justifyContent:"center",paddingHorizontal:12,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:c.controlEdge},vetEntryLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:theme.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:16,paddingVertical:10,backgroundColor:c.surface},iconSlot:{borderRadius:ICON_BUTTON_SIZE/2},iconButton:{width:ICON_BUTTON_SIZE,height:ICON_BUTTON_SIZE,borderRadius:ICON_BUTTON_SIZE/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:UNREAD_DOT_INSET,right:UNREAD_DOT_INSET,width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:UNREAD_DOT_SIZE,backgroundColor:c.danger,borderWidth:UNREAD_DOT_RING,borderColor:c.surface},center:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:theme.space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:HEADER_AVATAR_SIZE/2},avatarWrap:{width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,position:"relative"},placeholderDisc:{width:placeholderInner,height:placeholderInner,borderRadius:placeholderInner/2,backgroundColor:c.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:ADD_BADGE_SIZE/2,borderWidth:ADD_BADGE_BORDER,borderColor:c.mark,backgroundColor:c.surface,alignItems:"center",justifyContent:"center"}})}var MIN_TOUCH_TARGET4=44,SCRIM="rgba(17,17,17,0.55)",SHEET_RADIUS=26,HANDLE_WIDTH=36,HANDLE_HEIGHT=4,RADIO_SIZE=20,BADGE_SIZE=38,BADGE_GLYPH=18,RADIO_CHECK=12;function FeedbackReasons({visible:visible,onSubmit:onSubmit,onSkip:onSkip}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles8(theme),[theme]),[reason,setReason]=useState(null),[note,setNote]=useState(""),[pending,setPending]=useState(false),[failed,setFailed]=useState(false),reset=()=>{setReason(null),setNote(""),setPending(false),setFailed(false)},skip=()=>{pending||(reset(),onSkip())},submit=async()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=note.trim();await onSubmit(reason,trimmed.length>0?trimmed:null)?reset():(setPending(false),setFailed(true))};if(!visible)return null;let overLimit=[...note].length>FEEDBACK_NOTES_MAX_CHARS;/* @__PURE__ */
|
|
208
|
+
return jsx(Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"slide",onRequestClose:skip,children:/* @__PURE__ */jsxs(KeyboardAvoidingView,{behavior:Platform.OS==="ios"?"padding":void 0,style:styles2.root,children:[
|
|
209
|
+
/* @__PURE__ */jsx(Pressable,{style:styles2.scrim,onPress:skip,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y}),
|
|
210
|
+
/* @__PURE__ */jsxs(View,{style:styles2.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
|
|
211
|
+
/* @__PURE__ */jsx(View,{style:styles2.handle}),
|
|
212
|
+
/* @__PURE__ */jsxs(View,{style:styles2.header,children:[
|
|
213
|
+
/* @__PURE__ */jsx(View,{style:styles2.iconBadge,children:/* @__PURE__ */jsx(ThumbGlyph,{size:BADGE_GLYPH,color:theme.color.brandInk,active:false,rotate:"180deg"})}),
|
|
214
|
+
/* @__PURE__ */jsxs(View,{style:styles2.headerText,children:[
|
|
215
|
+
/* @__PURE__ */jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:CHAT_COPY.feedbackTitle}),
|
|
216
|
+
/* @__PURE__ */jsx(Text,{style:styles2.subtitle,children:CHAT_COPY.feedbackSubtitle})]})]}),
|
|
217
|
+
/* @__PURE__ */jsx(View,{style:styles2.options,children:FEEDBACK_REASONS.map(option=>{let selected=reason===option.key;/* @__PURE__ */
|
|
218
|
+
return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:option.label,accessibilityState:{selected:selected},style:[styles2.option,selected?styles2.optionSelected:null],onPress:()=>setReason(current=>current===option.key?null:option.key),children:[
|
|
219
|
+
/* @__PURE__ */jsx(Text,{style:[styles2.optionLabel,selected?styles2.optionLabelSelected:null],children:option.label}),
|
|
220
|
+
/* @__PURE__ */jsx(View,{style:[styles2.radio,selected?styles2.radioSelected:null],children:selected?/* @__PURE__ */jsx(CheckGlyph,{size:RADIO_CHECK,color:theme.color.surface,strokeWidth:2}):null})]},option.key)})}),
|
|
221
|
+
/* @__PURE__ */jsxs(View,{style:styles2.inputWrap,children:[
|
|
222
|
+
/* @__PURE__ */jsx(TextInput,{style:styles2.input,placeholder:CHAT_COPY.feedbackNotesPlaceholder,placeholderTextColor:theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.feedbackNotesPlaceholder,value:note,onChangeText:setNote,multiline:true,editable:!pending}),note.length>0?/* @__PURE__ */jsx(Text,{tier:"compact",style:[styles2.counter,overLimit?styles2.counterOver:null],children:`${[...note].length}/${FEEDBACK_NOTES_MAX_CHARS}`}):null]}),failed?/* @__PURE__ */jsx(Text,{style:styles2.failed,accessibilityRole:"alert",children:CHAT_COPY.feedbackFailed}):null,
|
|
223
|
+
/* @__PURE__ */jsxs(View,{style:styles2.actions,children:[
|
|
224
|
+
/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSubmit,accessibilityState:{busy:pending,disabled:pending||overLimit},disabled:pending||overLimit,style:[styles2.submit,pending||overLimit?styles2.submitDisabled:null],onPress:()=>{submit()},children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.submitLabel,children:CHAT_COPY.feedbackSubmit})}),
|
|
225
|
+
/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles2.skip,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles8(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ABSOLUTE_FILL,backgroundColor:SCRIM},sheet:{backgroundColor:c.surface,borderTopLeftRadius:SHEET_RADIUS,borderTopRightRadius:SHEET_RADIUS,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:HANDLE_WIDTH,height:HANDLE_HEIGHT,borderRadius:HANDLE_HEIGHT/2,backgroundColor:c.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:BADGE_SIZE,height:BADGE_SIZE,borderRadius:BADGE_SIZE/2,alignItems:"center",justifyContent:"center",backgroundColor:c.brandSoft},headerText:{flex:1,gap:2},title:{...face(theme,"bold"),fontSize:20,lineHeight:28,color:c.text.primary,letterSpacing:t.letterSpacing.tight},subtitle:{...face(theme,"regular"),fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.relaxed,color:c.text.muted},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:r.md,borderWidth:StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface},optionSelected:{borderColor:c.brandInk,backgroundColor:c.brandSoft},optionLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.primary},optionLabelSelected:{color:c.brandInk},radio:{width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:RADIO_SIZE/2,borderWidth:2,borderColor:c.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:c.brandInk,backgroundColor:c.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(theme,"regular"),fontSize:t.size.body,color:c.text.primary,textAlignVertical:"top"},counter:{...face(theme,"mono"),alignSelf:"flex-end",fontSize:t.size.caption,letterSpacing:.3,color:c.text.placeholder},counterOver:{color:c.danger},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET4,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.xl,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.onPrimary,...slotText(slots.primaryButton)},skip:{minHeight:MIN_TOUCH_TARGET4,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.lg},skipLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.muted}})}var PANEL_WIDTH_FRACTION=.88,PANEL_MAX_WIDTH=420,PANEL_PADDING_TOP=58,BACKDROP3="rgba(17,17,17,0.28)",ACTIVE_ROW_ALPHA=.15,ACTION_SIZE=14,LABEL_SIZE=12,CONTROL_SIZE=44,CLOSE_GLYPH2=16,CARD_RADIUS2=14,ERROR_RADIUS=12,SEARCH_GLYPH=14,UNREAD_DOT=8,HALF_STEP=2,END_REACHED_THRESHOLD=.5,STANDARD2=bezierEasing(CHAT_EASING.standard);function drawerPanelWidth(windowWidth){return Math.min(Math.round(windowWidth*PANEL_WIDTH_FRACTION),PANEL_MAX_WIDTH)}function HistoryDrawer({chat:chat,history:history}){let[mounted,setMounted]=useState(history.open),onHidden=useCallback(()=>setMounted(false),[]);return history.open&&!mounted&&setMounted(true),mounted?/* @__PURE__ */jsx(DrawerModal,{chat:chat,history:history,onHidden:onHidden}):null}function DrawerModal({chat:chat,history:history,onHidden:onHidden}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles9(theme),[theme]),motion=useChatMotion(),insets=useSafeAreaInsets(),{width:width}=useWindowDimensions(),panelWidth=drawerPanelWidth(width),open=history.open,progress=useRef(null);progress.current===null&&(progress.current=new Animated.Value(motion.drawerMs<=0&&open?1:0));let value=progress.current;useEffect(()=>{if(!open&&motion.drawerMs<=0){onHidden();return}let animation=Animated.timing(value,{toValue:open?1:0,duration:motion.drawerMs,easing:STANDARD2,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&!open&&onHidden()}),()=>animation.stop()},[open,value,motion.drawerMs,onHidden]);let translateX=value.interpolate({inputRange:[0,1],outputRange:[-panelWidth,0]}),rows=history.filtered,hasNoConversations=history.rows.length===0,complete=history.cursor===null&&!history.loading&&history.error===null,empty=hasNoConversations&&history.loading?/* @__PURE__ */jsxs(View,{style:styles2.emptyCard,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
|
|
226
|
+
/* @__PURE__ */jsx(ActivityIndicator,{color:styles2.emptyTitle.color}),
|
|
227
|
+
/* @__PURE__ */jsx(Text,{style:styles2.emptyBody,children:HISTORY_COPY.loading})]}):hasNoConversations&&history.error!==null?/* @__PURE__ */jsxs(View,{style:styles2.emptyCard,children:[
|
|
228
|
+
/* @__PURE__ */jsx(Text,{style:styles2.emptyTitle,accessibilityRole:"alert",children:HISTORY_COPY.loadFailed}),
|
|
229
|
+
/* @__PURE__ */jsx(Text,{style:styles2.emptyBody,children:history.error}),
|
|
230
|
+
/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.retry,containerStyle:styles2.retrySlot,style:styles2.retryButton,onPress:()=>{history.load()},children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.retryText,children:HISTORY_COPY.retry})})]}):history.emptyKind==="empty"?/* @__PURE__ */jsxs(View,{style:styles2.emptyCard,children:[
|
|
231
|
+
/* @__PURE__ */jsx(Text,{style:styles2.emptyTitle,children:HISTORY_COPY.empty}),
|
|
232
|
+
/* @__PURE__ */jsx(Text,{style:styles2.emptyBody,children:HISTORY_COPY.emptyBody})]}):
|
|
233
|
+
/* @__PURE__ */jsx(Text,{style:styles2.noMatch,children:HISTORY_COPY.noMatch}),footer=!history.searching&&history.loadingMore?/* @__PURE__ */jsx(View,{style:styles2.loadMoreFooter,children:/* @__PURE__ */jsx(Text,{style:styles2.loadMoreLabel,children:HISTORY_COPY.loadingMore})}):null;/* @__PURE__ */
|
|
234
|
+
return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:history.close,children:/* @__PURE__ */jsxs(View,{style:styles2.root,children:[
|
|
235
|
+
/* @__PURE__ */jsx(Pressable,{style:ABSOLUTE_FILL,onPress:history.close,accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.closeA11y,children:/* @__PURE__ */jsx(Animated.View,{style:[styles2.backdrop,{opacity:value}]})}),
|
|
236
|
+
/* @__PURE__ */jsx(Animated.View,{style:[styles2.panel,{width:panelWidth,paddingTop:Math.max(PANEL_PADDING_TOP,insets.top+theme.space.md),transform:[{translateX:translateX}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */jsxs(KeyboardAvoidingView,{style:styles2.keyboardAvoider,behavior:Platform.OS==="ios"?"padding":"height",children:[
|
|
237
|
+
/* @__PURE__ */jsxs(View,{style:styles2.header,children:[
|
|
238
|
+
/* @__PURE__ */jsx(Text,{tier:"heading",style:styles2.heading,accessibilityRole:"header",children:HISTORY_COPY.heading}),
|
|
239
|
+
/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.newChat,style:styles2.newChat,onPress:history.newConversation,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.newChatLabel,children:HISTORY_COPY.newChat})}),
|
|
240
|
+
/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.close,hitSlop:0,style:styles2.closeButton,onPress:history.close,children:/* @__PURE__ */jsx(CloseGlyph,{size:CLOSE_GLYPH2,color:theme.color.text.muted,strokeWidth:1.75})})]}),
|
|
241
|
+
/* @__PURE__ */jsxs(View,{style:styles2.searchPill,children:[
|
|
242
|
+
/* @__PURE__ */jsx(SearchGlyph,{size:SEARCH_GLYPH,color:theme.color.text.muted,strokeWidth:1.5}),
|
|
243
|
+
/* @__PURE__ */jsx(TextInput,{value:history.query,onChangeText:next=>history.setQuery(next.replace(/^\s+/,"")),style:styles2.searchInput,placeholder:HISTORY_COPY.searchPlaceholder,placeholderTextColor:theme.color.text.placeholder,accessibilityLabel:HISTORY_COPY.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
|
|
244
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.countLabel,children:historyCountLabel(history.rows.length,complete)}),history.error!==null&&!hasNoConversations?/* @__PURE__ */jsx(View,{style:styles2.errorCard,children:/* @__PURE__ */jsx(Text,{style:styles2.errorText,accessibilityRole:"alert",children:history.error})}):null,
|
|
245
|
+
/* @__PURE__ */jsx(FlatList,{data:rows,keyExtractor:row=>row.id,renderItem:({item:item})=>/* @__PURE__ */jsx(Row,{row:item,active:item.id===chat.conversationId,disabled:history.loading,styles:styles2,onPress:()=>{history.resume(item.id)}}),contentContainerStyle:rows.length===0?styles2.listEmpty:styles2.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:empty,ListFooterComponent:footer,onEndReached:history.loadMore,onEndReachedThreshold:END_REACHED_THRESHOLD})]})})]})})}function Row({row:row,active:active,disabled:disabled,styles:styles2,onPress:onPress}){let unread=row.unreadCount!==null&&row.unreadCount>0,meta=conversationMeta(row);/* @__PURE__ */
|
|
246
|
+
return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:openConversationLabel(row),accessibilityState:{selected:active,disabled:disabled},disabled:disabled,style:[styles2.item,active?styles2.itemActive:null],onPress:onPress,children:[
|
|
247
|
+
/* @__PURE__ */jsxs(View,{style:styles2.itemRow,children:[
|
|
248
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.itemTitle,numberOfLines:1,children:conversationTitle(row.title)}),unread?/* @__PURE__ */jsx(View,{style:styles2.unreadDot}):null]}),meta!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.itemMeta,numberOfLines:1,children:meta}):null]})}function makeStyles9(theme){let c=theme.color,s=theme.space,t=theme.type,slots=theme.slots,ink=c.text.primary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:BACKDROP3},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:c.surface,paddingHorizontal:s.lg,borderRightWidth:StyleSheet.hairlineWidth,borderRightColor:c.borderRingCream,gap:s.md},keyboardAvoider:{flex:1,gap:s.md},header:{flexDirection:"row",alignItems:"center",gap:s.sm},heading:{...face(theme,"bold"),flex:1,fontSize:t.size.subtitle,color:ink},newChat:{minHeight:CONTROL_SIZE,justifyContent:"center",paddingHorizontal:s.xs},newChatLabel:{...face(theme,"bold"),fontSize:ACTION_SIZE,color:c.brandInk},closeButton:{width:CONTROL_SIZE,height:CONTROL_SIZE,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:s.sm,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,paddingHorizontal:s.md+HALF_STEP,paddingVertical:s.sm+HALF_STEP,borderWidth:1,borderColor:c.borderRingCream},searchInput:{...face(theme,"regular"),flex:1,fontSize:t.size.bodyTight,color:c.text.primary,padding:0},countLabel:{...face(theme,"mono"),fontSize:LABEL_SIZE,color:c.text.muted},list:{gap:s.xs,paddingBottom:s.xl},listEmpty:{flexGrow:1},item:{paddingVertical:s.sm+HALF_STEP,paddingHorizontal:s.sm,borderRadius:theme.radius.md,gap:HALF_STEP},itemActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??c.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:s.sm},itemTitle:{...face(theme,"bold"),flex:1,fontSize:t.size.bodyTight,color:ink},itemMeta:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted},unreadDot:{width:UNREAD_DOT,height:UNREAD_DOT,borderRadius:UNREAD_DOT/2,backgroundColor:c.danger},errorCard:{borderRadius:ERROR_RADIUS,borderWidth:StyleSheet.hairlineWidth,borderColor:c.danger,backgroundColor:c.surface,padding:s.md},errorText:{...face(theme,"regular"),fontSize:t.size.caption,color:c.danger},emptyCard:{borderRadius:CARD_RADIUS2,padding:s.md+HALF_STEP,gap:s.xs+HALF_STEP,backgroundColor:c.surfaceSubtle,borderWidth:StyleSheet.hairlineWidth,borderColor:c.borderRingCream},emptyTitle:{...face(theme,"bold"),fontSize:t.size.bodyTight,color:ink},emptyBody:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.secondary},noMatch:{...face(theme,"regular"),fontSize:t.size.bodyTight,color:c.text.muted,paddingVertical:s.sm},retrySlot:{marginTop:s.sm,alignSelf:"flex-start"},retryButton:{borderRadius:theme.radius.pill,paddingHorizontal:s.md+HALF_STEP,paddingVertical:s.sm,borderWidth:1,borderColor:c.brandInk,...slotBox(slots.primaryButton)},retryText:{...face(theme,"bold"),fontSize:t.size.caption,color:c.brandInk,...slotText(slots.primaryButton)},loadMoreFooter:{paddingVertical:s.md+HALF_STEP,alignItems:"center"},loadMoreLabel:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted}})}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number"&&Number.isFinite(hostOffset),probeRef=useRef(null),[reading,setReading]=useState(null),frame=useRef(null),retry=useRef(null),mounted=useRef(true),stopRetry=useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return useMemo(()=>{if(!lifts)return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset}:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset,onLayout:onLayout}:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsx(View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function useKeyboardOpen(){let[open,setOpen]=useState(false);return useEffect(()=>{let keyboard=Keyboard;if(typeof keyboard?.addListener!="function")return;let ios=Platform.OS==="ios",shown=keyboard.addListener(ios?"keyboardWillShow":"keyboardDidShow",()=>setOpen(true)),hidden=keyboard.addListener(ios?"keyboardWillHide":"keyboardDidHide",()=>setOpen(false));return()=>{shown.remove(),hidden.remove()}},[]),open}var SLOT_MIN_CONTRAST=4.5;var SLOT_MIN_BORDER_CONTRAST=3;function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency"||isEverfurLightLook(theme))return tier;let c=theme.color,caution=tier.level==="schedule_soon",fill=flattenOnto(caution?c.badgeBgCaution:c.brandSoft,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.structureEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.brandInk,[fill,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
|
|
249
|
+
return Object.freeze({...tier,borderColor:borderColor,backgroundColor:fill,textColor:textColor,reasonColor:readOn(c.text.primary,[fill],SLOT_MIN_CONTRAST),pillColor:c.surface})}function chatVetVisitOptions(petRef,vet){let options={entry:"chat",petRef:petRef};return vet?.returnTo!==void 0&&(options.returnTo=vet.returnTo),vet?.usState!==void 0&&(options.usState=vet.usState),vet?.prefer!==void 0&&(options.prefer=vet.prefer),options}var CARD_EDGE=.75,EMERGENCY_EDGE=1.5,EMERGENCY_EDGE_ALPHA=.4,CARD_PAD_X_EXTRA=4,REASON_LEAD=1.5,CLOSE_SIZE2=22,CLOSE_GLYPH3=14,CLOSE_HIT_SLOP2=8,INFO_GLYPH=20,INFO_HIT_SLOP=10,PIN_GLYPH=13,PILL_LABEL_SIZE=12,PILL_LABEL_LINE=15,ACTION_MIN_HEIGHT=44,ACTION_PAD_X=14,ACTION_EDGE=1.25,ACTION_LABEL_SIZE=14,ACTION_GLYPH_GAP=6,COMPACT_REASON_LINES=2;function tierPaint(theme,tier){let c=theme.color;return tier.level==="emergency"?{card:{backgroundColor:c.badgeBgCritical,borderColor:withAlpha(c.danger,EMERGENCY_EDGE_ALPHA)??c.danger,borderWidth:EMERGENCY_EDGE},label:c.danger,reason:c.text.primary,close:c.danger,action:{fill:c.surface,edge:c.danger,ink:c.danger}}:{card:{backgroundColor:tier.backgroundColor,borderColor:tier.borderColor,borderWidth:CARD_EDGE},label:tier.textColor,reason:tier.reasonColor,close:tier.textColor,action:null}}function UrgencyBanner({surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:compact=false}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles10(theme),[theme]),motion=useChatMotion(),tier=surface.tier===null?null:themedUrgencyTier(surface.tier,theme),source=surface.source;/* @__PURE__ */
|
|
250
|
+
return jsxs(Fragment,{children:[
|
|
251
|
+
/* @__PURE__ */jsx(FadePresence,{visible:surface.showBanner&&tier!==null,inMs:motion.bannerInMs,outMs:motion.bannerOutMs,style:styles2.pinned,children:tier!==null&&source!==null?/* @__PURE__ */jsx(BannerCard,{tier:tier,reason:source.reason,surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,styles:styles2,compact:compact}):null}),
|
|
252
|
+
/* @__PURE__ */jsx(FadePresence,{visible:surface.showCompactIcon,inMs:motion.iconInMs,outMs:motion.iconOutMs,style:styles2.indicatorRow,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.showLatestVetAlert,hitSlop:INFO_HIT_SLOP,onPress:surface.expand,children:/* @__PURE__ */jsx(InfoGlyph,{size:INFO_GLYPH,color:theme.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:tier,reason:reason,surface:surface,petRef:petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,styles:styles2,compact:compact}){let theme=useEverfurTheme(),paint=tierPaint(theme,tier),builtIn=/* @__PURE__ */jsx(VetAction,{tier:tier,paint:paint,petRef:petRef,onFindVet:onFindVet,vet:vet,styles:styles2}),vetAction=surface.showVetAction?renderVetAction!==void 0?/* @__PURE__ */jsx(HostRender,{render:()=>renderVetAction(tier.level),fallback:builtIn,resetKey:tier.level}):builtIn:null,poison=paint.action!==null?/* @__PURE__ */jsx(PoisonControl,{paint:paint.action,styles:styles2}):null;/* @__PURE__ */
|
|
253
|
+
return jsxs(View,{accessibilityRole:"alert",style:[styles2.card,paint.card,compact?styles2.cardCompact:null],testID:compact?"chat-urgency-compact":void 0,children:[
|
|
254
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:[styles2.label,{color:paint.label}],children:tier.label}),reason!==null?/* @__PURE__ */jsx(Text,{style:[styles2.reason,{color:paint.reason}],numberOfLines:compact?COMPACT_REASON_LINES:void 0,accessibilityLabel:compact?reason:void 0,children:reason}):null,vetAction!==null||poison!==null?/* @__PURE__ */jsxs(View,{style:styles2.actions,children:[vetAction,poison]}):null,surface.dismissLabel!==null?/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:surface.dismissLabel,hitSlop:CLOSE_HIT_SLOP2,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:surface.dismiss,children:/* @__PURE__ */jsx(CloseGlyph,{size:CLOSE_GLYPH3,color:paint.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:paint,styles:styles2}){let call=()=>{try{Linking.openURL(POISON_CONTROL_TEL).catch(()=>{})}catch{}};/* @__PURE__ */
|
|
255
|
+
return jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.poisonControlNative,hitSlop:0,style:[styles2.action,{backgroundColor:paint.fill,borderColor:paint.edge}],onPress:call,children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles2.actionLabel,{color:paint.ink}],children:CHAT_COPY.poisonControlNative})})}function VetAction({tier:tier,paint:paint,petRef:petRef,onFindVet:onFindVet,vet:vet,styles:styles2}){let theme=useEverfurTheme(),visit=useVetVisit(chatVetVisitOptions(petRef,vet)),busy=visit.status==="opening",hostFinder=!visit.available&&onFindVet!==void 0,onPress=visit.available?()=>{visit.open()}:onFindVet!==void 0?()=>{callHost(onFindVet,tier.level)}:null;if(onPress===null)return null;let action=paint.action;if(action!==null){let label=hostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVet,ink2=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??action.ink;/* @__PURE__ */
|
|
256
|
+
return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:hostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},hitSlop:0,style:[styles2.action,{backgroundColor:action.fill,borderColor:action.edge},styles2.findVetSlotBox,busy?styles2.findVetBusy:null],onPress:onPress,children:[
|
|
257
|
+
/* @__PURE__ */jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink2,strokeWidth:1.5}),
|
|
258
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:[styles2.actionLabel,{color:ink2}],children:label})]})}let ink=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??tier.textColor;/* @__PURE__ */
|
|
259
|
+
return jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},style:[styles2.findVetButton,{borderColor:tier.borderColor,backgroundColor:tier.pillColor},styles2.findVetSlotBox,busy?styles2.findVetBusy:null],onPress:onPress,children:[
|
|
260
|
+
/* @__PURE__ */jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink,strokeWidth:1.5}),
|
|
261
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:[styles2.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles10(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=useCallback(petRef=>handle.setActivePet(petRef),[handle]);return useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=useRef(false),scope=useRef({send:chat.send,id:chat.conversationId});useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var SPINNER_DELAY_MS=300,THANKS_VISIBLE_MS=3e3,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET5=44,INPUT_MAX_HEIGHT=120,BUBBLE_MAX_WIDTH="88%",BUBBLE_MAX_WIDTH_CAP=520,HALF_STEP2=2,BUBBLE_EDGE_WIDTH=.5,BUBBLE_LEAD_USER=1.5,BUBBLE_LEAD_ASSISTANT=1.6,PENDING_OPACITY=.6,COMPOSER_MIN_HEIGHT=56,COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_RIGHT=5,COMPOSER_PADDING_VERTICAL=5,INPUT_MIN_HEIGHT=36,INPUT_LINE_HEIGHT=20,APP_BODY_SIZE=14,SEND_CONTROL_SIZE=MIN_TOUCH_TARGET5,TEXT_ACTION_HIT_SLOP=4,SEND_GLYPH_SIZE=24,STOP_GLYPH_SIZE=22,SEND_DISABLED_OPACITY=.4,ATTACH_CONTROL_SIZE=MIN_TOUCH_TARGET5,ATTACH_GLYPH_SIZE=20,ATTACH_DISABLED_OPACITY=.4,EMPTY_MIN_HEIGHT=480,FOLLOW_UP_HEADING_SIZE=12,FOLLOW_UP_HEADING_TRACKING=.72,FOLLOW_UP_ROW_MIN_HEIGHT=48,RULE_WIDTH=1,FOOTNOTE_SIZE=12,FOOTNOTE_LINE=18,EMPTY_PADDING_TOP="12%";function useChatTheme(){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles11(theme),[theme]);return{theme:theme,styles:styles2}}function makeStyles11(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,userLine=Math.round(t.size.body*BUBBLE_LEAD_USER),assistantLine=Math.round(t.size.body*BUBBLE_LEAD_ASSISTANT),inputLine=Math.round(INPUT_LINE_HEIGHT*t.size.body/APP_BODY_SIZE),rule=c.borderRingCream,slots=theme.slots;return StyleSheet.create({container:{flex:1,minHeight:MIN_SURFACE_HEIGHT,backgroundColor:c.chatGround},body:{flex:1},centered:{minHeight:MIN_SURFACE_HEIGHT,flexGrow:1,alignItems:"center",justifyContent:"center",padding:s.xl},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:EMPTY_PADDING_TOP,paddingHorizontal:s.lg,paddingBottom:s.lg,minHeight:EMPTY_MIN_HEIGHT,gap:s.lg},errorText:{...face(theme,"regular"),fontSize:t.size.subtitle,lineHeight:t.size.subtitle*t.lineHeight.snug,color:c.danger,textAlign:"center",marginBottom:s.md},retryButton:{minHeight:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:s.xl,paddingVertical:s.sm,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},retryLabel:{...face(theme,"medium"),color:c.onPrimary,fontSize:t.size.body,...slotText(slots.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,paddingHorizontal:s.lg,paddingVertical:s.sm,backgroundColor:c.surfaceCream},setupNoticeText:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption,flexShrink:1},turnNotice:{gap:s.xs,padding:s.md,borderRadius:r.lg,backgroundColor:c.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:c.brandBorder,alignItems:"flex-start"},turnNoticeError:{borderColor:c.danger},turnNoticeTitle:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.body},turnNoticeTitleError:{color:c.danger},turnNoticeBody:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal},turnNoticeAction:{minHeight:MIN_TOUCH_TARGET5,justifyContent:"center"},turnNoticeActionLabel:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.body},setupNoticeAction:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.caption},reconnectingCaption:{...face(theme,"medium"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingLine:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*t.lineHeight.relaxed)},list:{flex:1},listContent:{padding:s.lg,gap:s.xl},rowBlock:{gap:s.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:s.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:BUBBLE_MAX_WIDTH,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,backgroundColor:c.bubbleUser,...c.primaryEdge!==c.primary&&c.bubbleUser===c.primary?{borderWidth:BUBBLE_EDGE_WIDTH,borderColor:c.primaryEdge}:{},borderRadius:r.lg,borderBottomRightRadius:r.xs,...slotBox(slots.userBubble,BUBBLE_EDGE_WIDTH)},bubbleAssistant:slots.assistantBubble?.backgroundColor===void 0?{...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)}:{paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,borderRadius:r.lg,...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)},bubbleVet:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,backgroundColor:c.bubbleVet,borderRadius:r.lg,borderTopLeftRadius:r.xs,...slotBox(slots.vetBubble,BUBBLE_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{...face(theme,"regular"),color:c.onPrimary,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.userBubble)},bubbleTextAssistant:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:assistantLine,...slotText(slots.assistantBubble)},bubbleTextVet:{...face(theme,"regular"),color:c.onBubbleVet,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.vetBubble)},assistantName:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,marginBottom:s.xs},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:s.sm,marginBottom:s.xs},vetSender:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight},vetTime:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption},bubbleBold:face(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(theme,"mono"),followUps:{alignSelf:"stretch",marginTop:s.md},followUpsHeading:{...face(theme,"monoBold"),color:c.text.muted,fontSize:FOLLOW_UP_HEADING_SIZE,textTransform:"uppercase",letterSpacing:FOLLOW_UP_HEADING_TRACKING,paddingBottom:s.sm,borderBottomWidth:RULE_WIDTH,borderBottomColor:rule},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:RULE_WIDTH,borderTopColor:rule},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.md,minHeight:FOLLOW_UP_ROW_MIN_HEIGHT,paddingVertical:s.sm+HALF_STEP2},followUpText:{...face(theme,"bold"),flex:1,color:c.brandInk,fontSize:t.size.bodyTight},composerOuter:{position:"relative"},composer:{marginHorizontal:s.md,marginTop:s.xs,minHeight:COMPOSER_MIN_HEIGHT,justifyContent:"center",paddingLeft:s.sm,paddingRight:COMPOSER_PADDING_RIGHT,paddingVertical:COMPOSER_PADDING_VERTICAL,backgroundColor:c.composerFill,borderWidth:COMPOSER_BORDER_WIDTH,borderColor:c.composerBorder,borderRadius:r.pill,...slotBox(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerRow:{flexDirection:"row",alignItems:"center",gap:s.xs,minHeight:INPUT_MIN_HEIGHT},attachControl:{width:ATTACH_CONTROL_SIZE,height:ATTACH_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:ATTACH_DISABLED_OPACITY},input:{flex:1,minHeight:INPUT_MIN_HEIGHT,maxHeight:INPUT_MAX_HEIGHT,paddingHorizontal:0,paddingVertical:0,...face(theme,"regular"),fontSize:t.size.body,lineHeight:inputLine,color:c.text.primary,...slotText(slots.composerInput)},sendControl:{minHeight:SEND_CONTROL_SIZE,minWidth:SEND_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},sendDisc:{width:SEND_CONTROL_SIZE,height:SEND_CONTROL_SIZE,borderRadius:SEND_CONTROL_SIZE/2,alignItems:"center",justifyContent:"center",...slotBox(slots.sendButton)},sendControlDisabled:{opacity:SEND_DISABLED_OPACITY},footnote:{...face(theme,"regular"),color:c.text.muted,fontSize:FOOTNOTE_SIZE,lineHeight:FOOTNOTE_LINE,textAlign:"center",marginTop:s.sm,marginBottom:s.xs,paddingHorizontal:s.lg},poweredBy:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.micro,textAlign:"center",paddingBottom:s.xs}})}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}var CHECKIN_COPY=/* @__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"})}),CHECKIN_OPTIONS=/* @__PURE__ */Object.freeze(CHECKIN_ANSWERS.map(answer=>/* @__PURE__ */Object.freeze({answer:answer,label:CHECKIN_COPY.answers[answer]})));function useCheckinCard(checkin,answerCheckin){let[pending,setPending]=useState(null),[error,setError]=useState(null),[tapped,setTapped]=useState(null),choose=useCallback(answer2=>{answerCheckin!==null&&(setPending(answer2),setError(null),answerCheckin(checkin.caseId,answer2).then(result=>{setPending(null),result.ok?setTapped(answer2):setError(result.error)}))},[answerCheckin,checkin.caseId]),answer=tapped??checkin.answer;return{answer:answer,answerable:!isCheckinSettled(checkin),escalated:answer==="worse",pending:pending,error:error,choose:choose}}var MIN_TOUCH_TARGET6=44,PENDING_OPACITY2=.6;function CheckinCard({message:message,checkin:checkin,onAnswer:onAnswer,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles12(theme),[theme]),state=useCheckinCard(checkin,onAnswer),settled=state.answer!==null||state.pending!==null,answerable=onAnswer!==null&&state.answerable,day=checkinDayNumber(checkin.openedAt,checkinDueDay(message));/* @__PURE__ */
|
|
262
|
+
return jsxs(View,{style:styles2.card,accessibilityLabel:CHECKIN_COPY.eyebrow,onLayout:onLayout,children:[
|
|
263
|
+
/* @__PURE__ */jsxs(View,{style:styles2.head,children:[
|
|
264
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.eyebrow,children:CHECKIN_COPY.eyebrow}),day!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.headDay,children:fillCopy(CHECKIN_COPY.day,{day:day})}):null]}),
|
|
265
|
+
/* @__PURE__ */jsx(Text,{style:styles2.question,accessibilityRole:"text",children:message.text}),answerable?/* @__PURE__ */jsx(View,{style:[styles2.row,state.pending?styles2.rowPending:null],children:CHECKIN_OPTIONS.map(({answer:answer,label:label})=>{let selected=(state.pending??state.answer)===answer;/* @__PURE__ */
|
|
266
|
+
return jsx(Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles2.pill,selected?styles2.pillSelected:null],children:/* @__PURE__ */jsx(Text,{tier:"control",style:[styles2.pillLabel,selected?styles2.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsx(Text,{style:styles2.logged,children:CHECKIN_COPY.logged}):null,state.escalated?onFindVet!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles2.findVet,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.findVetLabel,children:CHECKIN_COPY.findVet})}):petRef?/* @__PURE__ */jsx(VetVisitButton,{entry:"chat",petRef:petRef,label:CHECKIN_COPY.findVet,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles2.findVet,labelStyle:styles2.findVetLabel}):null:null,checkin.resolutionText?/* @__PURE__ */jsx(Text,{style:styles2.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsx(Text,{style:styles2.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function makeStyles12(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:c.brandBorder},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm},eyebrow:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal},row:{flexDirection:"row",gap:s.sm,marginTop:s.xs},rowPending:{opacity:PENDING_OPACITY2},pill:{flex:1,minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",paddingHorizontal:s.md,borderRadius:r.pill,borderWidth:1,borderColor:c.controlEdge,backgroundColor:c.surface},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk},pillLabel:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body},pillLabelSelected:{color:c.onPrimary},logged:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption},resolution:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal},error:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption},findVet:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",borderRadius:r.pill,borderWidth:1.5,borderColor:c.controlEdge,backgroundColor:c.surface},findVetLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.body}})}var RULE_WIDTH2=1.5,BODY_GAP=3;function CheckinPastAsk({text:text3,runDueDays:runDueDays,openedAt:openedAt,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles13(theme),[theme]),days=runDueDays.map(dueDay=>checkinDayNumber(openedAt,dueDay)).filter(day=>day!==null),collapsed=runDueDays.length>1;return collapsed&&days.length===0?null:/* @__PURE__ */jsxs(View,{style:styles2.row,onLayout:onLayout,children:[
|
|
267
|
+
/* @__PURE__ */jsx(View,{style:styles2.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),
|
|
268
|
+
/* @__PURE__ */jsxs(View,{style:styles2.body,children:[days.length>0?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.days,children:days.map(day=>fillCopy(CHECKIN_COPY.day,{day:day})).join(CHECKIN_COPY.daySeparator)}):null,collapsed?null:/* @__PURE__ */jsx(Text,{style:styles2.question,accessibilityRole:"text",children:text3})]})]})}function makeStyles13(theme){let c=theme.color,s=theme.space,t=theme.type;return StyleSheet.create({row:{flexDirection:"row",paddingVertical:s.xs},rule:{width:RULE_WIDTH2,borderRadius:1,backgroundColor:c.borderHairlineGreen,marginRight:s.md},body:{flex:1,gap:BODY_GAP},days:{...face(theme,"monoMedium"),fontSize:t.size.nano,letterSpacing:t.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase"},question:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:t.size.bodyTight*t.lineHeight.normal,color:c.text.muted}})}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
|
|
269
|
+
return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count){return count===1?`1 ${CHAT_COPY.sourceSingular}`:`${count} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}var CARD_WIDTH=244,TIER_DOT=8,PILL_GLYPH=13,LINK_GLYPH=14,TOGGLE_TRACKING=.3,TITLE_TRACKING=-.24,TITLE_LINE=22,META_LINE=10,EXCERPT_LINE=15;function CitationCards({citations:citations,onOpenUrl:onOpenUrl}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles14(theme),[theme]),cards=useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=useState(false);if(cards.length===0)return null;let count=cards.length;/* @__PURE__ */
|
|
270
|
+
return jsxs(View,{style:styles2.block,children:[
|
|
271
|
+
/* @__PURE__ */jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:sourcesToggleLabel(count,expanded),accessibilityState:{expanded:expanded},containerStyle:styles2.toggleSlot,style:styles2.togglePill,onPress:()=>setExpanded(current=>!current),children:[
|
|
272
|
+
/* @__PURE__ */jsx(BookGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}),
|
|
273
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.toggleLabel,children:sourcesLabel(count)}),
|
|
274
|
+
/* @__PURE__ */jsx(ChevronGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5,direction:expanded?"up":"down"})]}),expanded?/* @__PURE__ */jsx(Deck,{cards:cards,styles:styles2,open:onOpenUrl}):null]})}function Deck({cards:cards,styles:styles2,open:open}){let motion=useChatMotion(),fade=useFadeIn(motion.citationsInMs,{risePx:motion.citationsRisePx});/* @__PURE__ */
|
|
275
|
+
return jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:styles2.row,children:cards.map(card=>/* @__PURE__ */jsx(Card,{card:card,styles:styles2,open:open},card.key))})})}function Card({card:card,styles:styles2,open:open}){let theme=useEverfurTheme(),linked=card.url!==null&&open!==void 0,label=citationA11yLabel(linked?card:{...card,url:null}),inner=/* @__PURE__ */jsxs(Fragment,{children:[
|
|
276
|
+
/* @__PURE__ */jsxs(View,{style:styles2.cardHeader,children:[
|
|
277
|
+
/* @__PURE__ */jsx(View,{style:[styles2.tierDot,{backgroundColor:card.tierColor}]}),
|
|
278
|
+
/* @__PURE__ */jsx(Text,{style:[styles2.cardTitle,linked?styles2.cardTitleLink:null],numberOfLines:2,children:card.title}),linked?/* @__PURE__ */jsx(ArrowUpRightGlyph,{size:LINK_GLYPH,color:theme.color.linkInk,strokeWidth:1.5}):null]}),card.meta!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.cardMeta,numberOfLines:1,children:card.meta}):null,card.excerpt!==null?/* @__PURE__ */jsx(Text,{style:styles2.cardExcerpt,numberOfLines:3,children:card.excerpt}):null]});if(card.url!==null&&open!==void 0){let url=card.url;/* @__PURE__ */
|
|
279
|
+
return jsx(PressScale,{accessibilityRole:"link",accessibilityLabel:label,style:styles2.card,onPress:()=>open(url),children:inner})}/* @__PURE__ */
|
|
280
|
+
return jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:label,style:styles2.card,children:inner})}function makeStyles14(theme){let c=theme.color,s=theme.space,r=theme.radius,size=theme.type.size;return StyleSheet.create({block:{gap:s.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:r.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:s.xs+2,paddingHorizontal:s.md,paddingVertical:s.xs+2,borderRadius:r.pill,backgroundColor:c.brandSoft},toggleLabel:{...face(theme,"monoBold"),fontSize:size.micro,lineHeight:size.micro,letterSpacing:TOGGLE_TRACKING,color:c.brandInk,textTransform:"uppercase"},row:{gap:s.sm,paddingRight:s.xl,paddingTop:s.xs},card:{width:CARD_WIDTH,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface,padding:s.md,gap:s.xs+2},cardHeader:{flexDirection:"row",alignItems:"center",gap:s.sm},tierDot:{width:TIER_DOT,height:TIER_DOT,borderRadius:r.pill},cardTitle:{...face(theme,"bold"),flex:1,fontSize:size.bodyTight,lineHeight:TITLE_LINE,color:c.text.primary,letterSpacing:TITLE_TRACKING},cardTitleLink:{color:c.linkInk},cardMeta:{...face(theme,"monoMedium"),fontSize:size.nano,lineHeight:META_LINE,letterSpacing:theme.type.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...face(theme,"regular"),fontSize:size.tiny,lineHeight:EXCERPT_LINE,color:c.text.muted}})}var ICON_SIZE=15,ICON_HIT_SLOP=15,THUMB_HIT_SLOP=6,SENTIMENT_ROTATE=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:message,onCopy:onCopy,sentiment:sentiment=null,onSentiment:onSentiment,thanks:thanks=false}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles15(theme),[theme]),motion=useChatMotion(),isUser=message.role==="user",timeLabel=useMemo(()=>formatMessageTime(message.createdAt),[message.createdAt]),canCopy=onCopy!==void 0&&message.role!=="vet"&&message.text.length>0,thumbs=message.role==="assistant"&&onSentiment!==void 0&&message.responseId!==void 0,[justCopied,setJustCopied]=useState(false),resetTimer=useRef(null);useEffect(()=>()=>{resetTimer.current&&clearTimeout(resetTimer.current)},[]);let copy=()=>{onCopy!==void 0&&(callHostAsync(onCopy,message.text),setJustCopied(true),resetTimer.current&&clearTimeout(resetTimer.current),resetTimer.current=setTimeout(()=>{setJustCopied(false),resetTimer.current=null},motion.copiedMs))};return timeLabel===null&&!canCopy&&!thumbs?null:/* @__PURE__ */jsxs(View,{style:styles2.wrap,children:[
|
|
281
|
+
/* @__PURE__ */jsxs(View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],children:[timeLabel!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.timestamp,children:timeLabel}):null,canCopy?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:justCopied?CHAT_COPY.copied:isUser?CHAT_COPY.copyUserMessage:CHAT_COPY.copyAssistantMessage,hitSlop:ICON_HIT_SLOP,onPress:copy,style:styles2.iconHit,children:justCopied?/* @__PURE__ */jsx(CheckGlyph,{size:ICON_SIZE,color:theme.color.success,strokeWidth:2}):/* @__PURE__ */jsx(CopyGlyph,{size:ICON_SIZE,color:theme.color.text.timestamp,strokeWidth:1.5})}):null,thumbs?SENTIMENT_OPTIONS.map(({sentiment:kind,label:label})=>/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:sentiment===kind},hitSlop:THUMB_HIT_SLOP,onPress:()=>onSentiment?.(kind),style:styles2.iconHit,children:/* @__PURE__ */jsx(ThumbGlyph,{size:ICON_SIZE,color:theme.color.sentiment[kind],active:sentiment===kind,rotate:SENTIMENT_ROTATE[kind],strokeWidth:1.5})},kind)):null]}),thanks?/* @__PURE__ */jsx(Text,{style:styles2.thanks,accessibilityLiveRegion:"polite",children:CHAT_COPY.feedbackThanks}):null]})}function makeStyles15(theme){let t=theme.type;return StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(theme,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:theme.color.text.timestamp,textAlign:"center"},iconHit:{width:ICON_SIZE,height:ICON_SIZE,alignItems:"center",justifyContent:"center"},thanks:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.text.secondary}})}var QUICK_PROMPT_BRAND_EDGE="#10462E";var QUICK_PROMPT_TEXT_COLOR="#000000",PILL_ACTIVITY_ON_WHITE="#83E0B4",PROMPTS=/* @__PURE__ */Object.freeze([
|
|
282
|
+
/* @__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}),
|
|
283
|
+
/* @__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:PILL_ACTIVITY_ON_WHITE,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
284
|
+
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:QUICK_PROMPT_BRAND_EDGE,brandEdge:true,borderWidth:1}),
|
|
285
|
+
/* @__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 quickPromptThemePaint(everfurLook,highlight){return everfurLook?null:{fill:highlight.fill,ink:highlight.ink}}var TRAILING_SIZE_SUFFIX_RE=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function formatBreedForPrompt(breed){return breed==null?breed:breed.replace(TRAILING_SIZE_SUFFIX_RE,"").trim()}var UNINFORMATIVE_BREEDS=/* @__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 isUninformativeBreed(breed){let key=String(breed??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return UNINFORMATIVE_BREEDS.has(key)}function unspecifiedBreedLabel(species){return species==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function resolveBreedLabel(breed,species){return isUninformativeBreed(breed)?unspecifiedBreedLabel(species):String(breed).replace(/\s+/gu," ").trim()}function emptyStateTitle(pet){let petName=pet?.name?.trim()||CHAT_COPY.emptyTitlePetFallback;return fillCopy(CHAT_COPY.emptyTitle,{petName:petName})}function resolveQuickPrompts(pet,brandEdge=QUICK_PROMPT_BRAND_EDGE){let species=speciesOf(pet?.species),speciesFallback=species==="cat"?"my cat":"my dog",trimmedPetName=pet?.name?.trim()||null,petToken=trimmedPetName||speciesFallback,breedToken=resolveBreedLabel(formatBreedForPrompt(pet?.breed),species)||null,age=petAgeYears(pet?.ageYears),ageToken=age===null?null:String(age);/* @__PURE__ */
|
|
286
|
+
return Object.freeze(PROMPTS.map(template=>{let usesBreed=template.label.includes("{breed}"),usesAge=template.label.includes("{ageYears}"),baseLabel=template.fallbackLabel!==void 0&&(usesBreed&&!breedToken||usesAge&&!ageToken)&&template.fallbackLabel?template.fallbackLabel:template.label,resolvedLabel=fillCopy(baseLabel,{petName:petToken,breed:breedToken??speciesFallback,species:species,ageYears:ageToken??""}),label=!trimmedPetName&&baseLabel.startsWith("{petName}")?resolvedLabel.charAt(0).toUpperCase()+resolvedLabel.slice(1):resolvedLabel;/* @__PURE__ */
|
|
287
|
+
return Object.freeze({id:template.id,intent:template.intent,label:label,background:template.background,borderColor:template.brandEdge===true?brandEdge:template.borderColor,borderWidth:template.borderWidth})}))}var CHIP_MIN_HEIGHT=44,CHIP_HIT_SLOP=0,CHIP_EDGE_WIDTH=1,CHIP_EDGE_ALPHA=.28,CHIP_GAP_EXTRA=2,CHIP_PAD_X_EXTRA=2,CHIP_LEAD=1.3,TITLE_TRACKING_EM=-.015;function QuickPrompts({pet:pet,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles16(theme),[theme]),prompts=useMemo(()=>resolveQuickPrompts(pet,theme.color.brandInk),[pet,theme.color.brandInk]),themed=useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]),title=emptyStateTitle(pet);/* @__PURE__ */
|
|
288
|
+
return jsxs(View,{style:styles2.block,children:[
|
|
289
|
+
/* @__PURE__ */jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:title}),
|
|
290
|
+
/* @__PURE__ */jsx(View,{style:styles2.list,accessibilityLabel:CHAT_COPY.suggestions,children:prompts.map((prompt,index)=>/* @__PURE__ */jsx(Chip,{prompt:prompt,themed:themed,index:index,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet,pet:pet,styles:styles2},prompt.id))})]})}function Chip({prompt:prompt,themed:themed,index:index,pet:pet,petRef:petRef,onSend:onSend,onVetPrep:onVetPrep,vet:vet,styles:styles2}){let motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index),risePx:motion.promptRisePx}),paint={backgroundColor:themed?.fill??prompt.background},label=themed===null?styles2.chipLabel:[styles2.chipLabel,{color:themed.ink}];return prompt.intent==="vet_report"?onVetPrep!==void 0?/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,styles2.chipEdge,paint],onPress:()=>{callHost(onVetPrep,pet)},children:/* @__PURE__ */jsx(Text,{tier:"compact",style:label,children:prompt.label})})}):petRef===null?null:/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(VetVisitButton,{entry:"chat",petRef:petRef,label:prompt.label,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:[styles2.chip,styles2.chipEdge,paint],labelStyle:label})}):/* @__PURE__ */jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,styles2.chipEdge,paint],onPress:()=>onSend(prompt.label),children:/* @__PURE__ */jsx(Text,{tier:"compact",style:label,children:prompt.label})})})}function makeStyles16(theme){let c=theme.color,s=theme.space,t=theme.type;return StyleSheet.create({block:{gap:s.lg,alignItems:"stretch",width:"100%"},title:{...face(theme,"medium"),fontSize:t.size.heading,lineHeight:Math.round(t.size.heading*t.lineHeight.snug),color:c.brandInk,letterSpacing:t.size.heading*TITLE_TRACKING_EM,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:s.sm+CHIP_GAP_EXTRA},chip:{borderRadius:theme.radius.pill,paddingHorizontal:s.lg+CHIP_PAD_X_EXTRA,paddingVertical:s.sm,minHeight:CHIP_MIN_HEIGHT,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:CHIP_EDGE_WIDTH,borderColor:withAlpha(c.brandInk,CHIP_EDGE_ALPHA)??c.borderRingCream},chipLabel:{...face(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*CHIP_LEAD),color:QUICK_PROMPT_TEXT_COLOR,textAlign:"left"}})}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor&&runs.push({kind:"text",text:text3.slice(cursor,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor=match.index+match[0].length}return cursor<text3.length&&runs.push({kind:"text",text:text3.slice(cursor)}),runs}function renderInlineMarkdown(text3,styles2){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
|
|
291
|
+
return jsx(Text,{style:styles2.bold,children:run.text},key);case"italic":return styles2.italic?/* @__PURE__ */jsx(Text,{style:styles2.italic,children:run.text},key):run.text;case"code":return styles2.code?/* @__PURE__ */jsx(Text,{style:styles2.code,children:run.text},key):run.text;default:return run.text}}):text3}function TypingIndicator({petName:petName=null}){let{styles:styles2}=useChatTheme(),line=forPet(CHAT_COPY.reading,petName);/* @__PURE__ */
|
|
292
|
+
return jsx(Text,{tier:"compact",style:styles2.readingLine,accessibilityRole:"text",accessibilityLabel:line,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:line})}function resolveTurnScrollTarget(assistantTop,userTop,inset){let replyTarget=assistantTop-inset,target=userTop!=null?Math.min(replyTarget,userTop):replyTarget;return Math.max(0,target)}function latestTurn(messages){let assistantIndex=messages.length-1,last=messages[assistantIndex];if(last===void 0||last.role!=="assistant")return null;let above=messages[assistantIndex-1];return{assistantIndex:assistantIndex,userIndex:above!==void 0&&above.role==="user"?assistantIndex-1:null}}function nextFollowOffset(anchor,current,maxOffset){let end=Math.max(0,maxOffset),target=anchor===null?end:Math.min(Math.max(0,anchor),end);return target>current+1?target:null}function useThreadFollow(rows,isStreaming){let ref=useRef(null),following=useRef(true),wasStreaming=useRef(isStreaming),offset=useRef(0),viewport=useRef(0),content=useRef(0),tops=useRef(/* @__PURE__ */new Map),turn=latestTurn(rows),assistantId=turn===null?null:rows[turn.assistantIndex]?.id??null,userId=turn===null||turn.userIndex===null?null:rows[turn.userIndex]?.id??null,follow=useCallback(()=>{let view=ref.current;if(view===null||!following.current||viewport.current===0)return;let anchor=null;if(assistantId!==null){let assistantTop=tops.current.get(assistantId);if(assistantTop===void 0)return;let userTop=userId===null?null:tops.current.get(userId)??null;anchor=resolveTurnScrollTarget(assistantTop,userTop,96)}let next=nextFollowOffset(anchor,offset.current,content.current-viewport.current);next!==null&&(offset.current=next,view.scrollTo({y:next,animated:false}))},[assistantId,userId]);useEffect(()=>{isStreaming&&!wasStreaming.current&&(following.current=true),wasStreaming.current=isStreaming,follow()},[rows,isStreaming,follow]);let onLayout=useCallback(event=>{viewport.current=event.nativeEvent.layout.height,follow()},[follow]),onContentSizeChange=useCallback((_width,height)=>{content.current=height,viewport.current>0&&(offset.current=Math.min(offset.current,Math.max(0,height-viewport.current))),follow()},[follow]),onScroll=useCallback(event=>{offset.current=event.nativeEvent.contentOffset.y},[]),onScrollBeginDrag=useCallback(()=>{following.current=false},[]),onScrollEnd=useCallback(event=>{let{contentOffset:contentOffset,contentSize:contentSize,layoutMeasurement:layoutMeasurement}=event.nativeEvent;offset.current=contentOffset.y,following.current=contentSize.height-contentOffset.y-layoutMeasurement.height<=24},[]),rowLayout=useCallback(id=>event=>{tops.current.set(id,event.nativeEvent.layout.y),(id===assistantId||id===userId)&&follow()},[assistantId,userId,follow]);return{ref:ref,onLayout:onLayout,onContentSizeChange:onContentSizeChange,onScroll:onScroll,onScrollBeginDrag:onScrollBeginDrag,onScrollEnd:onScrollEnd,rowLayout:rowLayout}}function renderView(view,chat,extras){switch(view){case"loading":return extras.renderPending?/* @__PURE__ */jsx(HostRender,{render:extras.renderPending,fallback:/* @__PURE__ */jsx(LoadingState,{})}):/* @__PURE__ */jsx(LoadingState,{});case"empty":/* @__PURE__ */
|
|
293
|
+
return jsx(EmptyState,{pet:extras.shownPet,petRef:chat.petRef,onSelectPrompt:extras.onSelectPrompt,onVetPrep:extras.onVetPrep,vet:extras.vet});case"error":/* @__PURE__ */
|
|
294
|
+
return jsx(ErrorState,{error:chat.error,onRetry:chat.retryLast,onAddPet:extras.onAddPet});case"populated":/* @__PURE__ */
|
|
295
|
+
return jsx(PopulatedState,{messages:chat.messages,prompts:visibleFollowUps(chat),onSelectPrompt:extras.onSelectPrompt,isStreaming:chat.isStreaming,onAnswerCheckin:chat.petRef?chat.answerCheckin:null,onCopy:extras.onCopy,sentimentByMessage:chat.sentimentByMessage,onSentiment:extras.onSentiment,thanksFor:extras.thanksFor,imagesByMessage:extras.imagesByMessage,onPreview:extras.onPreview,notice:extras.notice,reconnecting:chat.reconnecting===true,onRetry:chat.retryLast,onStartNew:chat.newConversation,petRef:chat.petRef,onFindVet:extras.onCheckinFindVet,vet:extras.vet,onOpenUrl:extras.onOpenUrl,petName:extras.shownPet?.name??null});default:return assertNever(view)}}function LoadingState(){let{theme:theme,styles:styles2}=useChatTheme(),[visible,setVisible]=useState(false);return useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsx(View,{style:styles2.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:CHAT_COPY.loading,children:visible?/* @__PURE__ */jsx(ActivityIndicator,{color:theme.color.brandInk}):null})}function EmptyState({pet:pet,petRef:petRef,onSelectPrompt:onSelectPrompt,onVetPrep:onVetPrep,vet:vet}){let{styles:styles2}=useChatTheme();
|
|
296
|
+
/* @__PURE__ */
|
|
297
|
+
return jsx(ScrollView,{contentContainerStyle:styles2.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,accessibilityLabel:CHAT_COPY.empty,children:/* @__PURE__ */jsx(QuickPrompts,{pet:pet,petRef:petRef,onSend:onSelectPrompt,onVetPrep:onVetPrep,vet:vet})})}function FollowUps({prompts:prompts,onSelectPrompt:onSelectPrompt}){let{styles:styles2}=useChatTheme();return prompts.length===0?null:/* @__PURE__ */jsxs(View,{style:styles2.followUps,children:[
|
|
298
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.followUpsHeading,accessibilityRole:"header",children:CHAT_COPY.followUpsHeadingNative}),prompts.map((prompt,index)=>/* @__PURE__ */jsx(FollowUpRow,{prompt:prompt,index:index,onSelectPrompt:onSelectPrompt},prompt))]})}function FollowUpRow({prompt:prompt,index:index,onSelectPrompt:onSelectPrompt}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index)});/* @__PURE__ */
|
|
299
|
+
return jsx(Animated.View,{style:fade,children:/* @__PURE__ */jsxs(PressScale,{onPress:()=>onSelectPrompt(prompt),accessibilityRole:"button",accessibilityLabel:prompt,containerStyle:[styles2.followUpSlot,index>0?styles2.followUpSlotRuled:null],style:styles2.followUpRow,children:[
|
|
300
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.followUpText,children:prompt}),
|
|
301
|
+
/* @__PURE__ */jsx(PlusGlyph,{size:FOLLOW_UP_PLUS,color:theme.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:error,onRetry:onRetry,onAddPet:onAddPet}){let{styles:styles2}=useChatTheme(),addPet=isPetNotRegistered(error)?guardHost(onAddPet):void 0;/* @__PURE__ */
|
|
302
|
+
return jsxs(View,{style:styles2.centered,accessible:true,accessibilityRole:"alert",children:[
|
|
303
|
+
/* @__PURE__ */jsx(Text,{style:styles2.errorText,children:error.displayMessage}),addPet!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:addPet,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addPet,style:styles2.retryButton,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.addPet})}):null,error.retryable?/* @__PURE__ */jsx(Pressable,{onPress:onRetry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,style:styles2.retryButton,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.retry})}):null]})}function PopulatedState({messages:messages,prompts:prompts,onSelectPrompt:onSelectPrompt,isStreaming:isStreaming,onAnswerCheckin:onAnswerCheckin,onCopy:onCopy,sentimentByMessage:sentimentByMessage,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:imagesByMessage,onPreview:onPreview,notice:notice,reconnecting:reconnecting,onRetry:onRetry,onStartNew:onStartNew,petRef:petRef,onFindVet:onFindVet,vet:vet,onOpenUrl:onOpenUrl,petName:petName}){let{styles:styles2}=useChatTheme(),motion=useChatMotion();useAnimateLayoutOn(messages.length,motion);let checkins=useMemo(()=>placeCheckins(messages),[messages]),awaiting=awaitingAssistant(messages,isStreaming),last=messages[messages.length-1],rows=useMemo(()=>messages.filter(message=>!(message.checkin&&checkins.get(message.id)?.kind==="folded")),[messages,checkins]),follow=useThreadFollow(rows,isStreaming),isEntering=useEnteringRows(rows);/* @__PURE__ */
|
|
304
|
+
return jsxs(ScrollView,{ref:follow.ref,style:styles2.list,contentContainerStyle:styles2.listContent,accessibilityLabel:CHAT_COPY.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,onLayout:follow.onLayout,onContentSizeChange:follow.onContentSizeChange,onScroll:follow.onScroll,scrollEventThrottle:SCROLL_EVENT_THROTTLE_MS,onScrollBeginDrag:follow.onScrollBeginDrag,onScrollEndDrag:follow.onScrollEnd,onMomentumScrollEnd:follow.onScrollEnd,children:[messages.map(message=>{let placement=message.checkin?checkins.get(message.id):void 0;return placement?.kind==="folded"?null:placement?.kind==="past"?/* @__PURE__ */jsx(CheckinPastAsk,{text:message.text,runDueDays:placement.runDueDays,openedAt:message.checkin?.openedAt,onLayout:follow.rowLayout(message.id)},message.id):message.checkin&&placement!==void 0?/* @__PURE__ */jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,petRef:petRef,onFindVet:onFindVet,vet:vet,onLayout:follow.rowLayout(message.id)},message.id):/* @__PURE__ */jsx(MessageRow,{onLayout:follow.rowLayout(message.id),message:message,revealing:isStreaming&&message===last&&message.role==="assistant",onCopy:onCopy,sentiment:message.responseId===void 0?null:sentimentByMessage[String(message.responseId)]??null,onSentiment:onSentiment,thanks:thanksFor!==null&&message.responseId!==void 0&&String(message.responseId)===thanksFor,images:imagesByMessage[message.id]??NO_IMAGES,onPreview:onPreview,onOpenUrl:onOpenUrl,entering:isEntering(message.id)},message.id)}),reconnecting?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.reconnectingCaption,accessibilityRole:"text",children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsx(TurnNoticeCard,{notice:notice,onRetry:onRetry,onStartNew:onStartNew}):null,
|
|
305
|
+
/* @__PURE__ */jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt})]})}function TurnNoticeCard({notice:notice,onRetry:onRetry,onStartNew:onStartNew}){let{styles:styles2}=useChatTheme(),error=notice.tone==="error";/* @__PURE__ */
|
|
306
|
+
return jsxs(View,{style:[styles2.turnNotice,error?styles2.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
|
|
307
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:[styles2.turnNoticeTitle,error?styles2.turnNoticeTitleError:null],children:notice.title}),
|
|
308
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.turnNoticeBody,children:notice.body}),
|
|
309
|
+
/* @__PURE__ */jsx(Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles2.turnNoticeAction,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,thanks:thanks,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),enter=useBubbleEnter(entering,motion),shown=useRevealedText(message.text,revealing,motion),isUser=message.role==="user",isVet=message.role==="vet",isAssistant=message.role==="assistant",namesAssistant=isAssistant&&!theme.meta.hidePoweredBy,sender=isUser?CHAT_COPY.senderUser:isVet?vetSenderLabel(message):namesAssistant?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,vetTime=isVet?formatMessageTime(message.createdAt):null,rate=useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true;/* @__PURE__ */
|
|
310
|
+
return jsxs(View,{style:[styles2.rowBlock,isUser?styles2.rowBlockUser:styles2.rowBlockAssistant],onLayout:onLayout,children:[
|
|
311
|
+
/* @__PURE__ */jsx(View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxs(Animated.View,{style:[styles2.bubble,isUser?styles2.bubbleSideUser:null,enter],children:[namesAssistant?/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.assistantName,children:CHAT_COPY.assistantName}):null,isVet?/* @__PURE__ */jsxs(View,{style:styles2.vetHeader,children:[
|
|
312
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.vetSender,children:sender}),vetTime!==null?/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.vetTime,children:vetTime}):null]}):null,
|
|
313
|
+
/* @__PURE__ */jsxs(View,{style:[isUser?styles2.bubbleUser:isVet?styles2.bubbleVet:styles2.bubbleAssistant,message.pending?styles2.bubblePending:null],children:[isUser&&images.length>0?/* @__PURE__ */jsx(SentImages,{images:images,onPreview:image=>onPreview({uri:image.uri,label:image.filename})}):null,
|
|
314
|
+
/* @__PURE__ */jsx(Text,{style:isUser?styles2.bubbleTextUser:isVet?styles2.bubbleTextVet:styles2.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles2.bubbleBold,italic:styles2.bubbleItalic,code:styles2.bubbleCode}):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled?/* @__PURE__ */jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,thanks:thanks}):null]})}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),DEFAULT_MAX_PER_MESSAGE=1;function EverfurChat(props){let{style:style,renderPending:renderPending}=props;/* @__PURE__ */
|
|
315
|
+
return jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(ChatBody,{...props})})}function ChatBody({petRef:petRef,conversationId:conversationId,style:style,renderPending:renderPending,onCopy:onCopy,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,attachments:attachments,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),chatOpts=useMemo(()=>buildChatOpts(petRef,conversationId),[petRef,conversationId]),chat=useEverfurChat(chatOpts),view=selectView(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=useSafeAreaInsets(),notice=turnNotice(chat),onCheckinFindVet=useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=useMemo(()=>vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer},[vetReturnTo,vetUsState,vetPrefer]),shownPet=headerPet(pets.pets,chat.petRef),urgencySource=useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion),useCheckinTarget(chat.openCheckin,checkinTarget),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]);useChatLifecycle(lifecycle,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refresh:chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=useState(null),closePreview=useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=useState(null),[thanksFor,setThanksFor]=useState(null),thanksTimer=useRef(null);useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showThanks=useCallback(responseId=>{setThanksFor(String(responseId)),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=setTimeout(()=>{setThanksFor(null),thanksTimer.current=null},THANKS_VISIBLE_MS)},[]),onSentiment=useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];chat.feedback(responseId,sentiment),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat]),submitReasons=useCallback(async(reason,notes)=>feedbackTarget===null||!(await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showThanks(feedbackTarget),true),[chat,feedbackTarget,showThanks]),skipReasons=useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=Platform.OS==="ios"?"padding":void 0,keyboard=useChatKeyboardOffset(keyboardVerticalOffset,avoidBehavior!==void 0),topInset=keyboard.topInWindow===null?insets.top:Math.max(0,insets.top-keyboard.topInWindow),keyboardOpen=useKeyboardOpen(),composerProps={send:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,onStage:sentImages.stage,onPreview:setPreview,petName:shownPet?.name??null};
|
|
316
|
+
/* @__PURE__ */
|
|
317
|
+
return jsxs(KeyboardAvoidingView,{style:[styles2.container,{paddingTop:topInset},style],behavior:avoidBehavior,...keyboard.avoidingProps,children:[
|
|
318
|
+
/* @__PURE__ */jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),
|
|
319
|
+
/* @__PURE__ */jsx(ChatHeader,{pets:pets,petRef:chat.petRef,historyUnread:historyUnread,onOpenHistory:history.show,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}),pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef??null,pet:pet,onRegistered:pets.refresh}):null,
|
|
320
|
+
/* @__PURE__ */jsx(UrgencyBanner,{surface:urgency,petRef:chat.petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:keyboardOpen}),
|
|
321
|
+
/* @__PURE__ */jsx(View,{style:styles2.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:sentImages.byMessage,onPreview:setPreview,onAddPet:onAddPet,onOpenUrl:openCitation})}),attachments!==void 0?/* @__PURE__ */jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsx(Composer,{...composerProps,attachments:null}),
|
|
322
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.footnote,accessibilityRole:"text",children:CHAT_COPY.footnoteNative}),theme.meta.hidePoweredBy?null:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),
|
|
323
|
+
/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history}),
|
|
324
|
+
/* @__PURE__ */jsx(FeedbackReasons,{visible:feedbackTarget!==null,onSubmit:submitReasons,onSkip:skipReasons}),
|
|
325
|
+
/* @__PURE__ */jsx(AttachmentImageLightbox,{uri:preview?.uri??null,label:preview?.label??"",onClose:closePreview}),
|
|
326
|
+
/* @__PURE__ */jsx(EverfurTelevetHost,{})]})}function PetSetupNotice({petRef:petRef,pet:pet,onRegistered:onRegistered}){let{styles:styles2}=useChatTheme(),setup=useChatPetRegistration(petRef,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxs(View,{style:styles2.setupNotice,accessible:true,accessibilityRole:"alert",children:[
|
|
327
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.setupNoticeText,children:setup.error.displayMessage}),
|
|
328
|
+
/* @__PURE__ */jsx(Pressable,{onPress:setup.retry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,hitSlop:TEXT_ACTION_HIT_SLOP,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.setupNoticeAction,children:CHAT_COPY.retry})})]})}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??DEFAULT_MAX_PER_MESSAGE,transport:transport}),bound=useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
|
|
329
|
+
return jsx(Composer,{...rest,attachments:bound})}function Composer({send:send,stop:stop,isStreaming:isStreaming,conversationId:conversationId,attachments:attachments,seed:seed,draftStore:draftStore,onStage:onStage,onPreview:onPreview,petName:petName}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId,seed);usePersistedDraft(draftStore,conversationId===null?null:String(conversationId),draft,setDraft);let[pickerOpen,setPickerOpen]=useState(false),[pickFailed,setPickFailed]=useState(false);useEffect(()=>{setPickFailed(false)},[conversationId]);let placeholder=theme.meta.placeholder??forPet(CHAT_COPY.placeholder,petName),uploading=attachments?.state.uploading??false,uploadFailed=attachments?.state.failed??false,sendBlocked=uploading||uploadFailed,rows=attachments?.state.attachments??NO_ROWS;useAnimateLayoutOn(rows.length,motion);let onSend=useCallback(()=>{if(draft.trim().length===0||sendBlocked||[...draft].length>MESSAGE_MAX_CHARS)return;let keys=attachments?.state.s3Keys??NO_KEYS;attachments!==null&&keys.length>0?(onStage(attachments.state.attachments.filter(row=>row.status==="uploaded").map(row=>({uri:row.previewUri,filename:row.filename}))),send(draft,{imageS3Keys:keys}),attachments.state.clear()):send(draft),setDraft(""),setPickFailed(false)},[draft,send,sendBlocked,attachments,onStage]),onStop=useCallback(()=>{stop()},[stop]),pickFrom=useCallback(source=>{setPickerOpen(false),attachments!==null&&(setPickFailed(false),attachments.state.dismissRejected(),callHostAsync(attachments.pick,source).then(outcome=>{if(!outcome.ok){setPickFailed(true);return}outcome.value!==null&&attachments.state.add(outcome.value)}))},[attachments]),sendDisabled=useMemo(()=>[...draft].length>MESSAGE_MAX_CHARS,[draft])||sendBlocked,slotsFull=attachments!==null&&rows.length>=attachments.state.maxPerMessage,sendInk=theme.slots.sendButton?.textColor??theme.color.brandInk;/* @__PURE__ */
|
|
330
|
+
return jsxs(View,{style:styles2.composerOuter,children:[attachments!==null&&pickerOpen?/* @__PURE__ */jsx(AttachmentPickerPopover,{sources:attachments.sources,full:slotsFull,onPick:pickFrom,onClose:()=>setPickerOpen(false)}):null,
|
|
331
|
+
/* @__PURE__ */jsxs(View,{style:styles2.composer,children:[attachments!==null?/* @__PURE__ */jsx(AttachmentStrip,{attachments:rows,rejected:pickFailed?PICK_FAILED:attachments.state.rejected,uploadFailed:uploadFailed,onRetry:attachments.state.retry,onRemove:attachments.state.remove,onPreview:row=>onPreview({uri:row.previewUri,label:row.filename})}):null,
|
|
332
|
+
/* @__PURE__ */jsxs(View,{style:styles2.composerRow,children:[attachments!==null?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:slotsFull?attachControlLabel(rows.length,attachments.state.maxPerMessage):CHAT_COPY.attachPhotoOrFileNative,accessibilityState:{disabled:slotsFull,expanded:pickerOpen},disabled:slotsFull,style:[styles2.attachControl,slotsFull?styles2.attachControlDisabled:null],onPress:()=>setPickerOpen(open=>!open),children:/* @__PURE__ */jsx(UploadGlyph,{size:ATTACH_GLYPH_SIZE,color:slotsFull?theme.color.text.muted:theme.color.brandInk,strokeWidth:1.75})}):null,
|
|
333
|
+
/* @__PURE__ */jsx(TextInput,{style:styles2.input,value:draft,onChangeText:setDraft,placeholder:placeholder,placeholderTextColor:theme.slots.composerInput?.textColor??theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.composerLabel,onSubmitEditing:onSend,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),isStreaming?/* @__PURE__ */jsx(Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles2.sendControl,children:/* @__PURE__ */jsx(View,{style:styles2.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsx(StopGlyph,{size:STOP_GLYPH_SIZE,color:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsx(Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles2.sendControl,sendDisabled?styles2.sendControlDisabled:null],children:/* @__PURE__ */jsx(View,{style:styles2.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */jsx(SendGlyph,{size:SEND_GLYPH_SIZE,color:sendInk,testID:"everfur-send-glyph"})})})]})]})]})}var NO_ROWS=/* @__PURE__ */Object.freeze([]),NO_KEYS=/* @__PURE__ */Object.freeze([]),PICK_FAILED=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});export{EverfurChat,createRnChatAttachmentTransport,useChatAttachments,useEverfurChat,useEverfurPets};
|