@everfur/sdk 0.5.1 → 0.5.3
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 +351 -0
- package/dist/BookedScreen-BJPbXLCG.d.ts +54 -0
- package/dist/BookedScreen-Cnld-jB_.d.cts +54 -0
- package/dist/{Chat-Rzplrf5M.d.ts → Chat-CNRZEu92.d.ts} +3 -3
- package/dist/{Chat-ypo6miKm.d.cts → Chat-a6If51cF.d.cts} +3 -3
- package/dist/{DepthViews-CeTfPUBX.d.ts → DepthViews-Bfv2DTUl.d.ts} +1 -1
- package/dist/{DepthViews-Cui3oonj.d.cts → DepthViews-Cl4AoL3X.d.cts} +1 -1
- package/dist/{DepthViews-ClykXOJj.d.cts → DepthViews-kURiusNd.d.cts} +1 -1
- package/dist/{DepthViews-baYLMNQ-.d.ts → DepthViews-zhn3Rk5Z.d.ts} +1 -1
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/{attachments-D3HCBmOE.d.ts → attachments-5_p7kE38.d.ts} +2 -2
- package/dist/{attachments-CwsR-bPN.d.cts → attachments-CHgc11hT.d.cts} +5 -5
- package/dist/{attachments-CzZ7in24.d.ts → attachments-TXOhN36S.d.ts} +5 -5
- package/dist/{attachments-Nk73Lll8.d.cts → attachments-affGN_Uv.d.cts} +2 -2
- package/dist/{bookingCopy-SDkXaxDf.d.ts → bookingCopy-BQ7Pg7qg.d.ts} +38 -200
- package/dist/{bookingCopy-Dv8rKqyV.d.cts → bookingCopy-BpZvZO1S.d.cts} +38 -200
- package/dist/bookingTypes-DCs8mmBb.d.cts +188 -0
- package/dist/bookingTypes-DCs8mmBb.d.ts +188 -0
- package/dist/{callCopy-rDH9JTFo.d.cts → callCopy-CPe9mbwG.d.cts} +7 -2
- package/dist/{callCopy-rDH9JTFo.d.ts → callCopy-CPe9mbwG.d.ts} +7 -2
- package/dist/{casesRepository-BTAecTnF.d.ts → casesRepository-YCI0OVwl.d.ts} +1 -1
- package/dist/{casesRepository-aryld7fJ.d.cts → casesRepository-z2JAFlKA.d.cts} +1 -1
- package/dist/chat/index.cjs +1 -1
- package/dist/chat/index.d.cts +14 -10
- package/dist/chat/index.d.ts +14 -10
- package/dist/chat/index.js +1 -1
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +6 -6
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +1 -1
- package/dist/{config-X6BtwDwQ.d.ts → config-BXVgTLCh.d.ts} +1 -1
- package/dist/{config-6qS7Sohy.d.cts → config-Bkbqkjb0.d.cts} +1 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/{context-7f3Nb_xE.d.ts → context-BVpOBDMe.d.ts} +5 -5
- package/dist/{context-CkqPM4Ml.d.cts → context-ChPrlKhy.d.cts} +5 -5
- package/dist/{copy-Bd__Pw5s.d.cts → copy-Be2H2i-D.d.cts} +2 -2
- package/dist/{copy-NgKgOOET.d.ts → copy-SxmZ-Eps.d.ts} +2 -2
- package/dist/core/index.cjs +5 -5
- package/dist/core/index.d.cts +12 -12
- package/dist/core/index.d.ts +12 -12
- package/dist/core/index.js +5 -5
- package/dist/{depth-CYPH92jE.d.ts → depth-By8dFpLA.d.ts} +2 -2
- package/dist/{depth-CyjaJJ6V.d.cts → depth-Dne8Qoss.d.cts} +2 -2
- package/dist/{entitlementRepository-DdeFuEKp.d.ts → entitlementRepository-Big-K_In.d.ts} +2 -2
- package/dist/{entitlementRepository-Dl1qRLcJ.d.cts → entitlementRepository-BmghvtGT.d.cts} +2 -2
- package/dist/{identity-Dy_L7Yq4.d.ts → identity-AuoeDRTh.d.ts} +1 -1
- package/dist/{identity-DjqhDm5Z.d.cts → identity-Z0yj-fC_.d.cts} +1 -1
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +13 -13
- package/dist/index.d.ts +13 -13
- package/dist/index.js +6 -6
- package/dist/notifications/index.d.cts +2 -2
- package/dist/notifications/index.d.ts +2 -2
- package/dist/{pets-BSG2qbr_.d.cts → pets-DfXGYmMk.d.cts} +1 -1
- package/dist/{pets-D7cZutrX.d.ts → pets-FD-5nMXr.d.ts} +1 -1
- package/dist/{petsRepository-DhsX3GLw.d.ts → petsRepository-BaTOwJ5L.d.ts} +1 -1
- package/dist/{petsRepository-D1bnxDZg.d.cts → petsRepository-CsvreWlY.d.cts} +1 -1
- package/dist/{ports-C0m1G1fS.d.ts → ports-DNIvfzBP.d.ts} +16 -5
- package/dist/{ports-DNXyyzZF.d.cts → ports-Dof7AQjk.d.cts} +16 -5
- package/dist/records/depth/index.d.cts +7 -7
- package/dist/records/depth/index.d.ts +7 -7
- package/dist/records/index.cjs +3 -3
- package/dist/records/index.d.cts +10 -10
- package/dist/records/index.d.ts +10 -10
- package/dist/records/index.js +3 -3
- package/dist/{requestFunnel-FvE5yLDD.d.ts → requestFunnel-CJC_q4BZ.d.ts} +2 -2
- package/dist/{requestFunnel-Bqc1inM9.d.cts → requestFunnel-DrigK6q_.d.cts} +2 -2
- package/dist/{runtimeTypes-C0yPBz89.d.ts → runtimeTypes-BiqMY6pC.d.ts} +4 -4
- package/dist/{runtimeTypes-RN-VXTFV.d.cts → runtimeTypes-Doj95Gll.d.cts} +4 -4
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.d.cts +2 -2
- package/dist/server/events/index.d.ts +2 -2
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +2 -2
- package/dist/televet/booking/index.cjs +1 -1
- package/dist/televet/booking/index.d.cts +17 -9
- package/dist/televet/booking/index.d.ts +17 -9
- package/dist/televet/booking/index.js +1 -1
- package/dist/televet/call/index.cjs +1 -1
- package/dist/televet/call/index.d.cts +13 -1
- package/dist/televet/call/index.d.ts +13 -1
- package/dist/televet/call/index.js +1 -1
- package/dist/televet/index.cjs +1 -1
- package/dist/televet/index.js +1 -1
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/rn/index.d.cts +7 -7
- package/dist/testing/rn/index.d.ts +7 -7
- package/dist/testing/web/index.d.cts +7 -7
- package/dist/testing/web/index.d.ts +7 -7
- package/dist/{timelineRows-D4U6A8zE.d.ts → timelineRows-BHA0gIKH.d.ts} +1 -1
- package/dist/{timelineRows-DAB5dpjF.d.cts → timelineRows-CHeqZRpM.d.cts} +1 -1
- package/dist/{uploadTransport-DKJHs3Yj.d.cts → uploadTransport-C1p8FuG8.d.cts} +5 -1
- package/dist/{uploadTransport-D0M0T4hN.d.ts → uploadTransport-bZIKBTyK.d.ts} +5 -1
- package/dist/{useRecordsDepth--ObtMyjH.d.ts → useRecordsDepth-CG63cXFZ.d.ts} +1 -1
- package/dist/{useRecordsDepth-B35y8bV-.d.cts → useRecordsDepth-ChhS4c6r.d.cts} +1 -1
- package/dist/{view-B-Toym_j.d.cts → view-2pXv8ex7.d.cts} +7 -4
- package/dist/{view-D9JqNQai.d.ts → view-BKy44Q-3.d.ts} +7 -4
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/index.cjs +10 -10
- package/dist/web/index.d.cts +14 -14
- package/dist/web/index.d.ts +14 -14
- package/dist/web/index.js +10 -10
- package/dist/web/notifications/index.d.cts +3 -3
- package/dist/web/notifications/index.d.ts +3 -3
- package/dist/web/records/depth/index.d.cts +7 -7
- package/dist/web/records/depth/index.d.ts +7 -7
- package/dist/web/records/index.cjs +3 -3
- package/dist/web/records/index.d.cts +9 -9
- package/dist/web/records/index.d.ts +9 -9
- package/dist/web/records/index.js +3 -3
- package/dist/web/televet/booking/index.cjs +2 -2
- package/dist/web/televet/booking/index.d.cts +35 -50
- package/dist/web/televet/booking/index.d.ts +35 -50
- package/dist/web/televet/booking/index.js +2 -2
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.d.cts +12 -5
- package/dist/web/televet/call/index.d.ts +12 -5
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +4 -1
- package/dist/web/televet/index.d.cts +31 -2
- package/dist/web/televet/index.d.ts +31 -2
- package/dist/web/televet/index.js +4 -1
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {createContext,forwardRef,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useReducer,useLayoutEffect,Component}from'react';import {useSafeAreaInsets,SafeAreaProvider}from'react-native-safe-area-context';import {z}from'zod';import ah from'react-native-sse';import {StyleSheet,TextInput,View,Linking,KeyboardAvoidingView,Platform,Pressable,useColorScheme,AccessibilityInfo,PixelRatio,Dimensions,Text,Animated,UIManager,LayoutAnimation,Modal,Image,ActivityIndicator,ScrollView,useWindowDimensions,FlatList}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var nf=Object.defineProperty;var i=(e,t)=>nf(e,"name",{value:t,configurable:true});function Re(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(Re,"hasLoneSurrogate");function it(e){return [...e].length}i(it,"serverLength");function M(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(M,"ok");function v(e){return Object.freeze({ok:false,error:e})}i(v,"err");function of(e){return e.ok}i(of,"isOk");function sf(e){return !e.ok}i(sf,"isErr");var Or=class Or extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,Or.prototype);}};i(Or,"EverfurThrownError");var Ar=Or;function af(e){if(e.ok)return e.value;throw new Ar(e.error)}i(af,"unwrap");var Fr=class Fr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fr.prototype);}};i(Fr,"EverfurConfigError");var Q=Fr;var os=128,is=128,ss=/[\u0000-\u001F\u007F]/,lf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uf(e){let t=e,r=it(t);if(r===0||r>is)throw new Q("invalid-argument",`petRef must be 1..${is} characters`);if(ss.test(t))throw new Q("invalid-argument","petRef must be printable (no control characters)");return t}i(uf,"petRef");function df(e){let t=e,r=it(t);if(r===0||r>os)throw new Q("invalid-argument",`userRef must be 1..${os} characters`);if(t.includes("@"))throw new Q("invalid-argument","userRef must not contain '@'");if(ss.test(t))throw new Q("invalid-argument","userRef must be printable (no control characters)");return t}i(df,"userRef");function cf(e){if(!lf.test(e))throw new Q("invalid-argument","conversationId must be a UUID");return e}i(cf,"conversationId");var Vn=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(Vn.map(e=>e.wireCode));var pf=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"}),ls=Object.freeze(Vn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:pf[e.wireCode]}))),ff=new Map(ls.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),mf=Object.freeze(["http_envelope",...[...new Set(ls.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Mr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...mf]){let o=ff.get(n+r);if(o)return o}}i(Mr,"contractErrorFor");function yf(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(yf,"contractDocUrl");function us(e){return null}i(us,"publishedDocUrl");var gf=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 Hn(e){return gf[e]}i(Hn,"categoryFor");function Ae(e){let t=Mr(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(Ae,"fromWire");function ds(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(ds,"fromHttpStatus");var hf=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function He(e){return hf.has(e)}i(He,"isAutoRetryable");var bf=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Bn(e){return He(e)||bf.has(e)}i(Bn,"isRetryableCode");function Lr(e,t=false){return t||He(e)}i(Lr,"shouldRetry");var vf=500,zn=8e3,Yt=4;function Dr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(vf*2**r,zn);return Math.floor(t()*n)}i(Dr,"backoffDelayMs");function cs(e){return e==="conversationNotFound"}i(cs,"canRecreateOnNotFound");var Cf=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 It(e){return Cf[e]}i(It,"userFacingError");function ps(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(ps,"defineHidden");var Ef=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Mr(t?.wireCode,t?.wireEnvelope),n={code:e,category:Hn(e),retryable:t?.retryable??Bn(e),displayMessage:It(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Ef.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&ps(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ps(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");var Rf="file",Sf="document.pdf",Tf="records upload: the file handle has no uri",Pf="records upload failed";function kf(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Tf));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Pf)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(Rf,{uri:r.uri,name:Sf,type:"application/pdf"});let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(kf,"createRnRecordsUploadTransport");var Nr=Object.freeze({track(){},trackExpectedFailure(){}});var fs=Object.freeze({shouldRetry(e,t){return He(e)&&t<Yt},maxAttempts(){return Yt}});var ms=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Xe(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Xe,"assertNever");function ys(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ys,"acceptedFrame");function gs(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(gs,"heartbeatFrame");function hs(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(hs,"deltaFrame");function bs(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(bs,"doneFrame");function pe(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(pe,"errorFrame");function vs(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(vs,"analysisStartedFrame");function Cs(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Cs,"analysisCompleteFrame");function Es(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Es,"unknownFrame");function Rs(e,t,r){let n=null,o=null,s=false,a=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new Q("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:wf(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new Q("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:a()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(Rs,"createIdentityProvider");function wf(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(wf,"expiryMs");function Wn(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(Wn,"newSessionId");function If(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(If,"authHeaders");function Xt(e,t){return {...e,headers:{...Af(e.headers),...If(t)}}}i(Xt,"withAuthHeaders");function Af(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(Af,"stripAuthHeaders");async function Ss(e,t){if(t.mode==="anonymous")return t.transport.request(Xt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return v(jn())}let n=await t.transport.request(Xt(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 v(jn())}let s=await t.transport.request(Xt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?v(jn(s.error.httpStatus)):s}i(Ss,"authedSend");function jn(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(jn,"authRejectedError");var Ts=`
|
|
1
|
+
import {createContext,forwardRef,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useReducer,useLayoutEffect,Component}from'react';import {useSafeAreaInsets,SafeAreaProvider}from'react-native-safe-area-context';import {z}from'zod';import vh from'react-native-sse';import {StyleSheet,TextInput,View,Linking,KeyboardAvoidingView,Platform,Pressable,useColorScheme,AccessibilityInfo,PixelRatio,Dimensions,Text,Animated,UIManager,LayoutAnimation,Modal,Image,ActivityIndicator,ScrollView,useWindowDimensions,FlatList}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var ff=Object.defineProperty;var i=(e,t)=>ff(e,"name",{value:t,configurable:true});function Re(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(Re,"hasLoneSurrogate");function st(e){return [...e].length}i(st,"serverLength");function L(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(L,"ok");function v(e){return Object.freeze({ok:false,error:e})}i(v,"err");function mf(e){return e.ok}i(mf,"isOk");function yf(e){return !e.ok}i(yf,"isErr");var Mr=class Mr extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,Mr.prototype);}};i(Mr,"EverfurThrownError");var Fr=Mr;function gf(e){if(e.ok)return e.value;throw new Fr(e.error)}i(gf,"unwrap");var Lr=class Lr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Lr.prototype);}};i(Lr,"EverfurConfigError");var Q=Lr;var ss=128,as=128,ls=/[\u0000-\u001F\u007F]/,hf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function bf(e){let t=e,r=st(t);if(r===0||r>as)throw new Q("invalid-argument",`petRef must be 1..${as} characters`);if(ls.test(t))throw new Q("invalid-argument","petRef must be printable (no control characters)");return t}i(bf,"petRef");function vf(e){let t=e,r=st(t);if(r===0||r>ss)throw new Q("invalid-argument",`userRef must be 1..${ss} characters`);if(t.includes("@"))throw new Q("invalid-argument","userRef must not contain '@'");if(ls.test(t))throw new Q("invalid-argument","userRef must be printable (no control characters)");return t}i(vf,"userRef");function Ef(e){if(!hf.test(e))throw new Q("invalid-argument","conversationId must be a UUID");return e}i(Ef,"conversationId");var zn=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(zn.map(e=>e.wireCode));var Cf=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"}),ds=Object.freeze(zn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Cf[e.wireCode]}))),Rf=new Map(ds.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Sf=Object.freeze(["http_envelope",...[...new Set(ds.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Dr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...Sf]){let o=Rf.get(n+r);if(o)return o}}i(Dr,"contractErrorFor");function Tf(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Tf,"contractDocUrl");function cs(e){return null}i(cs,"publishedDocUrl");var Pf=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 jn(e){return Pf[e]}i(jn,"categoryFor");function Oe(e){let t=Dr(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(Oe,"fromWire");function ps(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(ps,"fromHttpStatus");var kf=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Be(e){return kf.has(e)}i(Be,"isAutoRetryable");var xf=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Wn(e){return Be(e)||xf.has(e)}i(Wn,"isRetryableCode");function Nr(e,t=false){return t||Be(e)}i(Nr,"shouldRetry");var _f=500,Gn=8e3,Jt=4;function Ur(e,t=Math.random){let r=Math.max(0,e),n=Math.min(_f*2**r,Gn);return Math.floor(t()*n)}i(Ur,"backoffDelayMs");function fs(e){return e==="conversationNotFound"}i(fs,"canRecreateOnNotFound");var wf=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 Ft(e){return wf[e]}i(Ft,"userFacingError");function ms(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(ms,"defineHidden");var If=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Dr(t?.wireCode,t?.wireEnvelope),n={code:e,category:jn(e),retryable:t?.retryable??Wn(e),displayMessage:Ft(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&If.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&ms(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ms(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");var Af="file",Kn="multipart upload failed";function Vr(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Af,e.file);}catch{return Promise.reject(new Error(Kn))}return e.fetch!==void 0?Mf(e.fetch,e.url,t,e.signal):Ff(e.url,t,e.signal)}i(Vr,"postRnMultipart");function Of(e){return e>=200&&e<300}i(Of,"stored");function Ff(e,t,r){return new Promise((n,o)=>{let s=globalThis.XMLHttpRequest;if(typeof s!="function"||r?.aborted===true){o(new Error(Kn));return}let a=null,l=i(()=>{a!==null&&r?.removeEventListener("abort",a);},"release"),u=i(()=>{l(),o(new Error(Kn));},"fail");try{let d=new s;d.open("POST",e),d.withCredentials=!1,d.onload=()=>{l(),n(Of(d.status));},d.onerror=u,d.ontimeout=u,d.onabort=u,r!==void 0&&(a=i(()=>{try{d.abort();}finally{u();}},"onAbort"),r.addEventListener("abort",a,{once:!0})),d.send(t);}catch{u();}})}i(Ff,"postWithXhr");function Mf(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(o=>o.ok)}i(Mf,"postWithFetch");var Lf="document.pdf",Df="records upload: the file handle has no uri",Nf="records upload failed";function Uf(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Df));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Nf)),"failed");return o?.aborted===true?a():Vr({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:Lf,type:"application/pdf"},signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(Uf,"createRnRecordsUploadTransport");var Hr=Object.freeze({track(){},trackExpectedFailure(){}});var ys=Object.freeze({shouldRetry(e,t){return Be(e)&&t<Jt},maxAttempts(){return Jt}});var gs=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Qe(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Qe,"assertNever");function hs(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(hs,"acceptedFrame");function bs(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(bs,"heartbeatFrame");function vs(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(vs,"deltaFrame");function Es(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(Es,"doneFrame");function pe(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(pe,"errorFrame");function Cs(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Cs,"analysisStartedFrame");function Rs(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Rs,"analysisCompleteFrame");function Ss(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Ss,"unknownFrame");function Ts(e,t,r){let n=null,o=null,s=false,a=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new Q("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:Bf(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new Q("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:a()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(Ts,"createIdentityProvider");function Bf(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(Bf,"expiryMs");function $n(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i($n,"newSessionId");function zf(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(zf,"authHeaders");function er(e,t){return {...e,headers:{...jf(e.headers),...zf(t)}}}i(er,"withAuthHeaders");function jf(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(jf,"stripAuthHeaders");async function Ps(e,t){if(t.mode==="anonymous")return t.transport.request(er(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return v(qn())}let n=await t.transport.request(er(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 v(qn())}let s=await t.transport.request(er(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?v(qn(s.error.httpStatus)):s}i(Ps,"authedSend");function qn(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(qn,"authRejectedError");var ks=`
|
|
2
2
|
|
|
3
|
-
`,
|
|
3
|
+
`,Wf=1048576,Gf=z.record(z.string(),z.unknown()),Kf=["emergency","schedule_soon","home_care"];async function*Br(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",a=0,l=false;for await(let u of e){for(s+=o.decode(u,{stream:true});;){let d=s.indexOf(ks,a);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+ks.length),a=0;let p=xs(c,n());if(p!==null&&(p.kind==="delta"&&(l=true),yield p,p.terminal))return}if(a=s.length>0?s.length-1:0,s.length>Wf){yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let u=xs(s,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Br,"parseSse");function xs(e,t){let r=null,n=[];for(let a of e.split(`
|
|
4
4
|
`)){let l=a.replace(/\s+$/,"");l.length===0||l.startsWith(":")||(l.startsWith("id:")?r=l.slice(3).trim():l.startsWith("data:")&&n.push(l.slice(5).replace(/^ /,"")));}if(n.length===0)return null;let o;try{o=JSON.parse(n.join(`
|
|
5
|
-
`));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=
|
|
5
|
+
`));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=Gf.safeParse(o);return s.success?qf(s.data,r,t):null}i(xs,"parseBlock");function qf(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return pe({code:le(e.code)??"unknown",retryable:e.retryable===true,wireMessage:le(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Es({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:Xf(e.follow_up_questions),citations:_s(e.citations),citationStatus:le(e.citation_status),urgencyLevel:ws(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:Yf(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return hs(le(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return bs(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=le(e.delta)??le(e.token)??"";return vs(s,t,r)}return o==="analysis_started"?Cs(le(e.request_id),t,r):o==="analysis_complete"?Rs({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:$f(e.confidence),detections:_s(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):Ss(e,t,r)}i(qf,"frameFromWire");function le(e){return typeof e=="string"?e:null}i(le,"asString");function $f(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i($f,"asNumber");function ws(e){return typeof e=="string"&&Kf.includes(e)?e:null}i(ws,"asUrgency");function Yf(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||ws(t)!==null}i(Yf,"urgencySlotProvided");function Xf(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Xf,"asStringList");function Qf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Qf,"isPlainObject");function _s(e){return Array.isArray(e)?e.filter(Qf):[]}i(_s,"asMapList");var Zf="0.5.3",Jf="react-native",em="2026-09-19",Is="EVERFUR_API_BASE_URL";function tr(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(tr,"configFailure");function Xn(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(Xn,"checkPublishableKey");function As(e,t){let r=Xn(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=tm(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||em;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Zf,platform:t?.platform??Jf,debug:e.debug===true})})}i(As,"tryResolveClientConfig");function tm(e){let t=e?.trim(),r=t&&t.length>0?t:um(Is);return r?am(r):tr("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Is}. The SDK never ships a hardcoded host.`)}i(tm,"tryResolveApiBaseUrl");function Os(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(Os,"buildBaseHeaders");var rm=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function nm(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(nm,"hostOf");function om(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(om,"isPrintableHost");function im(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:om(t)}i(im,"canEchoOrigin");function sm(e,t){return `${e}://${t}`}i(sm,"safeOrigin");function am(e){let t=e.trim(),r=rm.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return tr("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=nm(r[2]);if(o.length===0)return tr("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=im(t,o)?`: ${sm(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&lm(o)))return n==="http"?tr("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):tr("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let a=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:a})}i(am,"normalizeBaseUrl");function lm(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(lm,"isLoopbackHost");function um(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(um,"readEnv");var dm=3e4,Ds="x-request-id";async function*Fs(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(Fs,"fetchByteSource");function cm(e){let t=new TextEncoder,r=fm(),n=false,o=i(u=>{let d="";u.lastEventId&&(d+=`id: ${u.lastEventId}
|
|
6
6
|
`);let c=u.data??"";for(let p of c.split(`
|
|
7
7
|
`))d+=`data: ${p}
|
|
8
8
|
`;d+=`
|
|
9
|
-
`,r.push(t.encode(d));},"onMessage"),s=i(()=>{l(),r.end();},"onDone"),a=i(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let c=
|
|
9
|
+
`,r.push(t.encode(d));},"onMessage"),s=i(()=>{l(),r.end();},"onDone"),a=i(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let c=Vs(d),p=Be(Oe(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:p})}
|
|
10
10
|
|
|
11
|
-
`));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",a);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",a);try{e.close();}catch{}}}return i(l,"cleanup"),em(r.source,l)}i(Jf,"eventSourceByteSource");async function*em(e,t){try{yield*e;}finally{t();}}i(em,"sourceWithCleanup");function tm(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(a=>{r=a;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(tm,"createByteQueue");async function rm(e,t){let r=t.fetchImpl??Us(),n=Vs(t.config.apiBaseUrl,e.path,e.query),o=Hs(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=lm(Zf),a=um(s.signal,e.signal),l;try{l=await r(n,Bs({...e,signal:a},o));}catch(d){return v(qn(d))}finally{s.cancel();}let u=await zs(l);return l.ok?M(u):v(im(l.status,u,Ds(l)))}i(rm,"requestJson");function Ls(e){return {request:i(t=>rm(t,e),"request"),stream:i((t,r)=>nm(am(t,r),e),"stream")}}i(Ls,"createHttpTransport");async function*nm(e,t){let r=Vs(t.config.apiBaseUrl,e.path,e.query),n=Hs(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,om(e,n));yield*Ur(Jf(l),()=>sm(l));return}let o=t.fetchImpl??Us(),s;try{s=await o(r,Bs(e,n));}catch(l){yield Os("",true,Ks(l));return}let a=Ds(s);if(!s.ok){let l=await zs(s),u=js(l)??Ns(s.status),d=Gs(l)||He(Ae(u));yield Os(u,d,Ws(l),a);return}if(s.body){yield*Ur(As(s.body),a);return}yield*Ur(As(null),a);}i(nm,"streamFrames");function om(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(om,"buildEventSourceInit");function im(e,t,r){let n=js(t),o=n?Ae(n):ds(e),s=Ws(t);return D(o,{httpStatus:e,...Gs(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Fs(t)?{reasonCode:Fs(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(im,"errorFromResponse");function qn(e){return D("internalError",{retryable:true,wireMessage:Ks(e)})}i(qn,"networkError");function Ds(e){let t=e.headers.get(Ms);return typeof t=="string"&&t.length>0?t:null}i(Ds,"requestIdOf");function sm(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Ms);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(sm,"eventSourceRequestId");function Ns(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(Ns,"statusToWireCode");function Os(e,t,r,n=null){return pe({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(Os,"syntheticErrorFrame");function Us(){let e=globalThis.fetch;if(typeof e!="function")throw new Q("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Us,"getGlobalFetch");function Vs(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(a=>a[1]!==void 0).map(([a,l])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(l))}`).join("&");s&&(o+=`?${s}`);}return o}i(Vs,"buildUrl");function Hs(e,t,r,n){let o={...Is(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Hs,"mergeHeaders");function Bs(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(Bs,"buildInit");function am(e,t){return e.signal?e:{...e,signal:t}}i(am,"withSignal");function lm(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(lm,"timeoutSignal");function um(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(um,"mergeAbortSignals");async function zs(e){try{return await e.json()}catch{return null}}i(zs,"safeJson");function Fs(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Fs,"extractReasonCode");function js(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(js,"extractWireCode");function Ws(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Ws,"extractWireMessage");function Gs(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Gs,"extractRetryable");function Ks(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Ks,"describeCause");var dm=3e4,cm=zn*2,pm="idempotency-key",fm=new Set(["POST","PUT","PATCH","DELETE"]),mm=Object.freeze({onEvent(){}}),ym=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function gm(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(gm,"seededIdempotencyKey");function ke(e){let t=e.observer??mm,r=e.timers??ym,n=e.rng??Math.random,o=e.sleep??((f,m)=>Im(f,r,m)),s=e.maxAttempts??Yt,a=e.unaryTimeoutMs??dm,l=e.newIdempotencyKey??bm(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,y){let k=y?.maxAttempts,g=Math.max(1,k??s),R=y?.idempotent??fm.has(m.method),w=y?.idempotencyKey===void 0?null:gm(y.idempotencyKey),_=R?w??l():null,x=hm(m,_),b=0;for(;;){let P=i(j=>Object.freeze({call:f,method:m.method,path:m.path,attempt:b,..._?{idempotencyKey:_}:{},...j}),"stamp");u(P({phase:"attempt"}));let L=_m(a,r),I=wm(L.signal,m.signal),S;try{S=await Ss({...x,signal:I.signal},e.auth);}catch(j){S=v(qn(j));}finally{I.dispose(),L.cancel();}if(S.ok)return u(P({phase:"settled",ok:true,reason:"ok"})),S;let O=S.error,T=Cm(O,b,{maxAttempts:g,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...k!==void 0?{perCallMaxAttempts:k}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),V={ok:false,code:O.code,reason:T.reason,...O.httpStatus!==void 0?{httpStatus:O.httpStatus}:{},...O.requestId!==void 0?{requestId:O.requestId}:{}};if(!T.retry)return u(P({phase:"settled",...V})),v(O);if(u(P({phase:"retry",...V,delayMs:T.delayMs})),await o(T.delayMs,m.signal),m.signal?.aborted===true)return u(P({phase:"settled",...V,reason:"aborted"})),v(O);b+=1;}}i(d,"send");async function c(f){return Xt(f,await xm(e.auth))}i(c,"authorize");async function*p(f,m,y){u(Object.freeze({call:f,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,y);}catch{yield pe({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(ke,"createRequestFunnel");function hm(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==pm&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(hm,"assembleHeaders");function bm(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(bm,"defaultIdempotencyKeyFactory");var vm=10;function Cm(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Em(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!He(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 d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(vm,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=Rm(e,r.now);return u!==null?u>cm?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Dr(t,r.rng)}}i(Cm,"decideRetry");function Em(e){let t=e.code==="unknown"?Ae(km(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Em,"throttleKind");function Rm(e,t){let r=Tm(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=Sm(e.raw);return n===null?null:Math.round(n*1e3)}i(Rm,"retryOverrideMs");function Sm(e){for(let t of $n(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(Sm,"findRetryAfterSeconds");function Tm(e){for(let t of $n(e)){let r=t.resets_at,n=Pm(r);if(n!==null)return n}return null}i(Tm,"findResetsAt");function $n(e){if(!qs(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];qs(n)&&t.push(n);}return t}i($n,"candidateScopes");function Pm(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(Pm,"parseInstantMs");function km(e){for(let t of $n(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(km,"rawWireCode");function qs(e){return typeof e=="object"&&e!==null}i(qs,"isRecord");async function xm(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(xm,"resolveDeviceAuth");function _m(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(_m,"boundedSignal");function wm(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(wm,"mergeSignals");function Im(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(Im,"delayAbortable");var Vr=Object.freeze(["better","same","worse"]),Xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $s(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i($s,"invalid");function Yn(){return v(D("internalError",{retryable:false}))}i(Yn,"malformed");function Ys(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Re(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Ys,"petPath");var Be=i(e=>typeof e=="string"?e:null,"str"),Xs=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function Qs(e){if(typeof e!="object"||e===null)return null;let t=e,r=Be(t.case_id),n=Be(t.status);if(r===null||n===null)return null;let o=Be(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Be(t.body_location),lastResponse:o!==null&&Vr.includes(o)?o:null,checkInDueAt:Be(t.check_in_due_at),openedAt:Be(t.opened_at),resolvedAt:Be(t.resolved_at),resolutionText:Be(t.resolution_text),checkinAskCount:Xs(t.checkin_ask_count),checkinAnswerCount:Xs(t.checkin_answer_count)})}i(Qs,"caseFromWire");function Zs(e){return {async list(t,r){let n=Ys(t);if(typeof n!="string")return v(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return v(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return Yn();let a=s.map(Qs);return a.every(l=>l!==null)?M(Object.freeze(a)):Yn()},async checkin(t,r,n,o){let s=Ys(t);if(typeof s!="string")return v(s);if(typeof r!="string"||!Xn.test(r))return $s("case_id must be a UUID");if(!Vr.includes(n))return $s("response must be one of better, same, worse");let a=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!a.ok)return v(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=Qs(l.case);return u===null?Yn():M(Object.freeze({case:u,ctaDeepLink:Be(l.cta_deep_link)}))}}}i(Zs,"createCasesRepositoryOver");var Js=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ea=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Br(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(Br,"delayAbortable");function zr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(zr,"mergeSignals");var Qn=class Qn{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?zr(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(Qn,"MediaStore");var Hr=Qn;function Jn(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(Jn,"makeUser");function eo(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(eo,"makeAssistant");function Jt(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(Jt,"stripPending");function ta(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(ta,"appendText");function to(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(to,"finalizeAssistant");function ra(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(ra,"freezeSnapshot");function U(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function ro(e){let t=Ae(e.code);return D(t,{retryable:e.retryable||Lr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(ro,"errorFromFrame");function Oe(e){return pe({code:Am(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Oe,"synthErrorFrame");function Am(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Xe(e)}}i(Am,"canonicalWireCode");function na(e){let t=Array.isArray(e)?e:Zn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!Zn(n))continue;let o=Zt(n.category)??Zt(n.title)??"",s=Om(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(na,"parsePromptCategories");function no(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(no,"flattenPrompts");function Zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Zn,"isPlainObject");function Zt(e){return typeof e=="string"?e:null}i(Zt,"asStr");function Om(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Zn(r)){let n=Zt(r.text)??Zt(r.prompt)??Zt(r.title);n!==null&&t.push(n);}return t}i(Om,"asPromptTextList");function oa(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(oa,"defaultIdFactory");function ia(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(ia,"defaultIdempotencyFactory");var aa={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*la(e,t,r,n){let o=e[Symbol.asyncIterator](),s=sa(t.overallMs,n),a=sa(t.idleMs,n),l=Lm(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([u,a.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Mm();return}if(d.tag==="idle"||d.tag==="overall"){yield Fm();return}let c=d.value;if(c.done||(a.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{a.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(la,"withWatchdog");function Fm(){return pe({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Fm,"synthTimeoutFrame");function Mm(){return pe({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Mm,"synthStreamErrorFrame");function sa(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(sa,"deadline");function Lm(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Lm,"abortPromise");var Dm="checkin",Nm=/^\d{4}-\d{2}-\d{2}$/,jr="watching";function ua(e){return e.status!=null&&e.status!==jr}i(ua,"isCheckinSettled");function da(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(da,"isLiveAskAnswered");function oo(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Dm||n===void 0||o===void 0||!Xn.test(n)||!Nm.test(o)?null:{caseId:n,dueDay:o}}i(oo,"parseCheckinOrigin");function ca(e){return oo(e)?.caseId??null}i(ca,"parseCheckinOriginRef");function io(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return v(D("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Re(o))return v(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),M(r.length?`?${r.join("&")}`:"")}i(io,"historyQuery");function rr(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(rr,"validConversationId");function tr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(tr,"object");function pa(e){return e==null||typeof e=="string"&&e.length>0&&!Re(e)}i(pa,"cursor");function er(){return v(D("internalError",{retryable:false}))}i(er,"malformed");function fa(e){let t=tr(e);if(!t||!Array.isArray(t.conversations)||!pa(t.next_cursor))return er();let r=[];for(let n of t.conversations){let o=tr(n);if(!o||typeof o.conversation_id!="string"||!rr(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return er();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return er();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return M(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(fa,"mapConversationPage");function ma(e){let t=tr(e);if(!t||!Array.isArray(t.messages)||!pa(t.next_cursor))return er();let r=[],n=new Set;for(let o of t.messages){let s=tr(o);if(!s||typeof s.message_id!="string"||!rr(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return er();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let a=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,l=s.role==="assistant"?ca(a):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Um(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Vm(s.citations)}:{},...a!==null?{proactiveOriginRef:a}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return M(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(ma,"mapMessagePage");function Um(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Um,"normalizeUrgency");function Vm(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=tr(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let a=n[s];(typeof a=="string"||a===null)&&(o[s]=a);}return [Object.freeze(o)]}))}i(Vm,"historyCitations");var so=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),At=4e3;var Ot=4e3;function ya(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:U("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:U("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(ya,"validateImageKeys");function lo(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:U("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Ot?{reason:"too_long",error:U("validationFailed",false,`message is ${r} characters; the server accepts at most ${Ot}`)}:null}i(lo,"validateMessageText");function ga(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(ga,"urgencyTier");async function*nr(e){yield e;}i(nr,"singleFrameStream");async function*ha(){}i(ha,"emptyStream");var Hm=6e4,Bm=18e4,zm=24,jm=512,Wm=false;function ba(e){return new uo(e)}i(ba,"createChatController");var co=class co extends Hr{constructor(r){super(ra({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??ke({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=Zs(this.funnel),this.telemetry=r.telemetry??Nr,this.errorPolicy=r.errorPolicy??fs,this.timers=r.timers??aa,this.rng=r.rng??Math.random,this.newId=r.newId??oa(),this.makeIdempotencyKey=r.makeIdempotencyKey??ia(),this.budget={idleMs:r.budget?.idleMs??Hm,overallMs:r.budget?.overallMs??Bm};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=U(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):nr(Oe(u))}let a=lo(r)??ya(s.imageS3Keys);if(a!==null)return this.telemetry.track("chat.send.rejected",{reason:a.reason}),this.patch({status:"error",isStreaming:false,error:a.error}),o?(o.onError(a.error),()=>{}):nr(Oe(a.error));if(o)return this.driveWithHandlers(r,s,o);let l=this.beginTurn(r,s);return this.runTurn(l,s.signal)}askEverfur(r,n){if(this.disposed)return nr(Oe(U("accessDenied",false)));let o=lo(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),nr(Oe(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):ha()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Jn(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?Jt(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(no(r));this.bootstrapPrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=io(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return v(U("accessDenied",false));if(!a.ok)return a;let l=fa(a.value);if(l.ok){for(let c of l.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let u=this.snapshot.conversationId,d=u===null?void 0:this.unreadByConversation.get(u);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?M(n):v(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return v(s.error);let a=s.value.conversations[0];if(a===void 0)return M(null);let l=await this.resumeConversation(a.id);return l.ok?M(a.id):v(l.error)}async markRead(r){if(this.disposed)return v(U("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return M(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?v(U("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),M(void 0)):v(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return v(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Re(r))return v(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!so.includes(n))return v(U("validationFailed",false,`feedback_type must be one of ${so.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>At)return v(U("validationFailed",false,`notes is over ${At} characters`));let l={feedback_type:n};a.length>0&&(l.notes=a);let u=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},s?.signal);if(!this.alive(u)||this.disposed)return v(U("accessDenied",false));if(!d.ok)return v(d.error);let c=d.value?.feedback_id;return M(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return v(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return v(U("validationFailed",false,"a check-in needs the pet the case belongs to"));let a=this.epoch,l=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(a)||this.disposed)return v(U("accessDenied",false));if(!l.ok)return l;let u=l.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...u!==null?{openedAt:u}:{}}),c=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,checkin:d}):p)}),l}async getMessages(r,n){if(!rr(r))return v(U("validationFailed",false));let o=io(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?v(U("accessDenied",false)):a.ok?ma(a.value):a}async resumeConversation(r){if(this.disposed)return v(U("accessDenied",false));if(!rr(r))return v(U("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),M(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===jr).map(d=>d.caseId)),a=new Map(o.value.map(d=>[d.caseId,d])),l=false,u=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;l=true;let p=a.get(c.caseId),f=c.openedAt??p?.openedAt??null,m=s.has(c.caseId),y=p!==void 0&&(!m||da({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:m?jr:p?.status??"resolved",answer:c.answer??y,resolutionText:c.resolutionText??p?.resolutionText??null,...f!==null?{openedAt:f}:{}})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return M(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return v(o.error);let s=new Set(this.snapshot.messages.map(l=>l.id)),a=o.value.messages.filter(l=>!s.has(l.id));return a.length>0&&this.patch({messages:[...this.snapshot.messages,...a]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),M(void 0)}async loadOlderMessages(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return M(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let a=new Set(this.snapshot.messages.map(u=>u.id)),l=s.value.messages.filter(u=>!a.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),M(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Oe(n.error));}async primeConversation(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?v(U("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return M(n);let o=this.snapshot.conversationId;return o!==null?M(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let a=await s.settled;return !this.alive(n)||this.disposed?v(U("accessDenied",false)):(!a.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),a)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?v(U("internalError",true)):M(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Re(o))return v(D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",a=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?v(U("accessDenied",false)):a.ok?M(na(a.value)):v(a.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,a=zr(s.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,a),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of u){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Jn(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,a=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=u?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let g=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;g.ok&&this.snapshot.conversationId===null&&this.adoptConversation(g.value);}if(u&&this.snapshot.conversationId===null){let g=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!g.ok){yield*this.emitTerminal(r,g.error,Oe(g.error));return}this.adoptConversation(g.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let g=U("internalError",!0);yield*this.emitTerminal(r,g,Oe(g));return}this.clearAssistantInProgress(r);let p=new AbortController,f=zr(o.signal,p.signal),m=null;try{let g;try{g=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let w=this.authRejected();yield*this.emitTerminal(r,w,Oe(w));return}if(o.signal.aborted||!this.alive(o.epoch))return;let R=this.funnel.stream("chat.send",g,f);for await(let w of la(R,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(w.kind==="error"&&w.terminal){m=w;break}if(this.applyFrame(w,r),yield w,w.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(m===null){if(this.snapshot.status==="complete")return;let g=U("streamIncomplete",!0);yield*this.emitTerminal(r,g,Oe(g));return}let y=Ae(m.code);if(y==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let g=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!g){let R=this.authRejected();yield*this.emitTerminal(r,R,m);return}this.patch({reconnecting:!0});continue}if(y==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let g=this.authRejected();yield*this.emitTerminal(r,g,m);return}if(y==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,ro(m),m);return}if(cs(y)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let k=m.retryable&&Lr(y,!0);if(Wm&&k&&s+1<this.errorPolicy.maxAttempts(y));yield*this.emitTerminal(r,ro(m),m);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Xe(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(a=>a.id===n.userMessageId&&a.pending===true?Jt(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,eo(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=jm){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},zm);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(a=>a.id===o?ta(a,n):a);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?to(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?Jt(d):d),to(eo(l,"",this.stamp()),r)];}let a=no([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=a.length>0?Object.freeze(a):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,a=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(s)||this.disposed||a!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=ga(l.value?.urgency),d=typeof l.value?.reason=="string"?l.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?Jt(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return U("authRejected",false)}};i(co,"ChatControllerImpl");var uo=co;async function Ea(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],a=false,l=false,u=false,d=null,c=null,p=o?r.resumeConversation(o).then(x=>x.ok?M(o):x):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,y]=await Promise.all([p,f]),k=null;if(m.ok)k=m.value,s.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let x=m.error;c=x,va(x)?(l=true,d=x):(Ca(x)&&(a=true),u=true);}let g=[];y.ok?g=y.value:R(y.error);function R(x){va(x)?(l=true,d===null&&(d=x)):Ca(x)&&(a=true);}i(R,"recordAuthSignals");let w=d!==null?d.displayMessage:null;return Object.freeze({conversationId:k,petRef:n,suggestedPrompts:g,error:w,warning:w===null&&k===null&&u?Gm:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Ea,"bootstrapChat");var Gm="Chat is ready. Your first message will start the conversation.";function va(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(va,"isUnauthorized");function Ca(e){return e.httpStatus===403||e.code==="accessDenied"}i(Ca,"isForbidden");var po=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Ra(e){return e!==po}i(Ra,"isUploadTransportAvailable");var Km=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Wr=10*1024*1024,Gr=5,or=120,qm="/widget/v1/uploads/initiate";function $m(e){return typeof e=="string"&&Km.includes(e.trim().toLowerCase())}i($m,"isAttachmentMime");function fo(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<=or)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,or);let n=t.slice(r);return n.length>=or?t.slice(0,or):`${t.slice(0,r).slice(0,or-n.length)}${n}`}i(fo,"sanitizeFilename");function mo(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(mo,"formatBytes");var ir=i(e=>Object.freeze({ok:true,value:e}),"ok"),xe=i(e=>Object.freeze({ok:false,error:e}),"err");function oe(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(oe,"failure");function Ym(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(Ym,"attachmentSize");function Xm(e){let t=fo(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!$m(r))return xe(oe("unsupported_type",false,t));let n=Ym(e);return n===null?xe(oe("unknown",false,t)):n>Wr?xe(oe("too_large",false,t,{sizeBytes:n})):ir(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Xm,"validateAttachment");function Qm(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d: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={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[d,c]of Object.entries(u))typeof c=="string"&&(l[d]=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)??Wr,s3_key:a,purpose:r(t.purpose)})}i(Qm,"parsePolicy");function Zm(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return oe("quota_exceeded",false,t,{cause:e});case "rateLimited":return oe("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return oe("idempotency_conflict",true,t,{cause:e});case "validationFailed":return oe("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return oe("network",true,t,{cause:e});default:return r===429?oe("rate_limited",true,t,{cause:e}):r===503?oe("network",true,t,{cause:e}):r===void 0?oe("network",true,t,{cause:e}):oe("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Zm,"initiateFailure");async function Jm(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:qm,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return xe(Zm(n.error,t.filename));let o=Qm(n.value);return o===null?xe(oe("server",false,t.filename)):ir(o)}i(Jm,"initiateAttachmentUpload");async function ey(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return xe(oe("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),ir(void 0)}catch{return o()?xe(oe("cancelled",true,r.filename)):xe(oe("server",true,r.filename))}}i(ey,"uploadAttachmentBytes");var ty=2,ry=3,ny=Object.freeze([1e3,2e3,4e3]),Sa=0;function oy(){return Sa+=1,`attachment-${Sa}`}i(oy,"defaultNewId");function Ta(e){let t=Math.max(1,e.concurrency??ty),r=Math.max(1,e.maxAttempts??ry),n=e.backoffMs??ny,o=Math.max(1,e.maxPerMessage??Gr),s=e.timers??ea,a=e.newId??oy,l=Ra(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),y=false,k=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(b=>{let P=u.get(b);return P===void 0?[]:[P.state]}))});for(let b of f)b();},"publish"),g=i((b,P)=>{b.state=Object.freeze({...b.state,...P}),k();},"patch"),R=i(()=>{for(;!y&&p.size<t&&c.length>0;){let b=c.shift(),P=u.get(b);P!==void 0&&(p.add(b),w(P).finally(()=>{p.delete(b),R();}));}},"pump"),w=i(async b=>{let{attachment:P}=b;for(;b.attempts<r;){if(y||b.controller.signal.aborted)return;b.attempts+=1;let L=b.controller.signal;g(b,{status:"uploading",error:null,progress:0});let I=await Jm(e.funnel,P,{signal:L});if(y||L.aborted)return;let S;if(!I.ok)S=xe(I.error);else {let j=await ey(e.transport,I.value,P,{signal:L,onProgress:i(G=>{!L.aborted&&b.state.status==="uploading"&&g(b,{progress:iy(G)});},"onProgress")});if(y||L.aborted)return;S=j.ok?ir(I.value.s3_key):xe(j.error);}if(S.ok){g(b,{status:"uploaded",s3Key:S.value,error:null,progress:1});return}let O=S.error,T=O.retryable&&b.attempts<r;if(g(b,{status:T?"uploading":"failed",error:O,progress:0}),!T)return;let V=n[Math.min(b.attempts-1,n.length-1)]??0;await Br(V,L,s);}},"run"),_=i(b=>{c.push(b.state.id),R();},"enqueue"),x={available:l,subscribe(b){return f.add(b),()=>{f.delete(b);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(b=>b.status==="uploading")},get s3Keys(){return m.attachments.flatMap(b=>b.status==="uploaded"&&b.s3Key!==null?[b.s3Key]:[])},add(b){let P=Xm(b);if(!P.ok)return P;if(y||d.length>=o)return xe(oe("too_many",false,P.value.filename));let L=a(),I={attachment:P.value,controller:new AbortController,attempts:0,state:Object.freeze({id:L,filename:P.value.filename,previewUri:b.uri,contentType:P.value.contentType,sizeBytes:P.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(L,I),d.push(L),k(),_(I),ir(I.state)},retry(b){let P=u.get(b);P===void 0||y||P.state.status!=="failed"||(P.controller=new AbortController,P.attempts=0,g(P,{status:"uploading",error:null,progress:0,s3Key:null}),_(P));},remove(b){let P=u.get(b);if(P===void 0)return;P.controller.abort(),u.delete(b);let L=d.indexOf(b);L>=0&&d.splice(L,1);let I=c.indexOf(b);I>=0&&c.splice(I,1),k();},clear(){for(let b of [...d])x.remove(b);},dispose(){y=true;for(let b of u.values())b.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return x}i(Ta,"createAttachmentQueue");function iy(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(iy,"clamp");var Pa=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function sr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Pa,t)?Pa[t]:null}i(sr,"canonicalPetSpecies");var ka=50,sy=128,yo=120,xa=120,ay=2e3,_a=120,ly=80,Aa=new Set(["male","female","unknown"]),Oa=new Set(["day","month","year"]),Fa=new Set(["low","medium","high","athletic"]),Ma=new Set(["indoor","outdoor","both"]),La=new Set(["mild","moderate","severe"]),uy=/^(\d{4})-(\d{2})-(\d{2})$/,Da=[["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"]],Na=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Da,...Na].map(([e])=>e));function dy(e){let t=uy.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(dy,"isRealDate");var lr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),cy=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),qr=i((e,t)=>typeof t=="string"&&dy(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Fe=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Re(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=it(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),py={sex:lr(Aa),spayedNeutered:cy,birthDate:qr,birthDatePrecision:lr(Oa),activityLevel:lr(Fa),indoorOutdoor:lr(Ma),foodBrand:Fe(_a),foodType:Fe(_a),microchipId:Fe(ly)},go=["ref","ref",false,Fe(sy,{required:true,trimmed:true})],ho=["notes","notes",false,Fe(ay,{trimmed:true})],wa=[go,["name","name",true,Fe(yo,{required:true,trimmed:true})],["dose","dose",false,Fe(xa,{trimmed:true})],["frequency","frequency",false,Fe(xa,{trimmed:true})],["startDate","start_date",false,qr],["endDate","end_date",false,qr],ho],fy={allergies:[go,["allergen","allergen",true,Fe(yo,{required:true,trimmed:true})],["severity","severity",false,lr(La)],ho],medications:wa,supplements:wa,conditions:[go,["conditionName","condition_name",true,Fe(yo,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,qr],ho]};function my(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[u,d,c,p]of fy[e]){let f=o[u];if(f==null){if(c)return {error:`${n}.${u} is required`};f===null&&(s[d]=null);continue}let m=p(`${n}.${u}`,f);if(m!==null)return {error:m};s[d]=f;}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(my,"itemToWire");function yy(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>ka)return {error:`${e} has ${t.length} items; the server accepts at most ${ka}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=my(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(yy,"listToWire");function Ua(e,t){let r=e,n={};for(let[a,l]of Da){let u=r[a];if(u!==void 0){if(u!==null){let d=py[a](a,u);if(d!==null)return {error:d}}n[l]=u;}}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 Na){let u=r[a];if(u===void 0)continue;let d=yy(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&sr(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(Ua,"petHealthToWire");var ee=i(e=>typeof e=="string"?e:null,"str"),ar=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),gy=i(e=>typeof e=="boolean"?e:null,"bool");function Kr(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(Kr,"itemsFromWire");function Ia(e){let t=ee(e.name);return t===null||t.length===0?null:Object.freeze({ref:ee(e.ref),name:t,dose:ee(e.dose),frequency:ee(e.frequency),startDate:ee(e.start_date),endDate:ee(e.end_date),notes:ee(e.notes)})}i(Ia,"medicationFromWire");function Va(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:ar(Aa,e.sex),spayedNeutered:gy(e.spayed_neutered),birthDate:ee(e.birth_date),birthDatePrecision:ar(Oa,e.birth_date_precision),activityLevel:ar(Fa,e.activity_level),indoorOutdoor:ar(Ma,e.indoor_outdoor),foodBrand:ee(e.food_brand),foodType:ee(e.food_type),microchipId:ee(e.microchip_id),allergies:Kr(e.allergies,r=>{let n=ee(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),allergen:n,severity:ar(La,r.severity),notes:ee(r.notes)})}),medications:Kr(e.medications,Ia),supplements:Kr(e.supplements,Ia),conditions:Kr(e.conditions,r=>{let n=ee(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),conditionName:n,diagnosedDate:ee(r.diagnosed_date),notes:ee(r.notes)})})})}i(Va,"petHealthFromWire");var za=100,ja=50,Wa=100,Ga=50,Ka=500,hy=128,by=6e4;function Le(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(Le,"invalid");function st(e,t,r){if(typeof t!="string")return Le(`${e} must be a string`);let n=it(t);return n<=r?null:Le(`${e} is ${n} characters; the server accepts at most ${r}`)}i(st,"checkString");function $r(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Le(`${e} must be a finite number between 0 and ${r}`)}i($r,"outOfRange");function Ha(e,t){if(typeof e!="string")return Le("pet_ref must be a string");if(e.trim().length===0)return Le("pet_ref must not be blank");if(Re(e))return Le("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Le("profile must be an object");let r=[st("pet_ref",e,hy)];return t?.name!==void 0&&r.push(st("name",t.name,za)),t?.species!==void 0&&r.push(st("species",t.species,ja)),t?.breed!==void 0&&r.push(st("breed",t.breed,Wa)),t?.ageYears!==void 0&&r.push($r("age_years",t.ageYears,Ga)),t?.weightKg!==void 0&&r.push($r("weight_kg",t.weightKg,Ka)),r.find(n=>n!==null)??null}i(Ha,"validate");function qa(e,t){let r=Ua(e,t);return "error"in r?{error:Le(r.error)}:r}i(qa,"healthToWire");function vy(e){if(typeof e!="object"||e===null)return {error:Le("patch must be an object")};let t=e,r=[["name","name",s=>st("name",s,za)],["species","species",s=>st("species",s,ja)],["breed","breed",s=>st("breed",s,Wa)],["ageYears","age_years",s=>$r("age_years",s,Ga)],["weightKg","weight_kg",s=>$r("weight_kg",s,Ka)]],n={};for(let[s,a,l]of r){let u=t[s];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}n[a]=u;}}let o=qa(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Le("patch must change at least one field")}:{body:n})}i(vy,"patchToWire");function Cy(e){if(e==null)return {body:{}};let t=qa(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(Cy,"toWire");var Me=i(e=>typeof e=="string"?e:null,"str"),Yr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Ba(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Me(r.pet_ref)??t,name:Me(r.name),species:Me(r.species),breed:Me(r.breed),ageYears:Yr(r.age_years),weightKg:Yr(r.weight_kg)})}i(Ba,"fromWire");function $a(e){if(typeof e!="object"||e===null)return null;let t=e,r=Me(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Me(t.pet_id),petRef:r,name:Me(t.name),species:Me(t.species),breed:Me(t.breed),ageYears:Yr(t.age_years),weightKg:Yr(t.weight_kg),updatedAt:Me(t.updated_at)})}i($a,"widgetPetFromWire");function Ey(e){let t=$a(e);return t===null?null:Object.freeze({...t,...Va(e)})}i(Ey,"widgetPetProfileFromWire");function Ry(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=$a(r);return n===null?[]:[n]}))}i(Ry,"petListFromWire");function Qe(e){return Sy(ke({auth:e}),ke({auth:e,unaryTimeoutMs:by}))}i(Qe,"createPetsRepository");function Sy(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Ha(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?M(Ry(s.value)):v(s.error)},async registerPet(o,s,a){let l=Ha(o,s);if(l!==null)return v(l);let u=Cy(s);if("error"in u)return v(u.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",a?.signal?{...c,signal:a.signal}:c);return p.ok?M(Ba(p.value,o)):v(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return v(l);let u=vy(s);if("error"in u)return v(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?M(Ba(d.value,o)):v(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return v(l.error);let u=Ey(l.value);return u===null?v(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):M(u)},async deletePet(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?M(void 0):v(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?M(void 0):v(s.error)}}}i(Sy,"createPetsRepositoryOver");var vo=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 Ty(e){return vo[e]}i(Ty,"requires");function Ya(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(vo))for(let a of vo[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(Ya,"deniedDecisionsFor");function Xa(e,t,r){let n=Ty(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 bo({name:e,enabled:false,isPending:true,limits:{}});let s=Py(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?bo({name:e,enabled:true,isPending:false,limits:s}):bo({name:e,enabled:false,isPending:false,limits:s,disabled:ky(n,o)})}i(Xa,"decideCapability");function Py(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(Py,"mergeLimits");function ky(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:It("accessDenied"),level:"user_entitlement",recoverable:false})}i(ky,"disabledFor");function bo(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(bo,"freezeDecision");function ye(e){let t=ie(e);return t===null?null:_y(t)}i(ye,"parseColor");function ie(e){if(typeof e=="number")return Qa(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Co(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Co(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return xy(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=Co(t);if(r!==null)return r}return /^\d+$/.test(t)?Qa(Number.parseInt(t,10)):null}i(ie,"toRgba");function Co(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Eo(t[0]),g:Eo(t[1]),b:Eo(t[2]),a:1};if(t.length===6)return {r:at(t,0),g:at(t,2),b:at(t,4),a:1};if(t.length===8){let r=at(t,0);return {r:at(t,2),g:at(t,4),b:at(t,6),a:r/255}}return null}i(Co,"fromHex");function xy(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(u=>u.trim());if(n.length<3)return null;let o=Ro(Number(n[0])),s=Ro(Number(n[1])),a=Ro(Number(n[2]));if(o===null||s===null||a===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:s,b:a,a:l}}i(xy,"fromRgbFunc");function Qa(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(Qa,"argbIntToRgba");function at(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(at,"byte");function Eo(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Eo,"dup");function Ro(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Ro,"clampByte");function _y(e){if(e.a>=1)return ut(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(_y,"normalizeRgba");function ut(e,t,r){return `#${So(e)}${So(t)}${So(r)}`.toUpperCase()}i(ut,"rgbToHex");function So(e){return e.toString(16).padStart(2,"0")}i(So,"hex2");var wy="#111111",Ft="#FFFFFF",Xr="#000000";function Ja(e){let t=ie(e);if(t===null)return Ft;let r=lt(t),n=lt({r:17,g:17,b:17}),o=lt({r:255,g:255,b:255});return ko(r,o)>=ko(r,n)?Ft:wy}i(Ja,"readableOn");function ur(e,t){let r=Ja(e);return ue(r,e)>=t?r:ue(Ft,e)>=ue(Xr,e)?Ft:Xr}i(ur,"legibleOn");function dr(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Ft)>=t(Xr)?Ft:Xr}i(dr,"poleForGrounds");function lt(e){let t=To(e.r/255),r=To(e.g/255),n=To(e.b/255);return .2126*t+.7152*r+.0722*n}i(lt,"relativeLuminance");function To(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(To,"linearize");function ko(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(ko,"luminanceContrast");function ue(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:el(r,o);return ko(lt(s),lt(o))}i(ue,"contrastRatio");function el(e,t){let r=e.a,n=i((o,s)=>Math.round(o*r+s*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(el,"composite");function dt(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return null;let o=r.a>=1?r:el(r,{...n});return ut(o.r,o.g,o.b)}i(dt,"flattenOnto");function tl(e,t){let r=ie(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(tl,"withAlpha");var Za=.05;function Ze(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>ue(d,c)>=n),"reads");if(ie(e)===null)return r;if(s(e))return e;let a=dt(e,o),l=a===null?null:ie(a),u=ie(r);if(l===null||u===null)return r;for(let d=1;d<1/Za;d+=1){let c=d*Za,p=i((m,y)=>Math.round(m+(y-m)*c),"mix"),f=ut(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(Ze,"pushToContrast");function rl(e,t,r){let n=e/255,o=t/255,s=r/255,a=Math.max(n,o,s),l=Math.min(n,o,s),u=(a+l)/2;if(a===l)return {h:0,s:0,l:u};let d=a-l,c=d/(1-Math.abs(2*u-1)),p;return a===n?(p=(o-s)/d*60,p<0&&(p=p+360)):a===o?p=((s-n)/d+2)*60:p=((n-o)/d+4)*60,{h:p,s:c,l:u}}i(rl,"rgbToHsl");function xo(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,s=t/60,a=o*(1-Math.abs(s%2-1)),l=n-o/2,u=Math.floor(s)%6,d=[[o,a,0],[a,o,0],[0,o,a],[0,a,o],[a,0,o],[o,0,a]],[c,p,f]=d[u];return {r:Po(c+l),g:Po(p+l),b:Po(f+l)}}i(xo,"hslToRgb");function Po(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(Po,"channel");function ze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))ze(e[t]);}return e}i(ze,"deepFreeze");var Zr=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),ol={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},il={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},nl={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Iy={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Ay={regular:"400",medium:"500",bold:"700"},Oy={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},_o=0,ct="System",De="monospace",Fy=["content","heading","control","compact","badge"];function My(e){let t={};for(let r of Fy)t[r]=e;return t}i(My,"authoredTierSizes");function sl(){return {family:ct,mono:De,fontUrl:null,families:{regular:ct,medium:ct,bold:ct,mono:De,monoMedium:De,monoBold:De},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:nl,tierSizes:My(nl),lineHeight:Iy,weight:Ay,letterSpacing:Oy,scale:1,maxScale:_o,scaleCaps:Zr}}i(sl,"baseType");var al={},pt=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function Qr(e){return `cubic-bezier(${e.join(", ")})`}i(Qr,"cssCubicBezier");var ll={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:Qr(pt.standard),emphasized:Qr(pt.emphasized),exit:Qr(pt.exit)},reducedMotion:false},Ly={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:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",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:"#B91C1C",errorRed:"#FF1B00",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(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},ft=ze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Ly,space:ol,radius:il,type:sl(),motion:ll,slots:al}),Dy={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:"#9A938C",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",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",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},Jr=ze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Dy,space:ol,radius:il,type:sl(),motion:ll,slots:al});var Ny="#23272C",ul=4.5,Uy=.6,wo=.9,Vy=.02,Hy="#FFFFFF",By="#111111";function zy(e){return ue(e,Ny)>=ul&&Math.max(ue(e,Hy),ue(e,By))>=ul}i(zy,"readsOnDark");function pl(e){let t=ie(e);if(t===null)return null;let{h:r,s:n,l:o}=rl(t.r,t.g,t.b),s=Math.min(Math.max(o,Uy),wo);for(let l=0;;l+=1){let u=s+l*Vy;if(u>wo)break;let d=xo({h:r,s:n,l:u}),c=ut(d.r,d.g,d.b);if(zy(c))return c}let a=xo({h:r,s:n,l:wo});return ut(a.r,a.g,a.b)}i(pl,"deriveDarkVariant");var jy=7,dl=.05,Wy="#000000",Gy="#FFFFFF";function Ky(e,t,r,n){let o=dt(e,t);if(o===null)return r;if(ue(o,t)>=n)return o;let s=ie(o),a=ie(r);if(s===null||a===null)return r;for(let l=1;l<1/dl;l+=1){let u=l*dl,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=ut(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(ue(c,t)>=n)return c}return r}i(Ky,"pushContrast");function qy(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=cl(n);for(let s of r){let a=cl(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(qy,"hardestGround");function cl(e){let t=ie(e);return t===null?0:lt(t)}i(cl,"luminanceOf");function Je(e,t){return dt(e,t)??ye(e)??t}i(Je,"solid");function fl(e){let t=e.color,r=e.brightness==="dark",n=r?Gy:Wy,o=qy(t,r),s=i(l=>Ky(l,o,n,jy),"text"),a={...t,brandSoft:Je(t.brandSoft,t.surface),brandSofter:Je(t.brandSofter,t.surface),brandBorder:s(t.brandBorder),borderHairlineGreen:s(t.borderHairlineGreen),brandBorderStrong:s(t.brandBorderStrong),brandInk:s(t.brandInk),linkInk:s(t.linkInk),borderRingCream:s(t.borderRingCream),composerBorder:s(t.composerBorder),text:{primary:s(t.text.primary),secondary:s(t.text.secondary),muted:s(t.text.muted),placeholder:s(t.text.placeholder),onBrand:t.text.onBrand,metaCool:s(t.text.metaCool),timestamp:s(t.text.timestamp)},badgeBgPositive:Je(t.badgeBgPositive,t.surface),badgeBgCaution:Je(t.badgeBgCaution,t.surface),badgeBgCritical:Je(t.badgeBgCritical,t.surface),badgeBgNeutral:Je(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Je(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Je(t.checkupCardConcernBg,t.surface)};return ze({...e,highContrast:true,color:a})}i(fl,"deriveHighContrast");var mt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),$y=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),_e=4.5,Yy=Object.freeze({});function Xy(e){return mt.includes(e)}i(Xy,"isSlotName");function Qy(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Qy,"parseRadius");function ml(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Xy(n)||o===null||typeof o!="object")continue;let s=Zy(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(ml,"parseThemeSlots");function en(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(en,"pick");function Zy(e){let t={},r=ye(en(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ye(en(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Qy(en(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=ye(en(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Zy,"parseSlot");function yl(e,t){return t===null||Object.keys(t).length===0?e??Yy:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(yl,"mergeThemeSlots");var Io=3;function Jy(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>dt(e,r)??r)}i(Jy,"seatsOf");function eg(e,t){let r=dr(e);return e.every(n=>ue(r,n)>=t)}i(eg,"someInkReads");function tg(e,t){let r=t[0];return r===void 0?null:dt(e,r)}i(tg,"collapseUnsatisfiableFill");function rg(e){let t=ur(e[0],_e);return e.every(r=>ue(t,r)>=_e)?t:dr(e)}i(rg,"inkFor");function gl(e,t){let r=false,n={};for(let o of mt){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=Jy(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!eg(u,_e)){let p=tg(a,l);p!==null&&(d.backgroundColor=p,u=[p],c=true);}if(u.length>0){let p=s.textColor;if(a!==void 0)(p===void 0||u.some(f=>ue(p,f)<_e))&&(d.textColor=rg(u),c=true);else if(p!==void 0){let f=Ze(p,u,dr(u),_e);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=Ze(s.borderColor,u,dr(u),Io);f!==s.borderColor&&(d.borderColor=f,c=true);}}n[o]=c?Object.freeze(d):s,r=r||c;}return r?Object.freeze(n):e}i(gl,"guardSlotContrast");var vl=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),cr="slots.",Cl=Object.freeze([1,2]);function tn(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(tn,"isEmptyBranding");function El(e){let t=e?.schemaVersion??null;return t===null||Cl.includes(t)}i(El,"isKnownBrandingSchema");function Rl(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(Rl,"lockedFieldsOf");function ng(e){return e==="hide_powered_by"||vl.includes(e)?true:e.startsWith(cr)&&mt.includes(e.slice(cr.length))}i(ng,"isThemeLockName");function je(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:yt($(t,"display_name","displayName")),logoUrl:yt($(t,"logo_url","logoUrl")),primaryColor:ye($(t,"primary_color","primaryColor")),accentColor:ye($(t,"accent_color","accentColor")),brightness:ag($(t,"brightness","color_scheme","colorScheme")),fontFamily:yt($(t,"font_family","fontFamily")),fontUrl:yt($(t,"font_url","fontUrl")),fonts:hl($(t,"fonts")),fontUrls:hl($(t,"font_urls","fontUrls")),placeholder:yt($(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:og($(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ye($(t,"primary_color_dark","primaryColorDark")),accentColorDark:ye($(t,"accent_color_dark","accentColorDark")),surfaceStyle:bl($(t,"surface_style","surfaceStyle"),ig),radiusScale:bl($(t,"radius_scale","radiusScale"),sg),logoUrlDark:yt($(t,"logo_url_dark","logoUrlDark")),slots:ml($(t,"slots")),accessibilityMaxFontScale:ug($(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:cg($(t,"locked_fields","lockedFields")),schemaVersion:dg($(t,"schema_version","schemaVersion"))};return tn(r)?null:Object.freeze(r)}i(je,"parseClientBranding");function og(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(og,"parseBool");function $(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i($,"pick");function yt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(yt,"parseNonEmptyString");var pr=["regular","medium","bold","mono","monoMedium","monoBold"];function hl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of pr){let o=yt($(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(hl,"parseFaceMap");var ig=["white","cream","subtle"],sg=["sharp","default","round"];function bl(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(bl,"parseEnum");function ag(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(ag,"parseBrightness");function Sl(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(Sl,"parseNumber");var lg=1,Tl=3.1;function ug(e){let t=Sl(e);return t===null?null:t<=0?0:Math.min(Tl,Math.max(lg,t))}i(ug,"parseMaxFontScale");function dg(e){if(e==null)return null;let t=Sl(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(dg,"parseSchemaVersion");function Ao(e){let t=e.trim();return t.startsWith(cr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Ao,"toWireName");function cg(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Ao(r);ng(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(cg,"parseLockedFields");function Oo(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Oo,"hardenHttpsUrl");function Pl(e,t){if(t===null||tn(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Jr:ft:e,n=r.brightness==="dark"?Jr:ft,o=r.brightness==="dark",s=o?t.primaryColorDark??kl(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??kl(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&gg(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?ie(c):null,f=i(k=>Math.round(k+(255-k)*.4),"lift"),m=p!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:d?hg(n,r.color.text):{},y={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...m,...yg(t.surfaceStyle??null,n),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:vg(t.radiusScale??null,r.radius,n),type:{...r.type,...mg(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:yl(r.slots,t.slots??null)};return ze(y)}i(Pl,"withServerBranding");var pg={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},fg=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Fo(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(Fo,"isMonoFace");function mg(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of pr){let u=pg[l].map(p=>r[p]).find(p=>p!==void 0),d=Fo(l)?null:t.fontFamily;u!==void 0?(o[l]=u,s[l]=true):d!==null&&(o[l]=d,s[l]=false);let c=n[l]??(l==="regular"?t.fontUrl:null)??null;c!==null?a[l]=c:u!==void 0&&delete a[l];}for(let l of fg)for(let u of l)s[u]&&l.some(d=>d!==u&&o[d]===o[u])&&(s[u]=false);return {family:o.regular,mono:o.mono,fontUrl:a.regular??null,families:o,namedFaces:s,fontUrls:a}}i(mg,"mergeFaces");function kl(e){return e===null?null:pl(e)}i(kl,"darkVariantOf");function yg(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(yg,"surfaceOf");function xl(e,t){return e==null?false:ye(e)===ye(t)}i(xl,"sameColor");function gg(e,t,r,n){return xl(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&xl(e.primaryColor,ft.color.primary)}i(gg,"isCompiledPrimary");function hg(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(hg,"compiledBrandFamily");var bg={sharp:.5,default:1,round:1.5};function vg(e,t,r){if(e===null)return t;let n=bg[e],o=r.radius,s=i(a=>Math.round(a*n),"s");return {tile:s(o.tile),xs:s(o.xs),sm:s(o.sm),md:s(o.md),lg:s(o.lg),xl:s(o.xl),pill:o.pill}}i(vg,"radiusOf");var Cg="Everfur",Eg=.5;function Mo(e){let t=e?.branding??null,r=El(t)?t:null,n=kg(e?.clientOverride??null,Rl(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=Pl((s==="auto"?o:s)==="dark"?Jr:ft,_l(r)),d=Pl(u,_l(n));return Ug(d,e)}i(Mo,"resolveTheme");function Rg(e,t,r){return Mo({...r,branding:je(t),clientOverride:je(e)})}i(Rg,"previewTheme");function Sg(e){return e==="placeholder"?"chat_placeholder":Ao(e)}i(Sg,"wireNameOf");var Tg={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Pg(e,t){return t.has(Sg(e))?true:(Tg[e]??[]).some(r=>t.has(r))}i(Pg,"isLocked");function kg(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(Pg(a,t)||a==="lockedFields")&&(n[a]=null,r=true);let o=n.slots??null;if(o!==null){let a={},l=false;for(let u of mt){let d=o[u];d!==void 0&&(t.has(`${cr}${u}`)?l=true:a[u]=d);}l&&(n.slots=Object.keys(a).length===0?null:Object.freeze(a),r=true);}if(!r)return e;let s=Object.freeze(n);return tn(s)?null:s}i(kg,"withoutFields");function _l(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(_l,"withoutBrightness");function xg(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(xg,"scaledSizes");function _g(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Eg,e)}i(_g,"effectiveScale");var wl=["content","heading","control","compact","badge"];function wg(e){if(!(e>0))return Zr;let t={};for(let r of wl){let n=Zr[r];t[r]=n===0?0:Math.min(n,e);}return t}i(wg,"tierCaps");function Ig(e,t){return t>0?Math.min(e,t):e}i(Ig,"capped");function Ag(e,t,r,n){let o={};for(let s of wl)o[s]=n?xg(e,Ig(t,r[s])):e;return o}i(Ag,"sizesByTier");function Og(e){return e==="dark"?"#FFFFFF":"#000000"}i(Og,"inkPole");function Fg(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(Fg,"textGrounds");function Mg(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(Mg,"controlGrounds");function Il(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Il,"linkGrounds");function Lg(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Il(e)}}i(Lg,"slotGrounds");function Dg(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Dg,"registration");function Ng(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},s={...e.namedFaces};for(let a of pr)!(o[a]===ct||o[a]===De)&&r!==void 0&&Dg(r,o[a])===false&&(o[a]=Fo(a)?De:ct,s[a]=false),n!==null&&Fo(a)&&o[a]===De&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(Ng,"platformFaces");function Ug(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?Cg:e.meta.displayName,s=Oo(e.meta.logoUrl),a={};for(let _ of pr){let x=e.type.fontUrls[_];x!==void 0&&(a[_]=Oo(x));}let l=a.regular??null,d=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,c=Number.isFinite(e.type.maxScale)?e.type.maxScale:_o,p=_g(t?.textScale),f=wg(c),m=Ag(e.type.size,p,f,t?.scaleTypeSizes===true),y=e.color,k=Og(e.brightness),g=Fg(y),R={...y,primary:r,accent:n,onPrimary:ur(r,_e),onAccent:ur(n,_e),brandInk:Ze(y.brandInk,g,k,_e),linkInk:Ze(e.slots.link?.textColor??n,Il(y),k,_e),text:{...y.text,secondary:Ze(y.text.secondary,g,k,_e)},brandBorderStrong:Ze(y.brandBorderStrong,Mg(y),k,Io)},w={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:s,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:R,space:e.space,radius:e.radius,type:{...e.type,...Ng(e.type,t),fontUrl:l,fontUrls:a,size:m.content,tierSizes:m,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:gl(e.slots,Lg(R))};return t?.highContrast===true?fl(ze(w)):ze(w)}i(Ug,"finalize");var Al="/widget/v1/entitlements",Vg=304,Hg=Object.freeze({kind:"notModified"});async function Fl(e,t={},r=ke({auth:e})){let n=await r.send("entitlements.fetch",zg(t));return n.ok?jg(n.value):n.error.httpStatus===Vg?Hg:{kind:"failed",error:n.error}}i(Fl,"fetchEntitlements");var Bg=64;function zg(e){let t={};return Lo(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Bg?{method:"GET",path:Al,headers:t,query:{region:e.region}}:{method:"GET",path:Al,headers:t}}i(zg,"buildRequest");function jg(e){if(e===null||typeof e!="object"||!Lo(e.revision))return Ol();let t=typeof e.region=="string"?e.region:"",r=Lo(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Gg(e.capabilities),branding:Wg(e)})}i(jg,"parseUpdated");function Wg(e){let t=je(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=je(r.branding);return n!==null?n:je(r)}return null}i(Wg,"parseBranding");function Gg(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Kg(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Gg,"mapCapabilities");function Kg(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Kg,"isEnabled");function Ol(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Ol,"malformed");function Lo(e){return typeof e=="number"&&Number.isFinite(e)}i(Lo,"isFiniteNumber");var qg=30;function Ml(e){let t=e.scheduler??$g,r=e.resolve??Fl,n=Math.max(1,e.floorSeconds??qg),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),a=false,l=false,u=null,d=null,c=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),m=i(R=>{l||!a||(c=Math.max(n,R),u=t.set(()=>{u=null,g();},c*1e3));},"schedule"),y=null,k=i(async()=>{if(l)return null;let R=p;e.onFetch?.();let w=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},_;try{_=await r(e.authFor(),w);}catch(x){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Yg(x)}),!l&&R===p&&(e.onSettled?.(),m(s())),null}if(l||R!==p)return null;switch(_.kind){case "updated":d=_.revision,e.update(_.decisions,_.branding??null),m(_.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:_.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),_},"tick"),g=i(()=>{let R=k().finally(()=>{y===R&&(y=null);});return y=R,R},"run");return {start(){a||l||(a=true,g());},prime(){return l?Promise.resolve(null):y??g()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),g());}}}i(Ml,"createEntitlementPoller");var $g={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function Yg(e){return e instanceof Error?e.message:"poll failed"}i(Yg,"describe");var Ll="everfur.notifications.device";var Xg=3e3,Dl=Object.freeze([Ll]);function Nl(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),a=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),l=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:a.length});}catch{}},"report"),u=Promise.allSettled(a).then(d=>{let c=d.filter(p=>p.status==="rejected").length;c>0&&l("failed",c);});return new Promise(d=>{let c=false,p=i(()=>{c||(c=true,clearTimeout(f),d());},"finish"),f=setTimeout(()=>{c||l("timeout",a.length),p();},Xg);u.then(p,p);})}i(Nl,"startBeforeLogoutHooks");function Ul(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let a={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:a,userRef:t.userRef,sessionId:o}}i(Ul,"graceAuth");async function Vl(e,t){if(Dl.length===0)return;let r=await Promise.allSettled(Dl.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Vl,"sweepPerUserKv");function Qg(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Qg,"compiledDefaultDecisions");function Do(e=Qg){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Do,"createEntitlementStore");function No(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(No,"notConfiguredError");function Hl(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return ws(r,t===void 0?void 0:{platform:t})}i(Hl,"tryResolveClient");function Bl(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Bl,"guardTelemetry");function zl(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
|
|
12
|
-
[everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(zl,"reportConfigFailure");function Uo(e){return Object.freeze({request(){return Promise.resolve(v(No(e)))},stream(t,r){let n=pe({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(Uo,"refusingTransport");function jl(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(jl,"createInMemoryKv");var Wl=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function ql(e,t){return new Ho(e,t)}i(ql,"createEverfurRuntime");var Zg=6e4,Bo=class Bo{constructor(t,r){this.sessionId=Wn();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new Q("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Bl(n.telemetry):Nr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=Kn(n?.publishableKey),a=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)l=Uo(s);else if(n.transport!==void 0)l=n.transport;else {let c=Hl(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=Ls({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=Uo(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&zl(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??ms,this.upload=n.upload??Js,this.uploadTransport=n.uploadTransport??po,this.imageCache=n.imageCache??Wl,this.kv=n.storage??jl(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?Do():Do(()=>Ya("sdk_config",It("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",Vo(c),()=>this.buildChatController(c),Gl),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Vo(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,f,m)=>this.acquireInternal(c,p,f,m),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!a);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Rs(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Zg,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return Ml({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let a=`${this.epoch}|${t}|${r}`,l=this.entries.get(a);if(l)return s||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(a,{controller:u,refCount:1,warm:s}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=ba({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Ea(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=Wn(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Vl(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Nl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Ul({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?v(Kl(t)):r(Qe(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(a=>(s.result=a,a))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Kl("prepare"):n===null?null:No(n),s=this.identity,[a,l,u]=await Promise.all([o?v(o):s===null?M(void 0):s.currentToken().then(()=>M(void 0),()=>v(D("authRejected",{retryable:false}))),o?v(o):this.primeEntitlements(),t===null?void 0:o?v(o):this.primeChat(t)]),d=a.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:a,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?v(t.error):M(void 0):v(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Vo(r),()=>this.buildChatController(r),Gl,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?v(o.cause):M(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Bo,"EverfurRuntimeImpl");var Ho=Bo;function Vo(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Vo,"chatScopeKey");function Gl(e){e.dispose();}i(Gl,"disposeChat");function Kl(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Kl,"disposedError");var $l=Symbol.for("@everfur/sdk#EverfurContext@v1"),Yl=globalThis,rn=Yl[$l]??(Yl[$l]=createContext(null));rn.displayName??="EverfurContext";function Y(){let e=useContext(rn);if(e===null)throw new Q("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Y,"useEverfurContext");function Xl(){return Y().handle}i(Xl,"useEverfur");var Ql=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Zl=globalThis,fr=Zl[Ql]??(Zl[Ql]=createContext(ft));fr.displayName??="EverfurThemeContext";function F(){return useContext(fr)}i(F,"useEverfurTheme");function nn(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),s=e.seams.useReducedMotion(),a=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,d=e.seams.platformMonoFamily?.(),c=e.seams.isFontRegistered,p=e.clientTheme?ih(e.clientTheme):"",f=useMemo(()=>e.clientTheme?je(e.clientTheme):null,[p]),m=n.branding??null,y=useMemo(()=>Mo({branding:m,clientOverride:f,colorScheme:o,reducedMotion:s,textScale:a,scaleTypeSizes:u,highContrast:l,...d===void 0?{}:{platformMonoFamily:d},...c===void 0?{}:{isFontRegistered:c}}),[m,f,o,s,a,u,l,d,c]);return e.seams.useResolvedTheme?.(y),createElement(fr.Provider,{value:y},e.children)}i(nn,"EverfurThemeProviderCore");function ih(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(ih,"stableKey");function nu(e){let{config:t,user:r,activePet:n,theme:o,warmUp:s,children:a,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,d=useRef(null),c=useRef(null),[p,f]=useReducer(T=>T+1,0),m=useRef(null),y=useRef(void 0),k=r?.userRef??null;y.current!==k&&(y.current!==void 0&&(m.current=null),y.current=k);let g=m.current!==null?m.current.user:r??null,R=useRef(null),w=useRef(void 0),_=n??null;w.current!==_&&(w.current!==void 0&&(R.current=null),w.current=_);let x=R.current!==null?R.current.pet:n??null;(d.current===null||d.current.key!==u||d.current.runtime.isDisposed)&&(d.current!==null&&!d.current.runtime.isDisposed&&(c.current=d.current.runtime),d.current={key:u,runtime:ql({config:l.withDefaults?l.withDefaults(t):t,user:g,activePet:x,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let b=d.current.runtime,P=useRef(null);useEffect(()=>{let T=d.current?.runtime;T===void 0||!T.isDisposed||P.current!==T&&(P.current=T,f());}),useEffect(()=>{let T=c.current;T!==null&&(c.current=null,T.dispose());});let L=g?.userRef??null;useLayoutEffect(()=>{b.setUser(g);},[b,L]),useLayoutEffect(()=>{b.setActivePet(x);},[b,x]),useEffect(()=>()=>b.dispose(),[b]),useEffect(()=>{s==="onMount"&&b.prepare(x===null?{}:{petRef:x});},[b,s,L,x]);let I=useMemo(()=>({setUser:i(T=>{m.current={user:T},b.setUser(T),f();},"setUser"),setActivePet:i(T=>{R.current={pet:T},b.setActivePet(T),f();},"setActivePet"),open:i(T=>b.open(T),"open"),prepare:i(T=>b.prepare(T),"prepare"),registerPet:i((T,V)=>b.registerPet(T,V),"registerPet"),updatePet:i((T,V)=>b.updatePet(T,V),"updatePet"),deletePet:i(T=>b.deletePet(T),"deletePet"),eraseUserData:i(()=>b.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let T=b.logout();return f(),T},"logout")}),[b,f]),S=useMemo(()=>({runtime:b,handle:I,userRef:L,activePet:x,scopeEpoch:b.scopeEpoch}),[b,I,L,x,p]),O=createElement(nn,{clientTheme:o??null,seams:l.theme,children:a});return createElement(rn.Provider,{value:S},l.wrap?l.wrap(O):O)}i(nu,"EverfurProviderCore");var lh=2;function uh(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<lh)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(uh,"readEventSourceResponseHeader");function ou(){let e=ah;return (t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:i(o=>uh(n,o),"getResponseHeader")})}}i(ou,"createRnEventSourceFactory");function fh(){let e=useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(fh,"useRnColorScheme");function mh(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(mh,"isThenable");function yh(){let[e,t]=useState(false);return useEffect(()=>{let r=true,n=AccessibilityInfo?.isReduceMotionEnabled;if(typeof n=="function"){let s=n.call(AccessibilityInfo);s!=null&&typeof s.then=="function"&&s.then(a=>{r&&t(a===true);},()=>{});}let o=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",s=>t(s===true));return ()=>{r=false,o?.remove?.();}},[]),e}i(yh,"useRnReducedMotion");function au(){let e=PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}i(au,"readFontScale");function gh(e){let t=Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(Dimensions,"change",e);return ()=>r?.remove?.()}i(gh,"subscribeFontScale");function hh(){return useSyncExternalStore(gh,au,au)}i(hh,"useRnTextScale");function cu(){try{let e=Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(cu,"platformOS");function bh(){return cu()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(bh,"contrastSignal");function vh(){let[e,t]=useState(false);return useEffect(()=>{let r=true,{query:n,event:o}=bh(),a=AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(AccessibilityInfo);mh(d)&&Promise.resolve(d).then(c=>{r&&t(c===!0);},()=>{});}catch{}let l=AccessibilityInfo?.addEventListener,u=typeof l=="function"?l.call(AccessibilityInfo,o,d=>t(d===true)):void 0;return ()=>{r=false,u?.remove?.();}},[]),e}i(vh,"useRnHighContrast");function Ch(){return cu()==="ios"?"Menlo":De}i(Ch,"rnPlatformMonoFamily");function Eh(){return globalThis.__DEV__!==false}i(Eh,"isDevelopment");var lu=new Set;function Rh(e){if(!Eh()||lu.has(e))return;lu.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`);}catch{}}i(Rh,"warnUnregisteredFace");function Sh(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t);}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let o=n.includes(e);return o||Rh(e),o}i(Sh,"rnIsFontRegistered");var sn=Object.freeze({useColorScheme:fh,useReducedMotion:yh,useTextScale:hh,useHighContrast:vh,scaleTypeSizes:false,platformMonoFamily:Ch,isFontRegistered:Sh});function Ph(e){return createElement(SafeAreaProvider,null,e)}i(Ph,"wrapInSafeArea");var kh=Object.freeze({platform:"react-native",eventSourceFactory:ou(),wrap:Ph,theme:sn});function xh(e){return createElement(nu,{...e,seams:kh})}i(xh,"EverfurProvider");function Mt(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>Xa(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Mt,"useCapability");function Fh(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Fh,"tierMultiplier");function C({tier:e="content",...t}){let{type:r}=F(),n=Fh(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(C,"Text");var Lt=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Mh=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function E(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Mh[t]]}}i(E,"face");var jo=class jo 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(jo,"HostRenderBoundary");var zo=jo;function Dh({render:e}){return e()}i(Dh,"RenderHost");function bt({render:e,fallback:t,resetKey:r}){return createElement(zo,{fallback:t,resetKey:r,children:createElement(Dh,{render:e})})}i(bt,"HostRender");var Nh=48;function Uh(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Uh,"selectView");function Ko(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Mt(t),l=useMemo(()=>Uh(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(bt,{render:o,fallback:jsx(gu,{capability:t,style:s})}):jsx(gu,{capability:t,style:s});case "disabled":return n?jsx(bt,{render:()=>n(a),fallback:jsx(hu,{decision:a,style:s}),resetKey:a}):jsx(hu,{decision:a,style:s});default:return Xe(l)}}i(Ko,"CapabilityGate");function gu({capability:e,style:t}){let r=F(),n=useMemo(()=>bu(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(gu,"PendingSkeleton");function hu({decision:e,style:t}){let r=F(),n=useMemo(()=>bu(r),[r]),o=e.disabled?.reason??"";return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsx(C,{style:n.offstateText,children:o}):null})}i(hu,"OffState");function bu(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:Nh,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...E(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(bu,"makeStyles");var h=Object.freeze({placeholder:"Ask me anything!",send:"Send",stop:"Stop",retry:"Try again",followUps:"Helpful follow-ups",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",typing:"Assistant is typing",loading:"Loading",empty:"No messages yet",transcript:"Conversation",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",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openMenu:"Open menu",openMenuUnread:"Open menu, unread chats",yourPets:"Your Pets",yourPet:"Your pet",switchActivePet:"Switch active pet, {name}",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add another 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 K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");var qo=Object.freeze([Object.freeze({key:"inaccurate",label:h.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:h.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:h.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:h.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:h.feedbackReasonOther,feedbackType:"not_helpful"})]),vu=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function Vh(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Vh,"sentimentToFeedbackType");function Cu(e,t){if(e==="down"&&t!==null){let r=qo.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Vh(e)}i(Cu,"feedbackTypeFor");var jh=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function mr(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=Y(),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]),[u,d]=useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=useRef(null);useEffect(()=>{let S=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=S,d({scope:l,controller:S}),()=>{p.current=null,d(O=>O?.controller===S?null:O),t.registry.releaseChat(S);}},[t,r,s,a,o,l]);let f=useCallback(S=>c?c.subscribe(S):Wh,[c]),m=useCallback(()=>c?c.getSnapshot():jh,[c]),y=useSyncExternalStore(f,m,m),k=useCallback((S,O)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Yo(c,c.send(S,O?.imageS3Keys===void 0?{}:{imageS3Keys:O.imageS3Keys}),()=>p.current===c):Promise.resolve(Xo()),[c]),g=useCallback(S=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Yo(c,c.askEverfur(S),()=>p.current===c):Promise.resolve(Xo()),[c]),R=useCallback(()=>c&&p.current===c?Yo(c,c.retryLast(),()=>p.current===c):Promise.resolve(Xo()),[c]),w=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),_=useCallback(()=>{c&&p.current===c&&c.adoptConversation(null);},[c]),[x,b]=useState({controller:null,byMessage:{}}),P=x.controller===c?x.byMessage:Gh,L=useCallback(async(S,O,T,V)=>{if(!c||p.current!==c)return v(D("accessDenied"));let j=String(S),G=x.controller===c?x.byMessage[j]:void 0;if(G===O&&T==null)return b(de=>{let Pe={...de.controller===c?de.byMessage:{}};return delete Pe[j],{controller:c,byMessage:Pe}}),M(Object.freeze({feedbackId:""}));b(de=>({controller:c,byMessage:{...de.controller===c?de.byMessage:{},[j]:O}}));let ne=await c.submitFeedback(S,Cu(O,T??null),V??null);return p.current!==c?v(D("accessDenied")):(ne.ok||b(de=>{let Pe={...de.controller===c?de.byMessage:{}};return G===void 0?delete Pe[j]:Pe[j]=G,{controller:c,byMessage:Pe}}),ne)},[c,x]),I=useMemo(()=>{let S=i(async O=>{if(!c||p.current!==c)return v(D("accessDenied"));let T=await O(c);return p.current===c?T:v(D("accessDenied"))},"run");return {listConversations:i(O=>S(T=>T.listConversations({...s?{petRef:s}:{},...O})),"listConversations"),getMessages:i((O,T)=>S(V=>V.getMessages(O,T)),"getMessages"),resumeConversation:i(O=>S(T=>T.resumeConversation(O)),"resumeConversation"),loadOlderMessages:i(()=>S(O=>O.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>S(O=>O.markRead()),"markRead"),refreshActiveThread:i(()=>S(O=>O.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((O,T)=>S(V=>V.answerCheckin(O,T)),"answerCheckin"),openCheckin:i(O=>S(T=>T.openCheckin(O)),"openCheckin")}},[c,s]);return useMemo(()=>({status:y.status,messages:y.messages,conversationId:y.conversationId,petRef:s,error:y.error,isStreaming:y.isStreaming,isBootstrapping:y.isBootstrapping,historyCursor:y.historyCursor??null,isLoadingHistory:y.isLoadingHistory??false,stopped:y.stopped??false,reconnecting:y.reconnecting??false,...I,suggestedPrompts:y.suggestedPrompts,unreadCount:y.unreadCount,hasUnreadThreads:y.hasUnreadThreads??false,newConversation:_,sentimentByMessage:P,feedback:L,send:k,askEverfur:g,retryLast:R,stop:w}),[y,s,k,g,R,w,I,_,P,L])}i(mr,"useEverfurChat");var Wh=i(()=>{},"NOOP_UNSUBSCRIBE"),Gh=Object.freeze({});async function Yo(e,t,r){for await(let o of t);if(!r())return v(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?v(n.error):M(Kh(n.messages))}i(Yo,"driveToResult");function Kh(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(Kh,"lastAssistantResponseId");function Xo(){return v(D("internalError",{retryable:true}))}i(Xo,"notReadyError");function Su(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:mo(Wr),filename:e.filename,size:mo(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:Gr});case "unsupported_type":return K(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return K(h.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return h.attachmentCancelled;case "rate_limited":return h.attachmentRateLimited;case "quota_exceeded":return h.attachmentQuota;case "idempotency_conflict":return h.attachmentConflict;case "unknown":return h.attachmentUnknown}}i(Su,"attachmentErrorMessage");function Tu(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(Tu,"attachControlLabel");var Xh=Object.freeze({attachments:Object.freeze([])});function an(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=e.maxPerMessage??Gr,s=useMemo(()=>{if(e.queue)return e.queue;let{services:g}=t.registry;return Ta({funnel:ke({auth:g.authFor(r),...g.errorPolicy?{errorPolicy:g.errorPolicy}:{}}),transport:e.transport??g.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.queue,e.transport]);useEffect(()=>()=>{s!==e.queue&&s.dispose();},[s,e.queue]);let a=useSyncExternalStore(s.subscribe,s.getSnapshot,()=>Xh),[l,u]=useState(null),d=useCallback(g=>{let w=(Array.isArray(g)?g:[g]).map(x=>s.add(x)),_=w.find(x=>!x.ok);return _!==void 0&&!_.ok&&u(_.error),w},[s,u]),c=useCallback(g=>s.retry(g),[s]),p=useCallback(g=>s.remove(g),[s]),f=useCallback(()=>s.clear(),[s]),m=useCallback(()=>u(null),[u]),y=a.attachments.some(g=>g.status==="uploading"),k=a.attachments.some(g=>g.status==="failed");return useMemo(()=>({available:s.available,attachments:a.attachments,maxPerMessage:o,uploading:y,failed:k,blocked:y||k,s3Keys:a.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[]),rejected:l,add:d,retry:c,remove:p,clear:f,dismissRejected:m}),[s.available,a,o,y,k,l,d,c,p,f,m])}i(an,"useChatAttachments");var Jh="pet_not_registered";function xu(e){return e!=null&&e.reasonCode===Jh}i(xu,"isPetNotRegistered");var eb=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function _u(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=Y(),a=useCallback(()=>Qe(n.registry.services.authFor(o)),[n,o,s]),l=useMemo(()=>t===void 0?null:Zo(t),[t]),[u,d]=useState({key:null,status:"idle",error:null,registered:null}),c=useRef(0),p=useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,m=useCallback(()=>{if(e===null||t===void 0||f===null)return;let k=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(g=>{k===c.current&&(g.ok?(d({key:f,status:"registered",error:null,registered:g.value}),p.current?.()):d({key:f,status:"failed",error:g.error,registered:null}));});},[a,e,f]);useEffect(()=>{if(f===null){c.current+=1;return}return m(),()=>{c.current+=1;}},[f,m]);let y=useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return useMemo(()=>f===null?eb:u.key!==f?{status:"registering",error:null,registered:null,retry:y}:{status:u.status,error:u.error,registered:u.registered,retry:y},[f,u,y])}i(_u,"useChatPetRegistration");function Zo(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Zo).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)}:${Zo(n)}`).join(",")}}`}i(Zo,"stableKey");var Jo=Object.freeze({});function Iu(e){let[t,r]=useState(Jo),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===Jo?u:Jo);return}let a=n.current;if(a===null)return;let l=e.find(u=>u.role==="user"&&!a.known.has(u.id));l!==void 0&&(n.current=null,r(u=>({...u,[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(Iu,"useSentImages");var sb=500;function ei(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,sb):null}i(ei,"sanitizeSeedPrompt");function Ou(e,t,r){let n=ei(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(Ou,"useInitialAsk");function ab(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(ab,"isCoalesced");function Fu(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"}:ab(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Fu,"decideChatRefresh");function ti(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ti,"reportHostFailure");function lb(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(lb,"isThenable");function q(e,...t){if(typeof e=="function")try{let r=e(...t);return lb(r)&&Promise.resolve(r).then(void 0,ti),r}catch(r){ti(r);return}}i(q,"callHost");var Mu=new WeakMap;function Lu(e){if(typeof e!="function")return;let t=Mu.get(e);if(t!==void 0)return t;let r=i((...n)=>{q(e,...n);},"guarded");return Mu.set(e,r),r}i(Lu,"guardHost");function Dt(e,...t){let r;try{r=e(...t);}catch(n){return ti(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Dt,"callHostAsync");function Nu(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),s=e?.isOffline===void 0?false:q(()=>e.isOffline?.()===!0)===true,a=useRef(()=>{});a.current=l=>{let{conversationId:u,isTurnInFlight:d,refresh:c}=r.current,p=Fu(l,{activeConversationId:u,isTurnInFlight:d,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=[],u=i((d,c)=>{if(d===void 0)return;let p=q(()=>d(()=>{a.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let d of l)q(d);}},[e]);}i(Nu,"useChatLifecycle");function db(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(db,"targetKey");function Vu(e,t){let r=db(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(Vu,"useCheckinTarget");function zu(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 u=l.send===e&&(l.conversationId===null||l.conversationId===t),d=u?l.text:"",c=u?l.seeded:null,p=r!=null&&r!==c&&d.length===0;return {send:e,conversationId:t,text:p?r:d,seeded:p?r:c}});},[e,t,r]);let a=useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [s?n.text:"",a]}i(zu,"useChatDraft");function ju(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 u=`${t??""}`;if(s.current===u)return;s.current=u;let d=true;return (async()=>{let c=await Dt(()=>e.read(t));if(!d)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{d=false;}},[e,t]),useEffect(()=>{e===void 0||a!==`${t??""}`||q(()=>e.write(t,r));},[e,t,r,a]);}i(ju,"usePersistedDraft");var Z=Object.freeze({heading:"Chat History",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No matching chats",noMatchBody:"Try a different title or start a new conversation.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newConversation:"New conversation",newChat:"New chat",search:"Search",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 un(e){let t=e?.replace(/\s+/g," ").trim();return t||Z.untitled}i(un,"conversationTitle");function Gu(e){return `${e.unreadCount!==null&&e.unreadCount>0?Z.unreadPrefix:""}${Z.openConversation} ${un(e.title)}`}i(Gu,"openConversationLabel");function Wu(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Wu,"normalizeForSearch");function gb(e,t){let r=Wu(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=Wu(un(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(gb,"filterConversations");function oi(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(oi,"fresh");function Ku(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,u]=useState(()=>oi(s)),d=l.scope===s?l:oi(s);useEffect(()=>(a.current+=1,r(false),o(""),u(oi(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async _=>{let x=++a.current,b=_!==void 0;u(L=>({...L,scope:s,loading:!b,loadingMore:b,error:null}));let P=await e.listConversations(_?{cursor:_}:void 0);if(x===a.current){if(!P.ok){u(L=>({...L,loading:false,loadingMore:false,error:P.error.displayMessage}));return}u(L=>{let I=_&&L.scope===s?L.rows:[],S=new Set(I.map(O=>O.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...I,...P.value.conversations.filter(O=>!S.has(O.id))],cursor:P.value.nextCursor===_?null:P.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async _=>{let x=++a.current;u(P=>({...P,loading:true,error:null}));let b=await e.resumeConversation(_);x===a.current&&(u(P=>({...P,loading:false,error:b.ok?null:b.error.displayMessage})),b.ok&&r(false));},"resume"),y=i(async()=>{let _=a.current,x=await e.loadOlderMessages();_===a.current&&!x.ok&&u(b=>({...b,error:x.error.displayMessage}));},"earlier"),k=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),g=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),R=useMemo(()=>gb(d.rows,n),[d.rows,n]),w=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:y,newConversation:k,loadMore:g,query:n,setQuery:o,searching:w,filtered:R,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(Ku,"useHistoryPanel");var dn="#111111",cn="#FFFFFF",vb=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:dn,pillColor:cn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:dn,pillColor:cn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:dn,pillColor:cn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:dn,pillColor:cn,showsVetAction:false})});function Cb(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(Cb,"urgencySignature");function Eb(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(Eb,"generalUrgencyReason");function Yu(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:n.urgencyReason??null}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Eb(t)}:null}return null}i(Yu,"latestUrgencySource");function Xu(e){let t=e===null?null:Cb(e),[r,n]=useState(null),[o,s]=useState(false);useEffect(()=>s(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:vb[e.level],d=e!==null&&!l&&e.level!=="general",c=useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=useCallback(()=>s(true),[]);return useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:d,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(h.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Xu,"useUrgencySurface");function Qu(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Qu,"selectView");function Rb(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Rb,"needsNewConversation");function Zu(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Rb(t);return {tone:"error",title:r?h.turnUnreachableTitle:h.turnFailedTitle,body:t.displayMessage,actionLabel:r?h.turnStartNewChat:h.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:h.turnStoppedTitle,body:h.turnStoppedBody,actionLabel:h.turnRetry,action:"retry"}:null}i(Zu,"turnNotice");function Ju(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(Ju,"awaitingAssistant");function ed(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(ed,"buildChatOpts");var gr=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function nd(e){let t=F(),r=useMemo(()=>Pb(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${gr.title}. ${gr.body}`,children:[jsx(C,{style:r.title,children:gr.title}),jsx(C,{style:r.body,children:gr.body})]})}i(nd,"ClinicalDisclaimer");function Pb(e){let{color:t,space:r,type:n}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{...E(e,"bold"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{...E(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.muted}})}i(Pb,"makeStyles");var se={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function te(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(te,"box");function fe(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(fe,"stroke");function od({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxs(View,{style:[te(e),{gap:e*.22}],...se,children:[jsx(View,{style:o}),jsx(View,{style:o}),jsx(View,{style:o})]})}i(od,"MenuGlyph");function id({size:e,color:t,strokeWidth:r,rotate:n}){let o=fe(e,r),s=e*.78;return jsxs(View,{style:[te(e),{transform:[{rotate:n}]}],...se,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(id,"Cross");function sd(e){return jsx(id,{...e,rotate:"0deg"})}i(sd,"PlusGlyph");function vt(e){return jsx(id,{...e,rotate:"45deg"})}i(vt,"CloseGlyph");function tt({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsx(View,{style:te(e),...se,children:jsx(View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(tt,"CheckGlyph");var _b={down:{rotate:"45deg",marginTop:-0.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-0.4}};function pn({size:e,color:t,strokeWidth:r,direction:n}){let o=fe(e,r),s=e*.46,a=_b[n];return jsx(View,{style:te(e),...se,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(pn,"ChevronGlyph");function ad({size:e,color:t,strokeWidth:r}){let n=fe(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}],...se,children:[jsx(View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsx(View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(ad,"BookGlyph");function ld({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.5;return jsxs(View,{style:te(e),...se,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(ld,"ArrowUpRightGlyph");function ud({size:e,color:t,strokeWidth:r}){let n=fe(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),...se,children:[jsx(View,{style:[s,{top:0,left:0}]}),jsx(View,{style:[s,{bottom:0,right:0}]})]})}i(ud,"CopyGlyph");function fn({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=fe(e,r),a=n?t:"transparent";return jsxs(View,{style:[te(e),{transform:[{rotate:o}]}],...se,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(fn,"ThumbGlyph");function dd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:[te(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...se,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(dd,"InfoGlyph");function cd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.34;return jsxs(View,{style:te(e),...se,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(cd,"UploadGlyph");function pd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:[te(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...se,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(pd,"PhotoGlyph");function fd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:te(e),...se,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(fd,"CameraGlyph");function md({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.66;return jsxs(View,{style:te(e),...se,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(md,"SearchGlyph");function yd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),jsx(View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}i(yd,"EditGlyph");function gd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.62;return jsxs(View,{style:te(e),...se,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(gd,"MapPinGlyph");function hd({size:e,color:t,testID:r}){let n=e*.36;return jsx(View,{style:te(e),testID:r,...se,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(hd,"SendGlyph");function bd({size:e,color:t,testID:r}){return jsx(View,{style:te(e),testID:r,...se,children:jsx(View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(bd,"StopGlyph");function mn({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(mn,"Ring");var hr=Object.freeze({standard:pt.standard,emphasized:pt.emphasized,exit:pt.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var vd=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,reduced:false}),wb=Object.freeze({...vd,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,reduced:true});function Cd(e){return e.motion.reducedMotion?wb:vd}i(Cd,"chatMotion");function yn(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(yn,"followUpDelayMs");function Ed(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(Ed,"nextRevealLength");function X(){let e=F();return Cd(e)}i(X,"useChatMotion");var Lb=8;function Sd(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(Sd,"bezierComponent");function Db(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(Db,"bezierSlope");function gn(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<Lb;l+=1){let u=Db(a,t,n);if(u===0)break;a-=(Sd(a,t,n)-s)/u;}return Sd(Math.min(1,Math.max(0,a)),r,o)}}i(gn,"bezierEasing");var ii=gn(hr.standard),Nb=gn(hr.outQuad);function ui(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(ui,"useAnimatedValue");function Ct(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=ui(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:Nb,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(Ct,"useFadeIn");function di({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=ui(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let d=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:ii,useNativeDriver:true});return d.start(),()=>d.stop()}if(!s)return;if(r<=0){a(false);return}let u=Animated.timing(l,{toValue:0,duration:r,easing:ii,useNativeDriver:true});return u.start(({finished:d})=>{d&&a(false);}),()=>u.stop()},[e,s,t,r,l]),!s&&!e?null:jsx(Animated.View,{style:[n,{opacity:l}],children:o})}i(di,"FadePresence");var Ub=12;function B({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=X(),u=ui(1),d=useCallback(c=>{l.pressMs<=0||l.pressScale===1||Animated.timing(u,{toValue:c,duration:l.pressMs,easing:ii,useNativeDriver:true}).start();},[u,l.pressMs,l.pressScale]);return jsx(Pressable,{...a,hitSlop:s??Ub,style:t,onPressIn:c=>{d(l.pressScale),n?.(c);},onPressOut:c=>{d(1),o?.(c);},children:jsx(Animated.View,{style:[e,{transform:[{scale:u}]}],children:r})})}i(B,"PressScale");function kd(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(u=>Ed(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(kd,"useRevealedText");var Td=false;function Vb(e){e.layoutMs<=0||(Td||(Td=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(Vb,"animateLayout");function br(e,t){let r=useRef(e);r.current!==e&&(r.current=e,Vb(t));}i(br,"useAnimateLayoutOn");var ci=36,Kb=22,qb=12,$b=12,Yb=16,Xb="#000",Qb="rgba(0,0,0,0.45)";function xd({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:h.closePreview,style:hn.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:hn.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[hn.closeWrap,{top:o.top+$b}],children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:qb,style:hn.closeButton,onPress:r,children:jsx(vt,{size:Kb,color:n.color.surface,strokeWidth:2})})})]})}i(xd,"AttachmentImageLightbox");var hn=StyleSheet.create({backdrop:{flex:1,backgroundColor:Xb,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:Yb},closeButton:{width:ci,height:ci,borderRadius:ci/2,backgroundColor:Qb,alignItems:"center",justifyContent:"center"}});var bn=12,rv=80,pi=44,_d=22,nv=.14,ov=18,iv=8,wd=Object.freeze({photo:h.attachmentPhoto,camera:h.attachmentCamera});function Id({sources:e,full:t,onPick:r,onClose:n}){let o=F(),s=useMemo(()=>sv(o),[o]);return jsxs(View,{style:s.anchor,pointerEvents:"box-none",children:[jsx(Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:h.closeAttachmentPicker,onPress:n}),jsxs(View,{style:s.bubble,children:[jsx(View,{style:s.tilesRow,children:e.map(a=>jsxs(B,{accessibilityRole:"button",accessibilityLabel:wd[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(pd,{size:_d,color:o.color.brandInk,strokeWidth:1.5}):jsx(fd,{size:_d,color:o.color.brandInk,strokeWidth:1.5})}),jsx(C,{tier:"control",style:s.tileLabel,children:wd[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(Id,"AttachmentPickerPopover");function sv(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:nv,shadowRadius:ov,shadowOffset:{width:0,height:iv},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:rv,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:pi,height:pi,borderRadius:pi/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...E(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-bn/2,width:bn,height:bn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:bn+4,height:2,backgroundColor:t.surfaceCream}})}i(sv,"makeStyles");var Ad=56,Od=12,uv=14,dv=10,cv=.45,pv="rgba(7,193,104,0.55)",fv="rgba(185,28,28,0.55)",mv=200,yv=300,Hd=20,mi=22,gv=12,hv="rgba(0,0,0,0.78)",Fd=220,Md=100,Ld="rgba(255,255,255,0.15)";function Bd({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=F(),l=useMemo(()=>jd(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(u=>jsx(bv,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:h.attachmentsFailedBlocked}):null,t!==null?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:Su(t)}):null]})}i(Bd,"AttachmentStrip");function bv({row:e,styles:t,onRetry:r,onRemove:n,onPreview:o}){let s=F(),a=e.status==="uploading",l=e.status==="failed",u=e.status==="uploaded",d=useRef(e.status),[c,p]=useState(false);return useEffect(()=>{let f=d.current;d.current=e.status,e.status==="uploaded"&&f==="uploading"&&p(true);},[e.status]),jsxs(View,{style:t.card,children:[jsx(Pressable,{accessibilityRole:u?"button":"image",accessibilityLabel:u?K(h.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:a,disabled:!u},disabled:!u,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(vv,{styles:t,onDone:()=>p(false)}):null]})}),l?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsx(View,{style:t.failedInner,children:jsx(vt,{size:Hd,color:s.color.surface,strokeWidth:2})})}):null,jsx(B,{accessibilityRole:"button",accessibilityLabel:K(h.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsx(vt,{size:gv,color:s.color.surface,strokeWidth:1.5})})]})}i(bv,"PreviewCard");function vv({styles:e,onDone:t}){let r=F(),n=X(),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:mv,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:yv,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(tt,{size:Hd,color:r.color.surface,strokeWidth:2})})}i(vv,"SuccessFlash");function zd({images:e,onPreview:t}){let r=F(),n=useMemo(()=>jd(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:K(h.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(zd,"SentImages");function jd(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:Ad,height:Ad,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Od,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:tl(e.color.brandInk,cv)??e.color.brandSofter},successOverlay:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center",backgroundColor:pv},failedOverlay:{...StyleSheet.absoluteFillObject,borderRadius:Od,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:fv},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:mi,height:mi,borderRadius:mi/2,backgroundColor:hv,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...E(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:Fd,height:Fd,borderRadius:uv,backgroundColor:Ld},gridImage:{width:Md,height:Md,borderRadius:dv,backgroundColor:Ld}})}i(jd,"makeStyles");var Cv="file",Ev="chat attachment upload: the file handle has no uri",Rv="chat attachment upload failed";function Sv(e){return {uri:e.uri,name:fo(e.name),type:e.mimeType}}i(Sv,"filePartOf");function Wd(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Ev));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Rv)),"failed");if(o?.aborted===true)return a();let l=new FormData;for(let[d,c]of Object.entries(t.upload_fields))l.append(d,c);l.append(Cv,Sv(r));let u=e.fetch??fetch;return Promise.resolve().then(()=>u(t.upload_url,{method:"POST",body:l,credentials:"omit",...o?{signal:o}:{}})).then(d=>{if(!d.ok)return a();s?.(1);},a)}})}i(Wd,"createRnChatAttachmentTransport");function vn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=Y(),o=useMemo(()=>Qe(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},u=useRef(0),d=useCallback(async()=>{let p=++u.current;a(m=>({...m,repository:o,loading:true,error:null,pets:m.repository===o?m.pets:[]}));let f=await o.list();p===u.current&&a(f.ok?{repository:o,pets:f.value,loading:false,error:null}:m=>({repository:o,pets:m.repository===o?m.pets:[],loading:false,error:f.error}));},[o]);useEffect(()=>(d(),()=>{u.current+=1;}),[d]);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:d}),[l.pets,l.loading,l.error,c,d])}i(vn,"useEverfurPets");function Gd(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(Gd,"headerPetOf");function me(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(me,"slotBox");function bi(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(bi,"ownGroundSlot");function we(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(we,"slotText");var Kd=Object.freeze({visitButton:"Talk to a vet"});var qd=Symbol.for("@everfur/sdk/televet");function Ge(){let e=globalThis,t=e[qd];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[qd]=r,r}i(Ge,"televetGlobal");function Cn(e){let t=Ge();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Cn,"publish");function $d(e){let t=Ge().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($d,"callTelevetPresenter");function Yd(e){let t=Ge();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(Yd,"subscribeTelevetExperience");function vi(){return Ge().snapshot}i(vi,"televetExperienceSnapshot");function _v(){return Ge().hosts.length>0}i(_v,"hasTelevetHost");function Xd(e){if(!_v())return false;let t=Object.freeze({...e});return Cn({request:t,serial:Ge().snapshot.serial+1}),true}i(Xd,"presentTelevetExperience");function Ci(){Ge().snapshot.request!==null&&Cn({request:null});}i(Ci,"dismissTelevetExperience");function Qd(){let e=Ge(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Cn({activeHost:e.hosts[0]??null}),t}i(Qd,"claimTelevetHost");function Zd(e){let t=Ge();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Cn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(Zd,"releaseTelevetHost");var Jd=false;function En(e,t){return t!==void 0?(q(t,e),"onStartInApp"):$d(e)==="presented"?"presenter":Xd(e)?"experience":(Jd||(Jd=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(En,"openVetVisitInApp");function rc(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(rc,"memoizeTelevetLoader");function nc(e){let[t,r]=useState(null);useEffect(()=>{let d=Qd();return r(d),()=>{Zd(d);}},[]);let n=useSyncExternalStore(Yd,vi,vi),s=t!==null&&n.activeHost===t?n.request:null,[a,l]=useState(null),u=s!==null&&a===null;return useEffect(()=>{if(!u)return;let d=true;return e().then(c=>{d&&l(()=>c);},c=>{d&&(console.warn("[everfur] The in-app vet visit could not load its screens.",c),Ci());}),()=>{d=false;}},[u,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:Ci}}i(nc,"useTelevetExperienceHost");var Iv=rc(()=>import('@everfur/sdk/televet/booking'));function Er(){let e=nc(Iv);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(Er,"EverfurTelevetHost");var Ei=Object.freeze(["visit","join","summary","messages"]);function Ri(e){return typeof e=="string"&&Ei.includes(e)}i(Ri,"isVetVisitIntent");var Ov="/widget/v1/televet/handoffs",Fv="/widget/v1/televet/availability",Mv="/widget/v1/televet/chat-entry",Lv=/^[a-z0-9][a-z0-9_-]{0,39}$/,Dv=/^[A-Za-z0-9_-]{22}$/;var oc=32,ic=128,sc=64;function Ti(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(Ti,"vetVisitErrorReasonOf");function ac(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i(ac,"invalid");function Si(e){return v(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Si,"unusable");function Nv(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Lv.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 u=typeof s=="string"?s.trim():"";if(u.length<1||[...u].length>sc)return {ok:false,message:`visitRef must be 1..${sc} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Ri(a))return {ok:false,message:`intent must be one of ${Ei.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(Nv,"handoffBody");function Uv(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Ri(r)?null:Object.freeze({visitRef:t,intent:r})}i(Uv,"parseVisitEcho");function uc(e){let t=e.funnel??ke({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(lc(r,"televet.visit.handoff_failed",{reason:Ti(o)}),v(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let g=typeof o=="string"?[...o].length:0;if(g<1||g>ic)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${ic} characters`}));a=o;}let l=Nv(a,s);if(!l.ok){let g=ac(l.message);return g.ok?g:n(g.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:Ov,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=Vv(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!Dv.test(f))){let g=Si("the handoff response carried no usable return flow id");return g.ok?g:n(g.error)}let m=u.visit_ref!==void 0,y=m?Uv(d.value?.visit):null;if(m&&y===null){let g=Si("the handoff response did not confirm the visit it opens");return g.ok?g:n(g.error)}let k=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...y!==null?{visit:y}:{}});return k===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(lc(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),M(k))},async checkAvailability(o){if(typeof o!="string"||o.length>oc)return ac(`state must be at most ${oc} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:Fv,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.available;return typeof a!="boolean"?Si("the availability response carried no usable answer"):M(Object.freeze({available:a}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:Mv},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(uc,"createVetVisitController");function Vv(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||!jv(t)?null:Object.freeze({url:t,expiresAt:r})}i(Vv,"parseHandoff");var Hv=new Set(["localhost","127.0.0.1","[::1]"]),Bv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,zv=/[\s\u0000-\u001f\u007f]/;function jv(e){if(zv.test(e))return false;let t=Bv.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"&&Hv.has(o);if(!s&&!a)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(jv,"isOpenableVisitUrl");function lc(e,t,r){if(e)try{e.track(t,r);}catch{}}i(lc,"safeTrack");var Pi=Object.freeze({status:"idle",error:null,errorReason:null});function Gv(e,t,r){let{usState:n,chat:o,scope:s}=r,a=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,d]=useState(null);if(useEffect(()=>{if(!a)return;let p=true,f=e.current;return d(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let y=await f.checkAvailability(n);return y.ok&&y.value.available}catch{return false}},"ask")().then(y=>{p&&d({key:l,open:y});}),()=>{p=false;}},[a,l,n,o,s,e]),!a)return null;let c=u!==null&&u.key===l;return {open:c&&u.open,pending:!c}}i(Gv,"usePreflight");var Kv=Object.freeze({status:"opening",error:null,errorReason:null});function pc(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=Y(),s=Mt("televet"),a=s.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",d=t.petRef??null,c=t.prefer==="redirect",p=useMemo(()=>{if(t.controller)return t.controller;let{services:T}=r.registry;return uc({auth:T.authFor(n),telemetry:T.telemetry,...T.errorPolicy?{errorPolicy:T.errorPolicy}:{}})},[r,n,o,t.controller]),f=useRef(p);f.current=p;let m=useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),y=Gv(f,a,{usState:l,chat:u,scope:m}),k=a&&(y===null||y.open)&&(!u||d!==null),g=t.returnTo??null,[R,w]=useState(Pi),_=useRef(null),x=useRef({runtime:r,userRef:n,scopeEpoch:o});x.current={runtime:r,userRef:n,scopeEpoch:o};let b=useRef(p);b.current=p;let P=useRef(k);P.current=k;let L=useCallback((T,V)=>{if(_.current)return _.current;let j=i((ce,ot)=>(w({status:ce==="cancelled"?"idle":"error",error:ot,errorReason:ce==="cancelled"?null:ce}),Object.freeze({opened:false,reason:ce,error:ot})),"fail");if(!P.current)return Promise.resolve(j("unavailable",null));let G=e.prepare();if(!G.ok)return Promise.resolve(j(G.reason,null));let ne=x.current,de=b.current;w(Kv);let Gt=(async()=>{let ce,ot={...g!==null?{returnTo:g}:{},...u?{entry:"chat"}:{},...V!==null?{visitRef:V.visitRef}:{},...V!==null&&V.intent!==null&&V.intent!==void 0?{intent:V.intent}:{}},wr=Object.keys(ot).length===0?void 0:ot,Kt=T===void 0?d:T;try{ce=await(wr===void 0?de.createHandoff(Kt):de.createHandoff(Kt,wr));}catch{return e.abandon(G.value),j("unknown",null)}let xt=x.current;if(xt.runtime!==ne.runtime||xt.userRef!==ne.userRef||xt.scopeEpoch!==ne.scopeEpoch)return e.abandon(G.value),j("cancelled",null);if(!ce.ok)return e.abandon(G.value),j(Ti(ce.error),ce.error);let _t=await e.finish(G.value,ce.value);return _t!==null?j(_t,null):(w(Pi),Object.freeze(ce.value.flowId===void 0?{opened:true}:{opened:true,flowId:ce.value.flowId}))})().finally(()=>{_.current===Gt&&(_.current=null);});return _.current=Gt,Gt},[e,d,g,u]),I=useCallback((T,V)=>{if(!P.current)return w({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let j=T===void 0?d:T,G={...j!==null?{petRef:j}:{},...l!==null?{usState:l}:{},...V!==null?{visitRef:V.visitRef,intent:V.intent}:{}};return En(G)===null?(w({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(w(Pi),Promise.resolve(Object.freeze({opened:true})))},[d,l]),S=useCallback(T=>c?L(T,null):I(T,null),[c,L,I]),O=useCallback((T,V)=>c?L(void 0,{visitRef:T,intent:V??null}):I(void 0,{visitRef:T,intent:V??null}),[c,L,I]);return {available:k,isPending:s.isPending||(y?.pending??false),status:R.status,error:R.error,errorReason:R.errorReason,open:S,openVisit:O}}i(pc,"useVetVisitWith");var Yv=i(e=>Linking.openURL(e),"defaultOpenUrl");function Sn(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??Yv;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 pc(n,r)}i(Sn,"useVetVisit");var fc=44,eC=.6;function Vt(e){let{petRef:t,label:r,openUrl:n,onOpened:o,onError:s,style:a,labelStyle:l,controller:u,returnTo:d,usState:c,entry:p,visitRef:f,intent:m,onStartInApp:y,prefer:k}=e,g=k==="redirect",R=Sn({...d!==void 0?{returnTo:d}:{},...c!==void 0?{usState:c}:{},...p!==void 0?{entry:p}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:g?"redirect":"in-app"}),w=F(),_=useMemo(()=>tC(w),[w]),x=useRef(false);if(!R.available)return jsxs(Fragment,{children:[null,jsx(Er,{})]});let b=R.status==="opening",P=r??Kd.visitButton;return jsxs(Fragment,{children:[jsx(Pressable,{onPress:i(()=>{if(!(b||x.current)){if(!g){let I={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...f!=null?{visitRef:f,intent:m??null}:{}};En(I,y)===null&&q(s,"unavailable",null);return}x.current=true,(f==null?R.open():R.openVisit(f,m??null)).then(I=>{I.opened?q(o,I.flowId??null):I.reason!=="cancelled"&&q(s,I.reason,I.error);}).finally(()=>{x.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:P,accessibilityState:{busy:b,disabled:b},style:[_.button,b?_.busy:null,a],children:jsx(C,{style:[_.label,l],children:P})}),jsx(Er,{})]})}i(Vt,"VetVisitButton");function tC(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:fc,minWidth:fc,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...me(s.vetVisitButton)},busy:{opacity:eC},label:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...we(s.vetVisitButton)}})}i(tC,"makeStyles");function ki(e){return sr(e)==="cat"?"cat":"dog"}i(ki,"speciesOf");function xi(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(xi,"petAgeYears");function hc(e){let t=xi(e.ageYears),r=ki(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(hc,"formatPetMeta");var gc=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 rC(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return gc[t%gc.length]}i(rC,"pickInitialsPalette");function _i(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(_i,"getInitial");function bc(e){return {...rC(e.petRef),initial:_i(e.name)}}i(bc,"petInitials");function sC(e){return Math.max(12,Math.round(e*.42))}i(sC,"letterSize");function Sr({pet:e,size:t,ringStroke:r}){let n=F(),o=useMemo(()=>aC(n),[n]),s=t-r*2,a=e===null?null:bc(e),l=sC(s);return jsx(mn,{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(C,{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?_i(null):a.initial})})})}i(Sr,"PetDisc");function aC(e){return StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...E(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(aC,"makeStyles");var Ii=48,Rc=2,pC=320,fC="80%",mC="rgba(17,17,17,0.45)",yC=18,vc=22,gC=12,Cc=.4,hC=44;function Ai(e){return e?.name?.trim()||h.yourPet}i(Ai,"petDisplayName");function Sc({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=F(),l=useMemo(()=>bC(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:StyleSheet.absoluteFill,onPress:s,accessibilityRole:"button",accessibilityLabel:h.close,children:jsx(View,{style:l.backdrop})}),jsxs(View,{style:l.panel,accessibilityViewIsModal:true,children:[jsx(C,{tier:"heading",style:l.title,accessibilityRole:"header",children:h.yourPets}),jsx(ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(u=>{let d=u.petRef===r,c=Ai(u),p=hc(u);return jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(d?h.petCurrentlyActive:h.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsx(Sr,{pet:u,size:Ii,ringStroke:Rc}),jsxs(View,{style:l.copy,children:[jsx(C,{style:l.name,numberOfLines:1,children:c}),jsx(C,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${h.activePrefix}${p}`:p})]}),d?jsx(tt,{size:yC,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.addAnotherPet,style:l.addRow,onPress:o,children:[jsx(View,{style:l.addDisc,children:jsx(C,{tier:"control",style:l.addPlus,children:"+"})}),jsx(C,{style:l.addLabel,children:h.addAnotherPet})]}):null,jsx(B,{accessibilityRole:"button",accessibilityLabel:h.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsx(C,{tier:"control",style:l.closeText,children:h.close})})]})]})}):null}i(Sc,"PetSwitcherSheet");function bC(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:mC},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:vc,borderTopRightRadius:vc,gap:14,maxHeight:fC},title:{...E(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:pC,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:hC,paddingHorizontal:8},addDisc:{width:Ii,height:Ii,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Rc,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...E(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...E(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:{...E(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...E(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Cc},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:gC,backgroundColor:t.brandSoft},closeText:{...E(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Cc}})}i(bC,"makeStyles");var EC=44,Pn=36,RC=22,Fi=9,SC=1.5,Tc=6,Rt=35,kn=1.75,Mi=12.4,TC=.5,PC=8,kC=28,xC=160;function Di(e,t){return Gd(e,t)}i(Di,"headerPet");function kc({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=F(),u=useMemo(()=>wC(l),[l]),[d,c]=useState(false),p=Di(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,y=Ai(p),k=i(R=>{c(false),e.setActivePet(R),q(o,R);},"select"),g=s===void 0?null:()=>{c(false),q(s);};return jsxs(View,{style:u.row,children:[jsxs(B,{accessibilityRole:"button",accessibilityLabel:r?h.openMenuUnread:h.openMenu,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsx(od,{size:RC,color:l.color.text.primary,strokeWidth:2}),r?jsx(View,{style:u.unreadDot,pointerEvents:"none"}):null]}),jsx(View,{style:u.center,pointerEvents:"box-none",children:jsx(_C,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsx(Vt,{entry:"chat",petRef:m,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:u.vetEntry,labelStyle:u.vetEntryLabel}),jsx(View,{style:u.right,children:f?jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(h.switchActivePet,{name:y}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsx(Sr,{pet:p,size:Rt,ringStroke:kn}),jsx(View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(sd,{size:PC,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsx(mn,{size:Rt,strokeWidth:kn,color:l.color.success,children:jsx(View,{style:u.placeholderDisc})})}):jsx(View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?h.yourPet:y,children:jsx(Sr,{pet:p,size:Rt,ringStroke:kn})})}),jsx(Sc,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:k,onAddPet:g,onClose:()=>c(false)})]})}i(kc,"ChatHeader");function _C({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(_C,"BrandLogo");function wC(e){let t=e.color,r=Rt-kn*2;return StyleSheet.create({vetEntry:{minHeight:EC,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...E(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:Pn/2},iconButton:{width:Pn,height:Pn,borderRadius:Pn/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Tc,right:Tc,width:Fi,height:Fi,borderRadius:Fi,backgroundColor:t.danger,borderWidth:SC,borderColor:t.surface},center:{...StyleSheet.absoluteFillObject,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:kC,width:xC},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Rt/2},avatarWrap:{width:Rt,height:Rt,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Mi,height:Mi,borderRadius:Mi/2,borderWidth:TC,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(wC,"makeStyles");var _c=44,MC="rgba(17,17,17,0.55)",wc=26,LC=36,Ic=4,Ui=20,Vi=38,DC=18,NC=12;function Ac({visible:e,onSubmit:t,onSkip:r}){let n=F(),o=useMemo(()=>UC(n),[n]),[s,a]=useState(null),[l,u]=useState(""),[d,c]=useState(false),[p,f]=useState(false),m=i(()=>{a(null),u(""),c(false),f(false);},"reset"),y=i(()=>{d||(m(),r());},"skip"),k=i(async()=>{if(d)return;c(true),f(false);let R=l.trim();await t(s,R.length>0?R:null)?m():(c(false),f(true));},"submit");if(!e)return null;let g=[...l].length>At;return jsx(Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:y,children:jsxs(KeyboardAvoidingView,{behavior:Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsx(Pressable,{style:o.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:h.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(fn,{size:DC,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxs(View,{style:o.headerText,children:[jsx(C,{tier:"heading",style:o.title,accessibilityRole:"header",children:h.feedbackTitle}),jsx(C,{style:o.subtitle,children:h.feedbackSubtitle})]})]}),jsx(View,{style:o.options,children:qo.map(R=>{let w=s===R.key;return jsxs(B,{accessibilityRole:"button",accessibilityLabel:R.label,accessibilityState:{selected:w},style:[o.option,w?o.optionSelected:null],onPress:()=>a(_=>_===R.key?null:R.key),children:[jsx(C,{style:[o.optionLabel,w?o.optionLabelSelected:null],children:R.label}),jsx(View,{style:[o.radio,w?o.radioSelected:null],children:w?jsx(tt,{size:NC,color:n.color.surface,strokeWidth:2}):null})]},R.key)})}),jsxs(View,{style:o.inputWrap,children:[jsx(Lt,{style:o.input,placeholder:h.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:h.feedbackNotesPlaceholder,value:l,onChangeText:u,multiline:true,editable:!d}),l.length>0?jsx(C,{tier:"compact",style:[o.counter,g?o.counterOver:null],children:`${[...l].length}/${At}`}):null]}),p?jsx(C,{style:o.failed,accessibilityRole:"alert",children:h.feedbackFailed}):null,jsxs(View,{style:o.actions,children:[jsx(B,{accessibilityRole:"button",accessibilityLabel:h.feedbackSubmit,accessibilityState:{busy:d,disabled:d||g},disabled:d||g,style:[o.submit,d||g?o.submitDisabled:null],onPress:()=>{k();},children:jsx(C,{tier:"control",style:o.submitLabel,children:h.feedbackSubmit})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y,hitSlop:8,onPress:y,style:o.skip,children:jsx(C,{tier:"control",style:o.skipLabel,children:h.feedbackSkip})})]})]})]})})}i(Ac,"FeedbackReasons");function UC(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...StyleSheet.absoluteFillObject,backgroundColor:MC},sheet:{backgroundColor:t.surface,borderTopLeftRadius:wc,borderTopRightRadius:wc,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:LC,height:Ic,borderRadius:Ic/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Vi,height:Vi,borderRadius:Vi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...E(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...E(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:{...E(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:Ui,height:Ui,borderRadius:Ui/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,...E(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...E(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...E(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:_c,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...me(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...we(o.primaryButton)},skip:{minHeight:_c,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...E(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(UC,"makeStyles");var ZC=.88,JC=420,eE=58,tE="rgba(17,17,17,0.28)",rE=.08,nE=.1,oE=.08,iE=.18,sE=.78,aE=.7,Hi=36,lE=10,uE=14,dE=12,cE=16,pE=14,Bi=8,fE=1.5,mE=.5,yE=gn(hr.standard);function gE(e){return Math.min(Math.round(e*ZC),JC)}i(gE,"drawerPanelWidth");function Fc({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(hE,{chat:e,history:t,onHidden:o}):null}i(Fc,"HistoryDrawer");function hE({chat:e,history:t,onHidden:r}){let n=F(),o=useMemo(()=>vE(n),[n]),s=X(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),u=gE(l),d=t.open,c=useRef(null);c.current===null&&(c.current=new Animated.Value(s.drawerMs<=0&&d?1:0));let p=c.current;useEffect(()=>{if(!d&&s.drawerMs<=0){r();return}let R=Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:yE,useNativeDriver:true});return R.start(({finished:w})=>{w&&!d&&r();}),()=>R.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,y=t.rows.length===0,k=y&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:Z.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:n.color.onPrimary}),jsx(C,{style:o.emptyBody,children:Z.loading})]}):y&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,accessibilityRole:"alert",children:Z.loadFailed}),jsx(C,{style:o.emptyBody,children:t.error}),jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(C,{tier:"control",style:o.retryText,children:Z.retry})})]}):jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,children:t.emptyKind==="empty"?Z.empty:Z.noMatch}),jsx(C,{style:o.emptyBody,children:t.emptyKind==="empty"?Z.emptyBody:Z.noMatchBody})]}),g=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(C,{style:o.loadMoreLabel,children:Z.loadingMore})}):null;return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxs(View,{style:o.root,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Z.closeA11y,children:jsx(Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsx(Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(eE,a.top+n.space.md),transform:[{translateX:f}]}],accessibilityViewIsModal:true,children:jsxs(KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:Platform.OS==="ios"?"padding":"height",children:[jsxs(View,{style:o.searchRow,children:[jsxs(View,{style:o.searchPill,children:[jsx(md,{size:pE,color:n.color.text.muted,strokeWidth:1.5}),jsx(Lt,{value:t.query,onChangeText:R=>t.setQuery(R.replace(/^\s+/,"")),style:o.searchInput,placeholder:Z.search,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:Z.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.newConversation,style:o.newButton,onPress:t.newConversation,children:jsx(yd,{size:cE,color:n.color.text.primary,strokeWidth:1.5})})]}),jsx(C,{tier:"heading",style:o.heading,accessibilityRole:"header",children:Z.heading}),t.error!==null&&!y?jsx(View,{style:o.errorCard,children:jsx(C,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsx(FlatList,{data:m,keyExtractor:R=>R.id,renderItem:({item:R})=>jsx(bE,{row:R,active:R.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(R.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:g,onEndReached:t.loadMore,onEndReachedThreshold:mE})]})})]})})}i(hE,"DrawerModal");function bE({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsx(B,{accessibilityRole:"button",accessibilityLabel:Gu(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(C,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:un(e.title)}),s?jsx(View,{style:n.unreadDot}):null]})})}i(bE,"Row");function wn(e,t){if(!/^#[0-9a-f]{6}$/i.test(e))return "transparent";let r=Math.round(Math.min(1,Math.max(0,t))*255);return `${e}${r.toString(16).padStart(2,"0").toUpperCase()}`}i(wn,"inkWash");function vE(e){let t=e.color,r=e.slots,n=t.onPrimary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:tE},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.brand,paddingHorizontal:16,borderRightWidth:.5,borderRightColor:t.brandBorder,gap:12},keyboardAvoider:{flex:1,gap:12},searchRow:{flexDirection:"row",alignItems:"center",gap:10},searchPill:{flex:1,flexDirection:"row",alignItems:"center",gap:8,borderRadius:e.radius.pill,backgroundColor:t.surface,paddingHorizontal:14,paddingVertical:10,borderWidth:1,borderColor:wn(n,nE)},searchInput:{...E(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:Hi,height:Hi,borderRadius:Hi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},heading:{...E(e,"bold"),fontSize:14,lineHeight:17,color:n,marginTop:4},list:{gap:10,paddingBottom:28},listEmpty:{flexGrow:1},item:{paddingVertical:12,paddingHorizontal:4,borderRadius:lE},itemActive:{backgroundColor:wn(n,rE)},itemRow:{flexDirection:"row",alignItems:"center",gap:8},itemTitle:{...E(e,"regular"),flex:1,fontSize:14,lineHeight:18,color:n},itemTitleUnread:E(e,"bold"),unreadDot:{width:Bi,height:Bi,borderRadius:Bi/2,backgroundColor:t.danger,borderWidth:fE,borderColor:n},errorCard:{borderRadius:dE,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...E(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:uE,padding:14,gap:6,backgroundColor:wn(n,oE),borderWidth:.5,borderColor:wn(n,iE)},emptyTitle:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n},emptyBody:{...E(e,"regular"),fontSize:11,lineHeight:17,color:n,opacity:sE},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:n,...me(r.primaryButton)},retryText:{...E(e,"bold"),fontSize:12,lineHeight:15,color:n,...we(r.primaryButton)},loadMoreFooter:{paddingVertical:14,alignItems:"center"},loadMoreLabel:{...E(e,"regular"),fontSize:11,lineHeight:14,color:n,opacity:aE}})}i(vE,"makeStyles");function Mc(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(Mc,"chatVetVisitOptions");var SE=16,TE=.75,zi=12,Lc=15,PE=18,In=22,kE=14,xE=8,_E=20,wE=10,IE=13;function Nc({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=F(),a=useMemo(()=>AE(s),[s]),l=X(),u=e.tier,d=e.source;return jsxs(Fragment,{children:[jsx(di,{visible:e.showBanner&&u!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:u!==null&&d!==null?jsxs(View,{accessibilityRole:"alert",style:[a.card,{borderColor:u.borderColor,backgroundColor:u.backgroundColor}],children:[jsx(C,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsx(C,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsx(bt,{render:()=>r(u.level),fallback:jsx(Dc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsx(Dc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsx(B,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:xE,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsx(vt,{size:kE,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsx(di,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:wE,onPress:e.expand,children:jsx(dd,{size:_E,color:s.color.text.muted,strokeWidth:2})})})]})}i(Nc,"UrgencyBanner");function Dc({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=F(),a=Sn(Mc(t,n)),l=a.status==="opening",u=a.available?()=>{a.open();}:r!==void 0?()=>{q(r,e.level);}:null;if(u===null)return null;let d=bi(s.slots.vetVisitButton)?.textColor??e.textColor;return jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.findVetA11y,accessibilityState:{busy:l},containerStyle:o.findVetSlot,style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,l?o.findVetBusy:null],onPress:u,children:[jsx(gd,{size:IE,color:d,strokeWidth:1.5}),jsx(C,{tier:"control",style:[o.findVetLabel,{color:d}],children:h.findVet})]})}i(Dc,"VetAction");function AE(e){let t=bi(e.slots.vetVisitButton);return StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:SE,borderWidth:TE,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...E(e,"monoBold"),fontSize:zi,lineHeight:Lc},reason:{...E(e,"regular"),fontSize:zi,lineHeight:PE,paddingRight:In},findVetSlot:{alignSelf:"flex-start",marginTop:6},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...me(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...E(e,"monoBold"),fontSize:zi,lineHeight:Lc},closeSlot:{position:"absolute",top:6,right:6},closeButton:{width:In,height:In,borderRadius:In/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:16,paddingTop:2,paddingBottom:4}})}i(AE,"makeStyles");function Uc(){let e=vn(),{handle:t}=Y(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(Uc,"useChatPets");var Kc=300,qc=3e3,Hc=120,Bt=44,DE=120,NE="86%",Bc=15,zc=22,An=.5,UE=.04,VE=8,HE=2,BE=1,zE=.6,jE=22,WE=48,jc=1.25,GE=14,KE=18,qE=6,$E=14,YE=.04,XE=12,QE=2,ZE=2,Wc=36,JE=20,Ht=36,zt=(Bt-Ht)/2,$c=24,Yc=22,eR=.4,On=30,Xc=20,tR=.4,rR=480,nR=8,Gc=14,oR=10,iR=14,sR=12,aR=13,lR=18,uR="12%";function Ce(){let e=F(),t=useMemo(()=>dR(e),[e]);return {theme:e,styles:t}}i(Ce,"useChatTheme");function dR(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=e.slots;return StyleSheet.create({container:{flex:1,minHeight:Hc,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Hc,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:uR,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:rR,gap:18},errorText:{...E(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Bt,minWidth:Bt,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...me(s.primaryButton)},retryLabel:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...we(s.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...E(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:{...E(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:Bt,justifyContent:"center"},turnNoticeActionLabel:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...E(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...E(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},list:{flex:1},listContent:{padding:r.lg,gap:r.md},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:NE},bubbleUser:{padding:Bc,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:An,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:UE,shadowRadius:VE,shadowOffset:{width:0,height:HE},elevation:BE,...me(s.userBubble,An)},bubbleAssistant:s.assistantBubble?.backgroundColor===void 0?{...me(s.assistantBubble,An)}:{padding:Bc,borderRadius:n.xl,...me(s.assistantBubble,An)},bubblePending:{opacity:zE},bubbleTextUser:{...E(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:zc,...we(s.userBubble)},bubbleTextAssistant:{...E(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:zc,...we(s.assistantBubble)},bubbleBold:E(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:E(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.sm,gap:nR},followUpSlot:{alignSelf:"stretch",borderRadius:Gc},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:sR,paddingVertical:oR,paddingHorizontal:iR,borderRadius:Gc,backgroundColor:t.brandSoft},followUpText:{...E(e,"medium"),flex:1,color:t.text.primary,fontSize:aR,lineHeight:lR},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,marginBottom:r.sm,minHeight:WE,justifyContent:"center",paddingLeft:GE,paddingRight:KE,paddingVertical:qE,backgroundColor:t.composerFill,borderWidth:jc,borderColor:t.composerBorder,borderRadius:jE,shadowColor:t.shadow,shadowOpacity:YE,shadowRadius:XE,shadowOffset:{width:0,height:QE},elevation:ZE,...me(s.composerInput,jc)},composerRow:{flexDirection:"row",alignItems:"center",gap:$E,minHeight:Wc},attachControl:{width:On,height:On,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:tR},input:{flex:1,minHeight:Wc,maxHeight:DE,paddingHorizontal:0,paddingVertical:0,...E(e,"regular"),fontSize:o.size.body,lineHeight:JE,color:t.text.primary,...we(s.composerInput)},sendControl:{minHeight:Ht,minWidth:Ht,alignItems:"center",justifyContent:"center"},sendDisc:{width:Ht,height:Ht,borderRadius:Ht/2,alignItems:"center",justifyContent:"center",...me(s.sendButton)},sendControlDisabled:{opacity:eR},poweredBy:{...E(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(dR,"makeStyles");var cR=Object.freeze({kind:"live"}),pR=Object.freeze({kind:"folded"});function Wi(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=oo(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(Wi,"askOf");function Zc(e){let t=new Map,r=new Map;for(let o of e){let s=Wi(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=Wi(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,cR),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,pR);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(Zc,"placeCheckins");var Qc=864e5,fR=365;function Fn(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/Qc)-Math.floor(r/Qc);return o<1||o>fR?null:o}i(Fn,"checkinDayNumber");function Jc(e){return Wi(e)?.dueDay||null}i(Jc,"checkinDueDay");var Se=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"})}),ep=Object.freeze(Vr.map(e=>Object.freeze({answer:e,label:Se.answers[e]})));function tp(e,t){let[r,n]=useState(null),[o,s]=useState(null),[a,l]=useState(null),u=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]),d=a??e.answer;return {answer:d,answerable:!ua(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(tp,"useCheckinCard");var op=44,gR=.6;function sp({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s}){let a=F(),l=useMemo(()=>hR(a),[a]),u=tp(t,r),d=u.answer!==null||u.pending!==null,c=r!==null&&u.answerable,p=Fn(t.openedAt,Jc(e));return jsxs(View,{style:l.card,accessibilityLabel:Se.eyebrow,children:[jsxs(View,{style:l.head,children:[jsx(C,{tier:"compact",style:l.eyebrow,children:Se.eyebrow}),p!==null?jsx(C,{tier:"compact",style:l.headDay,children:K(Se.day,{day:p})}):null]}),jsx(C,{style:l.question,accessibilityRole:"text",children:e.text}),c?jsx(View,{style:[l.row,u.pending?l.rowPending:null],children:ep.map(({answer:f,label:m})=>{let y=(u.pending??u.answer)===f;return jsx(Pressable,{onPress:()=>u.choose(f),disabled:d,accessibilityRole:"button",accessibilityLabel:m,accessibilityState:{selected:y,disabled:d,busy:u.pending===f},style:[l.pill,y?l.pillSelected:null],children:jsx(C,{tier:"control",style:[l.pillLabel,y?l.pillLabelSelected:null],children:m})},f)})}):null,u.answer!==null?jsx(C,{style:l.logged,children:Se.logged}):null,u.escalated?o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Se.findVet,style:l.findVet,children:jsx(C,{tier:"control",style:l.findVetLabel,children:Se.findVet})}):n?jsx(Vt,{entry:"chat",petRef:n,label:Se.findVet,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:l.findVet,labelStyle:l.findVetLabel}):null:null,t.resolutionText?jsx(C,{style:l.resolution,children:t.resolutionText}):null,u.error?jsx(C,{style:l.error,accessibilityRole:"alert",children:u.error.displayMessage}):null]})}i(sp,"CheckinCard");function hR(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:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...E(e,"bold"),color:t.text.primary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...E(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:gR},pill:{flex:1,minHeight:op,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brand},pillLabel:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...E(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...E(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...E(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:op,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...E(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(hR,"makeStyles");var CR=1.5,ER=3;function lp({text:e,runDueDays:t,openedAt:r}){let n=F(),o=useMemo(()=>RR(n),[n]),s=t.map(l=>Fn(r,l)).filter(l=>l!==null),a=t.length>1;return a&&s.length===0?null:jsxs(View,{style:o.row,children:[jsx(View,{style:o.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),jsxs(View,{style:o.body,children:[s.length>0?jsx(C,{tier:"compact",style:o.days,children:s.map(l=>K(Se.day,{day:l})).join(Se.daySeparator)}):null,a?null:jsx(C,{style:o.question,accessibilityRole:"text",children:e})]})]})}i(lp,"CheckinPastAsk");function RR(e){let t=e.color,r=e.space,n=e.type;return StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:CR,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:ER},days:{...E(e,"monoMedium"),fontSize:n.size.nano,letterSpacing:n.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},question:{...E(e,"regular"),fontSize:n.size.bodyTight,lineHeight:n.size.bodyTight*n.lineHeight.normal,color:t.text.muted}})}i(RR,"makeStyles");var SR=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),up="#C8BEB4";function TR(e){return e?SR[e.toUpperCase()]??up:up}i(TR,"tierColor");function PR(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(PR,"tierLabel");function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Ve,"text");function kR(e){let t=Ve(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(kR,"httpsUrl");function xR(e,t){let r=Ve(e.source_name)??Ve(e.sourceName),n=Ve(e.section),o=Ve(e.authority_tier)??Ve(e.authorityTier),s=PR(o),a=r??Ve(e.title)??`Source ${t+1}`,l=Ve(e.monograph_chunk_id)??Ve(e.chunkId),u=[n,s].filter(d=>d!==null).join(" \xB7 ");return Object.freeze({title:a,sourceName:r,section:n,authorityTier:o,tierLabel:s,meta:u.length===0?null:u,url:kR(e.url),excerpt:Ve(e.excerpt),tierColor:TR(o),key:`${a}-${l??"none"}-${t}`})}i(xR,"toCitationCard");function dp(e){return e===void 0||e.length===0?_R:Object.freeze(e.map((t,r)=>xR(t,r)))}i(dp,"toCitationCards");var _R=Object.freeze([]);function Yi(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i(Yi,"sourcesLabel");function cp(e,t){return `${t?h.hideSources:h.showSources} ${Yi(e)}`}i(cp,"sourcesToggleLabel");function pp(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(pp,"citationA11yLabel");var FR=244,mp=8,yp=13,MR=14,LR=.3,DR=-0.24,NR=22,UR=10,VR=15;function gp({citations:e,onOpenUrl:t}){let r=F(),n=useMemo(()=>zR(r),[r]),o=useMemo(()=>dp(e),[e]),[s,a]=useState(false);if(o.length===0)return null;let l=o.length;return jsxs(View,{style:n.block,children:[jsxs(B,{accessibilityRole:"button",accessibilityLabel:cp(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(u=>!u),children:[jsx(ad,{size:yp,color:r.color.brandInk,strokeWidth:1.5}),jsx(C,{tier:"compact",style:n.toggleLabel,children:Yi(l)}),jsx(pn,{size:yp,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsx(HR,{cards:o,styles:n,open:t}):null]})}i(gp,"CitationCards");function HR({cards:e,styles:t,open:r}){let n=X(),o=Ct(n.citationsInMs,{risePx:n.citationsRisePx});return jsx(Animated.View,{style:o,children:jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsx(BR,{card:s,styles:t,open:r},s.key))})})}i(HR,"Deck");function BR({card:e,styles:t,open:r}){let n=F(),o=e.url!==null&&r!==void 0,s=pp(o?e:{...e,url:null}),a=jsxs(Fragment,{children:[jsxs(View,{style:t.cardHeader,children:[jsx(View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsx(C,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsx(ld,{size:MR,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsx(C,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsx(C,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let l=e.url;return jsx(B,{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(BR,"Card");function zR(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:{...E(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:LR,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:FR,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:mp,height:mp,borderRadius:n.pill},cardTitle:{...E(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:NR,color:t.text.primary,letterSpacing:DR},cardTitleLink:{color:t.linkInk},cardMeta:{...E(e,"monoMedium"),fontSize:o.nano,lineHeight:UR,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...E(e,"regular"),fontSize:o.tiny,lineHeight:VR,color:t.text.muted}})}i(zR,"makeStyles");function hp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(hp,"formatMessageTime");var kr=15,$R=15,YR=6,XR=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function Rp({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=F(),a=useMemo(()=>QR(s),[s]),l=X(),u=e.role==="user",d=useMemo(()=>hp(e.createdAt),[e.createdAt]),c=t!==void 0&&e.text.length>0,p=!u&&n!==void 0&&e.responseId!==void 0,[f,m]=useState(false),y=useRef(null);useEffect(()=>()=>{y.current&&clearTimeout(y.current);},[]);let k=i(()=>{t!==void 0&&(Dt(t,e.text),m(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null;},l.copiedMs));},"copy");return d===null&&!c&&!p?null:jsxs(View,{style:a.wrap,children:[jsxs(View,{style:[a.row,u?a.rowUser:a.rowAssistant],children:[d!==null?jsx(C,{tier:"compact",style:a.timestamp,children:d}):null,c?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f?h.copied:u?h.copyUserMessage:h.copyAssistantMessage,hitSlop:$R,onPress:k,style:a.iconHit,children:f?jsx(tt,{size:kr,color:s.color.success,strokeWidth:2}):jsx(ud,{size:kr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?vu.map(({sentiment:g,label:R})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:R,accessibilityState:{selected:r===g},hitSlop:YR,onPress:()=>n?.(g),style:a.iconHit,children:jsx(fn,{size:kr,color:s.color.sentiment[g],active:r===g,rotate:XR[g],strokeWidth:1.5})},g)):null]}),o?jsx(C,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(Rp,"MessageFooter");function QR(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:{...E(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:kr,height:kr,alignItems:"center",justifyContent:"center"},thanks:{...E(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(QR,"makeStyles");var Sp="#10462E",Tp="#000000",ZR="#83E0B4",JR=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:ZR,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:Sp,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})]),eS=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function tS(e){return e==null?e:e.replace(eS,"").trim()}i(tS,"formatBreedForPrompt");var rS=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 nS(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return rS.has(t)}i(nS,"isUninformativeBreed");function oS(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(oS,"unspecifiedBreedLabel");function iS(e,t){return nS(e)?oS(t):String(e).replace(/\s+/gu," ").trim()}i(iS,"resolveBreedLabel");function Pp(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(Pp,"emptyStateTitle");function kp(e,t=Sp){let r=ki(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=iS(tS(e?.breed),r)||null,l=xi(e?.ageYears),u=l===null?null:String(l);return Object.freeze(JR.map(d=>{let c=d.label.includes("{breed}"),p=d.label.includes("{ageYears}"),m=d.fallbackLabel!==void 0&&(c&&!a||p&&!u)&&d.fallbackLabel?d.fallbackLabel:d.label,y=K(m,{petName:s,breed:a??n,species:r,ageYears:u??""}),k=!o&&m.startsWith("{petName}")?y.charAt(0).toUpperCase()+y.slice(1):y;return Object.freeze({id:d.id,intent:d.intent,label:k,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(kp,"resolveQuickPrompts");var aS=36,wp=4,lS=340;function Ip({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=F(),a=useMemo(()=>dS(s),[s]),l=useMemo(()=>kp(e,s.color.brandInk),[e,s.color.brandInk]),u=Pp(e);return jsxs(View,{style:a.block,children:[jsx(C,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsx(View,{style:a.list,children:l.map((d,c)=>jsx(uS,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(Ip,"QuickPrompts");function uS({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=X(),d=Ct(u.followUpInMs,{delayMs:yn(u,t)}),c={backgroundColor:e.background,borderColor:e.borderColor,borderWidth:e.borderWidth};return e.intent==="vet_report"?s!==void 0?jsx(Animated.View,{style:d,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:wp,style:[l.chip,c],onPress:()=>{q(s,r);},children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsx(Animated.View,{style:d,children:jsx(Vt,{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,c],labelStyle:l.chipLabel})}):jsx(Animated.View,{style:d,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:wp,style:[l.chip,c],onPress:()=>o(e.label),children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(uS,"Chip");function dS(e){let t=e.color;return StyleSheet.create({block:{gap:18,alignItems:"center",width:"100%"},title:{...E(e,"bold"),fontSize:28,lineHeight:34,color:t.text.primary,letterSpacing:-0.8,textAlign:"center",maxWidth:lS},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:aS,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...E(e,"bold"),fontSize:12,lineHeight:14,color:Tp,textAlign:"center"}})}i(dS,"makeStyles");var Qi=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function Ap(e){return e.includes("*")||e.includes("`")}i(Ap,"hasInlineMarkup");function Op(e){let t=[],r=0;Qi.lastIndex=0;for(let n=Qi.exec(e);n!==null;n=Qi.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(Op,"tokenizeInlineMarkdown");function Fp(e,t){return Ap(e)?Op(e).map((r,n)=>{switch(r.kind){case "bold":return jsx(C,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx(C,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx(C,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(Fp,"renderInlineMarkdown");var Dp=6,Vp=520,gS=Math.round(Vp*.18),Np=.44,hS=.5,Up=[0,.5,1],bS=[0,1,2];function Hp(){let e=F(),t=useMemo(()=>CS(e),[e]),r=!e.motion.reducedMotion;return jsx(View,{style:t.card,accessible:true,accessibilityRole:"text",accessibilityLabel:h.typing,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:bS.map(n=>r?jsx(vS,{index:n,style:t.dot},n):jsx(View,{style:[t.dot,t.dotStatic]},n))})}i(Hp,"TypingIndicator");function vS({index:e,style:t}){let r=useRef(new Animated.Value(0)).current;useEffect(()=>{let s=Animated.sequence([Animated.delay(e*gS),Animated.loop(Animated.timing(r,{toValue:1,duration:Vp,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:Up,outputRange:[Np,1,Np]}),o=r.interpolate({inputRange:Up,outputRange:[0,-3.5,0]});return jsx(Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(vS,"AnimatedDot");function CS(e){let t=e.color,r=e.space,n=e.radius;return StyleSheet.create({card:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:r.xs,paddingHorizontal:r.md,paddingVertical:r.sm,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},dot:{width:Dp,height:Dp,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:hS}})}i(CS,"makeStyles");function Wp(e,t,r){switch(e){case "loading":return r.renderPending?jsx(bt,{render:r.renderPending,fallback:jsx(Bp,{})}):jsx(Bp,{});case "empty":return jsx(kS,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(_S,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx(wS,{messages:t.messages,prompts:t.suggestedPrompts,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});default:return Xe(e)}}i(Wp,"renderView");function Bp(){let{theme:e,styles:t}=Ce(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),Kc);return ()=>clearTimeout(o)},[]),jsx(View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:h.loading,children:r?jsx(ActivityIndicator,{color:e.color.brandInk}):null})}i(Bp,"LoadingState");function kS({pet:e,petRef:t,prompts:r,onSelectPrompt:n,onVetPrep:o,vet:s}){let{styles:a}=Ce();return jsxs(ScrollView,{contentContainerStyle:a.emptyContent,keyboardShouldPersistTaps:"handled",accessibilityLabel:h.empty,children:[jsx(Ip,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsx(Gp,{prompts:r,onSelectPrompt:n})]})}i(kS,"EmptyState");function Gp({prompts:e,onSelectPrompt:t}){let{styles:r}=Ce();return e.length===0?null:jsx(View,{style:r.followUps,children:e.map((n,o)=>jsx(xS,{prompt:n,index:o,onSelectPrompt:t},n))})}i(Gp,"FollowUps");function xS({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=Ce(),s=X(),a=Ct(s.followUpInMs,{delayMs:yn(s,t)});return jsx(Animated.View,{style:a,children:jsxs(B,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:o.followUpSlot,style:o.followUpRow,children:[jsx(C,{style:o.followUpText,children:e}),jsx(pn,{size:OS,color:n.color.brandInk,direction:"right"})]})})}i(xS,"FollowUpRow");function _S({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Ce(),o=xu(e)?Lu(r):void 0;return jsxs(View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsx(C,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:h.addPet,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.addPet})}):null,e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:h.retry,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.retry})}):null]})}i(_S,"ErrorState");function wS({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:o,onCopy:s,sentimentByMessage:a,onSentiment:l,thanksFor:u,imagesByMessage:d,onPreview:c,notice:p,reconnecting:f,onRetry:m,onStartNew:y,petRef:k,onFindVet:g,vet:R,onOpenUrl:w}){let{styles:_}=Ce(),x=X();br(e.length,x);let b=useMemo(()=>Zc(e),[e]),P=Ju(e,n),L=e[e.length-1];return jsxs(ScrollView,{style:_.list,contentContainerStyle:_.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",children:[e.map(I=>{let S=I.checkin?b.get(I.id):void 0;return S?.kind==="folded"?null:S?.kind==="past"?jsx(lp,{text:I.text,runDueDays:S.runDueDays,openedAt:I.checkin?.openedAt},I.id):I.checkin&&S!==void 0?jsx(sp,{message:I,checkin:I.checkin,onAnswer:o,petRef:k,onFindVet:g,vet:R},I.id):jsx(FS,{message:I,revealing:n&&I===L&&I.role==="assistant",onCopy:s,sentiment:I.responseId===void 0?null:a[String(I.responseId)]??null,onSentiment:l,thanks:u!==null&&I.responseId!==void 0&&String(I.responseId)===u,images:d[I.id]??AS,onPreview:c,onOpenUrl:w},I.id)}),f?jsx(C,{tier:"compact",style:_.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,P?jsx(Hp,{}):null,p!==null?jsx(IS,{notice:p,onRetry:m,onStartNew:y}):null,n?null:jsx(Gp,{prompts:t,onSelectPrompt:r})]})}i(wS,"PopulatedState");function IS({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Ce(),o=e.tone==="error";return jsxs(View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsx(C,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsx(Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:zt,style:n.turnNoticeAction,children:jsx(C,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(IS,"TurnNoticeCard");var AS=Object.freeze([]),OS=14;function FS({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l,onOpenUrl:u}){let{styles:d}=Ce(),c=X(),p=Ct(c.messageInMs),f=kd(e.text,t,c),m=e.role==="user",y=m?h.senderUser:h.senderAssistant,k=useCallback(R=>o(e,R),[o,e]),g=e.pending!==true;return jsxs(Animated.View,{style:[d.rowBlock,m?d.rowBlockUser:d.rowBlockAssistant,p],children:[jsx(View,{style:[d.row,m?d.rowUser:d.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxs(View,{style:[d.bubble,m?d.bubbleUser:d.bubbleAssistant,e.pending?d.bubblePending:null],children:[m&&a.length>0?jsx(zd,{images:a,onPreview:R=>l({uri:R.uri,label:R.filename})}):null,jsx(C,{style:m?d.bubbleTextUser:d.bubbleTextAssistant,children:m?e.text:Fp(f,{bold:d.bubbleBold,italic:d.bubbleItalic,code:d.bubbleCode})})]})}),!m&&!t?jsx(gp,{citations:e.citations,onOpenUrl:u}):null,g?jsx(Rp,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:k,thanks:s}):null]})}i(FS,"MessageRow");var US=Object.freeze(["photo"]),VS=1;function qp(e){let{style:t,renderPending:r}=e;return jsx(Ko,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(HS,{...e})})}i(qp,"EverfurChat");function HS({petRef:e,conversationId:t,style:r,renderPending:n,onCopy:o,onPetChange:s,onVetPrep:a,onFindVet:l,renderVetAction:u,attachments:d,pet:c,onAddPet:p,checkinTarget:f,initialAsk:m,composerSeed:y,lifecycle:k,draftStore:g,vetReturnTo:R,vetUsState:w,vetPrefer:_,onOpenUrl:x}){let{theme:b,styles:P}=Ce(),L=X(),I=useMemo(()=>ed(e,t),[e,t]),S=mr(I),O=Qu(S),T=Uc(),V=Ku(S),j=useSafeAreaInsets(),G=Zu(S),ne=useMemo(()=>l===void 0?void 0:()=>{q(l,"emergency");},[l]),de=useMemo(()=>R===void 0&&w===void 0&&_===void 0?void 0:{returnTo:R,usState:w,prefer:_},[R,w,_]),Pe=Di(T.pets,S.petRef),Gt=useMemo(()=>Yu(S.messages,Pe?.name??null),[S.messages,Pe?.name]),ce=Xu(Gt);br(ce.showBanner,L),Vu(S.openCheckin,f),Ou(S.askEverfur,S.isBootstrapping,m);let ot=useMemo(()=>ei(y),[y]);Nu(k,{conversationId:S.conversationId===null?null:String(S.conversationId),isTurnInFlight:S.isStreaming,refresh:S.refreshActiveThread});let wr=(S.hasUnreadThreads??false)||V.rows.some(Ee=>Ee.unreadCount!==null&&Ee.unreadCount>0)||(S.unreadCount??0)>0,Kt=Iu(S.messages),[xt,_t]=useState(null),Yp=useCallback(()=>_t(null),[]),[qt,Un]=useState(null),[Xp,ts]=useState(null),wt=useRef(null);useEffect(()=>()=>{wt.current&&clearTimeout(wt.current);},[]);let rs=useCallback(Ee=>{ts(String(Ee)),wt.current&&clearTimeout(wt.current),wt.current=setTimeout(()=>{ts(null),wt.current=null;},qc);},[]),Qp=useCallback((Ee,Ir)=>{let $t=Ee.responseId;if($t===void 0)return;let rf=S.sentimentByMessage[String($t)];S.feedback($t,Ir),Ir==="down"&&rf!=="down"&&Un($t);},[S]),Zp=useCallback(async(Ee,Ir)=>qt===null||!(await S.feedback(qt,"down",Ee??"other",Ir)).ok?false:(Un(null),rs(qt),true),[S,qt,rs]),Jp=useCallback(()=>Un(null),[]),ef=useCallback(Ee=>{S.send(Ee);},[S.send]),tf=useMemo(()=>x===void 0?void 0:Ee=>{q(x,Ee,"citation");},[x]),ns={send:S.send,stop:S.stop,isStreaming:S.isStreaming,conversationId:S.conversationId,seed:ot,draftStore:g,onStage:Kt.stage,onPreview:_t};return jsxs(KeyboardAvoidingView,{style:[P.container,{paddingTop:j.top},r],behavior:Platform.OS==="ios"?"padding":void 0,children:[jsx(kc,{pets:T,petRef:S.petRef,historyUnread:wr,onOpenHistory:V.show,onPetChange:s,onAddPet:p,vet:de}),c!==void 0?jsx(BS,{petRef:e??null,pet:c,onRegistered:T.refresh}):null,jsx(Nc,{surface:ce,petRef:S.petRef,renderVetAction:u,onFindVet:l,vet:de}),jsx(View,{style:P.body,children:Wp(O,S,{notice:G,vet:de,onCheckinFindVet:ne,onSelectPrompt:ef,renderPending:n,shownPet:Pe,onVetPrep:a,onCopy:o,onSentiment:Qp,thanksFor:Xp,imagesByMessage:Kt.byMessage,onPreview:_t,onAddPet:p,onOpenUrl:tf})}),d!==void 0?jsx(zS,{...ns,attachments:d}):jsx($p,{...ns,attachments:null}),jsx(nd,{}),b.meta.hidePoweredBy?null:jsx(C,{tier:"compact",style:P.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsx(Fc,{chat:S,history:V}),jsx(Ac,{visible:qt!==null,onSubmit:Zp,onSkip:Jp}),jsx(xd,{uri:xt?.uri??null,label:xt?.label??"",onClose:Yp}),jsx(Er,{})]})}i(HS,"ChatBody");function BS({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Ce(),o=_u(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs(View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsx(Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:h.retry,hitSlop:zt,children:jsx(C,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(BS,"PetSetupNotice");function zS({attachments:e,...t}){let r=useMemo(()=>Wd(),[]),n=an({maxPerMessage:e.maxPerMessage??VS,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??US,pick:e.pick}),[n,e.sources,e.pick]);return jsx($p,{...t,attachments:o})}i(zS,"ComposerWithAttachments");function $p({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:u}){let{theme:d,styles:c}=Ce(),p=X(),[f,m]=zu(e,n,s);ju(a,n===null?null:String(n),f,m);let[y,k]=useState(false),[g,R]=useState(false);useEffect(()=>{R(false);},[n]);let w=d.meta.placeholder??h.placeholder,_=o?.state.uploading??false,x=o?.state.failed??false,b=_||x,P=o?.state.attachments??jS;br(P.length,p);let L=useCallback(()=>{if(f.trim().length===0||b||[...f].length>Ot)return;let G=o?.state.s3Keys??WS;o!==null&&G.length>0?(l(o.state.attachments.filter(ne=>ne.status==="uploaded").map(ne=>({uri:ne.previewUri,filename:ne.filename}))),e(f,{imageS3Keys:G}),o.state.clear()):e(f),m(""),R(false);},[f,e,b,o,l]),I=useCallback(()=>{t();},[t]),S=useCallback(G=>{k(false),o!==null&&(R(false),o.state.dismissRejected(),Dt(o.pick,G).then(ne=>{if(!ne.ok){R(true);return}ne.value!==null&&o.state.add(ne.value);}));},[o]),T=useMemo(()=>[...f].length>Ot,[f])||b,V=o!==null&&P.length>=o.state.maxPerMessage,j=d.slots.sendButton?.textColor??d.color.brandInk;return jsxs(View,{style:c.composerOuter,children:[o!==null&&y?jsx(Id,{sources:o.sources,full:V,onPick:S,onClose:()=>k(false)}):null,jsxs(View,{style:c.composer,children:[o!==null?jsx(Bd,{attachments:P,rejected:g?GS:o.state.rejected,uploadFailed:x,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:G=>u({uri:G.previewUri,label:G.filename})}):null,jsxs(View,{style:c.composerRow,children:[o!==null?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:Tu(P.length,o.state.maxPerMessage),accessibilityState:{disabled:V,expanded:y},disabled:V,hitSlop:(Bt-On)/2,style:[c.attachControl,V?c.attachControlDisabled:null],onPress:()=>k(G=>!G),children:jsx(cd,{size:Xc,color:V?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsx(Lt,{style:c.input,value:f,onChangeText:m,placeholder:w,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,accessibilityLabel:w,onSubmitEditing:L,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsx(Pressable,{onPress:I,accessibilityRole:"button",accessibilityLabel:h.stop,hitSlop:zt,style:c.sendControl,children:jsx(View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsx(bd,{size:Yc,color:j,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:L,disabled:T,accessibilityRole:"button",accessibilityLabel:h.send,accessibilityState:{disabled:T,busy:_},hitSlop:zt,style:[c.sendControl,T?c.sendControlDisabled:null],children:jsx(View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsx(hd,{size:$c,color:j,testID:"everfur-send-glyph"})})})]})]})]})}i($p,"Composer");var jS=Object.freeze([]),WS=Object.freeze([]),GS=Object.freeze({code:"unknown",retryable:true,filename:""});function XS(e){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=useMemo(()=>Qe(t.registry.services.authFor(r)),[t,r,n]),s=useMemo(()=>({repository:o,petRef:e}),[o,e]),[a,l]=useState({key:s,profile:null,loading:e!==null,error:null}),u=a.key===s?a:{profile:null,loading:e!==null,error:null},d=useRef(0),c=useCallback(async()=>{let p=++d.current;if(s.petRef===null){l({key:s,profile:null,loading:false,error:null});return}l(m=>({key:s,profile:m.key===s?m.profile:null,loading:true,error:null}));let f=await s.repository.getPetProfile(s.petRef);p===d.current&&l(f.ok?{key:s,profile:f.value,loading:false,error:null}:{key:s,profile:null,loading:false,error:f.error});},[s]);return useEffect(()=>(c(),()=>{d.current+=1;}),[c]),useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:c}),[u.profile,u.loading,u.error,c])}i(XS,"useEverfurPetProfile");function ZS(e){return createElement(nn,{clientTheme:e.clientTheme??null,seams:sn,children:e.children})}i(ZS,"EverfurThemeProvider");export{Ko as CapabilityGate,qp as EverfurChat,Q as EverfurConfigError,xh as EverfurProvider,ZS as EverfurThemeProvider,Ar as EverfurThrownError,$y as THEME_SLOT_KEYS,mt as THEME_SLOT_NAMES,sr as canonicalPetSpecies,Hn as categoryFor,cf as conversationId,kf as createRnRecordsUploadTransport,E as face,sf as isErr,of as isOk,Bn as isRetryableCode,uf as petRef,Rg as previewTheme,af as unwrap,Mt as useCapability,an as useChatAttachments,Xl as useEverfur,mr as useEverfurChat,XS as useEverfurPetProfile,vn as useEverfurPets,F as useEverfurTheme,It as userFacingError,df as userRef};
|
|
11
|
+
`));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",a);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",a);try{e.close();}catch{}}}return i(l,"cleanup"),pm(r.source,l)}i(cm,"eventSourceByteSource");async function*pm(e,t){try{yield*e;}finally{t();}}i(pm,"sourceWithCleanup");function fm(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(a=>{r=a;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(fm,"createByteQueue");async function mm(e,t){let r=t.fetchImpl??Hs(),n=Bs(t.config.apiBaseUrl,e.path,e.query),o=zs(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=Em(dm),a=Cm(s.signal,e.signal),l;try{l=await r(n,js({...e,signal:a},o));}catch(d){return v(Qn(d))}finally{s.cancel();}let u=await Ws(l);return l.ok?L(u):v(hm(l.status,u,Us(l)))}i(mm,"requestJson");function Ns(e){return {request:i(t=>mm(t,e),"request"),stream:i((t,r)=>ym(vm(t,r),e),"stream")}}i(Ns,"createHttpTransport");async function*ym(e,t){let r=Bs(t.config.apiBaseUrl,e.path,e.query),n=zs(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,gm(e,n));yield*Br(cm(l),()=>bm(l));return}let o=t.fetchImpl??Hs(),s;try{s=await o(r,js(e,n));}catch(l){yield Ms("",true,$s(l));return}let a=Us(s);if(!s.ok){let l=await Ws(s),u=Gs(l)??Vs(s.status),d=qs(l)||Be(Oe(u));yield Ms(u,d,Ks(l),a);return}if(s.body){yield*Br(Fs(s.body),a);return}yield*Br(Fs(null),a);}i(ym,"streamFrames");function gm(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(gm,"buildEventSourceInit");function hm(e,t,r){let n=Gs(t),o=n?Oe(n):ps(e),s=Ks(t);return D(o,{httpStatus:e,...qs(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Ls(t)?{reasonCode:Ls(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(hm,"errorFromResponse");function Qn(e){return D("internalError",{retryable:true,wireMessage:$s(e)})}i(Qn,"networkError");function Us(e){let t=e.headers.get(Ds);return typeof t=="string"&&t.length>0?t:null}i(Us,"requestIdOf");function bm(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Ds);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(bm,"eventSourceRequestId");function Vs(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(Vs,"statusToWireCode");function Ms(e,t,r,n=null){return pe({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(Ms,"syntheticErrorFrame");function Hs(){let e=globalThis.fetch;if(typeof e!="function")throw new Q("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Hs,"getGlobalFetch");function Bs(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(a=>a[1]!==void 0).map(([a,l])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(l))}`).join("&");s&&(o+=`?${s}`);}return o}i(Bs,"buildUrl");function zs(e,t,r,n){let o={...Os(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(zs,"mergeHeaders");function js(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(js,"buildInit");function vm(e,t){return e.signal?e:{...e,signal:t}}i(vm,"withSignal");function Em(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(Em,"timeoutSignal");function Cm(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Cm,"mergeAbortSignals");async function Ws(e){try{return await e.json()}catch{return null}}i(Ws,"safeJson");function Ls(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Ls,"extractReasonCode");function Gs(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Gs,"extractWireCode");function Ks(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Ks,"extractWireMessage");function qs(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(qs,"extractRetryable");function $s(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i($s,"describeCause");var Rm=3e4,Sm=Gn*2,Tm="idempotency-key",Pm=new Set(["POST","PUT","PATCH","DELETE"]),km=Object.freeze({onEvent(){}}),xm=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function _m(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(_m,"seededIdempotencyKey");function xe(e){let t=e.observer??km,r=e.timers??xm,n=e.rng??Math.random,o=e.sleep??((f,y)=>zm(f,r,y)),s=e.maxAttempts??Jt,a=e.unaryTimeoutMs??Rm,l=e.newIdempotencyKey??Im(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,y,m){let w=m?.maxAttempts,b=Math.max(1,w??s),R=m?.idempotent??Pm.has(y.method),I=m?.idempotencyKey===void 0?null:_m(m.idempotencyKey),P=R?I??l():null,x=wm(y,P),g=0;for(;;){let _=i(j=>Object.freeze({call:f,method:y.method,path:y.path,attempt:g,...P?{idempotencyKey:P}:{},...j}),"stamp");u(_({phase:"attempt"}));let F=Hm(a,r),M=Bm(F.signal,y.signal),E;try{E=await Ps({...x,signal:M.signal},e.auth);}catch(j){E=v(Qn(j));}finally{M.dispose(),F.cancel();}if(E.ok)return u(_({phase:"settled",ok:true,reason:"ok"})),E;let k=E.error,T=Om(k,g,{maxAttempts:b,rng:n,now:r.now(),aborted:y.signal?.aborted===true,...w!==void 0?{perCallMaxAttempts:w}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),V={ok:false,code:k.code,reason:T.reason,...k.httpStatus!==void 0?{httpStatus:k.httpStatus}:{},...k.requestId!==void 0?{requestId:k.requestId}:{}};if(!T.retry)return u(_({phase:"settled",...V})),v(k);if(u(_({phase:"retry",...V,delayMs:T.delayMs})),await o(T.delayMs,y.signal),y.signal?.aborted===true)return u(_({phase:"settled",...V,reason:"aborted"})),v(k);g+=1;}}i(d,"send");async function c(f){return er(f,await Vm(e.auth))}i(c,"authorize");async function*p(f,y,m){u(Object.freeze({call:f,phase:"stream.open",method:y.method,path:y.path,attempt:0}));try{yield*e.auth.transport.stream(y,m);}catch{yield pe({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(xe,"createRequestFunnel");function wm(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==Tm&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(wm,"assembleHeaders");function Im(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Im,"defaultIdempotencyKeyFactory");var Am=10;function Om(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Fm(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!Be(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 d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(Am,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=Mm(e,r.now);return u!==null?u>Sm?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Ur(t,r.rng)}}i(Om,"decideRetry");function Fm(e){let t=e.code==="unknown"?Oe(Um(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Fm,"throttleKind");function Mm(e,t){let r=Dm(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=Lm(e.raw);return n===null?null:Math.round(n*1e3)}i(Mm,"retryOverrideMs");function Lm(e){for(let t of Zn(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(Lm,"findRetryAfterSeconds");function Dm(e){for(let t of Zn(e)){let r=t.resets_at,n=Nm(r);if(n!==null)return n}return null}i(Dm,"findResetsAt");function Zn(e){if(!Ys(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Ys(n)&&t.push(n);}return t}i(Zn,"candidateScopes");function Nm(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(Nm,"parseInstantMs");function Um(e){for(let t of Zn(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Um,"rawWireCode");function Ys(e){return typeof e=="object"&&e!==null}i(Ys,"isRecord");async function Vm(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(Vm,"resolveDeviceAuth");function Hm(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Hm,"boundedSignal");function Bm(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(Bm,"mergeSignals");function zm(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(zm,"delayAbortable");var zr=Object.freeze(["better","same","worse"]),eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Xs(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i(Xs,"invalid");function Jn(){return v(D("internalError",{retryable:false}))}i(Jn,"malformed");function Qs(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Re(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Qs,"petPath");var ze=i(e=>typeof e=="string"?e:null,"str"),Zs=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function Js(e){if(typeof e!="object"||e===null)return null;let t=e,r=ze(t.case_id),n=ze(t.status);if(r===null||n===null)return null;let o=ze(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:ze(t.body_location),lastResponse:o!==null&&zr.includes(o)?o:null,checkInDueAt:ze(t.check_in_due_at),openedAt:ze(t.opened_at),resolvedAt:ze(t.resolved_at),resolutionText:ze(t.resolution_text),checkinAskCount:Zs(t.checkin_ask_count),checkinAnswerCount:Zs(t.checkin_answer_count)})}i(Js,"caseFromWire");function ea(e){return {async list(t,r){let n=Qs(t);if(typeof n!="string")return v(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return v(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return Jn();let a=s.map(Js);return a.every(l=>l!==null)?L(Object.freeze(a)):Jn()},async checkin(t,r,n,o){let s=Qs(t);if(typeof s!="string")return v(s);if(typeof r!="string"||!eo.test(r))return Xs("case_id must be a UUID");if(!zr.includes(n))return Xs("response must be one of better, same, worse");let a=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!a.ok)return v(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=Js(l.case);return u===null?Jn():L(Object.freeze({case:u,ctaDeepLink:ze(l.cta_deep_link)}))}}}i(ea,"createCasesRepositoryOver");var ta=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ra=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Wr(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(Wr,"delayAbortable");function Gr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Gr,"mergeSignals");var to=class to{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?Gr(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(to,"MediaStore");var jr=to;function no(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(no,"makeUser");function oo(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(oo,"makeAssistant");function nr(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(nr,"stripPending");function na(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(na,"appendText");function io(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(io,"finalizeAssistant");function oa(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(oa,"freezeSnapshot");function U(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function so(e){let t=Oe(e.code);return D(t,{retryable:e.retryable||Nr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(so,"errorFromFrame");function Fe(e){return pe({code:jm(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Fe,"synthErrorFrame");function jm(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Qe(e)}}i(jm,"canonicalWireCode");function ia(e){let t=Array.isArray(e)?e:ro(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!ro(n))continue;let o=rr(n.category)??rr(n.title)??"",s=Wm(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(ia,"parsePromptCategories");function ao(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(ao,"flattenPrompts");function ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ro,"isPlainObject");function rr(e){return typeof e=="string"?e:null}i(rr,"asStr");function Wm(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(ro(r)){let n=rr(r.text)??rr(r.prompt)??rr(r.title);n!==null&&t.push(n);}return t}i(Wm,"asPromptTextList");function sa(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(sa,"defaultIdFactory");function aa(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(aa,"defaultIdempotencyFactory");var ua={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*da(e,t,r,n){let o=e[Symbol.asyncIterator](),s=la(t.overallMs,n),a=la(t.idleMs,n),l=qm(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([u,a.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Km();return}if(d.tag==="idle"||d.tag==="overall"){yield Gm();return}let c=d.value;if(c.done||(a.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{a.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(da,"withWatchdog");function Gm(){return pe({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Gm,"synthTimeoutFrame");function Km(){return pe({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Km,"synthStreamErrorFrame");function la(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(la,"deadline");function qm(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(qm,"abortPromise");var $m="checkin",Ym=/^\d{4}-\d{2}-\d{2}$/,Kr="watching";function ca(e){return e.status!=null&&e.status!==Kr}i(ca,"isCheckinSettled");function pa(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(pa,"isLiveAskAnswered");function lo(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==$m||n===void 0||o===void 0||!eo.test(n)||!Ym.test(o)?null:{caseId:n,dueDay:o}}i(lo,"parseCheckinOrigin");function fa(e){return lo(e)?.caseId??null}i(fa,"parseCheckinOriginRef");function uo(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return v(D("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Re(o))return v(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),L(r.length?`?${r.join("&")}`:"")}i(uo,"historyQuery");function sr(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(sr,"validConversationId");function ir(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(ir,"object");function ma(e){return e==null||typeof e=="string"&&e.length>0&&!Re(e)}i(ma,"cursor");function or(){return v(D("internalError",{retryable:false}))}i(or,"malformed");function ya(e){let t=ir(e);if(!t||!Array.isArray(t.conversations)||!ma(t.next_cursor))return or();let r=[];for(let n of t.conversations){let o=ir(n);if(!o||typeof o.conversation_id!="string"||!sr(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return or();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return or();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return L(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(ya,"mapConversationPage");function ga(e){let t=ir(e);if(!t||!Array.isArray(t.messages)||!ma(t.next_cursor))return or();let r=[],n=new Set;for(let o of t.messages){let s=ir(o);if(!s||typeof s.message_id!="string"||!sr(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return or();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let a=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,l=s.role==="assistant"?fa(a):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Xm(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Qm(s.citations)}:{},...a!==null?{proactiveOriginRef:a}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return L(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(ga,"mapMessagePage");function Xm(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Xm,"normalizeUrgency");function Qm(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=ir(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let a=n[s];(typeof a=="string"||a===null)&&(o[s]=a);}return [Object.freeze(o)]}))}i(Qm,"historyCitations");var co=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Mt=4e3;var Lt=4e3;function ha(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:U("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:U("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(ha,"validateImageKeys");function fo(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:U("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Lt?{reason:"too_long",error:U("validationFailed",false,`message is ${r} characters; the server accepts at most ${Lt}`)}:null}i(fo,"validateMessageText");function ba(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(ba,"urgencyTier");async function*ar(e){yield e;}i(ar,"singleFrameStream");async function*va(){}i(va,"emptyStream");var Zm=6e4,Jm=18e4,ey=24,ty=512,ry=false;function Ea(e){return new mo(e)}i(Ea,"createChatController");var yo=class yo extends jr{constructor(r){super(oa({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??xe({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=ea(this.funnel),this.telemetry=r.telemetry??Hr,this.errorPolicy=r.errorPolicy??ys,this.timers=r.timers??ua,this.rng=r.rng??Math.random,this.newId=r.newId??sa(),this.makeIdempotencyKey=r.makeIdempotencyKey??aa(),this.budget={idleMs:r.budget?.idleMs??Zm,overallMs:r.budget?.overallMs??Jm};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=U(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):ar(Fe(u))}let a=fo(r)??ha(s.imageS3Keys);if(a!==null)return this.telemetry.track("chat.send.rejected",{reason:a.reason}),this.patch({status:"error",isStreaming:false,error:a.error}),o?(o.onError(a.error),()=>{}):ar(Fe(a.error));if(o)return this.driveWithHandlers(r,s,o);let l=this.beginTurn(r,s);return this.runTurn(l,s.signal)}askEverfur(r,n){if(this.disposed)return ar(Fe(U("accessDenied",false)));let o=fo(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),ar(Fe(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):va()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,no(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?nr(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(r=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=r,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:r,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}newConversation(){this.disposed||this.resetThread(this.scopePrompts);}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(ao(r));this.bootstrapPrompts=n,this.scopePrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=uo(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return v(U("accessDenied",false));if(!a.ok)return a;let l=ya(a.value);if(l.ok){for(let c of l.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let u=this.snapshot.conversationId,d=u===null?void 0:this.unreadByConversation.get(u);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?L(n):v(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return v(s.error);let a=s.value.conversations[0];if(a===void 0)return L(null);let l=await this.resumeConversation(a.id);return l.ok?L(a.id):v(l.error)}async markRead(r){if(this.disposed)return v(U("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return L(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?v(U("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),L(void 0)):v(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return v(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Re(r))return v(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!co.includes(n))return v(U("validationFailed",false,`feedback_type must be one of ${co.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>Mt)return v(U("validationFailed",false,`notes is over ${Mt} characters`));let l={feedback_type:n};a.length>0&&(l.notes=a);let u=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},s?.signal);if(!this.alive(u)||this.disposed)return v(U("accessDenied",false));if(!d.ok)return v(d.error);let c=d.value?.feedback_id;return L(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return v(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return v(U("validationFailed",false,"a check-in needs the pet the case belongs to"));let a=this.epoch,l=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(a)||this.disposed)return v(U("accessDenied",false));if(!l.ok)return l;let u=l.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...u!==null?{openedAt:u}:{}}),c=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,checkin:d}):p)}),l}async getMessages(r,n){if(!sr(r))return v(U("validationFailed",false));let o=uo(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?v(U("accessDenied",false)):a.ok?ga(a.value):a}async resumeConversation(r){if(this.disposed)return v(U("accessDenied",false));if(!sr(r))return v(U("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),L(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===Kr).map(d=>d.caseId)),a=new Map(o.value.map(d=>[d.caseId,d])),l=false,u=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;l=true;let p=a.get(c.caseId),f=c.openedAt??p?.openedAt??null,y=s.has(c.caseId),m=p!==void 0&&(!y||pa({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:y?Kr:p?.status??"resolved",answer:c.answer??m,resolutionText:c.resolutionText??p?.resolutionText??null,...f!==null?{openedAt:f}:{}})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return L(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return v(o.error);let s=new Set(this.snapshot.messages.map(l=>l.id)),a=o.value.messages.filter(l=>!s.has(l.id));return a.length>0&&this.patch({messages:[...this.snapshot.messages,...a]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),L(void 0)}async loadOlderMessages(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return L(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let a=new Set(this.snapshot.messages.map(u=>u.id)),l=s.value.messages.filter(u=>!a.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),L(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Fe(n.error));}async primeConversation(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?v(U("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return L(n);let o=this.snapshot.conversationId;return o!==null?L(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let a=await s.settled;return !this.alive(n)||this.disposed?v(U("accessDenied",false)):(!a.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),a)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?v(U("internalError",true)):L(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Re(o))return v(D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",a=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?v(U("accessDenied",false)):a.ok?L(ia(a.value)):v(a.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,a=Gr(s.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,a),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of u){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,no(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,a=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=u?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let b=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;b.ok&&this.snapshot.conversationId===null&&this.adoptConversation(b.value);}if(u&&this.snapshot.conversationId===null){let b=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!b.ok){yield*this.emitTerminal(r,b.error,Fe(b.error));return}this.adoptConversation(b.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let b=U("internalError",!0);yield*this.emitTerminal(r,b,Fe(b));return}this.clearAssistantInProgress(r);let p=new AbortController,f=Gr(o.signal,p.signal),y=null;try{let b;try{b=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let I=this.authRejected();yield*this.emitTerminal(r,I,Fe(I));return}if(o.signal.aborted||!this.alive(o.epoch))return;let R=this.funnel.stream("chat.send",b,f);for await(let I of da(R,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(I.kind==="error"&&I.terminal){y=I;break}if(this.applyFrame(I,r),yield I,I.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(y===null){if(this.snapshot.status==="complete")return;let b=U("streamIncomplete",!0);yield*this.emitTerminal(r,b,Fe(b));return}let m=Oe(y.code);if(m==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let b=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!b){let R=this.authRejected();yield*this.emitTerminal(r,R,y);return}this.patch({reconnecting:!0});continue}if(m==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let b=this.authRejected();yield*this.emitTerminal(r,b,y);return}if(m==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,so(y),y);return}if(fs(m)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let w=y.retryable&&Nr(m,!0);if(ry&&w&&s+1<this.errorPolicy.maxAttempts(m));yield*this.emitTerminal(r,so(y),y);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Qe(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(a=>a.id===n.userMessageId&&a.pending===true?nr(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,oo(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=ty){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},ey);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(a=>a.id===o?na(a,n):a);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?io(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?nr(d):d),io(oo(l,"",this.stamp()),r)];}let a=ao([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=a.length>0?Object.freeze(a):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,a=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(s)||this.disposed||a!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=ba(l.value?.urgency),d=typeof l.value?.reason=="string"?l.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?nr(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return U("authRejected",false)}};i(yo,"ChatControllerImpl");var mo=yo;async function Sa(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],a=false,l=false,u=false,d=null,c=null,p=o?r.resumeConversation(o).then(x=>x.ok?L(o):x):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[y,m]=await Promise.all([p,f]),w=null;if(y.ok)w=y.value,s.push(y.value),r.getSnapshot().conversationId===null&&r.adoptConversation(y.value);else {let x=y.error;c=x,Ca(x)?(l=true,d=x):(Ra(x)&&(a=true),u=true);}let b=[];m.ok?b=m.value:R(m.error);function R(x){Ca(x)?(l=true,d===null&&(d=x)):Ra(x)&&(a=true);}i(R,"recordAuthSignals");let I=d!==null?d.displayMessage:null;return Object.freeze({conversationId:w,petRef:n,suggestedPrompts:b,error:I,warning:I===null&&w===null&&u?ny:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Sa,"bootstrapChat");var ny="Chat is ready. Your first message will start the conversation.";function Ca(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(Ca,"isUnauthorized");function Ra(e){return e.httpStatus===403||e.code==="accessDenied"}i(Ra,"isForbidden");var go=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Ta(e){return e!==go}i(Ta,"isUploadTransportAvailable");var oy=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var qr=10*1024*1024,$r=5,lr=120,iy="/widget/v1/uploads/initiate";function sy(e){return typeof e=="string"&&oy.includes(e.trim().toLowerCase())}i(sy,"isAttachmentMime");function ho(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<=lr)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,lr);let n=t.slice(r);return n.length>=lr?t.slice(0,lr):`${t.slice(0,r).slice(0,lr-n.length)}${n}`}i(ho,"sanitizeFilename");function bo(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(bo,"formatBytes");var ur=i(e=>Object.freeze({ok:true,value:e}),"ok"),_e=i(e=>Object.freeze({ok:false,error:e}),"err");function oe(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(oe,"failure");function ay(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(ay,"attachmentSize");function ly(e){let t=ho(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!sy(r))return _e(oe("unsupported_type",false,t));let n=ay(e);return n===null?_e(oe("unknown",false,t)):n>qr?_e(oe("too_large",false,t,{sizeBytes:n})):ur(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(ly,"validateAttachment");function uy(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d: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={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[d,c]of Object.entries(u))typeof c=="string"&&(l[d]=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)??qr,s3_key:a,purpose:r(t.purpose)})}i(uy,"parsePolicy");function dy(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return oe("quota_exceeded",false,t,{cause:e});case "rateLimited":return oe("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return oe("idempotency_conflict",true,t,{cause:e});case "validationFailed":return oe("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return oe("network",true,t,{cause:e});default:return r===429?oe("rate_limited",true,t,{cause:e}):r===503?oe("network",true,t,{cause:e}):r===void 0?oe("network",true,t,{cause:e}):oe("server",e.retryable,t,{httpStatus:r,cause:e})}}i(dy,"initiateFailure");async function cy(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:iy,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return _e(dy(n.error,t.filename));let o=uy(n.value);return o===null?_e(oe("server",false,t.filename)):ur(o)}i(cy,"initiateAttachmentUpload");async function py(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return _e(oe("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),ur(void 0)}catch{return o()?_e(oe("cancelled",true,r.filename)):_e(oe("server",true,r.filename))}}i(py,"uploadAttachmentBytes");var fy=2,my=3,yy=Object.freeze([1e3,2e3,4e3]),Pa=0;function gy(){return Pa+=1,`attachment-${Pa}`}i(gy,"defaultNewId");function ka(e){let t=Math.max(1,e.concurrency??fy),r=Math.max(1,e.maxAttempts??my),n=e.backoffMs??yy,o=Math.max(1,e.maxPerMessage??$r),s=e.timers??ra,a=e.newId??gy,l=Ta(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,y=Object.freeze({attachments:Object.freeze([])}),m=false,w=i(()=>{y=Object.freeze({attachments:Object.freeze(d.flatMap(g=>{let _=u.get(g);return _===void 0?[]:[_.state]}))});for(let g of f)g();},"publish"),b=i((g,_)=>{g.state=Object.freeze({...g.state,..._}),w();},"patch"),R=i(()=>{for(;!m&&p.size<t&&c.length>0;){let g=c.shift(),_=u.get(g);_!==void 0&&(p.add(g),I(_).finally(()=>{p.delete(g),R();}));}},"pump"),I=i(async g=>{let{attachment:_}=g;for(;g.attempts<r;){if(m||g.controller.signal.aborted)return;g.attempts+=1;let F=g.controller.signal;b(g,{status:"uploading",error:null,progress:0});let M=await cy(e.funnel,_,{signal:F});if(m||F.aborted)return;let E;if(!M.ok)E=_e(M.error);else {let j=await py(e.transport,M.value,_,{signal:F,onProgress:i(G=>{!F.aborted&&g.state.status==="uploading"&&b(g,{progress:hy(G)});},"onProgress")});if(m||F.aborted)return;E=j.ok?ur(M.value.s3_key):_e(j.error);}if(E.ok){b(g,{status:"uploaded",s3Key:E.value,error:null,progress:1});return}let k=E.error,T=k.retryable&&g.attempts<r;if(b(g,{status:T?"uploading":"failed",error:k,progress:0}),!T)return;let V=n[Math.min(g.attempts-1,n.length-1)]??0;await Wr(V,F,s);}},"run"),P=i(g=>{c.push(g.state.id),R();},"enqueue"),x={available:l,subscribe(g){return f.add(g),()=>{f.delete(g);}},getSnapshot:i(()=>y,"getSnapshot"),get uploading(){return y.attachments.some(g=>g.status==="uploading")},get s3Keys(){return y.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[])},add(g){let _=ly(g);if(!_.ok)return _;if(m||d.length>=o)return _e(oe("too_many",false,_.value.filename));let F=a(),M={attachment:_.value,controller:new AbortController,attempts:0,state:Object.freeze({id:F,filename:_.value.filename,previewUri:g.uri,contentType:_.value.contentType,sizeBytes:_.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(F,M),d.push(F),w(),P(M),ur(M.state)},retry(g){let _=u.get(g);_===void 0||m||_.state.status!=="failed"||(_.controller=new AbortController,_.attempts=0,b(_,{status:"uploading",error:null,progress:0,s3Key:null}),P(_));},remove(g){let _=u.get(g);if(_===void 0)return;_.controller.abort(),u.delete(g);let F=d.indexOf(g);F>=0&&d.splice(F,1);let M=c.indexOf(g);M>=0&&c.splice(M,1),w();},clear(){for(let g of [...d])x.remove(g);},dispose(){m=true;for(let g of u.values())g.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),y=Object.freeze({attachments:Object.freeze([])});}};return x}i(ka,"createAttachmentQueue");function hy(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(hy,"clamp");var xa=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function dr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(xa,t)?xa[t]:null}i(dr,"canonicalPetSpecies");var _a=50,by=128,vo=120,wa=120,vy=2e3,Ia=120,Ey=80,Fa=new Set(["male","female","unknown"]),Ma=new Set(["day","month","year"]),La=new Set(["low","medium","high","athletic"]),Da=new Set(["indoor","outdoor","both"]),Na=new Set(["mild","moderate","severe"]),Cy=/^(\d{4})-(\d{2})-(\d{2})$/,Ua=[["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"]],Va=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Ua,...Va].map(([e])=>e));function Ry(e){let t=Cy.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(Ry,"isRealDate");var pr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),Sy=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Xr=i((e,t)=>typeof t=="string"&&Ry(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Me=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Re(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=st(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),Ty={sex:pr(Fa),spayedNeutered:Sy,birthDate:Xr,birthDatePrecision:pr(Ma),activityLevel:pr(La),indoorOutdoor:pr(Da),foodBrand:Me(Ia),foodType:Me(Ia),microchipId:Me(Ey)},Eo=["ref","ref",false,Me(by,{required:true,trimmed:true})],Co=["notes","notes",false,Me(vy,{trimmed:true})],Aa=[Eo,["name","name",true,Me(vo,{required:true,trimmed:true})],["dose","dose",false,Me(wa,{trimmed:true})],["frequency","frequency",false,Me(wa,{trimmed:true})],["startDate","start_date",false,Xr],["endDate","end_date",false,Xr],Co],Py={allergies:[Eo,["allergen","allergen",true,Me(vo,{required:true,trimmed:true})],["severity","severity",false,pr(Na)],Co],medications:Aa,supplements:Aa,conditions:[Eo,["conditionName","condition_name",true,Me(vo,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Xr],Co]};function ky(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[u,d,c,p]of Py[e]){let f=o[u];if(f==null){if(c)return {error:`${n}.${u} is required`};f===null&&(s[d]=null);continue}let y=p(`${n}.${u}`,f);if(y!==null)return {error:y};s[d]=f;}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(ky,"itemToWire");function xy(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>_a)return {error:`${e} has ${t.length} items; the server accepts at most ${_a}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=ky(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(xy,"listToWire");function Ha(e,t){let r=e,n={};for(let[a,l]of Ua){let u=r[a];if(u!==void 0){if(u!==null){let d=Ty[a](a,u);if(d!==null)return {error:d}}n[l]=u;}}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 Va){let u=r[a];if(u===void 0)continue;let d=xy(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&dr(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(Ha,"petHealthToWire");var ee=i(e=>typeof e=="string"?e:null,"str"),cr=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),_y=i(e=>typeof e=="boolean"?e:null,"bool");function Yr(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(Yr,"itemsFromWire");function Oa(e){let t=ee(e.name);return t===null||t.length===0?null:Object.freeze({ref:ee(e.ref),name:t,dose:ee(e.dose),frequency:ee(e.frequency),startDate:ee(e.start_date),endDate:ee(e.end_date),notes:ee(e.notes)})}i(Oa,"medicationFromWire");function Ba(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:cr(Fa,e.sex),spayedNeutered:_y(e.spayed_neutered),birthDate:ee(e.birth_date),birthDatePrecision:cr(Ma,e.birth_date_precision),activityLevel:cr(La,e.activity_level),indoorOutdoor:cr(Da,e.indoor_outdoor),foodBrand:ee(e.food_brand),foodType:ee(e.food_type),microchipId:ee(e.microchip_id),allergies:Yr(e.allergies,r=>{let n=ee(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),allergen:n,severity:cr(Na,r.severity),notes:ee(r.notes)})}),medications:Yr(e.medications,Oa),supplements:Yr(e.supplements,Oa),conditions:Yr(e.conditions,r=>{let n=ee(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),conditionName:n,diagnosedDate:ee(r.diagnosed_date),notes:ee(r.notes)})})})}i(Ba,"petHealthFromWire");var Wa=100,Ga=50,Ka=100,qa=50,$a=500,wy=128,Iy=6e4;function De(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(De,"invalid");function at(e,t,r){if(typeof t!="string")return De(`${e} must be a string`);let n=st(t);return n<=r?null:De(`${e} is ${n} characters; the server accepts at most ${r}`)}i(at,"checkString");function Qr(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:De(`${e} must be a finite number between 0 and ${r}`)}i(Qr,"outOfRange");function za(e,t){if(typeof e!="string")return De("pet_ref must be a string");if(e.trim().length===0)return De("pet_ref must not be blank");if(Re(e))return De("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return De("profile must be an object");let r=[at("pet_ref",e,wy)];return t?.name!==void 0&&r.push(at("name",t.name,Wa)),t?.species!==void 0&&r.push(at("species",t.species,Ga)),t?.breed!==void 0&&r.push(at("breed",t.breed,Ka)),t?.ageYears!==void 0&&r.push(Qr("age_years",t.ageYears,qa)),t?.weightKg!==void 0&&r.push(Qr("weight_kg",t.weightKg,$a)),r.find(n=>n!==null)??null}i(za,"validate");function Ya(e,t){let r=Ha(e,t);return "error"in r?{error:De(r.error)}:r}i(Ya,"healthToWire");function Ay(e){if(typeof e!="object"||e===null)return {error:De("patch must be an object")};let t=e,r=[["name","name",s=>at("name",s,Wa)],["species","species",s=>at("species",s,Ga)],["breed","breed",s=>at("breed",s,Ka)],["ageYears","age_years",s=>Qr("age_years",s,qa)],["weightKg","weight_kg",s=>Qr("weight_kg",s,$a)]],n={};for(let[s,a,l]of r){let u=t[s];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}n[a]=u;}}let o=Ya(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:De("patch must change at least one field")}:{body:n})}i(Ay,"patchToWire");function Oy(e){if(e==null)return {body:{}};let t=Ya(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(Oy,"toWire");var Le=i(e=>typeof e=="string"?e:null,"str"),Zr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function ja(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Le(r.pet_ref)??t,name:Le(r.name),species:Le(r.species),breed:Le(r.breed),ageYears:Zr(r.age_years),weightKg:Zr(r.weight_kg)})}i(ja,"fromWire");function Xa(e){if(typeof e!="object"||e===null)return null;let t=e,r=Le(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Le(t.pet_id),petRef:r,name:Le(t.name),species:Le(t.species),breed:Le(t.breed),ageYears:Zr(t.age_years),weightKg:Zr(t.weight_kg),updatedAt:Le(t.updated_at)})}i(Xa,"widgetPetFromWire");function Fy(e){let t=Xa(e);return t===null?null:Object.freeze({...t,...Ba(e)})}i(Fy,"widgetPetProfileFromWire");function My(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=Xa(r);return n===null?[]:[n]}))}i(My,"petListFromWire");function Ze(e){return Ly(xe({auth:e}),xe({auth:e,unaryTimeoutMs:Iy}))}i(Ze,"createPetsRepository");function Ly(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>za(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?L(My(s.value)):v(s.error)},async registerPet(o,s,a){let l=za(o,s);if(l!==null)return v(l);let u=Oy(s);if("error"in u)return v(u.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",a?.signal?{...c,signal:a.signal}:c);return p.ok?L(ja(p.value,o)):v(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return v(l);let u=Ay(s);if("error"in u)return v(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?L(ja(d.value,o)):v(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return v(l.error);let u=Fy(l.value);return u===null?v(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):L(u)},async deletePet(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?L(void 0):v(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?L(void 0):v(s.error)}}}i(Ly,"createPetsRepositoryOver");var So=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 Dy(e){return So[e]}i(Dy,"requires");function Qa(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(So))for(let a of So[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(Qa,"deniedDecisionsFor");function Za(e,t,r){let n=Dy(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 Ro({name:e,enabled:false,isPending:true,limits:{}});let s=Ny(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?Ro({name:e,enabled:true,isPending:false,limits:s}):Ro({name:e,enabled:false,isPending:false,limits:s,disabled:Uy(n,o)})}i(Za,"decideCapability");function Ny(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(Ny,"mergeLimits");function Uy(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:Ft("accessDenied"),level:"user_entitlement",recoverable:false})}i(Uy,"disabledFor");function Ro(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(Ro,"freezeDecision");function ye(e){let t=ie(e);return t===null?null:Hy(t)}i(ye,"parseColor");function ie(e){if(typeof e=="number")return Ja(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return To(t.slice(1));if(t.toLowerCase().startsWith("0x"))return To(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Vy(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=To(t);if(r!==null)return r}return /^\d+$/.test(t)?Ja(Number.parseInt(t,10)):null}i(ie,"toRgba");function To(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Po(t[0]),g:Po(t[1]),b:Po(t[2]),a:1};if(t.length===6)return {r:lt(t,0),g:lt(t,2),b:lt(t,4),a:1};if(t.length===8){let r=lt(t,0);return {r:lt(t,2),g:lt(t,4),b:lt(t,6),a:r/255}}return null}i(To,"fromHex");function Vy(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(u=>u.trim());if(n.length<3)return null;let o=ko(Number(n[0])),s=ko(Number(n[1])),a=ko(Number(n[2]));if(o===null||s===null||a===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:s,b:a,a:l}}i(Vy,"fromRgbFunc");function Ja(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(Ja,"argbIntToRgba");function lt(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(lt,"byte");function Po(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Po,"dup");function ko(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(ko,"clampByte");function Hy(e){if(e.a>=1)return dt(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Hy,"normalizeRgba");function dt(e,t,r){return `#${xo(e)}${xo(t)}${xo(r)}`.toUpperCase()}i(dt,"rgbToHex");function xo(e){return e.toString(16).padStart(2,"0")}i(xo,"hex2");var By="#111111",Dt="#FFFFFF",Jr="#000000";function tl(e){let t=ie(e);if(t===null)return Dt;let r=ut(t),n=ut({r:17,g:17,b:17}),o=ut({r:255,g:255,b:255});return Io(r,o)>=Io(r,n)?Dt:By}i(tl,"readableOn");function fr(e,t){let r=tl(e);return ue(r,e)>=t?r:ue(Dt,e)>=ue(Jr,e)?Dt:Jr}i(fr,"legibleOn");function mr(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Dt)>=t(Jr)?Dt:Jr}i(mr,"poleForGrounds");function ut(e){let t=_o(e.r/255),r=_o(e.g/255),n=_o(e.b/255);return .2126*t+.7152*r+.0722*n}i(ut,"relativeLuminance");function _o(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(_o,"linearize");function Io(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(Io,"luminanceContrast");function ue(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:rl(r,o);return Io(ut(s),ut(o))}i(ue,"contrastRatio");function rl(e,t){let r=e.a,n=i((o,s)=>Math.round(o*r+s*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(rl,"composite");function ct(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return null;let o=r.a>=1?r:rl(r,{...n});return dt(o.r,o.g,o.b)}i(ct,"flattenOnto");function nl(e,t){let r=ie(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(nl,"withAlpha");var el=.05;function Je(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>ue(d,c)>=n),"reads");if(ie(e)===null)return r;if(s(e))return e;let a=ct(e,o),l=a===null?null:ie(a),u=ie(r);if(l===null||u===null)return r;for(let d=1;d<1/el;d+=1){let c=d*el,p=i((y,m)=>Math.round(y+(m-y)*c),"mix"),f=dt(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(Je,"pushToContrast");function ol(e,t,r){let n=e/255,o=t/255,s=r/255,a=Math.max(n,o,s),l=Math.min(n,o,s),u=(a+l)/2;if(a===l)return {h:0,s:0,l:u};let d=a-l,c=d/(1-Math.abs(2*u-1)),p;return a===n?(p=(o-s)/d*60,p<0&&(p=p+360)):a===o?p=((s-n)/d+2)*60:p=((n-o)/d+4)*60,{h:p,s:c,l:u}}i(ol,"rgbToHsl");function Ao(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,s=t/60,a=o*(1-Math.abs(s%2-1)),l=n-o/2,u=Math.floor(s)%6,d=[[o,a,0],[a,o,0],[0,o,a],[0,a,o],[a,0,o],[o,0,a]],[c,p,f]=d[u];return {r:wo(c+l),g:wo(p+l),b:wo(f+l)}}i(Ao,"hslToRgb");function wo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(wo,"channel");function je(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))je(e[t]);}return e}i(je,"deepFreeze");var tn=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),sl={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},al={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},il={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},zy={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},jy={regular:"400",medium:"500",bold:"700"},Wy={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Oo=0,pt="System",Ne="monospace",Gy=["content","heading","control","compact","badge"];function Ky(e){let t={};for(let r of Gy)t[r]=e;return t}i(Ky,"authoredTierSizes");function ll(){return {family:pt,mono:Ne,fontUrl:null,families:{regular:pt,medium:pt,bold:pt,mono:Ne,monoMedium:Ne,monoBold:Ne},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:il,tierSizes:Ky(il),lineHeight:zy,weight:jy,letterSpacing:Wy,scale:1,maxScale:Oo,scaleCaps:tn}}i(ll,"baseType");var ul={},ft=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function en(e){return `cubic-bezier(${e.join(", ")})`}i(en,"cssCubicBezier");var dl={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:en(ft.standard),emphasized:en(ft.emphasized),exit:en(ft.exit)},reducedMotion:false},qy={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:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",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:"#B91C1C",errorRed:"#FF1B00",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(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},mt=je({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:qy,space:sl,radius:al,type:ll(),motion:dl,slots:ul}),$y={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:"#9A938C",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",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",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},rn=je({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:$y,space:sl,radius:al,type:ll(),motion:dl,slots:ul});var Yy="#23272C",cl=4.5,Xy=.6,Fo=.9,Qy=.02,Zy="#FFFFFF",Jy="#111111";function eg(e){return ue(e,Yy)>=cl&&Math.max(ue(e,Zy),ue(e,Jy))>=cl}i(eg,"readsOnDark");function ml(e){let t=ie(e);if(t===null)return null;let{h:r,s:n,l:o}=ol(t.r,t.g,t.b),s=Math.min(Math.max(o,Xy),Fo);for(let l=0;;l+=1){let u=s+l*Qy;if(u>Fo)break;let d=Ao({h:r,s:n,l:u}),c=dt(d.r,d.g,d.b);if(eg(c))return c}let a=Ao({h:r,s:n,l:Fo});return dt(a.r,a.g,a.b)}i(ml,"deriveDarkVariant");var tg=7,pl=.05,rg="#000000",ng="#FFFFFF";function og(e,t,r,n){let o=ct(e,t);if(o===null)return r;if(ue(o,t)>=n)return o;let s=ie(o),a=ie(r);if(s===null||a===null)return r;for(let l=1;l<1/pl;l+=1){let u=l*pl,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=dt(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(ue(c,t)>=n)return c}return r}i(og,"pushContrast");function ig(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=fl(n);for(let s of r){let a=fl(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(ig,"hardestGround");function fl(e){let t=ie(e);return t===null?0:ut(t)}i(fl,"luminanceOf");function et(e,t){return ct(e,t)??ye(e)??t}i(et,"solid");function yl(e){let t=e.color,r=e.brightness==="dark",n=r?ng:rg,o=ig(t,r),s=i(l=>og(l,o,n,tg),"text"),a={...t,brandSoft:et(t.brandSoft,t.surface),brandSofter:et(t.brandSofter,t.surface),brandBorder:s(t.brandBorder),borderHairlineGreen:s(t.borderHairlineGreen),brandBorderStrong:s(t.brandBorderStrong),brandInk:s(t.brandInk),linkInk:s(t.linkInk),borderRingCream:s(t.borderRingCream),composerBorder:s(t.composerBorder),text:{primary:s(t.text.primary),secondary:s(t.text.secondary),muted:s(t.text.muted),placeholder:s(t.text.placeholder),onBrand:t.text.onBrand,metaCool:s(t.text.metaCool),timestamp:s(t.text.timestamp)},badgeBgPositive:et(t.badgeBgPositive,t.surface),badgeBgCaution:et(t.badgeBgCaution,t.surface),badgeBgCritical:et(t.badgeBgCritical,t.surface),badgeBgNeutral:et(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:et(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:et(t.checkupCardConcernBg,t.surface)};return je({...e,highContrast:true,color:a})}i(yl,"deriveHighContrast");var yt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),sg=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),we=4.5,ag=Object.freeze({});function lg(e){return yt.includes(e)}i(lg,"isSlotName");function ug(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(ug,"parseRadius");function gl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!lg(n)||o===null||typeof o!="object")continue;let s=dg(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(gl,"parseThemeSlots");function nn(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(nn,"pick");function dg(e){let t={},r=ye(nn(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ye(nn(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=ug(nn(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=ye(nn(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(dg,"parseSlot");function hl(e,t){return t===null||Object.keys(t).length===0?e??ag:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(hl,"mergeThemeSlots");var Mo=3;function cg(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>ct(e,r)??r)}i(cg,"seatsOf");function pg(e,t){let r=mr(e);return e.every(n=>ue(r,n)>=t)}i(pg,"someInkReads");function fg(e,t){let r=t[0];return r===void 0?null:ct(e,r)}i(fg,"collapseUnsatisfiableFill");function mg(e){let t=fr(e[0],we);return e.every(r=>ue(t,r)>=we)?t:mr(e)}i(mg,"inkFor");function bl(e,t){let r=false,n={};for(let o of yt){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=cg(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!pg(u,we)){let p=fg(a,l);p!==null&&(d.backgroundColor=p,u=[p],c=true);}if(u.length>0){let p=s.textColor;if(a!==void 0)(p===void 0||u.some(f=>ue(p,f)<we))&&(d.textColor=mg(u),c=true);else if(p!==void 0){let f=Je(p,u,mr(u),we);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=Je(s.borderColor,u,mr(u),Mo);f!==s.borderColor&&(d.borderColor=f,c=true);}}n[o]=c?Object.freeze(d):s,r=r||c;}return r?Object.freeze(n):e}i(bl,"guardSlotContrast");var Cl=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),yr="slots.",Rl=Object.freeze([1,2]);function on(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(on,"isEmptyBranding");function Sl(e){let t=e?.schemaVersion??null;return t===null||Rl.includes(t)}i(Sl,"isKnownBrandingSchema");function Tl(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(Tl,"lockedFieldsOf");function yg(e){return e==="hide_powered_by"||Cl.includes(e)?true:e.startsWith(yr)&&yt.includes(e.slice(yr.length))}i(yg,"isThemeLockName");function We(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:gt($(t,"display_name","displayName")),logoUrl:gt($(t,"logo_url","logoUrl")),primaryColor:ye($(t,"primary_color","primaryColor")),accentColor:ye($(t,"accent_color","accentColor")),brightness:vg($(t,"brightness","color_scheme","colorScheme")),fontFamily:gt($(t,"font_family","fontFamily")),fontUrl:gt($(t,"font_url","fontUrl")),fonts:vl($(t,"fonts")),fontUrls:vl($(t,"font_urls","fontUrls")),placeholder:gt($(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:gg($(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ye($(t,"primary_color_dark","primaryColorDark")),accentColorDark:ye($(t,"accent_color_dark","accentColorDark")),surfaceStyle:El($(t,"surface_style","surfaceStyle"),hg),radiusScale:El($(t,"radius_scale","radiusScale"),bg),logoUrlDark:gt($(t,"logo_url_dark","logoUrlDark")),slots:gl($(t,"slots")),accessibilityMaxFontScale:Cg($(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Sg($(t,"locked_fields","lockedFields")),schemaVersion:Rg($(t,"schema_version","schemaVersion"))};return on(r)?null:Object.freeze(r)}i(We,"parseClientBranding");function gg(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(gg,"parseBool");function $(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i($,"pick");function gt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(gt,"parseNonEmptyString");var gr=["regular","medium","bold","mono","monoMedium","monoBold"];function vl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of gr){let o=gt($(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(vl,"parseFaceMap");var hg=["white","cream","subtle"],bg=["sharp","default","round"];function El(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(El,"parseEnum");function vg(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(vg,"parseBrightness");function Pl(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(Pl,"parseNumber");var Eg=1,kl=3.1;function Cg(e){let t=Pl(e);return t===null?null:t<=0?0:Math.min(kl,Math.max(Eg,t))}i(Cg,"parseMaxFontScale");function Rg(e){if(e==null)return null;let t=Pl(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(Rg,"parseSchemaVersion");function Lo(e){let t=e.trim();return t.startsWith(yr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Lo,"toWireName");function Sg(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Lo(r);yg(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(Sg,"parseLockedFields");function Do(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Do,"hardenHttpsUrl");function xl(e,t){if(t===null||on(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?rn:mt:e,n=r.brightness==="dark"?rn:mt,o=r.brightness==="dark",s=o?t.primaryColorDark??_l(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??_l(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&_g(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?ie(c):null,f=i(w=>Math.round(w+(255-w)*.4),"lift"),y=p!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:d?wg(n,r.color.text):{},m={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...y,...xg(t.surfaceStyle??null,n),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:Ag(t.radiusScale??null,r.radius,n),type:{...r.type,...kg(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:hl(r.slots,t.slots??null)};return je(m)}i(xl,"withServerBranding");var Tg={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Pg=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function No(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(No,"isMonoFace");function kg(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of gr){let u=Tg[l].map(p=>r[p]).find(p=>p!==void 0),d=No(l)?null:t.fontFamily;u!==void 0?(o[l]=u,s[l]=true):d!==null&&(o[l]=d,s[l]=false);let c=n[l]??(l==="regular"?t.fontUrl:null)??null;c!==null?a[l]=c:u!==void 0&&delete a[l];}for(let l of Pg)for(let u of l)s[u]&&l.some(d=>d!==u&&o[d]===o[u])&&(s[u]=false);return {family:o.regular,mono:o.mono,fontUrl:a.regular??null,families:o,namedFaces:s,fontUrls:a}}i(kg,"mergeFaces");function _l(e){return e===null?null:ml(e)}i(_l,"darkVariantOf");function xg(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(xg,"surfaceOf");function wl(e,t){return e==null?false:ye(e)===ye(t)}i(wl,"sameColor");function _g(e,t,r,n){return wl(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&wl(e.primaryColor,mt.color.primary)}i(_g,"isCompiledPrimary");function wg(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(wg,"compiledBrandFamily");var Ig={sharp:.5,default:1,round:1.5};function Ag(e,t,r){if(e===null)return t;let n=Ig[e],o=r.radius,s=i(a=>Math.round(a*n),"s");return {tile:s(o.tile),xs:s(o.xs),sm:s(o.sm),md:s(o.md),lg:s(o.lg),xl:s(o.xl),pill:o.pill}}i(Ag,"radiusOf");var Og="Everfur",Fg=.5;function Uo(e){let t=e?.branding??null,r=Sl(t)?t:null,n=Ug(e?.clientOverride??null,Tl(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=xl((s==="auto"?o:s)==="dark"?rn:mt,Il(r)),d=xl(u,Il(n));return Xg(d,e)}i(Uo,"resolveTheme");function Mg(e,t,r){return Uo({...r,branding:We(t),clientOverride:We(e)})}i(Mg,"previewTheme");function Lg(e){return e==="placeholder"?"chat_placeholder":Lo(e)}i(Lg,"wireNameOf");var Dg={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Ng(e,t){return t.has(Lg(e))?true:(Dg[e]??[]).some(r=>t.has(r))}i(Ng,"isLocked");function Ug(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(Ng(a,t)||a==="lockedFields")&&(n[a]=null,r=true);let o=n.slots??null;if(o!==null){let a={},l=false;for(let u of yt){let d=o[u];d!==void 0&&(t.has(`${yr}${u}`)?l=true:a[u]=d);}l&&(n.slots=Object.keys(a).length===0?null:Object.freeze(a),r=true);}if(!r)return e;let s=Object.freeze(n);return on(s)?null:s}i(Ug,"withoutFields");function Il(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(Il,"withoutBrightness");function Vg(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(Vg,"scaledSizes");function Hg(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Fg,e)}i(Hg,"effectiveScale");var Al=["content","heading","control","compact","badge"];function Bg(e){if(!(e>0))return tn;let t={};for(let r of Al){let n=tn[r];t[r]=n===0?0:Math.min(n,e);}return t}i(Bg,"tierCaps");function zg(e,t){return t>0?Math.min(e,t):e}i(zg,"capped");function jg(e,t,r,n){let o={};for(let s of Al)o[s]=n?Vg(e,zg(t,r[s])):e;return o}i(jg,"sizesByTier");function Wg(e){return e==="dark"?"#FFFFFF":"#000000"}i(Wg,"inkPole");function Gg(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(Gg,"textGrounds");function Kg(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(Kg,"controlGrounds");function Ol(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Ol,"linkGrounds");function qg(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Ol(e)}}i(qg,"slotGrounds");function $g(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i($g,"registration");function Yg(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},s={...e.namedFaces};for(let a of gr)!(o[a]===pt||o[a]===Ne)&&r!==void 0&&$g(r,o[a])===false&&(o[a]=No(a)?Ne:pt,s[a]=false),n!==null&&No(a)&&o[a]===Ne&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(Yg,"platformFaces");function Xg(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?Og:e.meta.displayName,s=Do(e.meta.logoUrl),a={};for(let P of gr){let x=e.type.fontUrls[P];x!==void 0&&(a[P]=Do(x));}let l=a.regular??null,d=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,c=Number.isFinite(e.type.maxScale)?e.type.maxScale:Oo,p=Hg(t?.textScale),f=Bg(c),y=jg(e.type.size,p,f,t?.scaleTypeSizes===true),m=e.color,w=Wg(e.brightness),b=Gg(m),R={...m,primary:r,accent:n,onPrimary:fr(r,we),onAccent:fr(n,we),brandInk:Je(m.brandInk,b,w,we),linkInk:Je(e.slots.link?.textColor??n,Ol(m),w,we),text:{...m.text,secondary:Je(m.text.secondary,b,w,we)},brandBorderStrong:Je(m.brandBorderStrong,Kg(m),w,Mo)},I={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:s,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:R,space:e.space,radius:e.radius,type:{...e.type,...Yg(e.type,t),fontUrl:l,fontUrls:a,size:y.content,tierSizes:y,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:bl(e.slots,qg(R))};return t?.highContrast===true?yl(je(I)):je(I)}i(Xg,"finalize");var Fl="/widget/v1/entitlements",Qg=304,Zg=Object.freeze({kind:"notModified"});async function Ll(e,t={},r=xe({auth:e})){let n=await r.send("entitlements.fetch",eh(t));return n.ok?th(n.value):n.error.httpStatus===Qg?Zg:{kind:"failed",error:n.error}}i(Ll,"fetchEntitlements");var Jg=64;function eh(e){let t={};return Vo(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Jg?{method:"GET",path:Fl,headers:t,query:{region:e.region}}:{method:"GET",path:Fl,headers:t}}i(eh,"buildRequest");function th(e){if(e===null||typeof e!="object"||!Vo(e.revision))return Ml();let t=typeof e.region=="string"?e.region:"",r=Vo(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:nh(e.capabilities),branding:rh(e)})}i(th,"parseUpdated");function rh(e){let t=We(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=We(r.branding);return n!==null?n:We(r)}return null}i(rh,"parseBranding");function nh(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))oh(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(nh,"mapCapabilities");function oh(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(oh,"isEnabled");function Ml(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Ml,"malformed");function Vo(e){return typeof e=="number"&&Number.isFinite(e)}i(Vo,"isFiniteNumber");var ih=30;function Dl(e){let t=e.scheduler??sh,r=e.resolve??Ll,n=Math.max(1,e.floorSeconds??ih),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),a=false,l=false,u=null,d=null,c=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),y=i(R=>{l||!a||(c=Math.max(n,R),u=t.set(()=>{u=null,b();},c*1e3));},"schedule"),m=null,w=i(async()=>{if(l)return null;let R=p;e.onFetch?.();let I=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},P;try{P=await r(e.authFor(),I);}catch(x){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:ah(x)}),!l&&R===p&&(e.onSettled?.(),y(s())),null}if(l||R!==p)return null;switch(P.kind){case "updated":d=P.revision,e.update(P.decisions,P.branding??null),y(P.ttlSeconds);break;case "notModified":y(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:P.error.code}),y(s());break;default:y(s());}return e.onSettled?.(),P},"tick"),b=i(()=>{let R=w().finally(()=>{m===R&&(m=null);});return m=R,R},"run");return {start(){a||l||(a=true,b());},prime(){return l?Promise.resolve(null):m??b()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),b());}}}i(Dl,"createEntitlementPoller");var sh={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function ah(e){return e instanceof Error?e.message:"poll failed"}i(ah,"describe");var Nl="everfur.notifications.device";var lh=3e3,Ul=Object.freeze([Nl]);function Vl(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),a=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),l=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:a.length});}catch{}},"report"),u=Promise.allSettled(a).then(d=>{let c=d.filter(p=>p.status==="rejected").length;c>0&&l("failed",c);});return new Promise(d=>{let c=false,p=i(()=>{c||(c=true,clearTimeout(f),d());},"finish"),f=setTimeout(()=>{c||l("timeout",a.length),p();},lh);u.then(p,p);})}i(Vl,"startBeforeLogoutHooks");function Hl(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let a={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:a,userRef:t.userRef,sessionId:o}}i(Hl,"graceAuth");async function Bl(e,t){if(Ul.length===0)return;let r=await Promise.allSettled(Ul.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Bl,"sweepPerUserKv");function uh(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(uh,"compiledDefaultDecisions");function Ho(e=uh){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Ho,"createEntitlementStore");function Bo(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Bo,"notConfiguredError");function zl(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return As(r,t===void 0?void 0:{platform:t})}i(zl,"tryResolveClient");function jl(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(jl,"guardTelemetry");function Wl(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
|
|
12
|
+
[everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(Wl,"reportConfigFailure");function zo(e){return Object.freeze({request(){return Promise.resolve(v(Bo(e)))},stream(t,r){let n=pe({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(zo,"refusingTransport");function Gl(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Gl,"createInMemoryKv");var Kl=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function Yl(e,t){return new Wo(e,t)}i(Yl,"createEverfurRuntime");var dh=6e4,Go=class Go{constructor(t,r){this.sessionId=$n();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new Q("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?jl(n.telemetry):Hr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=Xn(n?.publishableKey),a=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)l=zo(s);else if(n.transport!==void 0)l=n.transport;else {let c=zl(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=Ns({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=zo(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&Wl(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??gs,this.upload=n.upload??ta,this.uploadTransport=n.uploadTransport??go,this.imageCache=n.imageCache??Kl,this.kv=n.storage??Gl(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?Ho():Ho(()=>Qa("sdk_config",Ft("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",jo(c),()=>this.buildChatController(c),ql),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${jo(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,f,y)=>this.acquireInternal(c,p,f,y),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!a);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Ts(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-dh,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return Dl({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let a=`${this.epoch}|${t}|${r}`,l=this.entries.get(a);if(l)return s||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(a,{controller:u,refCount:1,warm:s}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=Ea({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Sa(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=$n(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Bl(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Vl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Hl({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?v($l(t)):r(Ze(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(a=>(s.result=a,a))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?$l("prepare"):n===null?null:Bo(n),s=this.identity,[a,l,u]=await Promise.all([o?v(o):s===null?L(void 0):s.currentToken().then(()=>L(void 0),()=>v(D("authRejected",{retryable:false}))),o?v(o):this.primeEntitlements(),t===null?void 0:o?v(o):this.primeChat(t)]),d=a.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:a,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?v(t.error):L(void 0):v(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",jo(r),()=>this.buildChatController(r),ql,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?v(o.cause):L(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Go,"EverfurRuntimeImpl");var Wo=Go;function jo(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(jo,"chatScopeKey");function ql(e){e.dispose();}i(ql,"disposeChat");function $l(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i($l,"disposedError");var Xl=Symbol.for("@everfur/sdk#EverfurContext@v1"),Ql=globalThis,sn=Ql[Xl]??(Ql[Xl]=createContext(null));sn.displayName??="EverfurContext";function Y(){let e=useContext(sn);if(e===null)throw new Q("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Y,"useEverfurContext");function Zl(){return Y().handle}i(Zl,"useEverfur");var Jl=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),eu=globalThis,hr=eu[Jl]??(eu[Jl]=createContext(mt));hr.displayName??="EverfurThemeContext";function O(){return useContext(hr)}i(O,"useEverfurTheme");function an(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),s=e.seams.useReducedMotion(),a=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,d=e.seams.platformMonoFamily?.(),c=e.seams.isFontRegistered,p=e.clientTheme?hh(e.clientTheme):"",f=useMemo(()=>e.clientTheme?We(e.clientTheme):null,[p]),y=n.branding??null,m=useMemo(()=>Uo({branding:y,clientOverride:f,colorScheme:o,reducedMotion:s,textScale:a,scaleTypeSizes:u,highContrast:l,...d===void 0?{}:{platformMonoFamily:d},...c===void 0?{}:{isFontRegistered:c}}),[y,f,o,s,a,u,l,d,c]);return e.seams.useResolvedTheme?.(m),createElement(hr.Provider,{value:m},e.children)}i(an,"EverfurThemeProviderCore");function hh(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(hh,"stableKey");function iu(e){let{config:t,user:r,activePet:n,theme:o,warmUp:s,children:a,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,d=useRef(null),c=useRef(null),[p,f]=useReducer(T=>T+1,0),y=useRef(null),m=useRef(void 0),w=r?.userRef??null;m.current!==w&&(m.current!==void 0&&(y.current=null),m.current=w);let b=y.current!==null?y.current.user:r??null,R=useRef(null),I=useRef(void 0),P=n??null;I.current!==P&&(I.current!==void 0&&(R.current=null),I.current=P);let x=R.current!==null?R.current.pet:n??null;(d.current===null||d.current.key!==u||d.current.runtime.isDisposed)&&(d.current!==null&&!d.current.runtime.isDisposed&&(c.current=d.current.runtime),d.current={key:u,runtime:Yl({config:l.withDefaults?l.withDefaults(t):t,user:b,activePet:x,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let g=d.current.runtime,_=useRef(null);useEffect(()=>{let T=d.current?.runtime;T===void 0||!T.isDisposed||_.current!==T&&(_.current=T,f());}),useEffect(()=>{let T=c.current;T!==null&&(c.current=null,T.dispose());});let F=b?.userRef??null;useLayoutEffect(()=>{g.setUser(b);},[g,F]),useLayoutEffect(()=>{g.setActivePet(x);},[g,x]),useEffect(()=>()=>g.dispose(),[g]),useEffect(()=>{s==="onMount"&&g.prepare(x===null?{}:{petRef:x});},[g,s,F,x]);let M=useMemo(()=>({setUser:i(T=>{y.current={user:T},g.setUser(T),f();},"setUser"),setActivePet:i(T=>{R.current={pet:T},g.setActivePet(T),f();},"setActivePet"),open:i(T=>g.open(T),"open"),prepare:i(T=>g.prepare(T),"prepare"),registerPet:i((T,V)=>g.registerPet(T,V),"registerPet"),updatePet:i((T,V)=>g.updatePet(T,V),"updatePet"),deletePet:i(T=>g.deletePet(T),"deletePet"),eraseUserData:i(()=>g.eraseUserData(),"eraseUserData"),logout:i(()=>{y.current={user:null};let T=g.logout();return f(),T},"logout")}),[g,f]),E=useMemo(()=>({runtime:g,handle:M,userRef:F,activePet:x,scopeEpoch:g.scopeEpoch}),[g,M,F,x,p]),k=createElement(an,{clientTheme:o??null,seams:l.theme,children:a});return createElement(sn.Provider,{value:E},l.wrap?l.wrap(k):k)}i(iu,"EverfurProviderCore");var Eh=2;function Ch(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Eh)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(Ch,"readEventSourceResponseHeader");function su(){let e=vh;return (t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:i(o=>Ch(n,o),"getResponseHeader")})}}i(su,"createRnEventSourceFactory");function Ph(){let e=useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(Ph,"useRnColorScheme");function kh(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(kh,"isThenable");function xh(){let[e,t]=useState(false);return useEffect(()=>{let r=true,n=AccessibilityInfo?.isReduceMotionEnabled;if(typeof n=="function"){let s=n.call(AccessibilityInfo);s!=null&&typeof s.then=="function"&&s.then(a=>{r&&t(a===true);},()=>{});}let o=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",s=>t(s===true));return ()=>{r=false,o?.remove?.();}},[]),e}i(xh,"useRnReducedMotion");function uu(){let e=PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}i(uu,"readFontScale");function _h(e){let t=Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(Dimensions,"change",e);return ()=>r?.remove?.()}i(_h,"subscribeFontScale");function wh(){return useSyncExternalStore(_h,uu,uu)}i(wh,"useRnTextScale");function fu(){try{let e=Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(fu,"platformOS");function Ih(){return fu()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(Ih,"contrastSignal");function Ah(){let[e,t]=useState(false);return useEffect(()=>{let r=true,{query:n,event:o}=Ih(),a=AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(AccessibilityInfo);kh(d)&&Promise.resolve(d).then(c=>{r&&t(c===!0);},()=>{});}catch{}let l=AccessibilityInfo?.addEventListener,u=typeof l=="function"?l.call(AccessibilityInfo,o,d=>t(d===true)):void 0;return ()=>{r=false,u?.remove?.();}},[]),e}i(Ah,"useRnHighContrast");function Oh(){return fu()==="ios"?"Menlo":Ne}i(Oh,"rnPlatformMonoFamily");function Fh(){return globalThis.__DEV__!==false}i(Fh,"isDevelopment");var du=new Set;function Mh(e){if(!Fh()||du.has(e))return;du.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`);}catch{}}i(Mh,"warnUnregisteredFace");function Lh(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t);}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let o=n.includes(e);return o||Mh(e),o}i(Lh,"rnIsFontRegistered");var un=Object.freeze({useColorScheme:Ph,useReducedMotion:xh,useTextScale:wh,useHighContrast:Ah,scaleTypeSizes:false,platformMonoFamily:Oh,isFontRegistered:Lh});function Nh(e){return createElement(SafeAreaProvider,null,e)}i(Nh,"wrapInSafeArea");var Uh=Object.freeze({platform:"react-native",eventSourceFactory:su(),wrap:Nh,theme:un});function Vh(e){return createElement(iu,{...e,seams:Uh})}i(Vh,"EverfurProvider");function Nt(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>Za(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Nt,"useCapability");function Gh(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Gh,"tierMultiplier");function C({tier:e="content",...t}){let{type:r}=O(),n=Gh(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(C,"Text");var Ut=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Kh=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function S(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Kh[t]]}}i(S,"face");var qo=class qo 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(qo,"HostRenderBoundary");var Ko=qo;function $h({render:e}){return e()}i($h,"RenderHost");function vt({render:e,fallback:t,resetKey:r}){return createElement(Ko,{fallback:t,resetKey:r,children:createElement($h,{render:e})})}i(vt,"HostRender");var Yh=48;function Xh(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Xh,"selectView");function Xo(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Nt(t),l=useMemo(()=>Xh(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(vt,{render:o,fallback:jsx(bu,{capability:t,style:s})}):jsx(bu,{capability:t,style:s});case "disabled":return n?jsx(vt,{render:()=>n(a),fallback:jsx(vu,{decision:a,style:s}),resetKey:a}):jsx(vu,{decision:a,style:s});default:return Qe(l)}}i(Xo,"CapabilityGate");function bu({capability:e,style:t}){let r=O(),n=useMemo(()=>Eu(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(bu,"PendingSkeleton");function vu({decision:e,style:t}){let r=O(),n=useMemo(()=>Eu(r),[r]),o=e.disabled?.reason??"";return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsx(C,{style:n.offstateText,children:o}):null})}i(vu,"OffState");function Eu(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:Yh,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...S(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(Eu,"makeStyles");var h=Object.freeze({placeholder:"Ask me anything!",send:"Send",stop:"Stop",retry:"Try again",followUps:"Helpful follow-ups",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",typing:"Assistant is typing",loading:"Loading",empty:"No messages yet",transcript:"Conversation",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",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openMenu:"Open menu",openMenuUnread:"Open menu, unread chats",yourPets:"Your Pets",yourPet:"Your pet",switchActivePet:"Switch active pet, {name}",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add another 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 K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");var Qo=Object.freeze([Object.freeze({key:"inaccurate",label:h.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:h.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:h.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:h.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:h.feedbackReasonOther,feedbackType:"not_helpful"})]),Cu=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function Qh(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Qh,"sentimentToFeedbackType");function Ru(e,t){if(e==="down"&&t!==null){let r=Qo.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Qh(e)}i(Ru,"feedbackTypeFor");var tb=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function br(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=Y(),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]),[u,d]=useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=useRef(null);useEffect(()=>{let E=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=E,d({scope:l,controller:E}),()=>{p.current=null,d(k=>k?.controller===E?null:k),t.registry.releaseChat(E);}},[t,r,s,a,o,l]);let f=useCallback(E=>c?c.subscribe(E):rb,[c]),y=useCallback(()=>c?c.getSnapshot():tb,[c]),m=useSyncExternalStore(f,y,y),w=useCallback((E,k)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Jo(c,c.send(E,k?.imageS3Keys===void 0?{}:{imageS3Keys:k.imageS3Keys}),()=>p.current===c):Promise.resolve(ei()),[c]),b=useCallback(E=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?Jo(c,c.askEverfur(E),()=>p.current===c):Promise.resolve(ei()),[c]),R=useCallback(()=>c&&p.current===c?Jo(c,c.retryLast(),()=>p.current===c):Promise.resolve(ei()),[c]),I=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),P=useCallback(()=>{c&&p.current===c&&c.newConversation();},[c]),[x,g]=useState({controller:null,byMessage:{}}),_=x.controller===c?x.byMessage:nb,F=useCallback(async(E,k,T,V)=>{if(!c||p.current!==c)return v(D("accessDenied"));let j=String(E),G=x.controller===c?x.byMessage[j]:void 0;if(G===k&&T==null)return g(de=>{let ke={...de.controller===c?de.byMessage:{}};return delete ke[j],{controller:c,byMessage:ke}}),L(Object.freeze({feedbackId:""}));g(de=>({controller:c,byMessage:{...de.controller===c?de.byMessage:{},[j]:k}}));let ne=await c.submitFeedback(E,Ru(k,T??null),V??null);return p.current!==c?v(D("accessDenied")):(ne.ok||g(de=>{let ke={...de.controller===c?de.byMessage:{}};return G===void 0?delete ke[j]:ke[j]=G,{controller:c,byMessage:ke}}),ne)},[c,x]),M=useMemo(()=>{let E=i(async k=>{if(!c||p.current!==c)return v(D("accessDenied"));let T=await k(c);return p.current===c?T:v(D("accessDenied"))},"run");return {listConversations:i(k=>E(T=>T.listConversations({...s?{petRef:s}:{},...k})),"listConversations"),getMessages:i((k,T)=>E(V=>V.getMessages(k,T)),"getMessages"),resumeConversation:i(k=>E(T=>T.resumeConversation(k)),"resumeConversation"),loadOlderMessages:i(()=>E(k=>k.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>E(k=>k.markRead()),"markRead"),refreshActiveThread:i(()=>E(k=>k.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((k,T)=>E(V=>V.answerCheckin(k,T)),"answerCheckin"),openCheckin:i(k=>E(T=>T.openCheckin(k)),"openCheckin")}},[c,s]);return useMemo(()=>({status:m.status,messages:m.messages,conversationId:m.conversationId,petRef:s,error:m.error,isStreaming:m.isStreaming,isBootstrapping:m.isBootstrapping,historyCursor:m.historyCursor??null,isLoadingHistory:m.isLoadingHistory??false,stopped:m.stopped??false,reconnecting:m.reconnecting??false,...M,suggestedPrompts:m.suggestedPrompts,unreadCount:m.unreadCount,hasUnreadThreads:m.hasUnreadThreads??false,newConversation:P,sentimentByMessage:_,feedback:F,send:w,askEverfur:b,retryLast:R,stop:I}),[m,s,w,b,R,I,M,P,_,F])}i(br,"useEverfurChat");var rb=i(()=>{},"NOOP_UNSUBSCRIBE"),nb=Object.freeze({});async function Jo(e,t,r){for await(let o of t);if(!r())return v(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?v(n.error):L(ob(n.messages))}i(Jo,"driveToResult");function ob(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(ob,"lastAssistantResponseId");function ei(){return v(D("internalError",{retryable:true}))}i(ei,"notReadyError");function ku(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:bo(qr),filename:e.filename,size:bo(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:$r});case "unsupported_type":return K(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return K(h.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return h.attachmentCancelled;case "rate_limited":return h.attachmentRateLimited;case "quota_exceeded":return h.attachmentQuota;case "idempotency_conflict":return h.attachmentConflict;case "unknown":return h.attachmentUnknown}}i(ku,"attachmentErrorMessage");function xu(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(xu,"attachControlLabel");var lb=Object.freeze({attachments:Object.freeze([])});function dn(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=e.maxPerMessage??$r,s=useCallback(()=>{let{services:g}=t.registry;return ka({funnel:xe({auth:g.authFor(r),...g.errorPolicy?{errorPolicy:g.errorPolicy}:{}}),transport:e.transport??g.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.transport]),a=useMemo(()=>e.queue??s(),[e.queue,s]),l=useRef(new WeakSet),[u,d]=useState(null),c=u!==null&&u.of===a?u.queue:a;useEffect(()=>{if(c!==e.queue){if(l.current.has(c)){d({of:a,queue:s()});return}return ()=>{c.dispose(),l.current.add(c);}}},[c,a,s,e.queue]);let p=useSyncExternalStore(c.subscribe,c.getSnapshot,()=>lb),[f,y]=useState(null),m=useCallback(g=>{let F=(Array.isArray(g)?g:[g]).map(E=>c.add(E)),M=F.find(E=>!E.ok);return M!==void 0&&!M.ok&&y(M.error),F},[c,y]),w=useCallback(g=>c.retry(g),[c]),b=useCallback(g=>c.remove(g),[c]),R=useCallback(()=>c.clear(),[c]),I=useCallback(()=>y(null),[y]),P=p.attachments.some(g=>g.status==="uploading"),x=p.attachments.some(g=>g.status==="failed");return useMemo(()=>({available:c.available,attachments:p.attachments,maxPerMessage:o,uploading:P,failed:x,blocked:P||x,s3Keys:p.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[]),rejected:f,add:m,retry:w,remove:b,clear:R,dismissRejected:I}),[c.available,p,o,P,x,f,m,w,b,R,I])}i(dn,"useChatAttachments");var cb="pet_not_registered";function Iu(e){return e!=null&&e.reasonCode===cb}i(Iu,"isPetNotRegistered");var pb=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function Au(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=Y(),a=useCallback(()=>Ze(n.registry.services.authFor(o)),[n,o,s]),l=useMemo(()=>t===void 0?null:ri(t),[t]),[u,d]=useState({key:null,status:"idle",error:null,registered:null}),c=useRef(0),p=useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,y=useCallback(()=>{if(e===null||t===void 0||f===null)return;let w=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(b=>{w===c.current&&(b.ok?(d({key:f,status:"registered",error:null,registered:b.value}),p.current?.()):d({key:f,status:"failed",error:b.error,registered:null}));});},[a,e,f]);useEffect(()=>{if(f===null){c.current+=1;return}return y(),()=>{c.current+=1;}},[f,y]);let m=useCallback(()=>{u.status==="failed"&&y();},[u.status,y]);return useMemo(()=>f===null?pb:u.key!==f?{status:"registering",error:null,registered:null,retry:m}:{status:u.status,error:u.error,registered:u.registered,retry:m},[f,u,m])}i(Au,"useChatPetRegistration");function ri(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ri).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)}:${ri(n)}`).join(",")}}`}i(ri,"stableKey");var ni=Object.freeze({});function Fu(e){let[t,r]=useState(ni),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===ni?u:ni);return}let a=n.current;if(a===null)return;let l=e.find(u=>u.role==="user"&&!a.known.has(u.id));l!==void 0&&(n.current=null,r(u=>({...u,[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(Fu,"useSentImages");var bb=500;function oi(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,bb):null}i(oi,"sanitizeSeedPrompt");function Lu(e,t,r){let n=oi(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(Lu,"useInitialAsk");function vb(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(vb,"isCoalesced");function Du(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"}:vb(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Du,"decideChatRefresh");function ii(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ii,"reportHostFailure");function Eb(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Eb,"isThenable");function q(e,...t){if(typeof e=="function")try{let r=e(...t);return Eb(r)&&Promise.resolve(r).then(void 0,ii),r}catch(r){ii(r);return}}i(q,"callHost");var Nu=new WeakMap;function Uu(e){if(typeof e!="function")return;let t=Nu.get(e);if(t!==void 0)return t;let r=i((...n)=>{q(e,...n);},"guarded");return Nu.set(e,r),r}i(Uu,"guardHost");function Ht(e,...t){let r;try{r=e(...t);}catch(n){return ii(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Ht,"callHostAsync");function Hu(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),s=e?.isOffline===void 0?false:q(()=>e.isOffline?.()===!0)===true,a=useRef(()=>{});a.current=l=>{let{conversationId:u,isTurnInFlight:d,refresh:c}=r.current,p=Du(l,{activeConversationId:u,isTurnInFlight:d,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=[],u=i((d,c)=>{if(d===void 0)return;let p=q(()=>d(()=>{a.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let d of l)q(d);}},[e]);}i(Hu,"useChatLifecycle");function Rb(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(Rb,"targetKey");function zu(e,t){let r=Rb(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(zu,"useCheckinTarget");function Gu(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 u=l.send===e&&(l.conversationId===null||l.conversationId===t),d=u?l.text:"",c=u?l.seeded:null,p=r!=null&&r!==c&&d.length===0;return {send:e,conversationId:t,text:p?r:d,seeded:p?r:c}});},[e,t,r]);let a=useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [s?n.text:"",a]}i(Gu,"useChatDraft");function Ku(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 u=`${t??""}`;if(s.current===u)return;s.current=u;let d=true;return (async()=>{let c=await Ht(()=>e.read(t));if(!d)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{d=false;}},[e,t]),useEffect(()=>{e===void 0||a!==`${t??""}`||q(()=>e.write(t,r));},[e,t,r,a]);}i(Ku,"usePersistedDraft");var Z=Object.freeze({heading:"Chat History",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No matching chats",noMatchBody:"Try a different title or start a new conversation.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newConversation:"New conversation",newChat:"New chat",search:"Search",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 pn(e){let t=e?.replace(/\s+/g," ").trim();return t||Z.untitled}i(pn,"conversationTitle");function $u(e){return `${e.unreadCount!==null&&e.unreadCount>0?Z.unreadPrefix:""}${Z.openConversation} ${pn(e.title)}`}i($u,"openConversationLabel");function qu(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(qu,"normalizeForSearch");function _b(e,t){let r=qu(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=qu(pn(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(_b,"filterConversations");function li(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(li,"fresh");function Yu(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,u]=useState(()=>li(s)),d=l.scope===s?l:li(s);useEffect(()=>(a.current+=1,r(false),o(""),u(li(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async P=>{let x=++a.current,g=P!==void 0;u(F=>({...F,scope:s,loading:!g,loadingMore:g,error:null}));let _=await e.listConversations(P?{cursor:P}:void 0);if(x===a.current){if(!_.ok){u(F=>({...F,loading:false,loadingMore:false,error:_.error.displayMessage}));return}u(F=>{let M=P&&F.scope===s?F.rows:[],E=new Set(M.map(k=>k.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...M,..._.value.conversations.filter(k=>!E.has(k.id))],cursor:_.value.nextCursor===P?null:_.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),y=i(async P=>{let x=++a.current;u(_=>({..._,loading:true,error:null}));let g=await e.resumeConversation(P);x===a.current&&(u(_=>({..._,loading:false,error:g.ok?null:g.error.displayMessage})),g.ok&&r(false));},"resume"),m=i(async()=>{let P=a.current,x=await e.loadOlderMessages();P===a.current&&!x.ok&&u(g=>({...g,error:x.error.displayMessage}));},"earlier"),w=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),b=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),R=useMemo(()=>_b(d.rows,n),[d.rows,n]),I=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:y,earlier:m,newConversation:w,loadMore:b,query:n,setQuery:o,searching:I,filtered:R,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(Yu,"useHistoryPanel");var fn="#111111",mn="#FFFFFF",Ab=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:fn,pillColor:mn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:fn,pillColor:mn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:fn,pillColor:mn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:fn,pillColor:mn,showsVetAction:false})});function Ob(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(Ob,"urgencySignature");function Fb(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(Fb,"generalUrgencyReason");function Zu(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:n.urgencyReason??null}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Fb(t)}:null}return null}i(Zu,"latestUrgencySource");function Ju(e){let t=e===null?null:Ob(e),[r,n]=useState(null),[o,s]=useState(false);useEffect(()=>s(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:Ab[e.level],d=e!==null&&!l&&e.level!=="general",c=useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=useCallback(()=>s(true),[]);return useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:d,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(h.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Ju,"useUrgencySurface");function ed(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(ed,"selectView");function Mb(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Mb,"needsNewConversation");function td(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Mb(t);return {tone:"error",title:r?h.turnUnreachableTitle:h.turnFailedTitle,body:t.displayMessage,actionLabel:r?h.turnStartNewChat:h.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:h.turnStoppedTitle,body:h.turnStoppedBody,actionLabel:h.turnRetry,action:"retry"}:null}i(td,"turnNotice");function rd(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(rd,"awaitingAssistant");function nd(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(nd,"buildChatOpts");var vr=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function sd(e){let t=O(),r=useMemo(()=>Nb(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${vr.title}. ${vr.body}`,children:[jsx(C,{style:r.title,children:vr.title}),jsx(C,{style:r.body,children:vr.body})]})}i(sd,"ClinicalDisclaimer");function Nb(e){let{color:t,space:r,type:n}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{...S(e,"bold"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{...S(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.muted}})}i(Nb,"makeStyles");var se={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function te(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(te,"box");function fe(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(fe,"stroke");function ad({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxs(View,{style:[te(e),{gap:e*.22}],...se,children:[jsx(View,{style:o}),jsx(View,{style:o}),jsx(View,{style:o})]})}i(ad,"MenuGlyph");function ld({size:e,color:t,strokeWidth:r,rotate:n}){let o=fe(e,r),s=e*.78;return jsxs(View,{style:[te(e),{transform:[{rotate:n}]}],...se,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(ld,"Cross");function ud(e){return jsx(ld,{...e,rotate:"0deg"})}i(ud,"PlusGlyph");function Et(e){return jsx(ld,{...e,rotate:"45deg"})}i(Et,"CloseGlyph");function rt({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsx(View,{style:te(e),...se,children:jsx(View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(rt,"CheckGlyph");var Hb={down:{rotate:"45deg",marginTop:-0.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-0.4}};function yn({size:e,color:t,strokeWidth:r,direction:n}){let o=fe(e,r),s=e*.46,a=Hb[n];return jsx(View,{style:te(e),...se,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(yn,"ChevronGlyph");function dd({size:e,color:t,strokeWidth:r}){let n=fe(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}],...se,children:[jsx(View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsx(View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(dd,"BookGlyph");function cd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.5;return jsxs(View,{style:te(e),...se,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(cd,"ArrowUpRightGlyph");function pd({size:e,color:t,strokeWidth:r}){let n=fe(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),...se,children:[jsx(View,{style:[s,{top:0,left:0}]}),jsx(View,{style:[s,{bottom:0,right:0}]})]})}i(pd,"CopyGlyph");function gn({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=fe(e,r),a=n?t:"transparent";return jsxs(View,{style:[te(e),{transform:[{rotate:o}]}],...se,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(gn,"ThumbGlyph");function fd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:[te(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...se,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(fd,"InfoGlyph");function md({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.34;return jsxs(View,{style:te(e),...se,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(md,"UploadGlyph");function yd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:[te(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...se,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(yd,"PhotoGlyph");function gd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:te(e),...se,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(gd,"CameraGlyph");function hd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.66;return jsxs(View,{style:te(e),...se,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(hd,"SearchGlyph");function bd({size:e,color:t,strokeWidth:r}){let n=fe(e,r);return jsxs(View,{style:te(e),...se,children:[jsx(View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),jsx(View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}i(bd,"EditGlyph");function vd({size:e,color:t,strokeWidth:r}){let n=fe(e,r),o=e*.62;return jsxs(View,{style:te(e),...se,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(vd,"MapPinGlyph");function Ed({size:e,color:t,testID:r}){let n=e*.36;return jsx(View,{style:te(e),testID:r,...se,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(Ed,"SendGlyph");function Cd({size:e,color:t,testID:r}){return jsx(View,{style:te(e),testID:r,...se,children:jsx(View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(Cd,"StopGlyph");function hn({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(hn,"Ring");var Er=Object.freeze({standard:ft.standard,emphasized:ft.emphasized,exit:ft.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var Rd=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,reduced:false}),Bb=Object.freeze({...Rd,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,reduced:true});function Sd(e){return e.motion.reducedMotion?Bb:Rd}i(Sd,"chatMotion");function bn(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(bn,"followUpDelayMs");function Td(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(Td,"nextRevealLength");function X(){let e=O();return Sd(e)}i(X,"useChatMotion");var qb=8;function kd(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(kd,"bezierComponent");function $b(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i($b,"bezierSlope");function vn(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<qb;l+=1){let u=$b(a,t,n);if(u===0)break;a-=(kd(a,t,n)-s)/u;}return kd(Math.min(1,Math.max(0,a)),r,o)}}i(vn,"bezierEasing");var ui=vn(Er.standard),Yb=vn(Er.outQuad);function fi(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(fi,"useAnimatedValue");function Ct(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=fi(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:Yb,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(Ct,"useFadeIn");function mi({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=fi(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let d=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:ui,useNativeDriver:true});return d.start(),()=>d.stop()}if(!s)return;if(r<=0){a(false);return}let u=Animated.timing(l,{toValue:0,duration:r,easing:ui,useNativeDriver:true});return u.start(({finished:d})=>{d&&a(false);}),()=>u.stop()},[e,s,t,r,l]),!s&&!e?null:jsx(Animated.View,{style:[n,{opacity:l}],children:o})}i(mi,"FadePresence");var Xb=12;function B({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=X(),u=fi(1),d=useCallback(c=>{l.pressMs<=0||l.pressScale===1||Animated.timing(u,{toValue:c,duration:l.pressMs,easing:ui,useNativeDriver:true}).start();},[u,l.pressMs,l.pressScale]);return jsx(Pressable,{...a,hitSlop:s??Xb,style:t,onPressIn:c=>{d(l.pressScale),n?.(c);},onPressOut:c=>{d(1),o?.(c);},children:jsx(Animated.View,{style:[e,{transform:[{scale:u}]}],children:r})})}i(B,"PressScale");function wd(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(u=>Td(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(wd,"useRevealedText");var xd=false;function Qb(e){e.layoutMs<=0||(xd||(xd=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(Qb,"animateLayout");function Cr(e,t){let r=useRef(e);r.current!==e&&(r.current=e,Qb(t));}i(Cr,"useAnimateLayoutOn");var yi=36,ov=22,iv=12,sv=12,av=16,lv="#000",uv="rgba(0,0,0,0.45)";function Id({uri:e,label:t,onClose:r}){let n=O(),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:h.closePreview,style:En.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:En.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[En.closeWrap,{top:o.top+sv}],children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:iv,style:En.closeButton,onPress:r,children:jsx(Et,{size:ov,color:n.color.surface,strokeWidth:2})})})]})}i(Id,"AttachmentImageLightbox");var En=StyleSheet.create({backdrop:{flex:1,backgroundColor:lv,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:av},closeButton:{width:yi,height:yi,borderRadius:yi/2,backgroundColor:uv,alignItems:"center",justifyContent:"center"}});var Cn=12,mv=80,gi=44,Ad=22,yv=.14,gv=18,hv=8,Od=Object.freeze({photo:h.attachmentPhoto,camera:h.attachmentCamera});function Fd({sources:e,full:t,onPick:r,onClose:n}){let o=O(),s=useMemo(()=>bv(o),[o]);return jsxs(View,{style:s.anchor,pointerEvents:"box-none",children:[jsx(Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:h.closeAttachmentPicker,onPress:n}),jsxs(View,{style:s.bubble,children:[jsx(View,{style:s.tilesRow,children:e.map(a=>jsxs(B,{accessibilityRole:"button",accessibilityLabel:Od[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(yd,{size:Ad,color:o.color.brandInk,strokeWidth:1.5}):jsx(gd,{size:Ad,color:o.color.brandInk,strokeWidth:1.5})}),jsx(C,{tier:"control",style:s.tileLabel,children:Od[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(Fd,"AttachmentPickerPopover");function bv(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:yv,shadowRadius:gv,shadowOffset:{width:0,height:hv},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:mv,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:gi,height:gi,borderRadius:gi/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...S(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-Cn/2,width:Cn,height:Cn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Cn+4,height:2,backgroundColor:t.surfaceCream}})}i(bv,"makeStyles");var Se=Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var Ld=56,Dd=12,Cv=14,Rv=10,Sv=.45,Tv="rgba(7,193,104,0.55)",Pv="rgba(185,28,28,0.55)",kv=200,xv=300,Wd=20,bi=22,_v=12,wv="rgba(0,0,0,0.78)",Nd=220,Ud=100,Vd="rgba(255,255,255,0.15)";function Gd({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=O(),l=useMemo(()=>qd(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(u=>jsx(Iv,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:h.attachmentsFailedBlocked}):null,t!==null?jsx(C,{style:l.rejected,accessibilityRole:"alert",children:ku(t)}):null]})}i(Gd,"AttachmentStrip");function Iv({row:e,styles:t,onRetry:r,onRemove:n,onPreview:o}){let s=O(),a=e.status==="uploading",l=e.status==="failed",u=e.status==="uploaded",d=useRef(e.status),[c,p]=useState(false);return useEffect(()=>{let f=d.current;d.current=e.status,e.status==="uploaded"&&f==="uploading"&&p(true);},[e.status]),jsxs(View,{style:t.card,children:[jsx(Pressable,{accessibilityRole:u?"button":"image",accessibilityLabel:u?K(h.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:a,disabled:!u},disabled:!u,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(Av,{styles:t,onDone:()=>p(false)}):null]})}),l?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:K(h.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsx(View,{style:t.failedInner,children:jsx(Et,{size:Wd,color:s.color.surface,strokeWidth:2})})}):null,jsx(B,{accessibilityRole:"button",accessibilityLabel:K(h.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsx(Et,{size:_v,color:s.color.surface,strokeWidth:1.5})})]})}i(Iv,"PreviewCard");function Av({styles:e,onDone:t}){let r=O(),n=X(),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:kv,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:xv,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(rt,{size:Wd,color:r.color.surface,strokeWidth:2})})}i(Av,"SuccessFlash");function Kd({images:e,onPreview:t}){let r=O(),n=useMemo(()=>qd(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:K(h.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(Kd,"SentImages");function qd(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:Ld,height:Ld,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Dd,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Se,alignItems:"center",justifyContent:"center",backgroundColor:nl(e.color.brandInk,Sv)??e.color.brandSofter},successOverlay:{...Se,alignItems:"center",justifyContent:"center",backgroundColor:Tv},failedOverlay:{...Se,borderRadius:Dd,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:Pv},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:bi,height:bi,borderRadius:bi/2,backgroundColor:wv,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...S(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:Nd,height:Nd,borderRadius:Cv,backgroundColor:Vd},gridImage:{width:Ud,height:Ud,borderRadius:Rv,backgroundColor:Vd}})}i(qd,"makeStyles");var Ov="chat attachment upload: the file handle has no uri",Fv="chat attachment upload failed";function Mv(e){return {uri:e.uri,name:ho(e.name),type:e.mimeType}}i(Mv,"filePartOf");function $d(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Ov));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Fv)),"failed");return o?.aborted===true?a():Vr({url:t.upload_url,fields:t.upload_fields,file:Mv(r),signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i($d,"createRnChatAttachmentTransport");function Rn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=Y(),o=useMemo(()=>Ze(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},u=useRef(0),d=useCallback(async()=>{let p=++u.current;a(y=>({...y,repository:o,loading:true,error:null,pets:y.repository===o?y.pets:[]}));let f=await o.list();p===u.current&&a(f.ok?{repository:o,pets:f.value,loading:false,error:null}:y=>({repository:o,pets:y.repository===o?y.pets:[],loading:false,error:f.error}));},[o]);useEffect(()=>(d(),()=>{u.current+=1;}),[d]);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:d}),[l.pets,l.loading,l.error,c,d])}i(Rn,"useEverfurPets");function Yd(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(Yd,"headerPetOf");function me(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(me,"slotBox");function Ri(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(Ri,"ownGroundSlot");function Ie(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Ie,"slotText");var Xd=Object.freeze({visitButton:"Talk to a vet"});var Qd=Symbol.for("@everfur/sdk/televet");function Ke(){let e=globalThis,t=e[Qd];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[Qd]=r,r}i(Ke,"televetGlobal");function Sn(e){let t=Ke();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Sn,"publish");function Zd(e){let t=Ke().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(Zd,"callTelevetPresenter");function Jd(e){let t=Ke();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(Jd,"subscribeTelevetExperience");function Si(){return Ke().snapshot}i(Si,"televetExperienceSnapshot");function Vv(){return Ke().hosts.length>0}i(Vv,"hasTelevetHost");function ec(e){if(!Vv())return false;let t=Object.freeze({...e});return Sn({request:t,serial:Ke().snapshot.serial+1}),true}i(ec,"presentTelevetExperience");function Ti(){Ke().snapshot.request!==null&&Sn({request:null});}i(Ti,"dismissTelevetExperience");function tc(){let e=Ke(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Sn({activeHost:e.hosts[0]??null}),t}i(tc,"claimTelevetHost");function rc(e){let t=Ke();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Sn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(rc,"releaseTelevetHost");var nc=false;function Tn(e,t){return t!==void 0?(q(t,e),"onStartInApp"):Zd(e)==="presented"?"presenter":ec(e)?"experience":(nc||(nc=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(Tn,"openVetVisitInApp");function sc(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(sc,"memoizeTelevetLoader");function ac(e){let[t,r]=useState(null);useEffect(()=>{let d=tc();return r(d),()=>{rc(d);}},[]);let n=useSyncExternalStore(Jd,Si,Si),s=t!==null&&n.activeHost===t?n.request:null,[a,l]=useState(null),u=s!==null&&a===null;return useEffect(()=>{if(!u)return;let d=true;return e().then(c=>{d&&l(()=>c);},c=>{d&&(console.warn("[everfur] The in-app vet visit could not load its screens.",c),Ti());}),()=>{d=false;}},[u,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:Ti}}i(ac,"useTelevetExperienceHost");var Bv=sc(()=>import('@everfur/sdk/televet/booking'));function Sr(){let e=ac(Bv);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(Sr,"EverfurTelevetHost");var Pi=Object.freeze(["visit","join","summary","messages"]);function ki(e){return typeof e=="string"&&Pi.includes(e)}i(ki,"isVetVisitIntent");var jv="/widget/v1/televet/handoffs",Wv="/widget/v1/televet/availability",Gv="/widget/v1/televet/chat-entry",Kv=/^[a-z0-9][a-z0-9_-]{0,39}$/,qv=/^[A-Za-z0-9_-]{22}$/;var lc=32,uc=128,dc=64;function _i(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(_i,"vetVisitErrorReasonOf");function cc(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i(cc,"invalid");function xi(e){return v(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(xi,"unusable");function $v(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Kv.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 u=typeof s=="string"?s.trim():"";if(u.length<1||[...u].length>dc)return {ok:false,message:`visitRef must be 1..${dc} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!ki(a))return {ok:false,message:`intent must be one of ${Pi.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i($v,"handoffBody");function Yv(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!ki(r)?null:Object.freeze({visitRef:t,intent:r})}i(Yv,"parseVisitEcho");function fc(e){let t=e.funnel??xe({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(pc(r,"televet.visit.handoff_failed",{reason:_i(o)}),v(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let b=typeof o=="string"?[...o].length:0;if(b<1||b>uc)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${uc} characters`}));a=o;}let l=$v(a,s);if(!l.ok){let b=cc(l.message);return b.ok?b:n(b.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:jv,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=Xv(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!qv.test(f))){let b=xi("the handoff response carried no usable return flow id");return b.ok?b:n(b.error)}let y=u.visit_ref!==void 0,m=y?Yv(d.value?.visit):null;if(y&&m===null){let b=xi("the handoff response did not confirm the visit it opens");return b.ok?b:n(b.error)}let w=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...m!==null?{visit:m}:{}});return w===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(pc(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),L(w))},async checkAvailability(o){if(typeof o!="string"||o.length>lc)return cc(`state must be at most ${lc} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:Wv,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.available;return typeof a!="boolean"?xi("the availability response carried no usable answer"):L(Object.freeze({available:a}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:Gv},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(fc,"createVetVisitController");function Xv(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||!eE(t)?null:Object.freeze({url:t,expiresAt:r})}i(Xv,"parseHandoff");var Qv=new Set(["localhost","127.0.0.1","[::1]"]),Zv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Jv=/[\s\u0000-\u001f\u007f]/;function eE(e){if(Jv.test(e))return false;let t=Zv.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"&&Qv.has(o);if(!s&&!a)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(eE,"isOpenableVisitUrl");function pc(e,t,r){if(e)try{e.track(t,r);}catch{}}i(pc,"safeTrack");var wi=Object.freeze({status:"idle",error:null,errorReason:null});function rE(e,t,r){let{usState:n,chat:o,scope:s}=r,a=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,d]=useState(null);if(useEffect(()=>{if(!a)return;let p=true,f=e.current;return d(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let m=await f.checkAvailability(n);return m.ok&&m.value.available}catch{return false}},"ask")().then(m=>{p&&d({key:l,open:m});}),()=>{p=false;}},[a,l,n,o,s,e]),!a)return null;let c=u!==null&&u.key===l;return {open:c&&u.open,pending:!c}}i(rE,"usePreflight");var nE=Object.freeze({status:"opening",error:null,errorReason:null});function gc(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=Y(),s=Nt("televet"),a=s.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",d=t.petRef??null,c=t.prefer==="redirect",p=useMemo(()=>{if(t.controller)return t.controller;let{services:T}=r.registry;return fc({auth:T.authFor(n),telemetry:T.telemetry,...T.errorPolicy?{errorPolicy:T.errorPolicy}:{}})},[r,n,o,t.controller]),f=useRef(p);f.current=p;let y=useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),m=rE(f,a,{usState:l,chat:u,scope:y}),w=a&&(m===null||m.open)&&(!u||d!==null),b=t.returnTo??null,[R,I]=useState(wi),P=useRef(null),x=useRef({runtime:r,userRef:n,scopeEpoch:o});x.current={runtime:r,userRef:n,scopeEpoch:o};let g=useRef(p);g.current=p;let _=useRef(w);_.current=w;let F=useCallback((T,V)=>{if(P.current)return P.current;let j=i((ce,it)=>(I({status:ce==="cancelled"?"idle":"error",error:it,errorReason:ce==="cancelled"?null:ce}),Object.freeze({opened:false,reason:ce,error:it})),"fail");if(!_.current)return Promise.resolve(j("unavailable",null));let G=e.prepare();if(!G.ok)return Promise.resolve(j(G.reason,null));let ne=x.current,de=g.current;I(nE);let Yt=(async()=>{let ce,it={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...V!==null?{visitRef:V.visitRef}:{},...V!==null&&V.intent!==null&&V.intent!==void 0?{intent:V.intent}:{}},Ar=Object.keys(it).length===0?void 0:it,Xt=T===void 0?d:T;try{ce=await(Ar===void 0?de.createHandoff(Xt):de.createHandoff(Xt,Ar));}catch{return e.abandon(G.value),j("unknown",null)}let It=x.current;if(It.runtime!==ne.runtime||It.userRef!==ne.userRef||It.scopeEpoch!==ne.scopeEpoch)return e.abandon(G.value),j("cancelled",null);if(!ce.ok)return e.abandon(G.value),j(_i(ce.error),ce.error);let At=await e.finish(G.value,ce.value);return At!==null?j(At,null):(I(wi),Object.freeze(ce.value.flowId===void 0?{opened:true}:{opened:true,flowId:ce.value.flowId}))})().finally(()=>{P.current===Yt&&(P.current=null);});return P.current=Yt,Yt},[e,d,b,u]),M=useCallback((T,V)=>{if(!_.current)return I({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let j=T===void 0?d:T,G={...j!==null?{petRef:j}:{},...l!==null?{usState:l}:{},...V!==null?{visitRef:V.visitRef,intent:V.intent}:{}};return Tn(G)===null?(I({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(I(wi),Promise.resolve(Object.freeze({opened:true})))},[d,l]),E=useCallback(T=>c?F(T,null):M(T,null),[c,F,M]),k=useCallback((T,V)=>c?F(void 0,{visitRef:T,intent:V??null}):M(void 0,{visitRef:T,intent:V??null}),[c,F,M]);return {available:w,isPending:s.isPending||(m?.pending??false),status:R.status,error:R.error,errorReason:R.errorReason,open:E,openVisit:k}}i(gc,"useVetVisitWith");var sE=i(e=>Linking.openURL(e),"defaultOpenUrl");function kn(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??sE;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 gc(n,r)}i(kn,"useVetVisit");var hc=44,cE=.6;function jt(e){let{petRef:t,label:r,openUrl:n,onOpened:o,onError:s,style:a,labelStyle:l,controller:u,returnTo:d,usState:c,entry:p,visitRef:f,intent:y,onStartInApp:m,prefer:w}=e,b=w==="redirect",R=kn({...d!==void 0?{returnTo:d}:{},...c!==void 0?{usState:c}:{},...p!==void 0?{entry:p}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:b?"redirect":"in-app"}),I=O(),P=useMemo(()=>pE(I),[I]),x=useRef(false);if(!R.available)return jsxs(Fragment,{children:[null,jsx(Sr,{})]});let g=R.status==="opening",_=r??Xd.visitButton;return jsxs(Fragment,{children:[jsx(Pressable,{onPress:i(()=>{if(!(g||x.current)){if(!b){let M={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...f!=null?{visitRef:f,intent:y??null}:{}};Tn(M,m)===null&&q(s,"unavailable",null);return}x.current=true,(f==null?R.open():R.openVisit(f,y??null)).then(M=>{M.opened?q(o,M.flowId??null):M.reason!=="cancelled"&&q(s,M.reason,M.error);}).finally(()=>{x.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:_,accessibilityState:{busy:g,disabled:g},style:[P.button,g?P.busy:null,a],children:jsx(C,{style:[P.label,l],children:_})}),jsx(Sr,{})]})}i(jt,"VetVisitButton");function pE(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:hc,minWidth:hc,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...me(s.vetVisitButton)},busy:{opacity:cE},label:{...S(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...Ie(s.vetVisitButton)}})}i(pE,"makeStyles");function Ii(e){return dr(e)==="cat"?"cat":"dog"}i(Ii,"speciesOf");function Ai(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(Ai,"petAgeYears");function Cc(e){let t=Ai(e.ageYears),r=Ii(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(Cc,"formatPetMeta");var Ec=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 fE(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Ec[t%Ec.length]}i(fE,"pickInitialsPalette");function Oi(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(Oi,"getInitial");function Rc(e){return {...fE(e.petRef),initial:Oi(e.name)}}i(Rc,"petInitials");function hE(e){return Math.max(12,Math.round(e*.42))}i(hE,"letterSize");function Pr({pet:e,size:t,ringStroke:r}){let n=O(),o=useMemo(()=>bE(n),[n]),s=t-r*2,a=e===null?null:Rc(e),l=hE(s);return jsx(hn,{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(C,{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?Oi(null):a.initial})})})}i(Pr,"PetDisc");function bE(e){return StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...S(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(bE,"makeStyles");var Mi=48,Pc=2,TE=320,PE="80%",kE="rgba(17,17,17,0.45)",xE=18,Sc=22,_E=12,Tc=.4,wE=44;function Li(e){return e?.name?.trim()||h.yourPet}i(Li,"petDisplayName");function kc({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=O(),l=useMemo(()=>IE(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:Se,onPress:s,accessibilityRole:"button",accessibilityLabel:h.close,children:jsx(View,{style:l.backdrop})}),jsxs(View,{style:l.panel,accessibilityViewIsModal:true,children:[jsx(C,{tier:"heading",style:l.title,accessibilityRole:"header",children:h.yourPets}),jsx(ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(u=>{let d=u.petRef===r,c=Li(u),p=Cc(u);return jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(d?h.petCurrentlyActive:h.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsx(Pr,{pet:u,size:Mi,ringStroke:Pc}),jsxs(View,{style:l.copy,children:[jsx(C,{style:l.name,numberOfLines:1,children:c}),jsx(C,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${h.activePrefix}${p}`:p})]}),d?jsx(rt,{size:xE,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.addAnotherPet,style:l.addRow,onPress:o,children:[jsx(View,{style:l.addDisc,children:jsx(C,{tier:"control",style:l.addPlus,children:"+"})}),jsx(C,{style:l.addLabel,children:h.addAnotherPet})]}):null,jsx(B,{accessibilityRole:"button",accessibilityLabel:h.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsx(C,{tier:"control",style:l.closeText,children:h.close})})]})]})}):null}i(kc,"PetSwitcherSheet");function IE(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:kE},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Sc,borderTopRightRadius:Sc,gap:14,maxHeight:PE},title:{...S(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:TE,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:wE,paddingHorizontal:8},addDisc:{width:Mi,height:Mi,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Pc,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...S(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...S(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:{...S(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...S(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Tc},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:_E,backgroundColor:t.brandSoft},closeText:{...S(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Tc}})}i(IE,"makeStyles");var FE=44,_n=36,ME=22,Di=9,LE=1.5,_c=6,St=35,wn=1.75,Ni=12.4,DE=.5,NE=8,UE=28,VE=160;function Vi(e,t){return Yd(e,t)}i(Vi,"headerPet");function Ic({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=O(),u=useMemo(()=>BE(l),[l]),[d,c]=useState(false),p=Vi(e.pets,t),f=e.pets.length>=2,y=t??p?.petRef??null,m=Li(p),w=i(R=>{c(false),e.setActivePet(R),q(o,R);},"select"),b=s===void 0?null:()=>{c(false),q(s);};return jsxs(View,{style:u.row,children:[jsxs(B,{accessibilityRole:"button",accessibilityLabel:r?h.openMenuUnread:h.openMenu,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsx(ad,{size:ME,color:l.color.text.primary,strokeWidth:2}),r?jsx(View,{style:u.unreadDot,pointerEvents:"none"}):null]}),jsx(View,{style:u.center,pointerEvents:"box-none",children:jsx(HE,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),y===null?null:jsx(jt,{entry:"chat",petRef:y,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:u.vetEntry,labelStyle:u.vetEntryLabel}),jsx(View,{style:u.right,children:f?jsxs(B,{accessibilityRole:"button",accessibilityLabel:K(h.switchActivePet,{name:m}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsx(Pr,{pet:p,size:St,ringStroke:wn}),jsx(View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(ud,{size:NE,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsx(hn,{size:St,strokeWidth:wn,color:l.color.success,children:jsx(View,{style:u.placeholderDisc})})}):jsx(View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?h.yourPet:m,children:jsx(Pr,{pet:p,size:St,ringStroke:wn})})}),jsx(kc,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:w,onAddPet:b,onClose:()=>c(false)})]})}i(Ic,"ChatHeader");function HE({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(HE,"BrandLogo");function BE(e){let t=e.color,r=St-wn*2;return StyleSheet.create({vetEntry:{minHeight:FE,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...S(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:_n/2},iconButton:{width:_n,height:_n,borderRadius:_n/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:_c,right:_c,width:Di,height:Di,borderRadius:Di,backgroundColor:t.danger,borderWidth:LE,borderColor:t.surface},center:{...Se,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:UE,width:VE},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:St/2},avatarWrap:{width:St,height:St,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Ni,height:Ni,borderRadius:Ni/2,borderWidth:DE,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(BE,"makeStyles");var Fc=44,KE="rgba(17,17,17,0.55)",Mc=26,qE=36,Lc=4,Hi=20,Bi=38,$E=18,YE=12;function Dc({visible:e,onSubmit:t,onSkip:r}){let n=O(),o=useMemo(()=>XE(n),[n]),[s,a]=useState(null),[l,u]=useState(""),[d,c]=useState(false),[p,f]=useState(false),y=i(()=>{a(null),u(""),c(false),f(false);},"reset"),m=i(()=>{d||(y(),r());},"skip"),w=i(async()=>{if(d)return;c(true),f(false);let R=l.trim();await t(s,R.length>0?R:null)?y():(c(false),f(true));},"submit");if(!e)return null;let b=[...l].length>Mt;return jsx(Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:m,children:jsxs(KeyboardAvoidingView,{behavior:Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsx(Pressable,{style:o.scrim,onPress:m,accessibilityRole:"button",accessibilityLabel:h.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(gn,{size:$E,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxs(View,{style:o.headerText,children:[jsx(C,{tier:"heading",style:o.title,accessibilityRole:"header",children:h.feedbackTitle}),jsx(C,{style:o.subtitle,children:h.feedbackSubtitle})]})]}),jsx(View,{style:o.options,children:Qo.map(R=>{let I=s===R.key;return jsxs(B,{accessibilityRole:"button",accessibilityLabel:R.label,accessibilityState:{selected:I},style:[o.option,I?o.optionSelected:null],onPress:()=>a(P=>P===R.key?null:R.key),children:[jsx(C,{style:[o.optionLabel,I?o.optionLabelSelected:null],children:R.label}),jsx(View,{style:[o.radio,I?o.radioSelected:null],children:I?jsx(rt,{size:YE,color:n.color.surface,strokeWidth:2}):null})]},R.key)})}),jsxs(View,{style:o.inputWrap,children:[jsx(Ut,{style:o.input,placeholder:h.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:h.feedbackNotesPlaceholder,value:l,onChangeText:u,multiline:true,editable:!d}),l.length>0?jsx(C,{tier:"compact",style:[o.counter,b?o.counterOver:null],children:`${[...l].length}/${Mt}`}):null]}),p?jsx(C,{style:o.failed,accessibilityRole:"alert",children:h.feedbackFailed}):null,jsxs(View,{style:o.actions,children:[jsx(B,{accessibilityRole:"button",accessibilityLabel:h.feedbackSubmit,accessibilityState:{busy:d,disabled:d||b},disabled:d||b,style:[o.submit,d||b?o.submitDisabled:null],onPress:()=>{w();},children:jsx(C,{tier:"control",style:o.submitLabel,children:h.feedbackSubmit})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y,hitSlop:8,onPress:m,style:o.skip,children:jsx(C,{tier:"control",style:o.skipLabel,children:h.feedbackSkip})})]})]})]})})}i(Dc,"FeedbackReasons");function XE(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...Se,backgroundColor:KE},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Mc,borderTopRightRadius:Mc,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:qE,height:Lc,borderRadius:Lc/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Bi,height:Bi,borderRadius:Bi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...S(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...S(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:{...S(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:Hi,height:Hi,borderRadius:Hi/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,...S(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...S(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...S(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:Fc,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...me(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...S(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...Ie(o.primaryButton)},skip:{minHeight:Fc,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...S(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(XE,"makeStyles");var cC=.88,pC=420,fC=58,mC="rgba(17,17,17,0.28)",yC=.08,gC=.1,hC=.08,bC=.18,vC=.78,EC=.7,zi=36,CC=10,RC=14,SC=12,TC=16,PC=14,ji=8,kC=1.5,xC=.5,_C=vn(Er.standard);function wC(e){return Math.min(Math.round(e*cC),pC)}i(wC,"drawerPanelWidth");function Nc({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(IC,{chat:e,history:t,onHidden:o}):null}i(Nc,"HistoryDrawer");function IC({chat:e,history:t,onHidden:r}){let n=O(),o=useMemo(()=>OC(n),[n]),s=X(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),u=wC(l),d=t.open,c=useRef(null);c.current===null&&(c.current=new Animated.Value(s.drawerMs<=0&&d?1:0));let p=c.current;useEffect(()=>{if(!d&&s.drawerMs<=0){r();return}let R=Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:_C,useNativeDriver:true});return R.start(({finished:I})=>{I&&!d&&r();}),()=>R.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),y=t.filtered,m=t.rows.length===0,w=m&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:Z.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:n.color.onPrimary}),jsx(C,{style:o.emptyBody,children:Z.loading})]}):m&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,accessibilityRole:"alert",children:Z.loadFailed}),jsx(C,{style:o.emptyBody,children:t.error}),jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(C,{tier:"control",style:o.retryText,children:Z.retry})})]}):jsxs(View,{style:o.emptyCard,children:[jsx(C,{style:o.emptyTitle,children:t.emptyKind==="empty"?Z.empty:Z.noMatch}),jsx(C,{style:o.emptyBody,children:t.emptyKind==="empty"?Z.emptyBody:Z.noMatchBody})]}),b=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(C,{style:o.loadMoreLabel,children:Z.loadingMore})}):null;return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxs(View,{style:o.root,children:[jsx(Pressable,{style:Se,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Z.closeA11y,children:jsx(Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsx(Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(fC,a.top+n.space.md),transform:[{translateX:f}]}],accessibilityViewIsModal:true,children:jsxs(KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:Platform.OS==="ios"?"padding":"height",children:[jsxs(View,{style:o.searchRow,children:[jsxs(View,{style:o.searchPill,children:[jsx(hd,{size:PC,color:n.color.text.muted,strokeWidth:1.5}),jsx(Ut,{value:t.query,onChangeText:R=>t.setQuery(R.replace(/^\s+/,"")),style:o.searchInput,placeholder:Z.search,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:Z.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.newConversation,style:o.newButton,onPress:t.newConversation,children:jsx(bd,{size:TC,color:n.color.text.primary,strokeWidth:1.5})})]}),jsx(C,{tier:"heading",style:o.heading,accessibilityRole:"header",children:Z.heading}),t.error!==null&&!m?jsx(View,{style:o.errorCard,children:jsx(C,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsx(FlatList,{data:y,keyExtractor:R=>R.id,renderItem:({item:R})=>jsx(AC,{row:R,active:R.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(R.id);}}),contentContainerStyle:y.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:w,ListFooterComponent:b,onEndReached:t.loadMore,onEndReachedThreshold:xC})]})})]})})}i(IC,"DrawerModal");function AC({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsx(B,{accessibilityRole:"button",accessibilityLabel:$u(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(C,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:pn(e.title)}),s?jsx(View,{style:n.unreadDot}):null]})})}i(AC,"Row");function On(e,t){if(!/^#[0-9a-f]{6}$/i.test(e))return "transparent";let r=Math.round(Math.min(1,Math.max(0,t))*255);return `${e}${r.toString(16).padStart(2,"0").toUpperCase()}`}i(On,"inkWash");function OC(e){let t=e.color,r=e.slots,n=t.onPrimary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:mC},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.brand,paddingHorizontal:16,borderRightWidth:.5,borderRightColor:t.brandBorder,gap:12},keyboardAvoider:{flex:1,gap:12},searchRow:{flexDirection:"row",alignItems:"center",gap:10},searchPill:{flex:1,flexDirection:"row",alignItems:"center",gap:8,borderRadius:e.radius.pill,backgroundColor:t.surface,paddingHorizontal:14,paddingVertical:10,borderWidth:1,borderColor:On(n,gC)},searchInput:{...S(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:zi,height:zi,borderRadius:zi/2,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},heading:{...S(e,"bold"),fontSize:14,lineHeight:17,color:n,marginTop:4},list:{gap:10,paddingBottom:28},listEmpty:{flexGrow:1},item:{paddingVertical:12,paddingHorizontal:4,borderRadius:CC},itemActive:{backgroundColor:On(n,yC)},itemRow:{flexDirection:"row",alignItems:"center",gap:8},itemTitle:{...S(e,"regular"),flex:1,fontSize:14,lineHeight:18,color:n},itemTitleUnread:S(e,"bold"),unreadDot:{width:ji,height:ji,borderRadius:ji/2,backgroundColor:t.danger,borderWidth:kC,borderColor:n},errorCard:{borderRadius:SC,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...S(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:RC,padding:14,gap:6,backgroundColor:On(n,hC),borderWidth:.5,borderColor:On(n,bC)},emptyTitle:{...S(e,"bold"),fontSize:12,lineHeight:15,color:n},emptyBody:{...S(e,"regular"),fontSize:11,lineHeight:17,color:n,opacity:vC},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:n,...me(r.primaryButton)},retryText:{...S(e,"bold"),fontSize:12,lineHeight:15,color:n,...Ie(r.primaryButton)},loadMoreFooter:{paddingVertical:14,alignItems:"center"},loadMoreLabel:{...S(e,"regular"),fontSize:11,lineHeight:14,color:n,opacity:EC}})}i(OC,"makeStyles");function Uc(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(Uc,"chatVetVisitOptions");var DC=16,NC=.75,Wi=12,Vc=15,UC=18,Fn=22,VC=14,HC=8,BC=20,zC=10,jC=13;function Bc({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=O(),a=useMemo(()=>WC(s),[s]),l=X(),u=e.tier,d=e.source;return jsxs(Fragment,{children:[jsx(mi,{visible:e.showBanner&&u!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:u!==null&&d!==null?jsxs(View,{accessibilityRole:"alert",style:[a.card,{borderColor:u.borderColor,backgroundColor:u.backgroundColor}],children:[jsx(C,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsx(C,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsx(vt,{render:()=>r(u.level),fallback:jsx(Hc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsx(Hc,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsx(B,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:HC,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsx(Et,{size:VC,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsx(mi,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:zC,onPress:e.expand,children:jsx(fd,{size:BC,color:s.color.text.muted,strokeWidth:2})})})]})}i(Bc,"UrgencyBanner");function Hc({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=O(),a=kn(Uc(t,n)),l=a.status==="opening",u=a.available?()=>{a.open();}:r!==void 0?()=>{q(r,e.level);}:null;if(u===null)return null;let d=Ri(s.slots.vetVisitButton)?.textColor??e.textColor;return jsxs(B,{accessibilityRole:"button",accessibilityLabel:h.findVetA11y,accessibilityState:{busy:l},containerStyle:o.findVetSlot,style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,l?o.findVetBusy:null],onPress:u,children:[jsx(vd,{size:jC,color:d,strokeWidth:1.5}),jsx(C,{tier:"control",style:[o.findVetLabel,{color:d}],children:h.findVet})]})}i(Hc,"VetAction");function WC(e){let t=Ri(e.slots.vetVisitButton);return StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:DC,borderWidth:NC,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...S(e,"monoBold"),fontSize:Wi,lineHeight:Vc},reason:{...S(e,"regular"),fontSize:Wi,lineHeight:UC,paddingRight:Fn},findVetSlot:{alignSelf:"flex-start",marginTop:6},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...me(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...S(e,"monoBold"),fontSize:Wi,lineHeight:Vc},closeSlot:{position:"absolute",top:6,right:6},closeButton:{width:Fn,height:Fn,borderRadius:Fn/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:16,paddingTop:2,paddingBottom:4}})}i(WC,"makeStyles");function zc(){let e=Rn(),{handle:t}=Y(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(zc,"useChatPets");var Xc=300,Qc=3e3,Wc=120,Gt=44,YC=120,XC="86%",Gc=15,Kc=22,Mn=.5,QC=.04,ZC=8,JC=2,eR=1,tR=.6,rR=22,nR=48,qc=1.25,oR=14,iR=18,sR=6,aR=14,lR=.04,uR=12,dR=2,cR=2,$c=36,pR=20,Wt=36,Kt=(Gt-Wt)/2,Zc=24,Jc=22,fR=.4,Ln=30,ep=20,mR=.4,yR=480,gR=8,Yc=14,hR=10,bR=14,vR=12,ER=13,CR=18,RR="12%";function Ee(){let e=O(),t=useMemo(()=>SR(e),[e]);return {theme:e,styles:t}}i(Ee,"useChatTheme");function SR(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=e.slots;return StyleSheet.create({container:{flex:1,minHeight:Wc,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Wc,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:RR,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:yR,gap:18},errorText:{...S(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Gt,minWidth:Gt,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...me(s.primaryButton)},retryLabel:{...S(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...Ie(s.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...S(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:{...S(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...S(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:Gt,justifyContent:"center"},turnNoticeActionLabel:{...S(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...S(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...S(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},list:{flex:1},listContent:{padding:r.lg,gap:r.md},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:XC},bubbleUser:{padding:Gc,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:Mn,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:QC,shadowRadius:ZC,shadowOffset:{width:0,height:JC},elevation:eR,...me(s.userBubble,Mn)},bubbleAssistant:s.assistantBubble?.backgroundColor===void 0?{...me(s.assistantBubble,Mn)}:{padding:Gc,borderRadius:n.xl,...me(s.assistantBubble,Mn)},bubblePending:{opacity:tR},bubbleTextUser:{...S(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:Kc,...Ie(s.userBubble)},bubbleTextAssistant:{...S(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:Kc,...Ie(s.assistantBubble)},bubbleBold:S(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:S(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.sm,gap:gR},followUpSlot:{alignSelf:"stretch",borderRadius:Yc},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:vR,paddingVertical:hR,paddingHorizontal:bR,borderRadius:Yc,backgroundColor:t.brandSoft},followUpText:{...S(e,"medium"),flex:1,color:t.text.primary,fontSize:ER,lineHeight:CR},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,marginBottom:r.sm,minHeight:nR,justifyContent:"center",paddingLeft:oR,paddingRight:iR,paddingVertical:sR,backgroundColor:t.composerFill,borderWidth:qc,borderColor:t.composerBorder,borderRadius:rR,shadowColor:t.shadow,shadowOpacity:lR,shadowRadius:uR,shadowOffset:{width:0,height:dR},elevation:cR,...me(s.composerInput,qc)},composerRow:{flexDirection:"row",alignItems:"center",gap:aR,minHeight:$c},attachControl:{width:Ln,height:Ln,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:mR},input:{flex:1,minHeight:$c,maxHeight:YC,paddingHorizontal:0,paddingVertical:0,...S(e,"regular"),fontSize:o.size.body,lineHeight:pR,color:t.text.primary,...Ie(s.composerInput)},sendControl:{minHeight:Wt,minWidth:Wt,alignItems:"center",justifyContent:"center"},sendDisc:{width:Wt,height:Wt,borderRadius:Wt/2,alignItems:"center",justifyContent:"center",...me(s.sendButton)},sendControlDisabled:{opacity:fR},poweredBy:{...S(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(SR,"makeStyles");var TR=Object.freeze({kind:"live"}),PR=Object.freeze({kind:"folded"});function Ki(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=lo(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(Ki,"askOf");function rp(e){let t=new Map,r=new Map;for(let o of e){let s=Ki(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=Ki(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,TR),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,PR);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(rp,"placeCheckins");var tp=864e5,kR=365;function Dn(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/tp)-Math.floor(r/tp);return o<1||o>kR?null:o}i(Dn,"checkinDayNumber");function np(e){return Ki(e)?.dueDay||null}i(np,"checkinDueDay");var Te=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"})}),op=Object.freeze(zr.map(e=>Object.freeze({answer:e,label:Te.answers[e]})));function ip(e,t){let[r,n]=useState(null),[o,s]=useState(null),[a,l]=useState(null),u=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]),d=a??e.answer;return {answer:d,answerable:!ca(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(ip,"useCheckinCard");var lp=44,wR=.6;function dp({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s,onLayout:a}){let l=O(),u=useMemo(()=>IR(l),[l]),d=ip(t,r),c=d.answer!==null||d.pending!==null,p=r!==null&&d.answerable,f=Dn(t.openedAt,np(e));return jsxs(View,{style:u.card,accessibilityLabel:Te.eyebrow,onLayout:a,children:[jsxs(View,{style:u.head,children:[jsx(C,{tier:"compact",style:u.eyebrow,children:Te.eyebrow}),f!==null?jsx(C,{tier:"compact",style:u.headDay,children:K(Te.day,{day:f})}):null]}),jsx(C,{style:u.question,accessibilityRole:"text",children:e.text}),p?jsx(View,{style:[u.row,d.pending?u.rowPending:null],children:op.map(({answer:y,label:m})=>{let w=(d.pending??d.answer)===y;return jsx(Pressable,{onPress:()=>d.choose(y),disabled:c,accessibilityRole:"button",accessibilityLabel:m,accessibilityState:{selected:w,disabled:c,busy:d.pending===y},style:[u.pill,w?u.pillSelected:null],children:jsx(C,{tier:"control",style:[u.pillLabel,w?u.pillLabelSelected:null],children:m})},y)})}):null,d.answer!==null?jsx(C,{style:u.logged,children:Te.logged}):null,d.escalated?o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Te.findVet,style:u.findVet,children:jsx(C,{tier:"control",style:u.findVetLabel,children:Te.findVet})}):n?jsx(jt,{entry:"chat",petRef:n,label:Te.findVet,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:u.findVet,labelStyle:u.findVetLabel}):null:null,t.resolutionText?jsx(C,{style:u.resolution,children:t.resolutionText}):null,d.error?jsx(C,{style:u.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}i(dp,"CheckinCard");function IR(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:{...S(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...S(e,"bold"),color:t.text.primary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...S(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:wR},pill:{flex:1,minHeight:lp,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brand},pillLabel:{...S(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...S(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...S(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...S(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:lp,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...S(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(IR,"makeStyles");var FR=1.5,MR=3;function pp({text:e,runDueDays:t,openedAt:r,onLayout:n}){let o=O(),s=useMemo(()=>LR(o),[o]),a=t.map(u=>Dn(r,u)).filter(u=>u!==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(C,{tier:"compact",style:s.days,children:a.map(u=>K(Te.day,{day:u})).join(Te.daySeparator)}):null,l?null:jsx(C,{style:s.question,accessibilityRole:"text",children:e})]})]})}i(pp,"CheckinPastAsk");function LR(e){let t=e.color,r=e.space,n=e.type;return StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:FR,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:MR},days:{...S(e,"monoMedium"),fontSize:n.size.nano,letterSpacing:n.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},question:{...S(e,"regular"),fontSize:n.size.bodyTight,lineHeight:n.size.bodyTight*n.lineHeight.normal,color:t.text.muted}})}i(LR,"makeStyles");var DR=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),fp="#C8BEB4";function NR(e){return e?DR[e.toUpperCase()]??fp:fp}i(NR,"tierColor");function UR(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(UR,"tierLabel");function He(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(He,"text");function VR(e){let t=He(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(VR,"httpsUrl");function HR(e,t){let r=He(e.source_name)??He(e.sourceName),n=He(e.section),o=He(e.authority_tier)??He(e.authorityTier),s=UR(o),a=r??He(e.title)??`Source ${t+1}`,l=He(e.monograph_chunk_id)??He(e.chunkId),u=[n,s].filter(d=>d!==null).join(" \xB7 ");return Object.freeze({title:a,sourceName:r,section:n,authorityTier:o,tierLabel:s,meta:u.length===0?null:u,url:VR(e.url),excerpt:He(e.excerpt),tierColor:NR(o),key:`${a}-${l??"none"}-${t}`})}i(HR,"toCitationCard");function mp(e){return e===void 0||e.length===0?BR:Object.freeze(e.map((t,r)=>HR(t,r)))}i(mp,"toCitationCards");var BR=Object.freeze([]);function Qi(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i(Qi,"sourcesLabel");function yp(e,t){return `${t?h.hideSources:h.showSources} ${Qi(e)}`}i(yp,"sourcesToggleLabel");function gp(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(gp,"citationA11yLabel");var KR=244,bp=8,vp=13,qR=14,$R=.3,YR=-0.24,XR=22,QR=10,ZR=15;function Ep({citations:e,onOpenUrl:t}){let r=O(),n=useMemo(()=>tS(r),[r]),o=useMemo(()=>mp(e),[e]),[s,a]=useState(false);if(o.length===0)return null;let l=o.length;return jsxs(View,{style:n.block,children:[jsxs(B,{accessibilityRole:"button",accessibilityLabel:yp(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(u=>!u),children:[jsx(dd,{size:vp,color:r.color.brandInk,strokeWidth:1.5}),jsx(C,{tier:"compact",style:n.toggleLabel,children:Qi(l)}),jsx(yn,{size:vp,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsx(JR,{cards:o,styles:n,open:t}):null]})}i(Ep,"CitationCards");function JR({cards:e,styles:t,open:r}){let n=X(),o=Ct(n.citationsInMs,{risePx:n.citationsRisePx});return jsx(Animated.View,{style:o,children:jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsx(eS,{card:s,styles:t,open:r},s.key))})})}i(JR,"Deck");function eS({card:e,styles:t,open:r}){let n=O(),o=e.url!==null&&r!==void 0,s=gp(o?e:{...e,url:null}),a=jsxs(Fragment,{children:[jsxs(View,{style:t.cardHeader,children:[jsx(View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsx(C,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsx(cd,{size:qR,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsx(C,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsx(C,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let l=e.url;return jsx(B,{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(eS,"Card");function tS(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:{...S(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:$R,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:KR,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:bp,height:bp,borderRadius:n.pill},cardTitle:{...S(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:XR,color:t.text.primary,letterSpacing:YR},cardTitleLink:{color:t.linkInk},cardMeta:{...S(e,"monoMedium"),fontSize:o.nano,lineHeight:QR,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...S(e,"regular"),fontSize:o.tiny,lineHeight:ZR,color:t.text.muted}})}i(tS,"makeStyles");function Cp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(Cp,"formatMessageTime");var _r=15,aS=15,lS=6,uS=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function kp({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=O(),a=useMemo(()=>dS(s),[s]),l=X(),u=e.role==="user",d=useMemo(()=>Cp(e.createdAt),[e.createdAt]),c=t!==void 0&&e.text.length>0,p=!u&&n!==void 0&&e.responseId!==void 0,[f,y]=useState(false),m=useRef(null);useEffect(()=>()=>{m.current&&clearTimeout(m.current);},[]);let w=i(()=>{t!==void 0&&(Ht(t,e.text),y(true),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{y(false),m.current=null;},l.copiedMs));},"copy");return d===null&&!c&&!p?null:jsxs(View,{style:a.wrap,children:[jsxs(View,{style:[a.row,u?a.rowUser:a.rowAssistant],children:[d!==null?jsx(C,{tier:"compact",style:a.timestamp,children:d}):null,c?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f?h.copied:u?h.copyUserMessage:h.copyAssistantMessage,hitSlop:aS,onPress:w,style:a.iconHit,children:f?jsx(rt,{size:_r,color:s.color.success,strokeWidth:2}):jsx(pd,{size:_r,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?Cu.map(({sentiment:b,label:R})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:R,accessibilityState:{selected:r===b},hitSlop:lS,onPress:()=>n?.(b),style:a.iconHit,children:jsx(gn,{size:_r,color:s.color.sentiment[b],active:r===b,rotate:uS[b],strokeWidth:1.5})},b)):null]}),o?jsx(C,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(kp,"MessageFooter");function dS(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:{...S(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:_r,height:_r,alignItems:"center",justifyContent:"center"},thanks:{...S(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(dS,"makeStyles");var xp="#10462E",_p="#000000",cS="#83E0B4",pS=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:cS,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:xp,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})]),fS=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function mS(e){return e==null?e:e.replace(fS,"").trim()}i(mS,"formatBreedForPrompt");var yS=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 gS(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return yS.has(t)}i(gS,"isUninformativeBreed");function hS(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(hS,"unspecifiedBreedLabel");function bS(e,t){return gS(e)?hS(t):String(e).replace(/\s+/gu," ").trim()}i(bS,"resolveBreedLabel");function wp(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(wp,"emptyStateTitle");function Ip(e,t=xp){let r=Ii(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=bS(mS(e?.breed),r)||null,l=Ai(e?.ageYears),u=l===null?null:String(l);return Object.freeze(pS.map(d=>{let c=d.label.includes("{breed}"),p=d.label.includes("{ageYears}"),y=d.fallbackLabel!==void 0&&(c&&!a||p&&!u)&&d.fallbackLabel?d.fallbackLabel:d.label,m=K(y,{petName:s,breed:a??n,species:r,ageYears:u??""}),w=!o&&y.startsWith("{petName}")?m.charAt(0).toUpperCase()+m.slice(1):m;return Object.freeze({id:d.id,intent:d.intent,label:w,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(Ip,"resolveQuickPrompts");var ES=36,Fp=4,CS=340;function Mp({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=O(),a=useMemo(()=>SS(s),[s]),l=useMemo(()=>Ip(e,s.color.brandInk),[e,s.color.brandInk]),u=wp(e);return jsxs(View,{style:a.block,children:[jsx(C,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsx(View,{style:a.list,children:l.map((d,c)=>jsx(RS,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(Mp,"QuickPrompts");function RS({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=X(),d=Ct(u.followUpInMs,{delayMs:bn(u,t)}),c={backgroundColor:e.background,borderColor:e.borderColor,borderWidth:e.borderWidth};return e.intent==="vet_report"?s!==void 0?jsx(Animated.View,{style:d,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:Fp,style:[l.chip,c],onPress:()=>{q(s,r);},children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsx(Animated.View,{style:d,children:jsx(jt,{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,c],labelStyle:l.chipLabel})}):jsx(Animated.View,{style:d,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:Fp,style:[l.chip,c],onPress:()=>o(e.label),children:jsx(C,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(RS,"Chip");function SS(e){let t=e.color;return StyleSheet.create({block:{gap:18,alignItems:"center",width:"100%"},title:{...S(e,"bold"),fontSize:28,lineHeight:34,color:t.text.primary,letterSpacing:-0.8,textAlign:"center",maxWidth:CS},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:ES,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...S(e,"bold"),fontSize:12,lineHeight:14,color:_p,textAlign:"center"}})}i(SS,"makeStyles");var Ji=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function Lp(e){return e.includes("*")||e.includes("`")}i(Lp,"hasInlineMarkup");function Dp(e){let t=[],r=0;Ji.lastIndex=0;for(let n=Ji.exec(e);n!==null;n=Ji.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(Dp,"tokenizeInlineMarkdown");function Np(e,t){return Lp(e)?Dp(e).map((r,n)=>{switch(r.kind){case "bold":return jsx(C,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx(C,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx(C,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(Np,"renderInlineMarkdown");var Hp=6,jp=520,wS=Math.round(jp*.18),Bp=.44,IS=.5,zp=[0,.5,1],AS=[0,1,2];function Wp(){let e=O(),t=useMemo(()=>FS(e),[e]),r=!e.motion.reducedMotion;return jsx(View,{style:t.card,accessible:true,accessibilityRole:"text",accessibilityLabel:h.typing,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:AS.map(n=>r?jsx(OS,{index:n,style:t.dot},n):jsx(View,{style:[t.dot,t.dotStatic]},n))})}i(Wp,"TypingIndicator");function OS({index:e,style:t}){let r=useRef(new Animated.Value(0)).current;useEffect(()=>{let s=Animated.sequence([Animated.delay(e*wS),Animated.loop(Animated.timing(r,{toValue:1,duration:jp,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:zp,outputRange:[Bp,1,Bp]}),o=r.interpolate({inputRange:zp,outputRange:[0,-3.5,0]});return jsx(Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(OS,"AnimatedDot");function FS(e){let t=e.color,r=e.space,n=e.radius;return StyleSheet.create({card:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:r.xs,paddingHorizontal:r.md,paddingVertical:r.sm,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},dot:{width:Hp,height:Hp,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:IS}})}i(FS,"makeStyles");function Gp(e,t,r){let n=e-r,o=t!=null?Math.min(n,t):n;return Math.max(0,o)}i(Gp,"resolveTurnScrollTarget");function Kp(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(Kp,"latestTurn");function qp(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(qp,"nextFollowOffset");function $p(e,t){let r=useRef(null),n=useRef(true),o=useRef(t),s=useRef(0),a=useRef(0),l=useRef(0),u=useRef(new Map),d=Kp(e),c=d===null?null:e[d.assistantIndex]?.id??null,p=d===null||d.userIndex===null?null:e[d.userIndex]?.id??null,f=useCallback(()=>{let P=r.current;if(P===null||!n.current||a.current===0)return;let x=null;if(c!==null){let _=u.current.get(c);if(_===void 0)return;let F=p===null?null:u.current.get(p)??null;x=Gp(_,F,96);}let g=qp(x,s.current,l.current-a.current);g!==null&&(s.current=g,P.scrollTo({y:g,animated:false}));},[c,p]);useEffect(()=>{t&&!o.current&&(n.current=true),o.current=t,f();},[e,t,f]);let y=useCallback(P=>{a.current=P.nativeEvent.layout.height,f();},[f]),m=useCallback((P,x)=>{l.current=x,a.current>0&&(s.current=Math.min(s.current,Math.max(0,x-a.current))),f();},[f]),w=useCallback(P=>{s.current=P.nativeEvent.contentOffset.y;},[]),b=useCallback(()=>{n.current=false;},[]),R=useCallback(P=>{let{contentOffset:x,contentSize:g,layoutMeasurement:_}=P.nativeEvent;s.current=x.y,n.current=g.height-x.y-_.height<=24;},[]),I=useCallback(P=>x=>{u.current.set(P,x.nativeEvent.layout.y),(P===c||P===p)&&f();},[c,p,f]);return {ref:r,onLayout:y,onContentSizeChange:m,onScroll:w,onScrollBeginDrag:b,onScrollEnd:R,rowLayout:I}}i($p,"useThreadFollow");function Jp(e,t,r){switch(e){case "loading":return r.renderPending?jsx(vt,{render:r.renderPending,fallback:jsx(Xp,{})}):jsx(Xp,{});case "empty":return jsx(BS,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(jS,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx(WS,{messages:t.messages,prompts:t.suggestedPrompts,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});default:return Qe(e)}}i(Jp,"renderView");function Xp(){let{theme:e,styles:t}=Ee(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),Xc);return ()=>clearTimeout(o)},[]),jsx(View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:h.loading,children:r?jsx(ActivityIndicator,{color:e.color.brandInk}):null})}i(Xp,"LoadingState");function BS({pet:e,petRef:t,prompts:r,onSelectPrompt:n,onVetPrep:o,vet:s}){let{styles:a}=Ee();return jsxs(ScrollView,{contentContainerStyle:a.emptyContent,keyboardShouldPersistTaps:"handled",accessibilityLabel:h.empty,children:[jsx(Mp,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsx(ef,{prompts:r,onSelectPrompt:n})]})}i(BS,"EmptyState");function ef({prompts:e,onSelectPrompt:t}){let{styles:r}=Ee();return e.length===0?null:jsx(View,{style:r.followUps,children:e.map((n,o)=>jsx(zS,{prompt:n,index:o,onSelectPrompt:t},n))})}i(ef,"FollowUps");function zS({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=Ee(),s=X(),a=Ct(s.followUpInMs,{delayMs:bn(s,t)});return jsx(Animated.View,{style:a,children:jsxs(B,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:o.followUpSlot,style:o.followUpRow,children:[jsx(C,{style:o.followUpText,children:e}),jsx(yn,{size:$S,color:n.color.brandInk,direction:"right"})]})})}i(zS,"FollowUpRow");function jS({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Ee(),o=Iu(e)?Uu(r):void 0;return jsxs(View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsx(C,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:h.addPet,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.addPet})}):null,e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:h.retry,style:n.retryButton,children:jsx(C,{tier:"control",style:n.retryLabel,children:h.retry})}):null]})}i(jS,"ErrorState");function WS({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:o,onCopy:s,sentimentByMessage:a,onSentiment:l,thanksFor:u,imagesByMessage:d,onPreview:c,notice:p,reconnecting:f,onRetry:y,onStartNew:m,petRef:w,onFindVet:b,vet:R,onOpenUrl:I}){let{styles:P}=Ee(),x=X();Cr(e.length,x);let g=useMemo(()=>rp(e),[e]),_=rd(e,n),F=e[e.length-1],M=useMemo(()=>e.filter(k=>!(k.checkin&&g.get(k.id)?.kind==="folded")),[e,g]),E=$p(M,n);return jsxs(ScrollView,{ref:E.ref,style:P.list,contentContainerStyle:P.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",onLayout:E.onLayout,onContentSizeChange:E.onContentSizeChange,onScroll:E.onScroll,scrollEventThrottle:qS,onScrollBeginDrag:E.onScrollBeginDrag,onScrollEndDrag:E.onScrollEnd,onMomentumScrollEnd:E.onScrollEnd,children:[e.map(k=>{let T=k.checkin?g.get(k.id):void 0;return T?.kind==="folded"?null:T?.kind==="past"?jsx(pp,{text:k.text,runDueDays:T.runDueDays,openedAt:k.checkin?.openedAt,onLayout:E.rowLayout(k.id)},k.id):k.checkin&&T!==void 0?jsx(dp,{message:k,checkin:k.checkin,onAnswer:o,petRef:w,onFindVet:b,vet:R,onLayout:E.rowLayout(k.id)},k.id):jsx(YS,{onLayout:E.rowLayout(k.id),message:k,revealing:n&&k===F&&k.role==="assistant",onCopy:s,sentiment:k.responseId===void 0?null:a[String(k.responseId)]??null,onSentiment:l,thanks:u!==null&&k.responseId!==void 0&&String(k.responseId)===u,images:d[k.id]??KS,onPreview:c,onOpenUrl:I},k.id)}),f?jsx(C,{tier:"compact",style:P.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,_?jsx(Wp,{}):null,p!==null?jsx(GS,{notice:p,onRetry:y,onStartNew:m}):null,n?null:jsx(ef,{prompts:t,onSelectPrompt:r})]})}i(WS,"PopulatedState");function GS({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Ee(),o=e.tone==="error";return jsxs(View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsx(C,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsx(Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Kt,style:n.turnNoticeAction,children:jsx(C,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(GS,"TurnNoticeCard");var KS=Object.freeze([]),qS=16,$S=14;function YS({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l,onOpenUrl:u,onLayout:d}){let{styles:c}=Ee(),p=X(),f=Ct(p.messageInMs),y=wd(e.text,t,p),m=e.role==="user",w=m?h.senderUser:h.senderAssistant,b=useCallback(I=>o(e,I),[o,e]),R=e.pending!==true;return jsxs(Animated.View,{style:[c.rowBlock,m?c.rowBlockUser:c.rowBlockAssistant,f],onLayout:d,children:[jsx(View,{style:[c.row,m?c.rowUser:c.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${w}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxs(View,{style:[c.bubble,m?c.bubbleUser:c.bubbleAssistant,e.pending?c.bubblePending:null],children:[m&&a.length>0?jsx(Kd,{images:a,onPreview:I=>l({uri:I.uri,label:I.filename})}):null,jsx(C,{style:m?c.bubbleTextUser:c.bubbleTextAssistant,children:m?e.text:Np(y,{bold:c.bubbleBold,italic:c.bubbleItalic,code:c.bubbleCode})})]})}),!m&&!t?jsx(Ep,{citations:e.citations,onOpenUrl:u}):null,R?jsx(kp,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:b,thanks:s}):null]})}i(YS,"MessageRow");var eT=Object.freeze(["photo"]),tT=1;function rf(e){let{style:t,renderPending:r}=e;return jsx(Xo,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(rT,{...e})})}i(rf,"EverfurChat");function rT({petRef:e,conversationId:t,style:r,renderPending:n,onCopy:o,onPetChange:s,onVetPrep:a,onFindVet:l,renderVetAction:u,attachments:d,pet:c,onAddPet:p,checkinTarget:f,initialAsk:y,composerSeed:m,lifecycle:w,draftStore:b,vetReturnTo:R,vetUsState:I,vetPrefer:P,onOpenUrl:x}){let{theme:g,styles:_}=Ee(),F=X(),M=useMemo(()=>nd(e,t),[e,t]),E=br(M),k=ed(E),T=zc(),V=Yu(E),j=useSafeAreaInsets(),G=td(E),ne=useMemo(()=>l===void 0?void 0:()=>{q(l,"emergency");},[l]),de=useMemo(()=>R===void 0&&I===void 0&&P===void 0?void 0:{returnTo:R,usState:I,prefer:P},[R,I,P]),ke=Vi(T.pets,E.petRef),Yt=useMemo(()=>Zu(E.messages,ke?.name??null),[E.messages,ke?.name]),ce=Ju(Yt);Cr(ce.showBanner,F),zu(E.openCheckin,f),Lu(E.askEverfur,E.isBootstrapping,y);let it=useMemo(()=>oi(m),[m]);Hu(w,{conversationId:E.conversationId===null?null:String(E.conversationId),isTurnInFlight:E.isStreaming,refresh:E.refreshActiveThread});let Ar=(E.hasUnreadThreads??false)||V.rows.some(Ce=>Ce.unreadCount!==null&&Ce.unreadCount>0)||(E.unreadCount??0)>0,Xt=Fu(E.messages),[It,At]=useState(null),of=useCallback(()=>At(null),[]),[Qt,Bn]=useState(null),[sf,ns]=useState(null),Ot=useRef(null);useEffect(()=>()=>{Ot.current&&clearTimeout(Ot.current);},[]);let os=useCallback(Ce=>{ns(String(Ce)),Ot.current&&clearTimeout(Ot.current),Ot.current=setTimeout(()=>{ns(null),Ot.current=null;},Qc);},[]),af=useCallback((Ce,Or)=>{let Zt=Ce.responseId;if(Zt===void 0)return;let pf=E.sentimentByMessage[String(Zt)];E.feedback(Zt,Or),Or==="down"&&pf!=="down"&&Bn(Zt);},[E]),lf=useCallback(async(Ce,Or)=>Qt===null||!(await E.feedback(Qt,"down",Ce??"other",Or)).ok?false:(Bn(null),os(Qt),true),[E,Qt,os]),uf=useCallback(()=>Bn(null),[]),df=useCallback(Ce=>{E.send(Ce);},[E.send]),cf=useMemo(()=>x===void 0?void 0:Ce=>{q(x,Ce,"citation");},[x]),is={send:E.send,stop:E.stop,isStreaming:E.isStreaming,conversationId:E.conversationId,seed:it,draftStore:b,onStage:Xt.stage,onPreview:At};return jsxs(KeyboardAvoidingView,{style:[_.container,{paddingTop:j.top},r],behavior:Platform.OS==="ios"?"padding":void 0,children:[jsx(Ic,{pets:T,petRef:E.petRef,historyUnread:Ar,onOpenHistory:V.show,onPetChange:s,onAddPet:p,vet:de}),c!==void 0?jsx(nT,{petRef:e??null,pet:c,onRegistered:T.refresh}):null,jsx(Bc,{surface:ce,petRef:E.petRef,renderVetAction:u,onFindVet:l,vet:de}),jsx(View,{style:_.body,children:Jp(k,E,{notice:G,vet:de,onCheckinFindVet:ne,onSelectPrompt:df,renderPending:n,shownPet:ke,onVetPrep:a,onCopy:o,onSentiment:af,thanksFor:sf,imagesByMessage:Xt.byMessage,onPreview:At,onAddPet:p,onOpenUrl:cf})}),d!==void 0?jsx(oT,{...is,attachments:d}):jsx(nf,{...is,attachments:null}),jsx(sd,{}),g.meta.hidePoweredBy?null:jsx(C,{tier:"compact",style:_.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsx(Nc,{chat:E,history:V}),jsx(Dc,{visible:Qt!==null,onSubmit:lf,onSkip:uf}),jsx(Id,{uri:It?.uri??null,label:It?.label??"",onClose:of}),jsx(Sr,{})]})}i(rT,"ChatBody");function nT({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Ee(),o=Au(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs(View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsx(C,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsx(Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:h.retry,hitSlop:Kt,children:jsx(C,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(nT,"PetSetupNotice");function oT({attachments:e,...t}){let r=useMemo(()=>$d(),[]),n=dn({maxPerMessage:e.maxPerMessage??tT,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??eT,pick:e.pick}),[n,e.sources,e.pick]);return jsx(nf,{...t,attachments:o})}i(oT,"ComposerWithAttachments");function nf({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:u}){let{theme:d,styles:c}=Ee(),p=X(),[f,y]=Gu(e,n,s);Ku(a,n===null?null:String(n),f,y);let[m,w]=useState(false),[b,R]=useState(false);useEffect(()=>{R(false);},[n]);let I=d.meta.placeholder??h.placeholder,P=o?.state.uploading??false,x=o?.state.failed??false,g=P||x,_=o?.state.attachments??iT;Cr(_.length,p);let F=useCallback(()=>{if(f.trim().length===0||g||[...f].length>Lt)return;let G=o?.state.s3Keys??sT;o!==null&&G.length>0?(l(o.state.attachments.filter(ne=>ne.status==="uploaded").map(ne=>({uri:ne.previewUri,filename:ne.filename}))),e(f,{imageS3Keys:G}),o.state.clear()):e(f),y(""),R(false);},[f,e,g,o,l]),M=useCallback(()=>{t();},[t]),E=useCallback(G=>{w(false),o!==null&&(R(false),o.state.dismissRejected(),Ht(o.pick,G).then(ne=>{if(!ne.ok){R(true);return}ne.value!==null&&o.state.add(ne.value);}));},[o]),T=useMemo(()=>[...f].length>Lt,[f])||g,V=o!==null&&_.length>=o.state.maxPerMessage,j=d.slots.sendButton?.textColor??d.color.brandInk;return jsxs(View,{style:c.composerOuter,children:[o!==null&&m?jsx(Fd,{sources:o.sources,full:V,onPick:E,onClose:()=>w(false)}):null,jsxs(View,{style:c.composer,children:[o!==null?jsx(Gd,{attachments:_,rejected:b?aT:o.state.rejected,uploadFailed:x,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:G=>u({uri:G.previewUri,label:G.filename})}):null,jsxs(View,{style:c.composerRow,children:[o!==null?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:xu(_.length,o.state.maxPerMessage),accessibilityState:{disabled:V,expanded:m},disabled:V,hitSlop:(Gt-Ln)/2,style:[c.attachControl,V?c.attachControlDisabled:null],onPress:()=>w(G=>!G),children:jsx(md,{size:ep,color:V?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsx(Ut,{style:c.input,value:f,onChangeText:y,placeholder:I,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,accessibilityLabel:I,onSubmitEditing:F,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsx(Pressable,{onPress:M,accessibilityRole:"button",accessibilityLabel:h.stop,hitSlop:Kt,style:c.sendControl,children:jsx(View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsx(Cd,{size:Jc,color:j,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:F,disabled:T,accessibilityRole:"button",accessibilityLabel:h.send,accessibilityState:{disabled:T,busy:P},hitSlop:Kt,style:[c.sendControl,T?c.sendControlDisabled:null],children:jsx(View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsx(Ed,{size:Zc,color:j,testID:"everfur-send-glyph"})})})]})]})]})}i(nf,"Composer");var iT=Object.freeze([]),sT=Object.freeze([]),aT=Object.freeze({code:"unknown",retryable:true,filename:""});function pT(e){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=useMemo(()=>Ze(t.registry.services.authFor(r)),[t,r,n]),s=useMemo(()=>({repository:o,petRef:e}),[o,e]),[a,l]=useState({key:s,profile:null,loading:e!==null,error:null}),u=a.key===s?a:{profile:null,loading:e!==null,error:null},d=useRef(0),c=useCallback(async()=>{let p=++d.current;if(s.petRef===null){l({key:s,profile:null,loading:false,error:null});return}l(y=>({key:s,profile:y.key===s?y.profile:null,loading:true,error:null}));let f=await s.repository.getPetProfile(s.petRef);p===d.current&&l(f.ok?{key:s,profile:f.value,loading:false,error:null}:{key:s,profile:null,loading:false,error:f.error});},[s]);return useEffect(()=>(c(),()=>{d.current+=1;}),[c]),useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:c}),[u.profile,u.loading,u.error,c])}i(pT,"useEverfurPetProfile");function mT(e){return createElement(an,{clientTheme:e.clientTheme??null,seams:un,children:e.children})}i(mT,"EverfurThemeProvider");export{Xo as CapabilityGate,rf as EverfurChat,Q as EverfurConfigError,Vh as EverfurProvider,mT as EverfurThemeProvider,Fr as EverfurThrownError,sg as THEME_SLOT_KEYS,yt as THEME_SLOT_NAMES,dr as canonicalPetSpecies,jn as categoryFor,Ef as conversationId,Uf as createRnRecordsUploadTransport,S as face,yf as isErr,mf as isOk,Wn as isRetryableCode,bf as petRef,Mg as previewTheme,gf as unwrap,Nt as useCapability,dn as useChatAttachments,Zl as useEverfur,br as useEverfurChat,pT as useEverfurPetProfile,Rn as useEverfurPets,O as useEverfurTheme,Ft as userFacingError,vf as userRef};
|