@everfur/sdk 0.5.8 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/dist/{Chat-z0C6qgrU.d.cts → Chat-BoAvCWhI.d.cts} +3 -3
- package/dist/{Chat-V_fRV7kR.d.ts → Chat-CHqcgMyw.d.ts} +3 -3
- package/dist/{DepthViews-B-rnrFpR.d.ts → DepthViews-7Y8Ur058.d.ts} +1 -1
- package/dist/{DepthViews-CmIFMqoE.d.cts → DepthViews-B0g83e_N.d.cts} +1 -1
- package/dist/{DepthViews-DQo49-QL.d.cts → DepthViews-CT5mQld9.d.cts} +1 -1
- package/dist/{DepthViews-R8bKbJ6t.d.ts → DepthViews-Dg2bIon_.d.ts} +1 -1
- package/dist/animations/index.cjs +1 -1
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/animations/index.js +1 -1
- package/dist/{attachments-D9wvXx_d.d.cts → attachments-C3HJNYQ7.d.cts} +2 -2
- package/dist/{attachments-BxewZK83.d.ts → attachments-CThFsH4b.d.ts} +5 -5
- package/dist/{attachments-CXLSLEvy.d.ts → attachments-CfxsVg7W.d.ts} +2 -2
- package/dist/{attachments-HXsnkA6A.d.cts → attachments-rkox0ewd.d.cts} +5 -5
- package/dist/{bookingCopy-DpqgkSZ_.d.cts → bookingCopy-Do3zMeXb.d.cts} +2 -2
- package/dist/{bookingCopy-DJnAMiJw.d.ts → bookingCopy-Y3OGdoMT.d.ts} +2 -2
- package/dist/{branding-xpQ056sM.d.ts → branding-ChXm8gxI.d.cts} +136 -4
- package/dist/{branding-Xb_wL8N1.d.cts → branding-DYWma2il.d.ts} +136 -4
- package/dist/{casesRepository-s5EjE3Md.d.ts → casesRepository-BbgXYPxa.d.ts} +1 -1
- package/dist/{casesRepository-C2gzlgJW.d.cts → casesRepository-Jj6t60AY.d.cts} +1 -1
- package/dist/chat/index.cjs +1 -1
- package/dist/chat/index.d.cts +9 -9
- package/dist/chat/index.d.ts +9 -9
- package/dist/chat/index.js +1 -1
- package/dist/client/index.cjs +6 -6
- package/dist/client/index.d.cts +10 -10
- package/dist/client/index.d.ts +10 -10
- package/dist/client/index.js +6 -6
- package/dist/{config-CBJgbICJ.d.cts → config-BZX97FmW.d.cts} +1 -1
- package/dist/{config-CQ4VFCgE.d.ts → config-Dfbj5mlx.d.ts} +1 -1
- package/dist/consent/index.cjs +1 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/consent/index.js +1 -1
- package/dist/{context-CQohsg_w.d.ts → context-Cbe0zYym.d.ts} +7 -7
- package/dist/{context-t2PM_Hwc.d.cts → context-DJXnZ1Mx.d.cts} +7 -7
- package/dist/{copy-DfWmYRTc.d.ts → copy-DHekqSKE.d.ts} +2 -2
- package/dist/{copy-BuawMcCw.d.cts → copy-dKK5KoAQ.d.cts} +2 -2
- package/dist/core/index.cjs +9 -9
- package/dist/core/index.d.cts +15 -15
- package/dist/core/index.d.ts +15 -15
- package/dist/core/index.js +9 -9
- package/dist/{depth-Cvw1LdWV.d.ts → depth-CrpRjWGB.d.ts} +2 -2
- package/dist/{depth-DXK5Y7sO.d.cts → depth-NmWSbvfi.d.cts} +2 -2
- package/dist/{entitlementRepository-CatKDVru.d.cts → entitlementRepository-iL-9vS1i.d.cts} +3 -3
- package/dist/{entitlementRepository-MhuhRhmI.d.ts → entitlementRepository-tVNazi8R.d.ts} +3 -3
- package/dist/{identity-vvueVndA.d.ts → identity-B8rp0L9G.d.ts} +1 -1
- package/dist/{identity-DczAiVsf.d.cts → identity-D7PO5s9m.d.cts} +1 -1
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +16 -16
- package/dist/index.d.ts +16 -16
- 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-BP2lkMbR.d.ts → pets-BQbXmICf.d.ts} +1 -1
- package/dist/{pets-BRsxDv4g.d.cts → pets-BWx9BKea.d.cts} +1 -1
- package/dist/{petsRepository-C4oEuH9r.d.ts → petsRepository-0oBVydl6.d.ts} +1 -1
- package/dist/{petsRepository-DeQqFxAV.d.cts → petsRepository-SqIvEMiT.d.cts} +1 -1
- package/dist/photo/index.cjs +1 -1
- package/dist/photo/index.js +1 -1
- package/dist/{ports-D0YSZnxV.d.cts → ports-ChnzSy4E.d.cts} +25 -6
- package/dist/{ports-DOoFLAKN.d.ts → ports-iXPWd7Vt.d.ts} +25 -6
- package/dist/records/depth/index.cjs +1 -1
- package/dist/records/depth/index.d.cts +7 -7
- package/dist/records/depth/index.d.ts +7 -7
- package/dist/records/depth/index.js +1 -1
- package/dist/records/index.cjs +2 -2
- package/dist/records/index.d.cts +9 -9
- package/dist/records/index.d.ts +9 -9
- package/dist/records/index.js +2 -2
- package/dist/{requestFunnel-D6UOCs0L.d.ts → requestFunnel-CQzz2DIW.d.ts} +2 -2
- package/dist/{requestFunnel-BGpcJ_po.d.cts → requestFunnel-DAwb7haa.d.cts} +2 -2
- package/dist/{runtimeTypes-Bi-_nYuC.d.ts → runtimeTypes-BNOxfmfg.d.ts} +5 -5
- package/dist/{runtimeTypes-wFAjfnu3.d.cts → runtimeTypes-DB9-kigO.d.cts} +5 -5
- 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 +1 -1
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +1 -1
- package/dist/televet/booking/index.cjs +1 -1
- package/dist/televet/booking/index.d.cts +6 -6
- package/dist/televet/booking/index.d.ts +6 -6
- package/dist/televet/booking/index.js +1 -1
- package/dist/televet/call/index.cjs +1 -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.cjs +1 -1
- package/dist/testing/rn/index.d.cts +9 -9
- package/dist/testing/rn/index.d.ts +9 -9
- package/dist/testing/rn/index.js +1 -1
- package/dist/testing/web/index.d.cts +9 -9
- package/dist/testing/web/index.d.ts +9 -9
- package/dist/{timelineRows-CRy4jphH.d.cts → timelineRows-BuNhzDbH.d.cts} +1 -1
- package/dist/{timelineRows-BzaTUbq_.d.ts → timelineRows-Dll2IGFg.d.ts} +1 -1
- package/dist/{tokens-CIngRkvt.d.cts → tokens-ARWZtMOU.d.cts} +14 -2
- package/dist/{tokens-CIngRkvt.d.ts → tokens-ARWZtMOU.d.ts} +14 -2
- package/dist/{typeStyle-YPS_MXeI.d.ts → typeStyle-8iEqQmP_.d.ts} +2 -2
- package/dist/{typeStyle-DHJzDaUo.d.cts → typeStyle-YCS8dt19.d.cts} +2 -2
- package/dist/{useRecordsDepth-DIeDEXgB.d.cts → useRecordsDepth-CNEHZJtj.d.cts} +1 -1
- package/dist/{useRecordsDepth-UNvpPiHN.d.ts → useRecordsDepth-CuNdne6E.d.ts} +1 -1
- package/dist/video/index.cjs +1 -1
- package/dist/video/index.js +1 -1
- package/dist/{view-D4bOSC88.d.cts → view-BhqWlYrZ.d.cts} +2 -2
- package/dist/{view-DvY7eq4Q.d.ts → view-DFy8EDwf.d.ts} +2 -2
- package/dist/web/consent/index.cjs +1 -1
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/consent/index.js +1 -1
- package/dist/web/index.cjs +7 -7
- package/dist/web/index.d.cts +19 -19
- package/dist/web/index.d.ts +19 -19
- package/dist/web/index.js +7 -7
- package/dist/web/notifications/index.d.cts +3 -3
- package/dist/web/notifications/index.d.ts +3 -3
- package/dist/web/records/depth/index.cjs +1 -1
- package/dist/web/records/depth/index.d.cts +7 -7
- package/dist/web/records/depth/index.d.ts +7 -7
- package/dist/web/records/depth/index.js +1 -1
- 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 +7 -7
- package/dist/web/televet/booking/index.d.ts +7 -7
- package/dist/web/televet/booking/index.js +2 -2
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +3 -3
- package/dist/web/televet/index.js +3 -3
- package/package.json +1 -1
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 _h from'react-native-sse';import {StyleSheet,TextInput,View,Linking,Platform,KeyboardAvoidingView,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 Rf=Object.defineProperty;var i=(e,t)=>Rf(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 at(e){return [...e].length}i(at,"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 E(e){return Object.freeze({ok:false,error:e})}i(E,"err");function Sf(e){return e.ok}i(Sf,"isOk");function Tf(e){return !e.ok}i(Tf,"isErr");var Lr=class Lr 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,Lr.prototype);}};i(Lr,"EverfurThrownError");var Mr=Lr;function Pf(e){if(e.ok)return e.value;throw new Mr(e.error)}i(Pf,"unwrap");var Dr=class Dr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Dr.prototype);}};i(Dr,"EverfurConfigError");var Q=Dr;var fs=128,ms=128,ys=/[\u0000-\u001F\u007F]/,kf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xf(e){let t=e,r=at(t);if(r===0||r>ms)throw new Q("invalid-argument",`petRef must be 1..${ms} characters`);if(ys.test(t))throw new Q("invalid-argument","petRef must be printable (no control characters)");return t}i(xf,"petRef");function _f(e){let t=e,r=at(t);if(r===0||r>fs)throw new Q("invalid-argument",`userRef must be 1..${fs} characters`);if(t.includes("@"))throw new Q("invalid-argument","userRef must not contain '@'");if(ys.test(t))throw new Q("invalid-argument","userRef must be printable (no control characters)");return t}i(_f,"userRef");function wf(e){if(!kf.test(e))throw new Q("invalid-argument","conversationId must be a UUID");return e}i(wf,"conversationId");var Kn=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(Kn.map(e=>e.wireCode));var If=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"}),hs=Object.freeze(Kn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:If[e.wireCode]}))),Af=new Map(hs.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Of=Object.freeze(["http_envelope",...[...new Set(hs.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Nr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...Of]){let o=Af.get(n+r);if(o)return o}}i(Nr,"contractErrorFor");function Ff(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Ff,"contractDocUrl");function bs(e){return null}i(bs,"publishedDocUrl");var Mf=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 qn(e){return Mf[e]}i(qn,"categoryFor");function Oe(e){let t=Nr(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 vs(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(vs,"fromHttpStatus");var Lf=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Be(e){return Lf.has(e)}i(Be,"isAutoRetryable");var Df=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function $n(e){return Be(e)||Df.has(e)}i($n,"isRetryableCode");function Ur(e,t=false){return t||Be(e)}i(Ur,"shouldRetry");var Nf=500,Yn=8e3,Zt=4;function Vr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(Nf*2**r,Yn);return Math.floor(t()*n)}i(Vr,"backoffDelayMs");function Es(e){return e==="conversationNotFound"}i(Es,"canRecreateOnNotFound");var Uf=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 Uf[e]}i(Ft,"userFacingError");function Cs(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Cs,"defineHidden");var Vf=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Nr(t?.wireCode,t?.wireEnvelope),n={code:e,category:qn(e),retryable:t?.retryable??$n(e),displayMessage:Ft(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Vf.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&Cs(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Cs(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");var Hf="file",Xn="multipart upload failed";function Hr(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Hf,e.file);}catch{return Promise.reject(new Error(Xn))}return e.fetch!==void 0?jf(e.fetch,e.url,t,e.signal):zf(e.url,t,e.signal)}i(Hr,"postRnMultipart");function Bf(e){return e>=200&&e<300}i(Bf,"stored");function zf(e,t,r){return new Promise((n,o)=>{let s=globalThis.XMLHttpRequest;if(typeof s!="function"||r?.aborted===true){o(new Error(Xn));return}let a=null,l=i(()=>{a!==null&&r?.removeEventListener("abort",a);},"release"),u=i(()=>{l(),o(new Error(Xn));},"fail");try{let d=new s;d.open("POST",e),d.withCredentials=!1,d.onload=()=>{l(),n(Bf(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(zf,"postWithXhr");function jf(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(o=>o.ok)}i(jf,"postWithFetch");var Wf="document.pdf",Gf="records upload: the file handle has no uri",Kf="records upload failed";function qf(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Gf));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Kf)),"failed");return o?.aborted===true?a():Hr({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:Wf,type:"application/pdf"},signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(qf,"createRnRecordsUploadTransport");var Br=Object.freeze({track(){},trackExpectedFailure(){}});var Rs=Object.freeze({shouldRetry(e,t){return Be(e)&&t<Zt},maxAttempts(){return Zt}});var Ss=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Ze(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Ze,"assertNever");function Ts(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Ts,"acceptedFrame");function Ps(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(Ps,"heartbeatFrame");function ks(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ks,"deltaFrame");function xs(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(xs,"doneFrame");function de(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(de,"errorFrame");function _s(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(_s,"analysisStartedFrame");function ws(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(ws,"analysisCompleteFrame");function Is(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Is,"unknownFrame");function As(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:Xf(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(As,"createIdentityProvider");function Xf(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(Xf,"expiryMs");function Zn(){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(Zn,"newSessionId");function Qf(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(Qf,"authHeaders");function Jt(e,t){return {...e,headers:{...Zf(e.headers),...Qf(t)}}}i(Jt,"withAuthHeaders");function Zf(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(Zf,"stripAuthHeaders");async function Os(e,t){if(t.mode==="anonymous")return t.transport.request(Jt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return E(Qn())}let n=await t.transport.request(Jt(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 E(Qn())}let s=await t.transport.request(Jt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?E(Qn(s.error.httpStatus)):s}i(Os,"authedSend");function Qn(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(Qn,"authRejectedError");var Fs=`
|
|
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 as z$1}from'zod';import ub from'react-native-sse';import {StyleSheet,TextInput,View,Linking,Platform,KeyboardAvoidingView,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 $f=Object.defineProperty;var i=(e,t)=>$f(e,"name",{value:t,configurable:true});function ve(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(ve,"hasLoneSurrogate");function pt(e){return [...e].length}i(pt,"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 E(e){return Object.freeze({ok:false,error:e})}i(E,"err");function Yf(e){return e.ok}i(Yf,"isOk");function Xf(e){return !e.ok}i(Xf,"isErr");var Hr=class Hr 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,Hr.prototype);}};i(Hr,"EverfurThrownError");var Br=Hr;function Qf(e){if(e.ok)return e.value;throw new Br(e.error)}i(Qf,"unwrap");var zr=class zr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,zr.prototype);}};i(zr,"EverfurConfigError");var ee=zr;var xs=128,_s=128,ws=/[\u0000-\u001F\u007F]/,Zf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Jf(e){let t=e,r=pt(t);if(r===0||r>_s)throw new ee("invalid-argument",`petRef must be 1..${_s} characters`);if(ws.test(t))throw new ee("invalid-argument","petRef must be printable (no control characters)");return t}i(Jf,"petRef");function em(e){let t=e,r=pt(t);if(r===0||r>xs)throw new ee("invalid-argument",`userRef must be 1..${xs} characters`);if(t.includes("@"))throw new ee("invalid-argument","userRef must not contain '@'");if(ws.test(t))throw new ee("invalid-argument","userRef must be printable (no control characters)");return t}i(em,"userRef");function tm(e){if(!Zf.test(e))throw new ee("invalid-argument","conversationId must be a UUID");return e}i(tm,"conversationId");var Jn=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(Jn.map(e=>e.wireCode));var rm=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"}),As=Object.freeze(Jn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:rm[e.wireCode]}))),nm=new Map(As.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),om=Object.freeze(["http_envelope",...[...new Set(As.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function jr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...om]){let o=nm.get(n+r);if(o)return o}}i(jr,"contractErrorFor");function im(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(im,"contractDocUrl");function Os(e){return null}i(Os,"publishedDocUrl");var sm=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 eo(e){return sm[e]}i(eo,"categoryFor");function Me(e){let t=jr(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(Me,"fromWire");function Fs(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(Fs,"fromHttpStatus");var am=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function We(e){return am.has(e)}i(We,"isAutoRetryable");var lm=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function to(e){return We(e)||lm.has(e)}i(to,"isRetryableCode");function Wr(e,t=false){return t||We(e)}i(Wr,"shouldRetry");var um=500,ro=8e3,rr=4;function Gr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(um*2**r,ro);return Math.floor(t()*n)}i(Gr,"backoffDelayMs");function Ms(e){return e==="conversationNotFound"}i(Ms,"canRecreateOnNotFound");var dm=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 Mt(e){return dm[e]}i(Mt,"userFacingError");function Ls(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Ls,"defineHidden");var cm=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=jr(t?.wireCode,t?.wireEnvelope),n={code:e,category:eo(e),retryable:t?.retryable??to(e),displayMessage:Mt(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&cm.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&Ls(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Ls(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");var pm="file",no="multipart upload failed";function Kr(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(pm,e.file);}catch{return Promise.reject(new Error(no))}return e.fetch!==void 0?ym(e.fetch,e.url,t,e.signal):mm(e.url,t,e.signal)}i(Kr,"postRnMultipart");function fm(e){return e>=200&&e<300}i(fm,"stored");function mm(e,t,r){return new Promise((n,o)=>{let s=globalThis.XMLHttpRequest;if(typeof s!="function"||r?.aborted===true){o(new Error(no));return}let a=null,l=i(()=>{a!==null&&r?.removeEventListener("abort",a);},"release"),u=i(()=>{l(),o(new Error(no));},"fail");try{let d=new s;d.open("POST",e),d.withCredentials=!1,d.onload=()=>{l(),n(fm(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(mm,"postWithXhr");function ym(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(o=>o.ok)}i(ym,"postWithFetch");var gm="document.pdf",hm="records upload: the file handle has no uri",bm="records upload failed";function vm(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(hm));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(bm)),"failed");return o?.aborted===true?a():Kr({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:gm,type:"application/pdf"},signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(vm,"createRnRecordsUploadTransport");var qr=Object.freeze({track(){},trackExpectedFailure(){}});var Ds=Object.freeze({shouldRetry(e,t){return We(e)&&t<rr},maxAttempts(){return rr}});var Ns=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function nt(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(nt,"assertNever");function Us(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Us,"acceptedFrame");function Vs(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(Vs,"heartbeatFrame");function Bs(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Bs,"deltaFrame");function Hs(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(Hs,"doneFrame");function fe(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(fe,"errorFrame");function zs(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(zs,"analysisStartedFrame");function js(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(js,"analysisCompleteFrame");function Ws(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Ws,"unknownFrame");function Gs(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 ee("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:Rm(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new ee("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(Gs,"createIdentityProvider");function Rm(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(Rm,"expiryMs");function io(){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(io,"newSessionId");function Sm(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(Sm,"authHeaders");function nr(e,t){return {...e,headers:{...Tm(e.headers),...Sm(t)}}}i(nr,"withAuthHeaders");function Tm(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(Tm,"stripAuthHeaders");async function Ks(e,t){if(t.mode==="anonymous")return t.transport.request(nr(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return E(oo())}let n=await t.transport.request(nr(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 E(oo())}let s=await t.transport.request(nr(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?E(oo(s.error.httpStatus)):s}i(Ks,"authedSend");function oo(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(oo,"authRejectedError");var qs=`
|
|
2
2
|
|
|
3
|
-
`,
|
|
3
|
+
`,Pm=1048576,km=z$1.record(z$1.string(),z$1.unknown()),xm=["emergency","schedule_soon","home_care"];async function*$r(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(qs,a);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+qs.length),a=0;let p=$s(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>Pm){yield fe({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=$s(s,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield fe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i($r,"parseSse");function $s(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=km.safeParse(o);return s.success?_m(s.data,r,t):null}i($s,"parseBlock");function _m(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return fe({code:ce(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ce(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Hs({conversationId:ce(e.conversation_id)??"",messageId:ce(e.message_id),title:ce(e.title),followUpQuestions:Am(e.follow_up_questions),citations:Ys(e.citations),citationStatus:ce(e.citation_status),urgencyLevel:Xs(e.urgency_level),urgencyReason:ce(e.urgency_reason),urgencyProvided:Im(e),resultId:ce(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return Us(ce(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return Vs(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=ce(e.delta)??ce(e.token)??"";return Bs(s,t,r)}return o==="analysis_started"?zs(ce(e.request_id),t,r):o==="analysis_complete"?js({resultId:ce(e.result_id),analysisType:ce(e.analysis_type),modelVersion:ce(e.model_version),confidence:wm(e.confidence),detections:Ys(e.detections),interpretation:ce(e.interpretation),lastEventId:t},r):Ws(e,t,r)}i(_m,"frameFromWire");function ce(e){return typeof e=="string"?e:null}i(ce,"asString");function wm(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(wm,"asNumber");function Xs(e){return typeof e=="string"&&xm.includes(e)?e:null}i(Xs,"asUrgency");function Im(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Xs(t)!==null}i(Im,"urgencySlotProvided");function Am(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Am,"asStringList");function Om(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Om,"isPlainObject");function Ys(e){return Array.isArray(e)?e.filter(Om):[]}i(Ys,"asMapList");var Fm="0.6.0",ao="react-native",Mm="2026-09-19",Yr="EVERFUR_API_BASE_URL";function or(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(or,"configFailure");function lo(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(lo,"checkPublishableKey");function Qs(e,t){let r=lo(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=Lm(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||Mm;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Fm,platform:t?.platform??ao,debug:e.debug===true})})}i(Qs,"tryResolveClientConfig");function Lm(e){let t=e?.trim(),r=t&&t.length>0?t:jm(Yr);return r?Hm(r):or("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Yr}. The SDK never ships a hardcoded host.`)}i(Lm,"tryResolveApiBaseUrl");function Zs(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(Zs,"buildBaseHeaders");var Dm=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Nm(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Nm,"hostOf");function Um(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Um,"isPrintableHost");function Vm(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Um(t)}i(Vm,"canEchoOrigin");function Bm(e,t){return `${e}://${t}`}i(Bm,"safeOrigin");function Hm(e){let t=e.trim(),r=Dm.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return or("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 or("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=Vm(t,o)?`: ${Bm(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&zm(o)))return n==="http"?or("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):or("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(Hm,"normalizeBaseUrl");function zm(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(zm,"isLoopbackHost");function jm(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(jm,"readEnv");var Wm=3e4,ra="x-request-id";async function*Js(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(Js,"fetchByteSource");function Gm(e){let t=new TextEncoder,r=qm(),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=ia(d),p=We(Me(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(vm,"eventSourceByteSource");async function*Em(e,t){try{yield*e;}finally{t();}}i(Em,"sourceWithCleanup");function Cm(){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(Cm,"createByteQueue");async function Rm(e,t){let r=t.fetchImpl??Ks(),n=qs(t.config.apiBaseUrl,e.path,e.query),o=$s(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=_m(bm),a=wm(s.signal,e.signal),l;try{l=await r(n,Ys({...e,signal:a},o));}catch(d){return E(ro(d))}finally{s.cancel();}let u=await Xs(l);return l.ok?L(u):E(Pm(l.status,u,Ws(l)))}i(Rm,"requestJson");function js(e){return {request:i(t=>Rm(t,e),"request"),stream:i((t,r)=>Sm(xm(t,r),e),"stream")}}i(js,"createHttpTransport");async function*Sm(e,t){let r=qs(t.config.apiBaseUrl,e.path,e.query),n=$s(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Tm(e,n));yield*zr(vm(l),()=>km(l));return}let o=t.fetchImpl??Ks(),s;try{s=await o(r,Ys(e,n));}catch(l){yield Hs("",true,ea(l));return}let a=Ws(s);if(!s.ok){let l=await Xs(s),u=Qs(l)??Gs(s.status),d=Js(l)||Be(Oe(u));yield Hs(u,d,Zs(l),a);return}if(s.body){yield*zr(Vs(s.body),a);return}yield*zr(Vs(null),a);}i(Sm,"streamFrames");function Tm(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Tm,"buildEventSourceInit");function Pm(e,t,r){let n=Qs(t),o=n?Oe(n):vs(e),s=Zs(t);return D(o,{httpStatus:e,...Js(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Bs(t)?{reasonCode:Bs(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Pm,"errorFromResponse");function ro(e){return D("internalError",{retryable:true,wireMessage:ea(e)})}i(ro,"networkError");function Ws(e){let t=e.headers.get(zs);return typeof t=="string"&&t.length>0?t:null}i(Ws,"requestIdOf");function km(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(zs);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(km,"eventSourceRequestId");function Gs(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(Gs,"statusToWireCode");function Hs(e,t,r,n=null){return de({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(Hs,"syntheticErrorFrame");function Ks(){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(Ks,"getGlobalFetch");function qs(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(qs,"buildUrl");function $s(e,t,r,n){let o={...Us(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i($s,"mergeHeaders");function Ys(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(Ys,"buildInit");function xm(e,t){return e.signal?e:{...e,signal:t}}i(xm,"withSignal");function _m(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(_m,"timeoutSignal");function wm(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(wm,"mergeAbortSignals");async function Xs(e){try{return await e.json()}catch{return null}}i(Xs,"safeJson");function Bs(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Bs,"extractReasonCode");function Qs(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Qs,"extractWireCode");function Zs(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Zs,"extractWireMessage");function Js(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Js,"extractRetryable");function ea(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(ea,"describeCause");var Im=3e4,Am=Yn*2,Om="idempotency-key",Fm=new Set(["POST","PUT","PATCH","DELETE"]),Mm=Object.freeze({onEvent(){}}),Lm=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Dm(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Dm,"seededIdempotencyKey");function xe(e){let t=e.observer??Mm,r=e.timers??Lm,n=e.rng??Math.random,o=e.sleep??((f,m)=>Xm(f,r,m)),s=e.maxAttempts??Zt,a=e.unaryTimeoutMs??Im,l=e.newIdempotencyKey??Um(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,y){let x=y?.maxAttempts,b=Math.max(1,x??s),C=y?.idempotent??Fm.has(m.method),_=y?.idempotencyKey===void 0?null:Dm(y.idempotencyKey),P=C?_??l():null,k=Nm(m,P),g=0;for(;;){let w=i(j=>Object.freeze({call:f,method:m.method,path:m.path,attempt:g,...P?{idempotencyKey:P}:{},...j}),"stamp");u(w({phase:"attempt"}));let O=$m(a,r),M=Ym(O.signal,m.signal),I;try{I=await Os({...k,signal:M.signal},e.auth);}catch(j){I=E(ro(j));}finally{M.dispose(),O.cancel();}if(I.ok)return u(w({phase:"settled",ok:true,reason:"ok"})),I;let v=I.error,T=Hm(v,g,{maxAttempts:b,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...x!==void 0?{perCallMaxAttempts:x}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),V={ok:false,code:v.code,reason:T.reason,...v.httpStatus!==void 0?{httpStatus:v.httpStatus}:{},...v.requestId!==void 0?{requestId:v.requestId}:{}};if(!T.retry)return u(w({phase:"settled",...V})),E(v);if(u(w({phase:"retry",...V,delayMs:T.delayMs})),await o(T.delayMs,m.signal),m.signal?.aborted===true)return u(w({phase:"settled",...V,reason:"aborted"})),E(v);g+=1;}}i(d,"send");async function c(f){return Jt(f,await qm(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 de({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 Nm(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==Om&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Nm,"assembleHeaders");function Um(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Um,"defaultIdempotencyKeyFactory");var Vm=10;function Hm(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Bm(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(Vm,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=zm(e,r.now);return u!==null?u>Am?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Vr(t,r.rng)}}i(Hm,"decideRetry");function Bm(e){let t=e.code==="unknown"?Oe(Km(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Bm,"throttleKind");function zm(e,t){let r=Wm(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=jm(e.raw);return n===null?null:Math.round(n*1e3)}i(zm,"retryOverrideMs");function jm(e){for(let t of no(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(jm,"findRetryAfterSeconds");function Wm(e){for(let t of no(e)){let r=t.resets_at,n=Gm(r);if(n!==null)return n}return null}i(Wm,"findResetsAt");function no(e){if(!ta(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];ta(n)&&t.push(n);}return t}i(no,"candidateScopes");function Gm(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(Gm,"parseInstantMs");function Km(e){for(let t of no(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Km,"rawWireCode");function ta(e){return typeof e=="object"&&e!==null}i(ta,"isRecord");async function qm(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(qm,"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 Ym(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(Ym,"mergeSignals");function Xm(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(Xm,"delayAbortable");var Wr=Object.freeze(["better","same","worse"]),io=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ra(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(ra,"invalid");function oo(){return E(D("internalError",{retryable:false}))}i(oo,"malformed");function na(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(na,"petPath");var ze=i(e=>typeof e=="string"?e:null,"str"),oa=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function ia(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&&Wr.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:oa(t.checkin_ask_count),checkinAnswerCount:oa(t.checkin_answer_count)})}i(ia,"caseFromWire");function sa(e){return {async list(t,r){let n=na(t);if(typeof n!="string")return E(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return E(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return oo();let a=s.map(ia);return a.every(l=>l!==null)?L(Object.freeze(a)):oo()},async checkin(t,r,n,o){let s=na(t);if(typeof s!="string")return E(s);if(typeof r!="string"||!io.test(r))return ra("case_id must be a UUID");if(!Wr.includes(n))return ra("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 E(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=ia(l.case);return u===null?oo():L(Object.freeze({case:u,ctaDeepLink:ze(l.cta_deep_link)}))}}}i(sa,"createCasesRepositoryOver");var aa=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var la=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Kr(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(Kr,"delayAbortable");function qr(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(qr,"mergeSignals");var so=class so{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?qr(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(so,"MediaStore");var Gr=so;function lo(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(lo,"makeUser");function uo(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(uo,"makeAssistant");function rr(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(rr,"stripPending");function ua(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(ua,"appendText");function co(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(co,"finalizeAssistant");function da(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(da,"freezeSnapshot");function U(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function po(e){let t=Oe(e.code);return D(t,{retryable:e.retryable||Ur(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(po,"errorFromFrame");function Fe(e){return de({code:Qm(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Fe,"synthErrorFrame");function Qm(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 Ze(e)}}i(Qm,"canonicalWireCode");function ca(e){let t=Array.isArray(e)?e:ao(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!ao(n))continue;let o=tr(n.category)??tr(n.title)??"",s=Zm(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(ca,"parsePromptCategories");function fo(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(fo,"flattenPrompts");function ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ao,"isPlainObject");function tr(e){return typeof e=="string"?e:null}i(tr,"asStr");function Zm(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(ao(r)){let n=tr(r.text)??tr(r.prompt)??tr(r.title);n!==null&&t.push(n);}return t}i(Zm,"asPromptTextList");function pa(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(pa,"defaultIdFactory");function fa(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(fa,"defaultIdempotencyFactory");var ya={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*ga(e,t,r,n){let o=e[Symbol.asyncIterator](),s=ma(t.overallMs,n),a=ma(t.idleMs,n),l=ty(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 ey();return}if(d.tag==="idle"||d.tag==="overall"){yield Jm();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(ga,"withWatchdog");function Jm(){return de({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Jm,"synthTimeoutFrame");function ey(){return de({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(ey,"synthStreamErrorFrame");function ma(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(ma,"deadline");function ty(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(ty,"abortPromise");var ry="checkin",ny=/^\d{4}-\d{2}-\d{2}$/,$r="watching";function ha(e){return e.status!=null&&e.status!==$r}i(ha,"isCheckinSettled");function ba(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(ba,"isLiveAskAnswered");function mo(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==ry||n===void 0||o===void 0||!io.test(n)||!ny.test(o)?null:{caseId:n,dueDay:o}}i(mo,"parseCheckinOrigin");function va(e){return mo(e)?.caseId??null}i(va,"parseCheckinOriginRef");function yo(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return E(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 E(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),L(r.length?`?${r.join("&")}`:"")}i(yo,"historyQuery");function ir(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(ir,"validConversationId");function or(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(or,"object");function Ea(e){return e==null||typeof e=="string"&&e.length>0&&!Re(e)}i(Ea,"cursor");function nr(){return E(D("internalError",{retryable:false}))}i(nr,"malformed");function Ca(e){let t=or(e);if(!t||!Array.isArray(t.conversations)||!Ea(t.next_cursor))return nr();let r=[];for(let n of t.conversations){let o=or(n);if(!o||typeof o.conversation_id!="string"||!ir(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return nr();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return nr();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(Ca,"mapConversationPage");function Ra(e){let t=or(e);if(!t||!Array.isArray(t.messages)||!Ea(t.next_cursor))return nr();let r=[],n=new Set;for(let o of t.messages){let s=or(o);if(!s||typeof s.message_id!="string"||!ir(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return nr();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"?va(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:oy(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:iy(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(Ra,"mapMessagePage");function oy(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(oy,"normalizeUrgency");function iy(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=or(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(iy,"historyCitations");var go=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Mt=4e3;var Lt=4e3;function Sa(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(Sa,"validateImageKeys");function bo(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(bo,"validateMessageText");function Ta(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ta,"urgencyTier");async function*sr(e){yield e;}i(sr,"singleFrameStream");async function*Pa(){}i(Pa,"emptyStream");var sy=6e4,ay=18e4,ly=24,uy=512,dy=false;function ka(e){return new vo(e)}i(ka,"createChatController");var Eo=class Eo extends Gr{constructor(r){super(da({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=sa(this.funnel),this.telemetry=r.telemetry??Br,this.errorPolicy=r.errorPolicy??Rs,this.timers=r.timers??ya,this.rng=r.rng??Math.random,this.newId=r.newId??pa(),this.makeIdempotencyKey=r.makeIdempotencyKey??fa(),this.budget={idleMs:r.budget?.idleMs??sy,overallMs:r.budget?.overallMs??ay};}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),()=>{}):sr(Fe(u))}let a=bo(r)??Sa(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),()=>{}):sr(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 sr(Fe(U("accessDenied",false)));let o=bo(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),sr(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):Pa()}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,lo(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?rr(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(fo(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=yo(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return E(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 E(U("accessDenied",false));if(!a.ok)return a;let l=Ca(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 E(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?L(n):E(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return E(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):E(l.error)}async markRead(r){if(this.disposed)return E(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?E(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)):E(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return E(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Re(r))return E(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!go.includes(n))return E(U("validationFailed",false,`feedback_type must be one of ${go.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>Mt)return E(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 E(U("accessDenied",false));if(!d.ok)return E(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 E(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return E(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 E(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(!ir(r))return E(U("validationFailed",false));let o=yo(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return E(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?E(U("accessDenied",false)):a.ok?Ra(a.value):a}async resumeConversation(r){if(this.disposed)return E(U("accessDenied",false));if(!ir(r))return E(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 E(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===$r).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||ba({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:m?$r: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 E(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 E(U("accessDenied",false));if(!o.ok)return E(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 E(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 E(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 E(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?E(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 E(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?E(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 E(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?E(U("internalError",true)):L(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return E(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Re(o))return E(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?E(U("accessDenied",false)):a.ok?L(ca(a.value)):E(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=qr(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,lo(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=qr(o.signal,p.signal),m=null;try{let b;try{b=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let _=this.authRejected();yield*this.emitTerminal(r,_,Fe(_));return}if(o.signal.aborted||!this.alive(o.epoch))return;let C=this.funnel.stream("chat.send",b,f);for await(let _ of ga(C,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(_.kind==="error"&&_.terminal){m=_;break}if(this.applyFrame(_,r),yield _,_.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 b=U("streamIncomplete",!0);yield*this.emitTerminal(r,b,Fe(b));return}let y=Oe(m.code);if(y==="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 C=this.authRejected();yield*this.emitTerminal(r,C,m);return}this.patch({reconnecting:!0});continue}if(y==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let b=this.authRejected();yield*this.emitTerminal(r,b,m);return}if(y==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,po(m),m);return}if(Es(y)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let x=m.retryable&&Ur(y,!0);if(dy&&x&&s+1<this.errorPolicy.maxAttempts(y));yield*this.emitTerminal(r,po(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 Ze(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?rr(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,uo(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=uy){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);},ly);}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?ua(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?co(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?rr(d):d),co(uo(l,"",this.stamp()),r)];}let a=fo([{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=Ta(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?rr(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(Eo,"ChatControllerImpl");var vo=Eo;async function wa(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(k=>k.ok?L(o):k):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,y]=await Promise.all([p,f]),x=null;if(m.ok)x=m.value,s.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let k=m.error;c=k,xa(k)?(l=true,d=k):(_a(k)&&(a=true),u=true);}let b=[];y.ok?b=y.value:C(y.error);function C(k){xa(k)?(l=true,d===null&&(d=k)):_a(k)&&(a=true);}i(C,"recordAuthSignals");let _=d!==null?d.displayMessage:null;return Object.freeze({conversationId:x,petRef:n,suggestedPrompts:b,error:_,warning:_===null&&x===null&&u?cy:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(wa,"bootstrapChat");var cy="Chat is ready. Your first message will start the conversation.";function xa(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(xa,"isUnauthorized");function _a(e){return e.httpStatus===403||e.code==="accessDenied"}i(_a,"isForbidden");var Co=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Ia(e){return e!==Co}i(Ia,"isUploadTransportAvailable");var py=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Yr=10*1024*1024,Xr=5,ar=120,fy="/widget/v1/uploads/initiate";function my(e){return typeof e=="string"&&py.includes(e.trim().toLowerCase())}i(my,"isAttachmentMime");function Ro(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<=ar)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,ar);let n=t.slice(r);return n.length>=ar?t.slice(0,ar):`${t.slice(0,r).slice(0,ar-n.length)}${n}`}i(Ro,"sanitizeFilename");function So(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(So,"formatBytes");var lr=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 yy(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(yy,"attachmentSize");function gy(e){let t=Ro(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!my(r))return _e(oe("unsupported_type",false,t));let n=yy(e);return n===null?_e(oe("unknown",false,t)):n>Yr?_e(oe("too_large",false,t,{sizeBytes:n})):lr(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(gy,"validateAttachment");function hy(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)??Yr,s3_key:a,purpose:r(t.purpose)})}i(hy,"parsePolicy");function by(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(by,"initiateFailure");async function vy(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:fy,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return _e(by(n.error,t.filename));let o=hy(n.value);return o===null?_e(oe("server",false,t.filename)):lr(o)}i(vy,"initiateAttachmentUpload");async function Ey(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}:{}}),lr(void 0)}catch{return o()?_e(oe("cancelled",true,r.filename)):_e(oe("server",true,r.filename))}}i(Ey,"uploadAttachmentBytes");var Cy=2,Ry=3,Sy=Object.freeze([1e3,2e3,4e3]),Aa=0;function Ty(){return Aa+=1,`attachment-${Aa}`}i(Ty,"defaultNewId");function Oa(e){let t=Math.max(1,e.concurrency??Cy),r=Math.max(1,e.maxAttempts??Ry),n=e.backoffMs??Sy,o=Math.max(1,e.maxPerMessage??Xr),s=e.timers??la,a=e.newId??Ty,l=Ia(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),y=false,x=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(g=>{let w=u.get(g);return w===void 0?[]:[w.state]}))});for(let g of f)g();},"publish"),b=i((g,w)=>{g.state=Object.freeze({...g.state,...w}),x();},"patch"),C=i(()=>{for(;!y&&p.size<t&&c.length>0;){let g=c.shift(),w=u.get(g);w!==void 0&&(p.add(g),_(w).finally(()=>{p.delete(g),C();}));}},"pump"),_=i(async g=>{let{attachment:w}=g;for(;g.attempts<r;){if(y||g.controller.signal.aborted)return;g.attempts+=1;let O=g.controller.signal;b(g,{status:"uploading",error:null,progress:0});let M=await vy(e.funnel,w,{signal:O});if(y||O.aborted)return;let I;if(!M.ok)I=_e(M.error);else {let j=await Ey(e.transport,M.value,w,{signal:O,onProgress:i(W=>{!O.aborted&&g.state.status==="uploading"&&b(g,{progress:Py(W)});},"onProgress")});if(y||O.aborted)return;I=j.ok?lr(M.value.s3_key):_e(j.error);}if(I.ok){b(g,{status:"uploaded",s3Key:I.value,error:null,progress:1});return}let v=I.error,T=v.retryable&&g.attempts<r;if(b(g,{status:T?"uploading":"failed",error:v,progress:0}),!T)return;let V=n[Math.min(g.attempts-1,n.length-1)]??0;await Kr(V,O,s);}},"run"),P=i(g=>{c.push(g.state.id),C();},"enqueue"),k={available:l,subscribe(g){return f.add(g),()=>{f.delete(g);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(g=>g.status==="uploading")},get s3Keys(){return m.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[])},add(g){let w=gy(g);if(!w.ok)return w;if(y||d.length>=o)return _e(oe("too_many",false,w.value.filename));let O=a(),M={attachment:w.value,controller:new AbortController,attempts:0,state:Object.freeze({id:O,filename:w.value.filename,previewUri:g.uri,contentType:w.value.contentType,sizeBytes:w.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(O,M),d.push(O),x(),P(M),lr(M.state)},retry(g){let w=u.get(g);w===void 0||y||w.state.status!=="failed"||(w.controller=new AbortController,w.attempts=0,b(w,{status:"uploading",error:null,progress:0,s3Key:null}),P(w));},remove(g){let w=u.get(g);if(w===void 0)return;w.controller.abort(),u.delete(g);let O=d.indexOf(g);O>=0&&d.splice(O,1);let M=c.indexOf(g);M>=0&&c.splice(M,1),x();},clear(){for(let g of [...d])k.remove(g);},dispose(){y=true;for(let g of u.values())g.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return k}i(Oa,"createAttachmentQueue");function Py(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Py,"clamp");var Fa=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function ur(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Fa,t)?Fa[t]:null}i(ur,"canonicalPetSpecies");var Ma=50,ky=128,To=120,La=120,xy=2e3,Da=120,_y=80,Va=new Set(["male","female","unknown"]),Ha=new Set(["day","month","year"]),Ba=new Set(["low","medium","high","athletic"]),za=new Set(["indoor","outdoor","both"]),ja=new Set(["mild","moderate","severe"]),wy=/^(\d{4})-(\d{2})-(\d{2})$/,Wa=[["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"]],Ga=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Wa,...Ga].map(([e])=>e));function Iy(e){let t=wy.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(Iy,"isRealDate");var cr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),Ay=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Zr=i((e,t)=>typeof t=="string"&&Iy(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=at(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),Oy={sex:cr(Va),spayedNeutered:Ay,birthDate:Zr,birthDatePrecision:cr(Ha),activityLevel:cr(Ba),indoorOutdoor:cr(za),foodBrand:Me(Da),foodType:Me(Da),microchipId:Me(_y)},Po=["ref","ref",false,Me(ky,{required:true,trimmed:true})],ko=["notes","notes",false,Me(xy,{trimmed:true})],Na=[Po,["name","name",true,Me(To,{required:true,trimmed:true})],["dose","dose",false,Me(La,{trimmed:true})],["frequency","frequency",false,Me(La,{trimmed:true})],["startDate","start_date",false,Zr],["endDate","end_date",false,Zr],ko],Fy={allergies:[Po,["allergen","allergen",true,Me(To,{required:true,trimmed:true})],["severity","severity",false,cr(ja)],ko],medications:Na,supplements:Na,conditions:[Po,["conditionName","condition_name",true,Me(To,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Zr],ko]};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 Ly(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>Ma)return {error:`${e} has ${t.length} items; the server accepts at most ${Ma}`};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(Ly,"listToWire");function Ka(e,t){let r=e,n={};for(let[a,l]of Wa){let u=r[a];if(u!==void 0){if(u!==null){let d=Oy[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 Ga){let u=r[a];if(u===void 0)continue;let d=Ly(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&ur(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(Ka,"petHealthToWire");var ee=i(e=>typeof e=="string"?e:null,"str"),dr=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),Dy=i(e=>typeof e=="boolean"?e:null,"bool");function Qr(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(Qr,"itemsFromWire");function Ua(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(Ua,"medicationFromWire");function qa(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:dr(Va,e.sex),spayedNeutered:Dy(e.spayed_neutered),birthDate:ee(e.birth_date),birthDatePrecision:dr(Ha,e.birth_date_precision),activityLevel:dr(Ba,e.activity_level),indoorOutdoor:dr(za,e.indoor_outdoor),foodBrand:ee(e.food_brand),foodType:ee(e.food_type),microchipId:ee(e.microchip_id),allergies:Qr(e.allergies,r=>{let n=ee(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:ee(r.ref),allergen:n,severity:dr(ja,r.severity),notes:ee(r.notes)})}),medications:Qr(e.medications,Ua),supplements:Qr(e.supplements,Ua),conditions:Qr(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(qa,"petHealthFromWire");var Xa=100,Qa=50,Za=100,Ja=50,el=500,Ny=128,Uy=6e4;function De(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(De,"invalid");function lt(e,t,r){if(typeof t!="string")return De(`${e} must be a string`);let n=at(t);return n<=r?null:De(`${e} is ${n} characters; the server accepts at most ${r}`)}i(lt,"checkString");function Jr(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(Jr,"outOfRange");function $a(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=[lt("pet_ref",e,Ny)];return t?.name!==void 0&&r.push(lt("name",t.name,Xa)),t?.species!==void 0&&r.push(lt("species",t.species,Qa)),t?.breed!==void 0&&r.push(lt("breed",t.breed,Za)),t?.ageYears!==void 0&&r.push(Jr("age_years",t.ageYears,Ja)),t?.weightKg!==void 0&&r.push(Jr("weight_kg",t.weightKg,el)),r.find(n=>n!==null)??null}i($a,"validate");function tl(e,t){let r=Ka(e,t);return "error"in r?{error:De(r.error)}:r}i(tl,"healthToWire");function Vy(e){if(typeof e!="object"||e===null)return {error:De("patch must be an object")};let t=e,r=[["name","name",s=>lt("name",s,Xa)],["species","species",s=>lt("species",s,Qa)],["breed","breed",s=>lt("breed",s,Za)],["ageYears","age_years",s=>Jr("age_years",s,Ja)],["weightKg","weight_kg",s=>Jr("weight_kg",s,el)]],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=tl(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(Vy,"patchToWire");function Hy(e){if(e==null)return {body:{}};let t=tl(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(Hy,"toWire");var Le=i(e=>typeof e=="string"?e:null,"str"),en=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Ya(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:en(r.age_years),weightKg:en(r.weight_kg)})}i(Ya,"fromWire");function rl(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:en(t.age_years),weightKg:en(t.weight_kg),updatedAt:Le(t.updated_at)})}i(rl,"widgetPetFromWire");function By(e){let t=rl(e);return t===null?null:Object.freeze({...t,...qa(e)})}i(By,"widgetPetProfileFromWire");function zy(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=rl(r);return n===null?[]:[n]}))}i(zy,"petListFromWire");function Je(e){return jy(xe({auth:e}),xe({auth:e,unaryTimeoutMs:Uy}))}i(Je,"createPetsRepository");function jy(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>$a(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(zy(s.value)):E(s.error)},async registerPet(o,s,a){let l=$a(o,s);if(l!==null)return E(l);let u=Hy(s);if("error"in u)return E(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(Ya(p.value,o)):E(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return E(l);let u=Vy(s);if("error"in u)return E(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?L(Ya(d.value,o)):E(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return E(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return E(l.error);let u=By(l.value);return u===null?E(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 E(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?L(void 0):E(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):E(s.error)}}}i(jy,"createPetsRepositoryOver");var _o=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 Wy(e){return _o[e]}i(Wy,"requires");function nl(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(_o))for(let a of _o[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(nl,"deniedDecisionsFor");function ol(e,t,r){let n=Wy(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 xo({name:e,enabled:false,isPending:true,limits:{}});let s=Gy(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?xo({name:e,enabled:true,isPending:false,limits:s}):xo({name:e,enabled:false,isPending:false,limits:s,disabled:Ky(n,o)})}i(ol,"decideCapability");function Gy(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(Gy,"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:Ft("accessDenied"),level:"user_entitlement",recoverable:false})}i(Ky,"disabledFor");function xo(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(xo,"freezeDecision");function me(e){let t=ie(e);return t===null?null:$y(t)}i(me,"parseColor");function ie(e){if(typeof e=="number")return il(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return wo(t.slice(1));if(t.toLowerCase().startsWith("0x"))return wo(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return qy(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=wo(t);if(r!==null)return r}return /^\d+$/.test(t)?il(Number.parseInt(t,10)):null}i(ie,"toRgba");function wo(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Io(t[0]),g:Io(t[1]),b:Io(t[2]),a:1};if(t.length===6)return {r:ut(t,0),g:ut(t,2),b:ut(t,4),a:1};if(t.length===8){let r=ut(t,0);return {r:ut(t,2),g:ut(t,4),b:ut(t,6),a:r/255}}return null}i(wo,"fromHex");function qy(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=Ao(Number(n[0])),s=Ao(Number(n[1])),a=Ao(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(qy,"fromRgbFunc");function il(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(il,"argbIntToRgba");function ut(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ut,"byte");function Io(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Io,"dup");function Ao(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Ao,"clampByte");function $y(e){if(e.a>=1)return ct(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 ct(e,t,r){return `#${Oo(e)}${Oo(t)}${Oo(r)}`.toUpperCase()}i(ct,"rgbToHex");function Oo(e){return e.toString(16).padStart(2,"0")}i(Oo,"hex2");var Yy="#111111",Dt="#FFFFFF",tn="#000000";function al(e){let t=ie(e);if(t===null)return Dt;let r=dt(t),n=dt({r:17,g:17,b:17}),o=dt({r:255,g:255,b:255});return Lo(r,o)>=Lo(r,n)?Dt:Yy}i(al,"readableOn");function pr(e,t){let r=al(e);return ue(r,e)>=t?r:ue(Dt,e)>=ue(tn,e)?Dt:tn}i(pr,"legibleOn");function fr(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Dt)>=t(tn)?Dt:tn}i(fr,"poleForGrounds");function dt(e){let t=Fo(e.r/255),r=Fo(e.g/255),n=Fo(e.b/255);return .2126*t+.7152*r+.0722*n}i(dt,"relativeLuminance");function Fo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(Fo,"linearize");function Lo(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(Lo,"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:ll(r,o);return Lo(dt(s),dt(o))}i(ue,"contrastRatio");function ll(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(ll,"composite");function pt(e,t){let r=ie(e),n=ie(t);if(r===null||n===null)return null;let o=r.a>=1?r:ll(r,{...n});return ct(o.r,o.g,o.b)}i(pt,"flattenOnto");function ul(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(ul,"withAlpha");var sl=.05;function et(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=pt(e,o),l=a===null?null:ie(a),u=ie(r);if(l===null||u===null)return r;for(let d=1;d<1/sl;d+=1){let c=d*sl,p=i((m,y)=>Math.round(m+(y-m)*c),"mix"),f=ct(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(et,"pushToContrast");function dl(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(dl,"rgbToHsl");function Do(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:Mo(c+l),g:Mo(p+l),b:Mo(f+l)}}i(Do,"hslToRgb");function Mo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(Mo,"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 nn=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),pl={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},fl={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},cl={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Xy={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Qy={regular:"400",medium:"500",bold:"700"},Zy={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},No=0,ft="System",Ne="monospace",Jy=["content","heading","control","compact","badge"];function eg(e){let t={};for(let r of Jy)t[r]=e;return t}i(eg,"authoredTierSizes");function ml(){return {family:ft,mono:Ne,fontUrl:null,families:{regular:ft,medium:ft,bold:ft,mono:Ne,monoMedium:Ne,monoBold:Ne},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:cl,tierSizes:eg(cl),lineHeight:Xy,weight:Qy,letterSpacing:Zy,scale:1,maxScale:No,scaleCaps:nn}}i(ml,"baseType");var yl={},mt=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function rn(e){return `cubic-bezier(${e.join(", ")})`}i(rn,"cssCubicBezier");var gl={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:rn(mt.standard),emphasized:rn(mt.emphasized),exit:rn(mt.exit)},reducedMotion:false},tg={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)"},yt=je({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:tg,space:pl,radius:fl,type:ml(),motion:gl,slots:yl}),rg={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)"},on=je({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:rg,space:pl,radius:fl,type:ml(),motion:gl,slots:yl});var ng="#23272C",hl=4.5,og=.6,Uo=.9,ig=.02,sg="#FFFFFF",ag="#111111";function lg(e){return ue(e,ng)>=hl&&Math.max(ue(e,sg),ue(e,ag))>=hl}i(lg,"readsOnDark");function El(e){let t=ie(e);if(t===null)return null;let{h:r,s:n,l:o}=dl(t.r,t.g,t.b),s=Math.min(Math.max(o,og),Uo);for(let l=0;;l+=1){let u=s+l*ig;if(u>Uo)break;let d=Do({h:r,s:n,l:u}),c=ct(d.r,d.g,d.b);if(lg(c))return c}let a=Do({h:r,s:n,l:Uo});return ct(a.r,a.g,a.b)}i(El,"deriveDarkVariant");var ug=7,bl=.05,dg="#000000",cg="#FFFFFF";function pg(e,t,r,n){let o=pt(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/bl;l+=1){let u=l*bl,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=ct(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(pg,"pushContrast");function fg(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=vl(n);for(let s of r){let a=vl(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(fg,"hardestGround");function vl(e){let t=ie(e);return t===null?0:dt(t)}i(vl,"luminanceOf");function tt(e,t){return pt(e,t)??me(e)??t}i(tt,"solid");function Cl(e){let t=e.color,r=e.brightness==="dark",n=r?cg:dg,o=fg(t,r),s=i(l=>pg(l,o,n,ug),"text"),a={...t,brandSoft:tt(t.brandSoft,t.surface),brandSofter:tt(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:tt(t.badgeBgPositive,t.surface),badgeBgCaution:tt(t.badgeBgCaution,t.surface),badgeBgCritical:tt(t.badgeBgCritical,t.surface),badgeBgNeutral:tt(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:tt(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:tt(t.checkupCardConcernBg,t.surface)};return je({...e,highContrast:true,color:a})}i(Cl,"deriveHighContrast");var gt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),mg=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),we=4.5,yg=Object.freeze({});function gg(e){return gt.includes(e)}i(gg,"isSlotName");function hg(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(hg,"parseRadius");function Rl(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(!gg(n)||o===null||typeof o!="object")continue;let s=bg(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(Rl,"parseThemeSlots");function sn(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(sn,"pick");function bg(e){let t={},r=me(sn(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=me(sn(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=hg(sn(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=me(sn(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(bg,"parseSlot");function Sl(e,t){return t===null||Object.keys(t).length===0?e??yg:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(Sl,"mergeThemeSlots");var Vo=3;function vg(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>pt(e,r)??r)}i(vg,"seatsOf");function Eg(e,t){let r=fr(e);return e.every(n=>ue(r,n)>=t)}i(Eg,"someInkReads");function Cg(e,t){let r=t[0];return r===void 0?null:pt(e,r)}i(Cg,"collapseUnsatisfiableFill");function Rg(e){let t=pr(e[0],we);return e.every(r=>ue(t,r)>=we)?t:fr(e)}i(Rg,"inkFor");function Tl(e,t){let r=false,n={};for(let o of gt){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=vg(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!Eg(u,we)){let p=Cg(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=Rg(u),c=true);else if(p!==void 0){let f=et(p,u,fr(u),we);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=et(s.borderColor,u,fr(u),Vo);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(Tl,"guardSlotContrast");var xl=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"]),mr="slots.",_l=Object.freeze([1,2]);function an(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(an,"isEmptyBranding");function wl(e){let t=e?.schemaVersion??null;return t===null||_l.includes(t)}i(wl,"isKnownBrandingSchema");function Il(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(Il,"lockedFieldsOf");function Sg(e){return e==="hide_powered_by"||xl.includes(e)?true:e.startsWith(mr)&>.includes(e.slice(mr.length))}i(Sg,"isThemeLockName");function We(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:ht($(t,"display_name","displayName")),logoUrl:ht($(t,"logo_url","logoUrl")),primaryColor:me($(t,"primary_color","primaryColor")),accentColor:me($(t,"accent_color","accentColor")),brightness:xg($(t,"brightness","color_scheme","colorScheme")),fontFamily:ht($(t,"font_family","fontFamily")),fontUrl:ht($(t,"font_url","fontUrl")),fonts:Pl($(t,"fonts")),fontUrls:Pl($(t,"font_urls","fontUrls")),placeholder:ht($(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Tg($(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:me($(t,"primary_color_dark","primaryColorDark")),accentColorDark:me($(t,"accent_color_dark","accentColorDark")),surfaceStyle:kl($(t,"surface_style","surfaceStyle"),Pg),radiusScale:kl($(t,"radius_scale","radiusScale"),kg),logoUrlDark:ht($(t,"logo_url_dark","logoUrlDark")),slots:Rl($(t,"slots")),accessibilityMaxFontScale:wg($(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Ag($(t,"locked_fields","lockedFields")),schemaVersion:Ig($(t,"schema_version","schemaVersion"))};return an(r)?null:Object.freeze(r)}i(We,"parseClientBranding");function Tg(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(Tg,"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 ht(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(ht,"parseNonEmptyString");var yr=["regular","medium","bold","mono","monoMedium","monoBold"];function Pl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of yr){let o=ht($(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(Pl,"parseFaceMap");var Pg=["white","cream","subtle"],kg=["sharp","default","round"];function kl(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(kl,"parseEnum");function xg(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(xg,"parseBrightness");function Al(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(Al,"parseNumber");var _g=1,Ol=3.1;function wg(e){let t=Al(e);return t===null?null:t<=0?0:Math.min(Ol,Math.max(_g,t))}i(wg,"parseMaxFontScale");function Ig(e){if(e==null)return null;let t=Al(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(Ig,"parseSchemaVersion");function Ho(e){let t=e.trim();return t.startsWith(mr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Ho,"toWireName");function Ag(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Ho(r);Sg(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(Ag,"parseLockedFields");function Bo(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Bo,"hardenHttpsUrl");function Fl(e,t){if(t===null||an(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?on:yt:e,n=r.brightness==="dark"?on:yt,o=r.brightness==="dark",s=o?t.primaryColorDark??Ml(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??Ml(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&Dg(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?ie(c):null,f=i(x=>Math.round(x+(255-x)*.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?Ng(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,...Lg(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:Sl(r.slots,t.slots??null)};return je(y)}i(Fl,"withServerBranding");var Og={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 zo(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(zo,"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 yr){let u=Og[l].map(p=>r[p]).find(p=>p!==void 0),d=zo(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 Ml(e){return e===null?null:El(e)}i(Ml,"darkVariantOf");function Lg(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(Lg,"surfaceOf");function Ll(e,t){return e==null?false:me(e)===me(t)}i(Ll,"sameColor");function Dg(e,t,r,n){return Ll(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Ll(e.primaryColor,yt.color.primary)}i(Dg,"isCompiledPrimary");function Ng(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(Ng,"compiledBrandFamily");var Ug={sharp:.5,default:1,round:1.5};function Vg(e,t,r){if(e===null)return t;let n=Ug[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 Hg="Everfur",Bg=.5;function jo(e){let t=e?.branding??null,r=wl(t)?t:null,n=Kg(e?.clientOverride??null,Il(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=Fl((s==="auto"?o:s)==="dark"?on:yt,Dl(r)),d=Fl(u,Dl(n));return oh(d,e)}i(jo,"resolveTheme");function zg(e,t,r){return jo({...r,branding:We(t),clientOverride:We(e)})}i(zg,"previewTheme");function jg(e){return e==="placeholder"?"chat_placeholder":Ho(e)}i(jg,"wireNameOf");var Wg={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Gg(e,t){return t.has(jg(e))?true:(Wg[e]??[]).some(r=>t.has(r))}i(Gg,"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&&(Gg(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 gt){let d=o[u];d!==void 0&&(t.has(`${mr}${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 an(s)?null:s}i(Kg,"withoutFields");function Dl(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(Dl,"withoutBrightness");function qg(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(qg,"scaledSizes");function $g(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Bg,e)}i($g,"effectiveScale");var Nl=["content","heading","control","compact","badge"];function Yg(e){if(!(e>0))return nn;let t={};for(let r of Nl){let n=nn[r];t[r]=n===0?0:Math.min(n,e);}return t}i(Yg,"tierCaps");function Xg(e,t){return t>0?Math.min(e,t):e}i(Xg,"capped");function Qg(e,t,r,n){let o={};for(let s of Nl)o[s]=n?qg(e,Xg(t,r[s])):e;return o}i(Qg,"sizesByTier");function Zg(e){return e==="dark"?"#FFFFFF":"#000000"}i(Zg,"inkPole");function Jg(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(Jg,"textGrounds");function eh(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(eh,"controlGrounds");function Ul(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Ul,"linkGrounds");function th(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:Ul(e)}}i(th,"slotGrounds");function rh(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(rh,"registration");function nh(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 yr)!(o[a]===ft||o[a]===Ne)&&r!==void 0&&rh(r,o[a])===false&&(o[a]=zo(a)?Ne:ft,s[a]=false),n!==null&&zo(a)&&o[a]===Ne&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(nh,"platformFaces");function oh(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?Hg:e.meta.displayName,s=Bo(e.meta.logoUrl),a={};for(let P of yr){let k=e.type.fontUrls[P];k!==void 0&&(a[P]=Bo(k));}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:No,p=$g(t?.textScale),f=Yg(c),m=Qg(e.type.size,p,f,t?.scaleTypeSizes===true),y=e.color,x=Zg(e.brightness),b=Jg(y),C={...y,primary:r,accent:n,onPrimary:pr(r,we),onAccent:pr(n,we),brandInk:et(y.brandInk,b,x,we),linkInk:et(e.slots.link?.textColor??n,Ul(y),x,we),text:{...y.text,secondary:et(y.text.secondary,b,x,we)},brandBorderStrong:et(y.brandBorderStrong,eh(y),x,Vo)},_={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:s,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:C,space:e.space,radius:e.radius,type:{...e.type,...nh(e.type,t),fontUrl:l,fontUrls:a,size:m.content,tierSizes:m,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:Tl(e.slots,th(C))};return t?.highContrast===true?Cl(je(_)):je(_)}i(oh,"finalize");var Vl="/widget/v1/entitlements",ih=304,sh=Object.freeze({kind:"notModified"});async function Bl(e,t={},r=xe({auth:e})){let n=await r.send("entitlements.fetch",lh(t));return n.ok?uh(n.value):n.error.httpStatus===ih?sh:{kind:"failed",error:n.error}}i(Bl,"fetchEntitlements");var ah=64;function lh(e){let t={};return Wo(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=ah?{method:"GET",path:Vl,headers:t,query:{region:e.region}}:{method:"GET",path:Vl,headers:t}}i(lh,"buildRequest");function uh(e){if(e===null||typeof e!="object"||!Wo(e.revision))return Hl();let t=typeof e.region=="string"?e.region:"",r=Wo(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:ch(e.capabilities),branding:dh(e),livemode:e.livemode!==false})}i(uh,"parseUpdated");function dh(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(dh,"parseBranding");function ch(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))ph(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(ch,"mapCapabilities");function ph(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(ph,"isEnabled");function Hl(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Hl,"malformed");function Wo(e){return typeof e=="number"&&Number.isFinite(e)}i(Wo,"isFiniteNumber");var fh=30;function zl(e){let t=e.scheduler??mh,r=e.resolve??Bl,n=Math.max(1,e.floorSeconds??fh),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(C=>{l||!a||(c=Math.max(n,C),u=t.set(()=>{u=null,b();},c*1e3));},"schedule"),y=null,x=i(async()=>{if(l)return null;let C=p;e.onFetch?.();let _=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},P;try{P=await r(e.authFor(),_);}catch(k){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:yh(k)}),!l&&C===p&&(e.onSettled?.(),m(s())),null}if(l||C!==p)return null;switch(P.kind){case "updated":d=P.revision,e.update(P.decisions,P.branding??null,P.livemode!==false),m(P.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:P.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),P},"tick"),b=i(()=>{let C=x().finally(()=>{y===C&&(y=null);});return y=C,C},"run");return {start(){a||l||(a=true,b());},prime(){return l?Promise.resolve(null):y??b()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),b());}}}i(zl,"createEntitlementPoller");var mh={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function yh(e){return e instanceof Error?e.message:"poll failed"}i(yh,"describe");var jl="everfur.notifications.device";var gh=3e3,Wl=Object.freeze([jl]);function Gl(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();},gh);u.then(p,p);})}i(Gl,"startBeforeLogoutHooks");function Kl(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(Kl,"graceAuth");async function ql(e,t){if(Wl.length===0)return;let r=await Promise.allSettled(Wl.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(ql,"sweepPerUserKv");function hh(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(hh,"compiledDefaultDecisions");function Go(e=hh){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,...o.livemode===false?{livemode:false}:{}}),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(Go,"createEntitlementStore");function Ko(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Ko,"notConfiguredError");function $l(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 Ns(r,t===void 0?void 0:{platform:t})}i($l,"tryResolveClient");function Yl(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Yl,"guardTelemetry");var bh=Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${jr} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Xl(e,t,r=eo){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. `+bh[r]);}i(Xl,"reportConfigFailure");function qo(e){return Object.freeze({request(){return Promise.resolve(E(Ko(e)))},stream(t,r){let n=de({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(qo,"refusingTransport");function Ql(){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(Ql,"createInMemoryKv");var Zl=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function tu(e,t){return new Yo(e,t)}i(tu,"createEverfurRuntime");var vh=6e4,Xo=class Xo{constructor(t,r){this.sessionId=Zn();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?Yl(n.telemetry):Br;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=to(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=qo(s);else if(n.transport!==void 0)l=n.transport;else {let c=$l(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=js({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=qo(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&Xl(s,this.telemetry,r?.platform),this.errorPolicy=n.errorPolicy,this.camera=n.camera??Ss,this.upload=n.upload??aa,this.uploadTransport=n.uploadTransport??Co,this.imageCache=n.imageCache??Zl,this.kv=n.storage??Ql(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?Go():Go(()=>nl("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",$o(c),()=>this.buildChatController(c),Jl),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${$o(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=As(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-vh,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 zl({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n,o)=>this.updateEntitlements({decisions:r,isPending:false,branding:n,...o===false?{livemode:o}:{}}),"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=ka({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=wa(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=Zn(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await ql(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 Gl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Kl({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?E(eu(t)):r(Je(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?eu("prepare"):n===null?null:Ko(n),s=this.identity,[a,l,u]=await Promise.all([o?E(o):s===null?L(void 0):s.currentToken().then(()=>L(void 0),()=>E(D("authRejected",{retryable:false}))),o?E(o):this.primeEntitlements(),t===null?void 0:o?E(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"?E(t.error):L(void 0):E(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",$o(r),()=>this.buildChatController(r),Jl,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?E(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(Xo,"EverfurRuntimeImpl");var Yo=Xo;function $o(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i($o,"chatScopeKey");function Jl(e){e.dispose();}i(Jl,"disposeChat");function eu(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(eu,"disposedError");var ru=Symbol.for("@everfur/sdk#EverfurContext@v1"),nu=globalThis,ln=nu[ru]??(nu[ru]=createContext(null));ln.displayName??="EverfurContext";function Y(){let e=useContext(ln);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 ou(){return Y().handle}i(ou,"useEverfur");var iu=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),su=globalThis,gr=su[iu]??(su[iu]=createContext(yt));gr.displayName??="EverfurThemeContext";function F(){return useContext(gr)}i(F,"useEverfurTheme");function un(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?kh(e.clientTheme):"",f=useMemo(()=>e.clientTheme?We(e.clientTheme):null,[p]),m=n.branding??null,y=useMemo(()=>jo({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(gr.Provider,{value:y},e.children)}i(un,"EverfurThemeProviderCore");function kh(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(kh,"stableKey");function cu(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),x=r?.userRef??null;y.current!==x&&(y.current!==void 0&&(m.current=null),y.current=x);let b=m.current!==null?m.current.user:r??null,C=useRef(null),_=useRef(void 0),P=n??null;_.current!==P&&(_.current!==void 0&&(C.current=null),_.current=P);let k=C.current!==null?C.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:tu({config:l.withDefaults?l.withDefaults(t):t,user:b,activePet:k,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let g=d.current.runtime,w=useRef(null);useEffect(()=>{let T=d.current?.runtime;T===void 0||!T.isDisposed||w.current!==T&&(w.current=T,f());}),useEffect(()=>{let T=c.current;T!==null&&(c.current=null,T.dispose());});let O=b?.userRef??null;useLayoutEffect(()=>{g.setUser(b);},[g,O]),useLayoutEffect(()=>{g.setActivePet(k);},[g,k]),useEffect(()=>()=>g.dispose(),[g]),useEffect(()=>{s==="onMount"&&g.prepare(k===null?{}:{petRef:k});},[g,s,O,k]);let M=useMemo(()=>({setUser:i(T=>{m.current={user:T},g.setUser(T),f();},"setUser"),setActivePet:i(T=>{C.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(()=>{m.current={user:null};let T=g.logout();return f(),T},"logout")}),[g,f]),I=useMemo(()=>({runtime:g,handle:M,userRef:O,activePet:k,scopeEpoch:g.scopeEpoch}),[g,M,O,k,p]),v=createElement(un,{clientTheme:o??null,seams:l.theme,children:a});return createElement(ln.Provider,{value:I},l.wrap?l.wrap(v):v)}i(cu,"EverfurProviderCore");var wh=2;function Ih(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<wh)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(Ih,"readEventSourceResponseHeader");function pu(){let e=_h;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=>Ih(n,o),"getResponseHeader")})}}i(pu,"createRnEventSourceFactory");function Mh(){let e=useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(Mh,"useRnColorScheme");function Lh(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Lh,"isThenable");function Dh(){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(Dh,"useRnReducedMotion");function yu(){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(yu,"readFontScale");function Nh(e){let t=Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(Dimensions,"change",e);return ()=>r?.remove?.()}i(Nh,"subscribeFontScale");function Uh(){return useSyncExternalStore(Nh,yu,yu)}i(Uh,"useRnTextScale");function vu(){try{let e=Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(vu,"platformOS");function Vh(){return vu()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(Vh,"contrastSignal");function Hh(){let[e,t]=useState(false);return useEffect(()=>{let r=true,{query:n,event:o}=Vh(),a=AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(AccessibilityInfo);Lh(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(Hh,"useRnHighContrast");function Bh(){return vu()==="ios"?"Menlo":Ne}i(Bh,"rnPlatformMonoFamily");function zh(){return globalThis.__DEV__!==false}i(zh,"isDevelopment");var gu=new Set;function jh(e){if(!zh()||gu.has(e))return;gu.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(jh,"warnUnregisteredFace");function Wh(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||jh(e),o}i(Wh,"rnIsFontRegistered");var cn=Object.freeze({useColorScheme:Mh,useReducedMotion:Dh,useTextScale:Uh,useHighContrast:Hh,scaleTypeSizes:false,platformMonoFamily:Bh,isFontRegistered:Wh});function Kh(e){return createElement(SafeAreaProvider,null,e)}i(Kh,"wrapInSafeArea");var qh=Object.freeze({platform:"react-native",eventSourceFactory:pu(),wrap:Kh,theme:cn});function $h(e){return createElement(cu,{...e,seams:qh})}i($h,"EverfurProvider");function Nt(e){let{runtime:t}=Y(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>ol(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Nt,"useCapability");function eb(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(eb,"tierMultiplier");function R({tier:e="content",...t}){let{type:r}=F(),n=eb(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(R,"Text");var Ut=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var tb=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[tb[t]]}}i(S,"face");var Zo=class Zo 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(Zo,"HostRenderBoundary");var Qo=Zo;function nb({render:e}){return e()}i(nb,"RenderHost");function Et({render:e,fallback:t,resetKey:r}){return createElement(Qo,{fallback:t,resetKey:r,children:createElement(nb,{render:e})})}i(Et,"HostRender");var ob=48;function ib(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(ib,"selectView");function ti(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Nt(t),l=useMemo(()=>ib(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(Et,{render:o,fallback:jsx(Tu,{capability:t,style:s})}):jsx(Tu,{capability:t,style:s});case "disabled":return n?jsx(Et,{render:()=>n(a),fallback:jsx(Pu,{decision:a,style:s}),resetKey:a}):jsx(Pu,{decision:a,style:s});default:return Ze(l)}}i(ti,"CapabilityGate");function Tu({capability:e,style:t}){let r=F(),n=useMemo(()=>ku(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(Tu,"PendingSkeleton");function Pu({decision:e,style:t}){let r=F(),n=useMemo(()=>ku(r),[r]),o=e.disabled?.reason??"";return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsx(R,{style:n.offstateText,children:o}):null})}i(Pu,"OffState");function ku(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:ob,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(ku,"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 ri=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"})]),xu=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function sb(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(sb,"sentimentToFeedbackType");function _u(e,t){if(e==="down"&&t!==null){let r=ri.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return sb(e)}i(_u,"feedbackTypeFor");var db=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function hr(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 I=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=I,d({scope:l,controller:I}),()=>{p.current=null,d(v=>v?.controller===I?null:v),t.registry.releaseChat(I);}},[t,r,s,a,o,l]);let f=useCallback(I=>c?c.subscribe(I):cb,[c]),m=useCallback(()=>c?c.getSnapshot():db,[c]),y=useSyncExternalStore(f,m,m),x=useCallback((I,v)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?oi(c,c.send(I,v?.imageS3Keys===void 0?{}:{imageS3Keys:v.imageS3Keys}),()=>p.current===c):Promise.resolve(ii()),[c]),b=useCallback(I=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?oi(c,c.askEverfur(I),()=>p.current===c):Promise.resolve(ii()),[c]),C=useCallback(()=>c&&p.current===c?oi(c,c.retryLast(),()=>p.current===c):Promise.resolve(ii()),[c]),_=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),P=useCallback(()=>{c&&p.current===c&&c.newConversation();},[c]),[k,g]=useState({controller:null,byMessage:{}}),w=k.controller===c?k.byMessage:pb,O=useCallback(async(I,v,T,V)=>{if(!c||p.current!==c)return E(D("accessDenied"));let j=String(I),W=k.controller===c?k.byMessage[j]:void 0;if(W===v&&T==null)return g(he=>{let ke={...he.controller===c?he.byMessage:{}};return delete ke[j],{controller:c,byMessage:ke}}),L(Object.freeze({feedbackId:""}));g(he=>({controller:c,byMessage:{...he.controller===c?he.byMessage:{},[j]:v}}));let ne=await c.submitFeedback(I,_u(v,T??null),V??null);return p.current!==c?E(D("accessDenied")):(ne.ok||g(he=>{let ke={...he.controller===c?he.byMessage:{}};return W===void 0?delete ke[j]:ke[j]=W,{controller:c,byMessage:ke}}),ne)},[c,k]),M=useMemo(()=>{let I=i(async v=>{if(!c||p.current!==c)return E(D("accessDenied"));let T=await v(c);return p.current===c?T:E(D("accessDenied"))},"run");return {listConversations:i(v=>I(T=>T.listConversations({...s?{petRef:s}:{},...v})),"listConversations"),getMessages:i((v,T)=>I(V=>V.getMessages(v,T)),"getMessages"),resumeConversation:i(v=>I(T=>T.resumeConversation(v)),"resumeConversation"),loadOlderMessages:i(()=>I(v=>v.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>I(v=>v.markRead()),"markRead"),refreshActiveThread:i(()=>I(v=>v.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((v,T)=>I(V=>V.answerCheckin(v,T)),"answerCheckin"),openCheckin:i(v=>I(T=>T.openCheckin(v)),"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,...M,suggestedPrompts:y.suggestedPrompts,unreadCount:y.unreadCount,hasUnreadThreads:y.hasUnreadThreads??false,newConversation:P,sentimentByMessage:w,feedback:O,send:x,askEverfur:b,retryLast:C,stop:_}),[y,s,x,b,C,_,M,P,w,O])}i(hr,"useEverfurChat");var cb=i(()=>{},"NOOP_UNSUBSCRIBE"),pb=Object.freeze({});async function oi(e,t,r){for await(let o of t);if(!r())return E(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?E(n.error):L(fb(n.messages))}i(oi,"driveToResult");function fb(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(fb,"lastAssistantResponseId");function ii(){return E(D("internalError",{retryable:true}))}i(ii,"notReadyError");function Ou(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:So(Yr),filename:e.filename,size:So(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:Xr});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(Ou,"attachmentErrorMessage");function Fu(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(Fu,"attachControlLabel");var hb=Object.freeze({attachments:Object.freeze([])});function pn(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=e.maxPerMessage??Xr,s=useCallback(()=>{let{services:g}=t.registry;return Oa({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,()=>hb),[f,m]=useState(null),y=useCallback(g=>{let O=(Array.isArray(g)?g:[g]).map(I=>c.add(I)),M=O.find(I=>!I.ok);return M!==void 0&&!M.ok&&m(M.error),O},[c,m]),x=useCallback(g=>c.retry(g),[c]),b=useCallback(g=>c.remove(g),[c]),C=useCallback(()=>c.clear(),[c]),_=useCallback(()=>m(null),[m]),P=p.attachments.some(g=>g.status==="uploading"),k=p.attachments.some(g=>g.status==="failed");return useMemo(()=>({available:c.available,attachments:p.attachments,maxPerMessage:o,uploading:P,failed:k,blocked:P||k,s3Keys:p.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[]),rejected:f,add:y,retry:x,remove:b,clear:C,dismissRejected:_}),[c.available,p,o,P,k,f,y,x,b,C,_])}i(pn,"useChatAttachments");var Eb="pet_not_registered";function Du(e){return e!=null&&e.reasonCode===Eb}i(Du,"isPetNotRegistered");var Cb=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function Nu(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=Y(),a=useCallback(()=>Je(n.registry.services.authFor(o)),[n,o,s]),l=useMemo(()=>t===void 0?null:ai(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 x=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(b=>{x===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 m(),()=>{c.current+=1;}},[f,m]);let y=useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return useMemo(()=>f===null?Cb: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(Nu,"useChatPetRegistration");function ai(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ai).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)}:${ai(n)}`).join(",")}}`}i(ai,"stableKey");var li=Object.freeze({});function Vu(e){let[t,r]=useState(li),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===li?u:li);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(Vu,"useSentImages");var xb=500;function ui(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,xb):null}i(ui,"sanitizeSeedPrompt");function Bu(e,t,r){let n=ui(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(Bu,"useInitialAsk");function _b(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(_b,"isCoalesced");function zu(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"}:_b(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(zu,"decideChatRefresh");function di(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(di,"reportHostFailure");function wb(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(wb,"isThenable");function q(e,...t){if(typeof e=="function")try{let r=e(...t);return wb(r)&&Promise.resolve(r).then(void 0,di),r}catch(r){di(r);return}}i(q,"callHost");var ju=new WeakMap;function Wu(e){if(typeof e!="function")return;let t=ju.get(e);if(t!==void 0)return t;let r=i((...n)=>{q(e,...n);},"guarded");return ju.set(e,r),r}i(Wu,"guardHost");function Ht(e,...t){let r;try{r=e(...t);}catch(n){return di(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 Ku(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=zu(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(Ku,"useChatLifecycle");function Ab(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(Ab,"targetKey");function $u(e,t){let r=Ab(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($u,"useCheckinTarget");function Qu(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(Qu,"useChatDraft");function Zu(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(Zu,"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 mn(e){let t=e?.replace(/\s+/g," ").trim();return t||Z.untitled}i(mn,"conversationTitle");function ed(e){return `${e.unreadCount!==null&&e.unreadCount>0?Z.unreadPrefix:""}${Z.openConversation} ${mn(e.title)}`}i(ed,"openConversationLabel");function Ju(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Ju,"normalizeForSearch");function Nb(e,t){let r=Ju(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=Ju(mn(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(Nb,"filterConversations");function fi(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(fi,"fresh");function td(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,u]=useState(()=>fi(s)),d=l.scope===s?l:fi(s);useEffect(()=>(a.current+=1,r(false),o(""),u(fi(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async P=>{let k=++a.current,g=P!==void 0;u(O=>({...O,scope:s,loading:!g,loadingMore:g,error:null}));let w=await e.listConversations(P?{cursor:P}:void 0);if(k===a.current){if(!w.ok){u(O=>({...O,loading:false,loadingMore:false,error:w.error.displayMessage}));return}u(O=>{let M=P&&O.scope===s?O.rows:[],I=new Set(M.map(v=>v.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...M,...w.value.conversations.filter(v=>!I.has(v.id))],cursor:w.value.nextCursor===P?null:w.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async P=>{let k=++a.current;u(w=>({...w,loading:true,error:null}));let g=await e.resumeConversation(P);k===a.current&&(u(w=>({...w,loading:false,error:g.ok?null:g.error.displayMessage})),g.ok&&r(false));},"resume"),y=i(async()=>{let P=a.current,k=await e.loadOlderMessages();P===a.current&&!k.ok&&u(g=>({...g,error:k.error.displayMessage}));},"earlier"),x=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"),C=useMemo(()=>Nb(d.rows,n),[d.rows,n]),_=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:y,newConversation:x,loadMore:b,query:n,setQuery:o,searching:_,filtered:C,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(td,"useHistoryPanel");var yn="#111111",gn="#FFFFFF",Hb=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:yn,pillColor:gn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:yn,pillColor:gn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:yn,pillColor:gn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:yn,pillColor:gn,showsVetAction:false})});function Bb(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(Bb,"urgencySignature");function zb(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(zb,"generalUrgencyReason");function od(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:jb(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:zb(t)}:null}return null}i(od,"latestUrgencySource");function jb(e){return typeof e=="string"&&e.trim().length>0?e:null}i(jb,"shownReason");function id(e){let t=e===null?null:Bb(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:Hb[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(id,"useUrgencySurface");function sd(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(sd,"selectView");function Wb(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Wb,"needsNewConversation");function ad(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Wb(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(ad,"turnNotice");function ld(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(ld,"awaitingAssistant");function ud(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(ud,"buildChatOpts");var br=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 pd(e){let t=F(),r=useMemo(()=>qb(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${br.title}. ${br.body}`,children:[jsx(R,{style:r.title,children:br.title}),jsx(R,{style:r.body,children:br.body})]})}i(pd,"ClinicalDisclaimer");function qb(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(qb,"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 ce(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(ce,"stroke");function fd({size:e,color:t,strokeWidth:r}){let n=ce(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(fd,"MenuGlyph");function md({size:e,color:t,strokeWidth:r,rotate:n}){let o=ce(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(md,"Cross");function yd(e){return jsx(md,{...e,rotate:"0deg"})}i(yd,"PlusGlyph");function Ct(e){return jsx(md,{...e,rotate:"45deg"})}i(Ct,"CloseGlyph");function nt({size:e,color:t,strokeWidth:r}){let n=ce(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(nt,"CheckGlyph");var Xb={down:{rotate:"45deg",marginTop:-0.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-0.4}};function hn({size:e,color:t,strokeWidth:r,direction:n}){let o=ce(e,r),s=e*.46,a=Xb[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(hn,"ChevronGlyph");function gd({size:e,color:t,strokeWidth:r}){let n=ce(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(gd,"BookGlyph");function hd({size:e,color:t,strokeWidth:r}){let n=ce(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(hd,"ArrowUpRightGlyph");function bd({size:e,color:t,strokeWidth:r}){let n=ce(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(bd,"CopyGlyph");function bn({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=ce(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(bn,"ThumbGlyph");function vd({size:e,color:t,strokeWidth:r}){let n=ce(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(vd,"InfoGlyph");function Ed({size:e,color:t,strokeWidth:r}){let n=ce(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(Ed,"UploadGlyph");function Cd({size:e,color:t,strokeWidth:r}){let n=ce(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(Cd,"PhotoGlyph");function Rd({size:e,color:t,strokeWidth:r}){let n=ce(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(Rd,"CameraGlyph");function Sd({size:e,color:t,strokeWidth:r}){let n=ce(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(Sd,"SearchGlyph");function Td({size:e,color:t,strokeWidth:r}){let n=ce(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(Td,"EditGlyph");function Pd({size:e,color:t,strokeWidth:r}){let n=ce(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(Pd,"MapPinGlyph");function kd({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(kd,"SendGlyph");function xd({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(xd,"StopGlyph");function vn({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(vn,"Ring");var vr=Object.freeze({standard:mt.standard,emphasized:mt.emphasized,exit:mt.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var _d=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}),Qb=Object.freeze({..._d,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 wd(e){return e.motion.reducedMotion?Qb:_d}i(wd,"chatMotion");function En(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(En,"followUpDelayMs");function Id(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(Id,"nextRevealLength");function X(){let e=F();return wd(e)}i(X,"useChatMotion");var nv=8;function Od(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(Od,"bezierComponent");function ov(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(ov,"bezierSlope");function Cn(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<nv;l+=1){let u=ov(a,t,n);if(u===0)break;a-=(Od(a,t,n)-s)/u;}return Od(Math.min(1,Math.max(0,a)),r,o)}}i(Cn,"bezierEasing");var mi=Cn(vr.standard),iv=Cn(vr.outQuad);function bi(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(bi,"useAnimatedValue");function Rt(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=bi(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:iv,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(Rt,"useFadeIn");function vi({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=bi(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let d=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:mi,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:mi,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(vi,"FadePresence");var sv=12;function B({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=X(),u=bi(1),d=useCallback(c=>{l.pressMs<=0||l.pressScale===1||Animated.timing(u,{toValue:c,duration:l.pressMs,easing:mi,useNativeDriver:true}).start();},[u,l.pressMs,l.pressScale]);return jsx(Pressable,{...a,hitSlop:s??sv,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 Ld(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=>Id(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(Ld,"useRevealedText");var Fd=false;function av(e){e.layoutMs<=0||(Fd||(Fd=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(av,"animateLayout");function Er(e,t){let r=useRef(e);r.current!==e&&(r.current=e,av(t));}i(Er,"useAnimateLayoutOn");var Ei=36,mv=22,yv=12,gv=12,hv=16,bv="#000",vv="rgba(0,0,0,0.45)";function Dd({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:Rn.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:Rn.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[Rn.closeWrap,{top:o.top+gv}],children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.closePreview,hitSlop:yv,style:Rn.closeButton,onPress:r,children:jsx(Ct,{size:mv,color:n.color.surface,strokeWidth:2})})})]})}i(Dd,"AttachmentImageLightbox");var Rn=StyleSheet.create({backdrop:{flex:1,backgroundColor:bv,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:hv},closeButton:{width:Ei,height:Ei,borderRadius:Ei/2,backgroundColor:vv,alignItems:"center",justifyContent:"center"}});var Sn=12,Tv=80,Ci=44,Nd=22,Pv=.14,kv=18,xv=8,Ud=Object.freeze({photo:h.attachmentPhoto,camera:h.attachmentCamera});function Vd({sources:e,full:t,onPick:r,onClose:n}){let o=F(),s=useMemo(()=>_v(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:Ud[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(Cd,{size:Nd,color:o.color.brandInk,strokeWidth:1.5}):jsx(Rd,{size:Nd,color:o.color.brandInk,strokeWidth:1.5})}),jsx(R,{tier:"control",style:s.tileLabel,children:Ud[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(Vd,"AttachmentPickerPopover");function _v(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:Pv,shadowRadius:kv,shadowOffset:{width:0,height:xv},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:Tv,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Ci,height:Ci,borderRadius:Ci/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:-Sn/2,width:Sn,height:Sn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Sn+4,height:2,backgroundColor:t.surfaceCream}})}i(_v,"makeStyles");var Se=Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var Bd=56,zd=12,Av=14,Ov=10,Fv=.45,Mv="rgba(7,193,104,0.55)",Lv="rgba(185,28,28,0.55)",Dv=200,Nv=300,Xd=20,Si=22,Uv=12,Vv="rgba(0,0,0,0.78)",jd=220,Wd=100,Gd="rgba(255,255,255,0.15)";function Qd({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(Hv,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsx(R,{style:l.rejected,accessibilityRole:"alert",children:h.attachmentsFailedBlocked}):null,t!==null?jsx(R,{style:l.rejected,accessibilityRole:"alert",children:Ou(t)}):null]})}i(Qd,"AttachmentStrip");function Hv({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(Bv,{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(Ct,{size:Xd,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(Ct,{size:Uv,color:s.color.surface,strokeWidth:1.5})})]})}i(Hv,"PreviewCard");function Bv({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:Dv,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:Nv,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(nt,{size:Xd,color:r.color.surface,strokeWidth:2})})}i(Bv,"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:Bd,height:Bd,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:zd,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Se,alignItems:"center",justifyContent:"center",backgroundColor:ul(e.color.brandInk,Fv)??e.color.brandSofter},successOverlay:{...Se,alignItems:"center",justifyContent:"center",backgroundColor:Mv},failedOverlay:{...Se,borderRadius:zd,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:Lv},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:Si,height:Si,borderRadius:Si/2,backgroundColor:Vv,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:jd,height:jd,borderRadius:Av,backgroundColor:Gd},gridImage:{width:Wd,height:Wd,borderRadius:Ov,backgroundColor:Gd}})}i(Jd,"makeStyles");var zv="chat attachment upload: the file handle has no uri",jv="chat attachment upload failed";function Wv(e){return {uri:e.uri,name:Ro(e.name),type:e.mimeType}}i(Wv,"filePartOf");function ec(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(zv));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(jv)),"failed");return o?.aborted===true?a():Hr({url:t.upload_url,fields:t.upload_fields,file:Wv(r),signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(ec,"createRnChatAttachmentTransport");function Tn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=Y(),o=useMemo(()=>Je(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(Tn,"useEverfurPets");function tc(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(tc,"headerPetOf");function pe(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(pe,"slotBox");function xi(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(xi,"ownGroundSlot");function Ie(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Ie,"slotText");var rc=Object.freeze({visitButton:"Talk to a vet"});var nc=Symbol.for("@everfur/sdk/televet");function Ke(){let e=globalThis,t=e[nc];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[nc]=r,r}i(Ke,"televetGlobal");function Pn(e){let t=Ke();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Pn,"publish");function oc(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(oc,"callTelevetPresenter");function ic(e){let t=Ke();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(ic,"subscribeTelevetExperience");function _i(){return Ke().snapshot}i(_i,"televetExperienceSnapshot");function Yv(){return Ke().hosts.length>0}i(Yv,"hasTelevetHost");function sc(e){if(!Yv())return false;let t=Object.freeze({...e});return Pn({request:t,serial:Ke().snapshot.serial+1}),true}i(sc,"presentTelevetExperience");function wi(){Ke().snapshot.request!==null&&Pn({request:null});}i(wi,"dismissTelevetExperience");function ac(){let e=Ke(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Pn({activeHost:e.hosts[0]??null}),t}i(ac,"claimTelevetHost");function lc(e){let t=Ke();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Pn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(lc,"releaseTelevetHost");var uc=false;function kn(e,t){return t!==void 0?(q(t,e),"onStartInApp"):oc(e)==="presented"?"presenter":sc(e)?"experience":(uc||(uc=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(kn,"openVetVisitInApp");function pc(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(pc,"memoizeTelevetLoader");function fc(e){let[t,r]=useState(null);useEffect(()=>{let d=ac();return r(d),()=>{lc(d);}},[]);let n=useSyncExternalStore(ic,_i,_i),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),wi());}),()=>{d=false;}},[u,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:wi}}i(fc,"useTelevetExperienceHost");var Qv=pc(()=>import('@everfur/sdk/televet/booking'));function Rr(){let e=fc(Qv);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(Rr,"EverfurTelevetHost");var Ii=Object.freeze(["visit","join","summary","messages"]);function Ai(e){return typeof e=="string"&&Ii.includes(e)}i(Ai,"isVetVisitIntent");var Jv="/widget/v1/televet/handoffs",eE="/widget/v1/televet/availability",tE="/widget/v1/televet/chat-entry",rE=/^[a-z0-9][a-z0-9_-]{0,39}$/,nE=/^[A-Za-z0-9_-]{22}$/;var mc=32,yc=128,gc=64;function Fi(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(Fi,"vetVisitErrorReasonOf");function hc(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(hc,"invalid");function Oi(e){return E(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Oi,"unusable");function oE(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!rE.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>gc)return {ok:false,message:`visitRef must be 1..${gc} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Ai(a))return {ok:false,message:`intent must be one of ${Ii.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(oE,"handoffBody");function iE(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Ai(r)?null:Object.freeze({visitRef:t,intent:r})}i(iE,"parseVisitEcho");function vc(e){let t=e.funnel??xe({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(bc(r,"televet.visit.handoff_failed",{reason:Fi(o)}),E(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let b=typeof o=="string"?[...o].length:0;if(b<1||b>yc)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${yc} characters`}));a=o;}let l=oE(a,s);if(!l.ok){let b=hc(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=sE(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!nE.test(f))){let b=Oi("the handoff response carried no usable return flow id");return b.ok?b:n(b.error)}let m=u.visit_ref!==void 0,y=m?iE(d.value?.visit):null;if(m&&y===null){let b=Oi("the handoff response did not confirm the visit it opens");return b.ok?b:n(b.error)}let x=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...y!==null?{visit:y}:{}});return x===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(bc(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),L(x))},async checkAvailability(o){if(typeof o!="string"||o.length>mc)return hc(`state must be at most ${mc} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:eE,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return E(s.error);let a=s.value?.available;return typeof a!="boolean"?Oi("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:tE},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(vc,"createVetVisitController");function sE(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||!dE(t)?null:Object.freeze({url:t,expiresAt:r})}i(sE,"parseHandoff");var aE=new Set(["localhost","127.0.0.1","[::1]"]),lE=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,uE=/[\s\u0000-\u001f\u007f]/;function dE(e){if(uE.test(e))return false;let t=lE.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"&&aE.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(dE,"isOpenableVisitUrl");function bc(e,t,r){if(e)try{e.track(t,r);}catch{}}i(bc,"safeTrack");var Mi=Object.freeze({status:"idle",error:null,errorReason:null});function pE(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(pE,"usePreflight");var fE=Object.freeze({status:"opening",error:null,errorReason:null});function Rc(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 vc({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=pE(f,a,{usState:l,chat:u,scope:m}),x=a&&(y===null||y.open)&&(!u||d!==null),b=t.returnTo??null,[C,_]=useState(Mi),P=useRef(null),k=useRef({runtime:r,userRef:n,scopeEpoch:o});k.current={runtime:r,userRef:n,scopeEpoch:o};let g=useRef(p);g.current=p;let w=useRef(x);w.current=x;let O=useCallback((T,V)=>{if(P.current)return P.current;let j=i((fe,Qe)=>(_({status:fe==="cancelled"?"idle":"error",error:Qe,errorReason:fe==="cancelled"?null:fe}),Object.freeze({opened:false,reason:fe,error:Qe})),"fail");if(!w.current)return Promise.resolve(j("unavailable",null));let W=e.prepare();if(!W.ok)return Promise.resolve(j(W.reason,null));let ne=k.current,he=g.current;_(fE);let st=(async()=>{let fe,Qe={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...V!==null?{visitRef:V.visitRef}:{},...V!==null&&V.intent!==null&&V.intent!==void 0?{intent:V.intent}:{}},Ir=Object.keys(Qe).length===0?void 0:Qe,Ar=T===void 0?d:T;try{fe=await(Ir===void 0?he.createHandoff(Ar):he.createHandoff(Ar,Ir));}catch{return e.abandon(W.value),j("unknown",null)}let At=k.current;if(At.runtime!==ne.runtime||At.userRef!==ne.userRef||At.scopeEpoch!==ne.scopeEpoch)return e.abandon(W.value),j("cancelled",null);if(!fe.ok)return e.abandon(W.value),j(Fi(fe.error),fe.error);let Yt=await e.finish(W.value,fe.value);return Yt!==null?j(Yt,null):(_(Mi),Object.freeze(fe.value.flowId===void 0?{opened:true}:{opened:true,flowId:fe.value.flowId}))})().finally(()=>{P.current===st&&(P.current=null);});return P.current=st,st},[e,d,b,u]),M=useCallback((T,V)=>{if(!w.current)return _({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let j=T===void 0?d:T,W={...j!==null?{petRef:j}:{},...l!==null?{usState:l}:{},...V!==null?{visitRef:V.visitRef,intent:V.intent}:{}};return kn(W)===null?(_({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(_(Mi),Promise.resolve(Object.freeze({opened:true})))},[d,l]),I=useCallback(T=>c?O(T,null):M(T,null),[c,O,M]),v=useCallback((T,V)=>c?O(void 0,{visitRef:T,intent:V??null}):M(void 0,{visitRef:T,intent:V??null}),[c,O,M]);return {available:x,isPending:s.isPending||(y?.pending??false),status:C.status,error:C.error,errorReason:C.errorReason,open:I,openVisit:v}}i(Rc,"useVetVisitWith");var gE=i(e=>Linking.openURL(e),"defaultOpenUrl");function _n(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??gE;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 Rc(n,r)}i(_n,"useVetVisit");var Sc=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:m,onStartInApp:y,prefer:x}=e,b=x==="redirect",C=_n({...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"}),_=F(),P=useMemo(()=>RE(_),[_]),k=useRef(false);if(!C.available)return jsxs(Fragment,{children:[null,jsx(Rr,{})]});let g=C.status==="opening",w=r??rc.visitButton;return jsxs(Fragment,{children:[jsx(Pressable,{onPress:i(()=>{if(!(g||k.current)){if(!b){let M={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...f!=null?{visitRef:f,intent:m??null}:{}};kn(M,y)===null&&q(s,"unavailable",null);return}k.current=true,(f==null?C.open():C.openVisit(f,m??null)).then(M=>{M.opened?q(o,M.flowId??null):M.reason!=="cancelled"&&q(s,M.reason,M.error);}).finally(()=>{k.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:w,accessibilityState:{busy:g,disabled:g},style:[P.button,g?P.busy:null,a],children:jsx(R,{style:[P.label,l],children:w})}),jsx(Rr,{})]})}i(jt,"VetVisitButton");function RE(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:Sc,minWidth:Sc,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...pe(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(RE,"makeStyles");function Li(e){return ur(e)==="cat"?"cat":"dog"}i(Li,"speciesOf");function Di(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(Di,"petAgeYears");function xc(e){let t=Di(e.ageYears),r=Li(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(xc,"formatPetMeta");var kc=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 SE(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return kc[t%kc.length]}i(SE,"pickInitialsPalette");function Ni(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(Ni,"getInitial");function _c(e){return {...SE(e.petRef),initial:Ni(e.name)}}i(_c,"petInitials");function xE(e){return Math.max(12,Math.round(e*.42))}i(xE,"letterSize");function Tr({pet:e,size:t,ringStroke:r}){let n=F(),o=useMemo(()=>_E(n),[n]),s=t-r*2,a=e===null?null:_c(e),l=xE(s);return jsx(vn,{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(R,{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?Ni(null):a.initial})})})}i(Tr,"PetDisc");function _E(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(_E,"makeStyles");var Vi=48,Ac=2,ME=320,LE="80%",DE="rgba(17,17,17,0.45)",NE=18,wc=22,UE=12,Ic=.4,VE=44;function Hi(e){return e?.name?.trim()||h.yourPet}i(Hi,"petDisplayName");function Oc({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=F(),l=useMemo(()=>HE(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(R,{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=Hi(u),p=xc(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(Tr,{pet:u,size:Vi,ringStroke:Ac}),jsxs(View,{style:l.copy,children:[jsx(R,{style:l.name,numberOfLines:1,children:c}),jsx(R,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${h.activePrefix}${p}`:p})]}),d?jsx(nt,{size:NE,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(R,{tier:"control",style:l.addPlus,children:"+"})}),jsx(R,{style:l.addLabel,children:h.addAnotherPet})]}):null,jsx(B,{accessibilityRole:"button",accessibilityLabel:h.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsx(R,{tier:"control",style:l.closeText,children:h.close})})]})]})}):null}i(Oc,"PetSwitcherSheet");function HE(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:DE},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:wc,borderTopRightRadius:wc,gap:14,maxHeight:LE},title:{...S(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:ME,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:VE,paddingHorizontal:8},addDisc:{width:Vi,height:Vi,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Ac,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:Ic},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:UE,backgroundColor:t.brandSoft},closeText:{...S(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Ic}})}i(HE,"makeStyles");var jE=44,In=36,WE=22,Bi=9,GE=1.5,Mc=6,Tt=35,An=1.75,zi=12.4,KE=.5,qE=8,$E=28,YE=160;function Wi(e,t){return tc(e,t)}i(Wi,"headerPet");function Dc({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=F(),u=useMemo(()=>QE(l),[l]),[d,c]=useState(false),p=Wi(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,y=Hi(p),x=i(C=>{c(false),e.setActivePet(C),q(o,C);},"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(fd,{size:WE,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(XE,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsx(jt,{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(Tr,{pet:p,size:Tt,ringStroke:An}),jsx(View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(yd,{size:qE,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:u.avatarWrap,accessible:true,accessibilityLabel:h.yourPet,children:jsx(vn,{size:Tt,strokeWidth:An,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(Tr,{pet:p,size:Tt,ringStroke:An})})}),jsx(Oc,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:x,onAddPet:b,onClose:()=>c(false)})]})}i(Dc,"ChatHeader");function XE({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(XE,"BrandLogo");function QE(e){let t=e.color,r=Tt-An*2;return StyleSheet.create({vetEntry:{minHeight:jE,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:In/2},iconButton:{width:In,height:In,borderRadius:In/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:Mc,right:Mc,width:Bi,height:Bi,borderRadius:Bi,backgroundColor:t.danger,borderWidth:GE,borderColor:t.surface},center:{...Se,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:$E,width:YE},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Tt/2},avatarWrap:{width:Tt,height:Tt,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:zi,height:zi,borderRadius:zi/2,borderWidth:KE,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(QE,"makeStyles");var Vc=44,rC="rgba(17,17,17,0.55)",Hc=26,nC=36,Bc=4,Gi=20,Ki=38,oC=18,iC=12;function zc({visible:e,onSubmit:t,onSkip:r}){let n=F(),o=useMemo(()=>sC(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"),x=i(async()=>{if(d)return;c(true),f(false);let C=l.trim();await t(s,C.length>0?C:null)?m():(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: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(bn,{size:oC,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxs(View,{style:o.headerText,children:[jsx(R,{tier:"heading",style:o.title,accessibilityRole:"header",children:h.feedbackTitle}),jsx(R,{style:o.subtitle,children:h.feedbackSubtitle})]})]}),jsx(View,{style:o.options,children:ri.map(C=>{let _=s===C.key;return jsxs(B,{accessibilityRole:"button",accessibilityLabel:C.label,accessibilityState:{selected:_},style:[o.option,_?o.optionSelected:null],onPress:()=>a(P=>P===C.key?null:C.key),children:[jsx(R,{style:[o.optionLabel,_?o.optionLabelSelected:null],children:C.label}),jsx(View,{style:[o.radio,_?o.radioSelected:null],children:_?jsx(nt,{size:iC,color:n.color.surface,strokeWidth:2}):null})]},C.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(R,{tier:"compact",style:[o.counter,b?o.counterOver:null],children:`${[...l].length}/${Mt}`}):null]}),p?jsx(R,{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:()=>{x();},children:jsx(R,{tier:"control",style:o.submitLabel,children:h.feedbackSubmit})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:h.feedbackSkipA11y,hitSlop:8,onPress:y,style:o.skip,children:jsx(R,{tier:"control",style:o.skipLabel,children:h.feedbackSkip})})]})]})]})})}i(zc,"FeedbackReasons");function sC(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:rC},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Hc,borderTopRightRadius:Hc,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:nC,height:Bc,borderRadius:Bc/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Ki,height:Ki,borderRadius:Ki/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:Gi,height:Gi,borderRadius:Gi/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:Vc,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...pe(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...S(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...Ie(o.primaryButton)},skip:{minHeight:Vc,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...S(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(sC,"makeStyles");var CC=.88,RC=420,SC=58,TC="rgba(17,17,17,0.28)",PC=.08,kC=.1,xC=.08,_C=.18,wC=.78,IC=.7,qi=36,AC=10,OC=14,FC=12,MC=16,LC=14,$i=8,DC=1.5,NC=.5,UC=Cn(vr.standard);function VC(e){return Math.min(Math.round(e*CC),RC)}i(VC,"drawerPanelWidth");function jc({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(HC,{chat:e,history:t,onHidden:o}):null}i(jc,"HistoryDrawer");function HC({chat:e,history:t,onHidden:r}){let n=F(),o=useMemo(()=>zC(n),[n]),s=X(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),u=VC(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 C=Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:UC,useNativeDriver:true});return C.start(({finished:_})=>{_&&!d&&r();}),()=>C.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,y=t.rows.length===0,x=y&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:Z.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:n.color.onPrimary}),jsx(R,{style:o.emptyBody,children:Z.loading})]}):y&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(R,{style:o.emptyTitle,accessibilityRole:"alert",children:Z.loadFailed}),jsx(R,{style:o.emptyBody,children:t.error}),jsx(B,{accessibilityRole:"button",accessibilityLabel:Z.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(R,{tier:"control",style:o.retryText,children:Z.retry})})]}):jsxs(View,{style:o.emptyCard,children:[jsx(R,{style:o.emptyTitle,children:t.emptyKind==="empty"?Z.empty:Z.noMatch}),jsx(R,{style:o.emptyBody,children:t.emptyKind==="empty"?Z.emptyBody:Z.noMatchBody})]}),b=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(R,{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(SC,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(Sd,{size:LC,color:n.color.text.muted,strokeWidth:1.5}),jsx(Ut,{value:t.query,onChangeText:C=>t.setQuery(C.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(Td,{size:MC,color:n.color.text.primary,strokeWidth:1.5})})]}),jsx(R,{tier:"heading",style:o.heading,accessibilityRole:"header",children:Z.heading}),t.error!==null&&!y?jsx(View,{style:o.errorCard,children:jsx(R,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsx(FlatList,{data:m,keyExtractor:C=>C.id,renderItem:({item:C})=>jsx(BC,{row:C,active:C.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(C.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:x,ListFooterComponent:b,onEndReached:t.loadMore,onEndReachedThreshold:NC})]})})]})})}i(HC,"DrawerModal");function BC({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsx(B,{accessibilityRole:"button",accessibilityLabel:ed(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(R,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:mn(e.title)}),s?jsx(View,{style:n.unreadDot}):null]})})}i(BC,"Row");function Mn(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(Mn,"inkWash");function zC(e){let t=e.color,r=e.slots,n=t.onPrimary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:TC},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:Mn(n,kC)},searchInput:{...S(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:qi,height:qi,borderRadius:qi/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:AC},itemActive:{backgroundColor:Mn(n,PC)},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:$i,height:$i,borderRadius:$i/2,backgroundColor:t.danger,borderWidth:DC,borderColor:n},errorCard:{borderRadius:FC,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...S(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:OC,padding:14,gap:6,backgroundColor:Mn(n,xC),borderWidth:.5,borderColor:Mn(n,_C)},emptyTitle:{...S(e,"bold"),fontSize:12,lineHeight:15,color:n},emptyBody:{...S(e,"regular"),fontSize:11,lineHeight:17,color:n,opacity:wC},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:n,...pe(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:IC}})}i(zC,"makeStyles");var $C=Object.freeze({}),YC=100,XC=20;function QC(e,t,r,n){return ![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}i(QC,"readWindowTops");function Wc(e,t){let r=typeof e=="number"&&Number.isFinite(e),n=useRef(null),[o,s]=useState(null),a=useRef(null),l=useRef(null),u=useRef(true),d=useCallback(()=>{l.current!==null&&clearTimeout(l.current),l.current=null;},[]);useEffect(()=>(u.current=true,()=>{u.current=false,d();}),[d]);let c=useCallback(i(function f(m){n.current?.measureInWindow((y,x)=>{let b=a.current;if(!u.current||b===null)return;let C=QC(x,b.y,b.height,Dimensions.get("window").height);if(C!==null){s(_=>_!==null&&_.chatTop===C.chatTop&&_.parentTop===C.parentTop?_:C);return}m>=XC||(l.current=setTimeout(()=>{l.current=null,f(m+1);},YC));});},"measureAt"),[]),p=useCallback(f=>{let{y:m,height:y}=f.nativeEvent.layout;a.current={y:m,height:y},d(),c(0);},[c,d]);return useMemo(()=>{if(!t)return {avoidingProps:r?{keyboardVerticalOffset:e}:$C,probeRef:null,topInWindow:null};let f=o?.parentTop??0;return {avoidingProps:r?{keyboardVerticalOffset:e,onLayout:p}:f>0?{keyboardVerticalOffset:f,onLayout:p}:{onLayout:p},probeRef:n,topInWindow:o?.chatTop??null}},[t,r,e,o,p])}i(Wc,"useChatKeyboardOffset");function Gc({probeRef:e}){return e===null?null:jsx(View,{ref:e,collapsable:false,pointerEvents:"none",style:ZC})}i(Gc,"KeyboardOffsetProbe");var ZC=Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function Kc(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(Kc,"chatVetVisitOptions");var nR=16,oR=.75,Xi=12,qc=15,iR=18,Dn=22,sR=14,aR=8,lR=20,uR=10,dR=13;function Yc({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=F(),a=useMemo(()=>cR(s),[s]),l=X(),u=e.tier,d=e.source;return jsxs(Fragment,{children:[jsx(vi,{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(R,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsx(R,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsx(Et,{render:()=>r(u.level),fallback:jsx($c,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsx($c,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsx(B,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:aR,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsx(Ct,{size:sR,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsx(vi,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(B,{accessibilityRole:"button",accessibilityLabel:h.showLatestVetAlert,hitSlop:uR,onPress:e.expand,children:jsx(vd,{size:lR,color:s.color.text.muted,strokeWidth:2})})})]})}i(Yc,"UrgencyBanner");function $c({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=F(),a=_n(Kc(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=xi(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(Pd,{size:dR,color:d,strokeWidth:1.5}),jsx(R,{tier:"control",style:[o.findVetLabel,{color:d}],children:h.findVet})]})}i($c,"VetAction");function cR(e){let t=xi(e.slots.vetVisitButton);return StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:nR,borderWidth:oR,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...S(e,"monoBold"),fontSize:Xi,lineHeight:qc},reason:{...S(e,"regular"),fontSize:Xi,lineHeight:iR,paddingRight:Dn},findVetSlot:{alignSelf:"flex-start",marginTop:6},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...pe(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...S(e,"monoBold"),fontSize:Xi,lineHeight:qc},closeSlot:{position:"absolute",top:6,right:6},closeButton:{width:Dn,height:Dn,borderRadius:Dn/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:16,paddingTop:2,paddingBottom:4}})}i(cR,"makeStyles");function Xc(){let e=Tn(),{handle:t}=Y(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(Xc,"useChatPets");var op=300,ip=3e3,Zc=120,Gt=44,gR=120,hR="86%",Jc=15,ep=22,Nn=.5,bR=.04,vR=8,ER=2,CR=1,RR=.6,SR=22,TR=48,tp=1.25,PR=14,kR=18,xR=6,_R=14,wR=.04,IR=12,AR=2,OR=2,rp=36,FR=20,Wt=36,Kt=(Gt-Wt)/2,sp=24,ap=22,MR=.4,Un=30,lp=20,LR=.4,DR=480,NR=8,np=14,UR=10,VR=14,HR=12,BR=13,zR=18,jR="12%";function Ee(){let e=F(),t=useMemo(()=>WR(e),[e]);return {theme:e,styles:t}}i(Ee,"useChatTheme");function WR(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=e.slots;return StyleSheet.create({container:{flex:1,minHeight:Zc,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Zc,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:jR,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:DR,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,...pe(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:hR},bubbleUser:{padding:Jc,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:Nn,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:bR,shadowRadius:vR,shadowOffset:{width:0,height:ER},elevation:CR,...pe(s.userBubble,Nn)},bubbleAssistant:s.assistantBubble?.backgroundColor===void 0?{...pe(s.assistantBubble,Nn)}:{padding:Jc,borderRadius:n.xl,...pe(s.assistantBubble,Nn)},bubblePending:{opacity:RR},bubbleTextUser:{...S(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:ep,...Ie(s.userBubble)},bubbleTextAssistant:{...S(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:ep,...Ie(s.assistantBubble)},bubbleBold:S(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:S(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.sm,gap:NR},followUpSlot:{alignSelf:"stretch",borderRadius:np},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:HR,paddingVertical:UR,paddingHorizontal:VR,borderRadius:np,backgroundColor:t.brandSoft},followUpText:{...S(e,"medium"),flex:1,color:t.text.primary,fontSize:BR,lineHeight:zR},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,marginBottom:r.sm,minHeight:TR,justifyContent:"center",paddingLeft:PR,paddingRight:kR,paddingVertical:xR,backgroundColor:t.composerFill,borderWidth:tp,borderColor:t.composerBorder,borderRadius:SR,shadowColor:t.shadow,shadowOpacity:wR,shadowRadius:IR,shadowOffset:{width:0,height:AR},elevation:OR,...pe(s.composerInput,tp)},composerRow:{flexDirection:"row",alignItems:"center",gap:_R,minHeight:rp},attachControl:{width:Un,height:Un,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:LR},input:{flex:1,minHeight:rp,maxHeight:gR,paddingHorizontal:0,paddingVertical:0,...S(e,"regular"),fontSize:o.size.body,lineHeight:FR,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",...pe(s.sendButton)},sendControlDisabled:{opacity:MR},poweredBy:{...S(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(WR,"makeStyles");var GR=Object.freeze({kind:"live"}),KR=Object.freeze({kind:"folded"});function Zi(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=mo(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(Zi,"askOf");function dp(e){let t=new Map,r=new Map;for(let o of e){let s=Zi(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=Zi(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,GR),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,KR);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(dp,"placeCheckins");var up=864e5,qR=365;function Vn(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/up)-Math.floor(r/up);return o<1||o>qR?null:o}i(Vn,"checkinDayNumber");function cp(e){return Zi(e)?.dueDay||null}i(cp,"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"})}),pp=Object.freeze(Wr.map(e=>Object.freeze({answer:e,label:Te.answers[e]})));function fp(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:!ha(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(fp,"useCheckinCard");var gp=44,XR=.6;function bp({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s,onLayout:a}){let l=F(),u=useMemo(()=>QR(l),[l]),d=fp(t,r),c=d.answer!==null||d.pending!==null,p=r!==null&&d.answerable,f=Vn(t.openedAt,cp(e));return jsxs(View,{style:u.card,accessibilityLabel:Te.eyebrow,onLayout:a,children:[jsxs(View,{style:u.head,children:[jsx(R,{tier:"compact",style:u.eyebrow,children:Te.eyebrow}),f!==null?jsx(R,{tier:"compact",style:u.headDay,children:K(Te.day,{day:f})}):null]}),jsx(R,{style:u.question,accessibilityRole:"text",children:e.text}),p?jsx(View,{style:[u.row,d.pending?u.rowPending:null],children:pp.map(({answer:m,label:y})=>{let x=(d.pending??d.answer)===m;return jsx(Pressable,{onPress:()=>d.choose(m),disabled:c,accessibilityRole:"button",accessibilityLabel:y,accessibilityState:{selected:x,disabled:c,busy:d.pending===m},style:[u.pill,x?u.pillSelected:null],children:jsx(R,{tier:"control",style:[u.pillLabel,x?u.pillLabelSelected:null],children:y})},m)})}):null,d.answer!==null?jsx(R,{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(R,{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(R,{style:u.resolution,children:t.resolutionText}):null,d.error?jsx(R,{style:u.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}i(bp,"CheckinCard");function QR(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:XR},pill:{flex:1,minHeight:gp,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:gp,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(QR,"makeStyles");var eS=1.5,tS=3;function Ep({text:e,runDueDays:t,openedAt:r,onLayout:n}){let o=F(),s=useMemo(()=>rS(o),[o]),a=t.map(u=>Vn(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(R,{tier:"compact",style:s.days,children:a.map(u=>K(Te.day,{day:u})).join(Te.daySeparator)}):null,l?null:jsx(R,{style:s.question,accessibilityRole:"text",children:e})]})]})}i(Ep,"CheckinPastAsk");function rS(e){let t=e.color,r=e.space,n=e.type;return StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:eS,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:tS},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(rS,"makeStyles");var nS=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),Cp="#C8BEB4";function oS(e){return e?nS[e.toUpperCase()]??Cp:Cp}i(oS,"tierColor");function iS(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(iS,"tierLabel");function He(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(He,"text");function sS(e){let t=He(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(sS,"httpsUrl");function aS(e,t){let r=He(e.source_name)??He(e.sourceName),n=He(e.section),o=He(e.authority_tier)??He(e.authorityTier),s=iS(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:sS(e.url),excerpt:He(e.excerpt),tierColor:oS(o),key:`${a}-${l??"none"}-${t}`})}i(aS,"toCitationCard");function Rp(e){return e===void 0||e.length===0?lS:Object.freeze(e.map((t,r)=>aS(t,r)))}i(Rp,"toCitationCards");var lS=Object.freeze([]);function ns(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i(ns,"sourcesLabel");function Sp(e,t){return `${t?h.hideSources:h.showSources} ${ns(e)}`}i(Sp,"sourcesToggleLabel");function Tp(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(Tp,"citationA11yLabel");var fS=244,kp=8,xp=13,mS=14,yS=.3,gS=-0.24,hS=22,bS=10,vS=15;function _p({citations:e,onOpenUrl:t}){let r=F(),n=useMemo(()=>RS(r),[r]),o=useMemo(()=>Rp(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:Sp(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(u=>!u),children:[jsx(gd,{size:xp,color:r.color.brandInk,strokeWidth:1.5}),jsx(R,{tier:"compact",style:n.toggleLabel,children:ns(l)}),jsx(hn,{size:xp,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsx(ES,{cards:o,styles:n,open:t}):null]})}i(_p,"CitationCards");function ES({cards:e,styles:t,open:r}){let n=X(),o=Rt(n.citationsInMs,{risePx:n.citationsRisePx});return jsx(Animated.View,{style:o,children:jsx(ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsx(CS,{card:s,styles:t,open:r},s.key))})})}i(ES,"Deck");function CS({card:e,styles:t,open:r}){let n=F(),o=e.url!==null&&r!==void 0,s=Tp(o?e:{...e,url:null}),a=jsxs(Fragment,{children:[jsxs(View,{style:t.cardHeader,children:[jsx(View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsx(R,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsx(hd,{size:mS,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsx(R,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsx(R,{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(CS,"Card");function RS(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:yS,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:fS,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:kp,height:kp,borderRadius:n.pill},cardTitle:{...S(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:hS,color:t.text.primary,letterSpacing:gS},cardTitleLink:{color:t.linkInk},cardMeta:{...S(e,"monoMedium"),fontSize:o.nano,lineHeight:bS,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...S(e,"regular"),fontSize:o.tiny,lineHeight:vS,color:t.text.muted}})}i(RS,"makeStyles");function wp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(wp,"formatMessageTime");var xr=15,_S=15,wS=6,IS=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function Mp({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=F(),a=useMemo(()=>AS(s),[s]),l=X(),u=e.role==="user",d=useMemo(()=>wp(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 x=i(()=>{t!==void 0&&(Ht(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(R,{tier:"compact",style:a.timestamp,children:d}):null,c?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f?h.copied:u?h.copyUserMessage:h.copyAssistantMessage,hitSlop:_S,onPress:x,style:a.iconHit,children:f?jsx(nt,{size:xr,color:s.color.success,strokeWidth:2}):jsx(bd,{size:xr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?xu.map(({sentiment:b,label:C})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:C,accessibilityState:{selected:r===b},hitSlop:wS,onPress:()=>n?.(b),style:a.iconHit,children:jsx(bn,{size:xr,color:s.color.sentiment[b],active:r===b,rotate:IS[b],strokeWidth:1.5})},b)):null]}),o?jsx(R,{style:a.thanks,accessibilityLiveRegion:"polite",children:h.feedbackThanks}):null]})}i(Mp,"MessageFooter");function AS(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:xr,height:xr,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(AS,"makeStyles");var Lp="#10462E",Dp="#000000",OS="#83E0B4",FS=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:OS,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:Lp,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})]),MS=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function LS(e){return e==null?e:e.replace(MS,"").trim()}i(LS,"formatBreedForPrompt");var DS=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 DS.has(t)}i(NS,"isUninformativeBreed");function US(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(US,"unspecifiedBreedLabel");function VS(e,t){return NS(e)?US(t):String(e).replace(/\s+/gu," ").trim()}i(VS,"resolveBreedLabel");function Np(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(Np,"emptyStateTitle");function Up(e,t=Lp){let r=Li(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=VS(LS(e?.breed),r)||null,l=Di(e?.ageYears),u=l===null?null:String(l);return Object.freeze(FS.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??""}),x=!o&&m.startsWith("{petName}")?y.charAt(0).toUpperCase()+y.slice(1):y;return Object.freeze({id:d.id,intent:d.intent,label:x,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(Up,"resolveQuickPrompts");var BS=36,Bp=4,zS=340;function zp({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=F(),a=useMemo(()=>WS(s),[s]),l=useMemo(()=>Up(e,s.color.brandInk),[e,s.color.brandInk]),u=Np(e);return jsxs(View,{style:a.block,children:[jsx(R,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsx(View,{style:a.list,children:l.map((d,c)=>jsx(jS,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(zp,"QuickPrompts");function jS({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=X(),d=Rt(u.followUpInMs,{delayMs:En(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:Bp,style:[l.chip,c],onPress:()=>{q(s,r);},children:jsx(R,{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:Bp,style:[l.chip,c],onPress:()=>o(e.label),children:jsx(R,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(jS,"Chip");function WS(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:zS},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:BS,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...S(e,"bold"),fontSize:12,lineHeight:14,color:Dp,textAlign:"center"}})}i(WS,"makeStyles");var is=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function jp(e){return e.includes("*")||e.includes("`")}i(jp,"hasInlineMarkup");function Wp(e){let t=[],r=0;is.lastIndex=0;for(let n=is.exec(e);n!==null;n=is.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(Wp,"tokenizeInlineMarkdown");function Gp(e,t){return jp(e)?Wp(e).map((r,n)=>{switch(r.kind){case "bold":return jsx(R,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx(R,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx(R,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(Gp,"renderInlineMarkdown");var $p=6,Qp=520,XS=Math.round(Qp*.18),Yp=.44,QS=.5,Xp=[0,.5,1],ZS=[0,1,2];function Zp(){let e=F(),t=useMemo(()=>eT(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:ZS.map(n=>r?jsx(JS,{index:n,style:t.dot},n):jsx(View,{style:[t.dot,t.dotStatic]},n))})}i(Zp,"TypingIndicator");function JS({index:e,style:t}){let r=useRef(new Animated.Value(0)).current;useEffect(()=>{let s=Animated.sequence([Animated.delay(e*XS),Animated.loop(Animated.timing(r,{toValue:1,duration:Qp,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:Xp,outputRange:[Yp,1,Yp]}),o=r.interpolate({inputRange:Xp,outputRange:[0,-3.5,0]});return jsx(Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(JS,"AnimatedDot");function eT(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:$p,height:$p,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:QS}})}i(eT,"makeStyles");function Jp(e,t,r){let n=e-r,o=t!=null?Math.min(n,t):n;return Math.max(0,o)}i(Jp,"resolveTurnScrollTarget");function ef(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(ef,"latestTurn");function tf(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(tf,"nextFollowOffset");function rf(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=ef(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 k=null;if(c!==null){let w=u.current.get(c);if(w===void 0)return;let O=p===null?null:u.current.get(p)??null;k=Jp(w,O,96);}let g=tf(k,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 m=useCallback(P=>{a.current=P.nativeEvent.layout.height,f();},[f]),y=useCallback((P,k)=>{l.current=k,a.current>0&&(s.current=Math.min(s.current,Math.max(0,k-a.current))),f();},[f]),x=useCallback(P=>{s.current=P.nativeEvent.contentOffset.y;},[]),b=useCallback(()=>{n.current=false;},[]),C=useCallback(P=>{let{contentOffset:k,contentSize:g,layoutMeasurement:w}=P.nativeEvent;s.current=k.y,n.current=g.height-k.y-w.height<=24;},[]),_=useCallback(P=>k=>{u.current.set(P,k.nativeEvent.layout.y),(P===c||P===p)&&f();},[c,p,f]);return {ref:r,onLayout:m,onContentSizeChange:y,onScroll:x,onScrollBeginDrag:b,onScrollEnd:C,rowLayout:_}}i(rf,"useThreadFollow");function lf(e,t,r){switch(e){case "loading":return r.renderPending?jsx(Et,{render:r.renderPending,fallback:jsx(of,{})}):jsx(of,{});case "empty":return jsx(lT,{pet:r.shownPet,petRef:t.petRef,prompts:t.suggestedPrompts,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(dT,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx(cT,{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 Ze(e)}}i(lf,"renderView");function of(){let{theme:e,styles:t}=Ee(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),op);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(of,"LoadingState");function lT({pet:e,petRef:t,prompts:r,onSelectPrompt:n,onVetPrep:o,vet:s}){let{styles:a}=Ee();return jsxs(ScrollView,{contentContainerStyle:a.emptyContent,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,accessibilityLabel:h.empty,children:[jsx(zp,{pet:e,petRef:t,onSend:n,onVetPrep:o,vet:s}),jsx(uf,{prompts:r,onSelectPrompt:n})]})}i(lT,"EmptyState");function uf({prompts:e,onSelectPrompt:t}){let{styles:r}=Ee();return e.length===0?null:jsx(View,{style:r.followUps,children:e.map((n,o)=>jsx(uT,{prompt:n,index:o,onSelectPrompt:t},n))})}i(uf,"FollowUps");function uT({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=Ee(),s=X(),a=Rt(s.followUpInMs,{delayMs:En(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(R,{style:o.followUpText,children:e}),jsx(hn,{size:yT,color:n.color.brandInk,direction:"right"})]})})}i(uT,"FollowUpRow");function dT({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Ee(),o=Du(e)?Wu(r):void 0;return jsxs(View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsx(R,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:h.addPet,style:n.retryButton,children:jsx(R,{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(R,{tier:"control",style:n.retryLabel,children:h.retry})}):null]})}i(dT,"ErrorState");function cT({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:x,onFindVet:b,vet:C,onOpenUrl:_}){let{styles:P}=Ee(),k=X();Er(e.length,k);let g=useMemo(()=>dp(e),[e]),w=ld(e,n),O=e[e.length-1],M=useMemo(()=>e.filter(v=>!(v.checkin&&g.get(v.id)?.kind==="folded")),[e,g]),I=rf(M,n);return jsxs(ScrollView,{ref:I.ref,style:P.list,contentContainerStyle:P.listContent,accessibilityLabel:h.transcript,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,onLayout:I.onLayout,onContentSizeChange:I.onContentSizeChange,onScroll:I.onScroll,scrollEventThrottle:mT,onScrollBeginDrag:I.onScrollBeginDrag,onScrollEndDrag:I.onScrollEnd,onMomentumScrollEnd:I.onScrollEnd,children:[e.map(v=>{let T=v.checkin?g.get(v.id):void 0;return T?.kind==="folded"?null:T?.kind==="past"?jsx(Ep,{text:v.text,runDueDays:T.runDueDays,openedAt:v.checkin?.openedAt,onLayout:I.rowLayout(v.id)},v.id):v.checkin&&T!==void 0?jsx(bp,{message:v,checkin:v.checkin,onAnswer:o,petRef:x,onFindVet:b,vet:C,onLayout:I.rowLayout(v.id)},v.id):jsx(gT,{onLayout:I.rowLayout(v.id),message:v,revealing:n&&v===O&&v.role==="assistant",onCopy:s,sentiment:v.responseId===void 0?null:a[String(v.responseId)]??null,onSentiment:l,thanks:u!==null&&v.responseId!==void 0&&String(v.responseId)===u,images:d[v.id]??fT,onPreview:c,onOpenUrl:_},v.id)}),f?jsx(R,{tier:"compact",style:P.reconnectingCaption,accessibilityRole:"text",children:h.reconnecting}):null,w?jsx(Zp,{}):null,p!==null?jsx(pT,{notice:p,onRetry:m,onStartNew:y}):null,n?null:jsx(uf,{prompts:t,onSelectPrompt:r})]})}i(cT,"PopulatedState");function pT({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(R,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsx(R,{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(R,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(pT,"TurnNoticeCard");var fT=Object.freeze([]),mT=16,yT=14;function gT({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=Rt(p.messageInMs),m=Ld(e.text,t,p),y=e.role==="user",x=y?h.senderUser:h.senderAssistant,b=useCallback(_=>o(e,_),[o,e]),C=e.pending!==true;return jsxs(Animated.View,{style:[c.rowBlock,y?c.rowBlockUser:c.rowBlockAssistant,f],onLayout:d,children:[jsx(View,{style:[c.row,y?c.rowUser:c.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${x}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxs(View,{style:[c.bubble,y?c.bubbleUser:c.bubbleAssistant,e.pending?c.bubblePending:null],children:[y&&a.length>0?jsx(Zd,{images:a,onPreview:_=>l({uri:_.uri,label:_.filename})}):null,jsx(R,{style:y?c.bubbleTextUser:c.bubbleTextAssistant,children:y?e.text:Gp(m,{bold:c.bubbleBold,italic:c.bubbleItalic,code:c.bubbleCode})})]})}),!y&&!t?jsx(_p,{citations:e.citations,onOpenUrl:u}):null,C?jsx(Mp,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:b,thanks:s}):null]})}i(gT,"MessageRow");var CT=Object.freeze(["photo"]),RT=1;function cf(e){let{style:t,renderPending:r}=e;return jsx(ti,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(ST,{...e})})}i(cf,"EverfurChat");function ST({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:x,draftStore:b,vetReturnTo:C,vetUsState:_,vetPrefer:P,onOpenUrl:k,keyboardVerticalOffset:g}){let{theme:w,styles:O}=Ee(),M=X(),I=useMemo(()=>ud(e,t),[e,t]),v=hr(I),T=sd(v),V=Xc(),j=td(v),W=useSafeAreaInsets(),ne=ad(v),he=useMemo(()=>l===void 0?void 0:()=>{q(l,"emergency");},[l]),ke=useMemo(()=>C===void 0&&_===void 0&&P===void 0?void 0:{returnTo:C,usState:_,prefer:P},[C,_,P]),st=Wi(V.pets,v.petRef),fe=useMemo(()=>od(v.messages,st?.name??null),[v.messages,st?.name]),Qe=id(fe);Er(Qe.showBanner,M),$u(v.openCheckin,f),Bu(v.askEverfur,v.isBootstrapping,m);let Ir=useMemo(()=>ui(y),[y]);Ku(x,{conversationId:v.conversationId===null?null:String(v.conversationId),isTurnInFlight:v.isStreaming,refresh:v.refreshActiveThread});let Ar=(v.hasUnreadThreads??false)||j.rows.some(Ce=>Ce.unreadCount!==null&&Ce.unreadCount>0)||(v.unreadCount??0)>0,At=Vu(v.messages),[Yt,Wn]=useState(null),ff=useCallback(()=>Wn(null),[]),[Xt,Gn]=useState(null),[mf,us]=useState(null),Ot=useRef(null);useEffect(()=>()=>{Ot.current&&clearTimeout(Ot.current);},[]);let ds=useCallback(Ce=>{us(String(Ce)),Ot.current&&clearTimeout(Ot.current),Ot.current=setTimeout(()=>{us(null),Ot.current=null;},ip);},[]),yf=useCallback((Ce,Fr)=>{let Qt=Ce.responseId;if(Qt===void 0)return;let Cf=v.sentimentByMessage[String(Qt)];v.feedback(Qt,Fr),Fr==="down"&&Cf!=="down"&&Gn(Qt);},[v]),gf=useCallback(async(Ce,Fr)=>Xt===null||!(await v.feedback(Xt,"down",Ce??"other",Fr)).ok?false:(Gn(null),ds(Xt),true),[v,Xt,ds]),hf=useCallback(()=>Gn(null),[]),bf=useCallback(Ce=>{v.send(Ce);},[v.send]),vf=useMemo(()=>k===void 0?void 0:Ce=>{q(k,Ce,"citation");},[k]),cs=Platform.OS==="ios"?"padding":void 0,Or=Wc(g,cs!==void 0),Ef=Or.topInWindow===null?W.top:Math.max(0,W.top-Or.topInWindow),ps={send:v.send,stop:v.stop,isStreaming:v.isStreaming,conversationId:v.conversationId,seed:Ir,draftStore:b,onStage:At.stage,onPreview:Wn};return jsxs(KeyboardAvoidingView,{style:[O.container,{paddingTop:Ef},r],behavior:cs,...Or.avoidingProps,children:[jsx(Gc,{probeRef:Or.probeRef}),jsx(Dc,{pets:V,petRef:v.petRef,historyUnread:Ar,onOpenHistory:j.show,onPetChange:s,onAddPet:p,vet:ke}),c!==void 0?jsx(TT,{petRef:e??null,pet:c,onRegistered:V.refresh}):null,jsx(Yc,{surface:Qe,petRef:v.petRef,renderVetAction:u,onFindVet:l,vet:ke}),jsx(View,{style:O.body,children:lf(T,v,{notice:ne,vet:ke,onCheckinFindVet:he,onSelectPrompt:bf,renderPending:n,shownPet:st,onVetPrep:a,onCopy:o,onSentiment:yf,thanksFor:mf,imagesByMessage:At.byMessage,onPreview:Wn,onAddPet:p,onOpenUrl:vf})}),d!==void 0?jsx(PT,{...ps,attachments:d}):jsx(pf,{...ps,attachments:null}),jsx(pd,{}),w.meta.hidePoweredBy?null:jsx(R,{tier:"compact",style:O.poweredBy,accessibilityRole:"text",accessibilityLabel:h.poweredBy,children:h.poweredBy}),jsx(jc,{chat:v,history:j}),jsx(zc,{visible:Xt!==null,onSubmit:gf,onSkip:hf}),jsx(Dd,{uri:Yt?.uri??null,label:Yt?.label??"",onClose:ff}),jsx(Rr,{})]})}i(ST,"ChatBody");function TT({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Ee(),o=Nu(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs(View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsx(R,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsx(Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:h.retry,hitSlop:Kt,children:jsx(R,{tier:"control",style:n.setupNoticeAction,children:h.retry})})]})}i(TT,"PetSetupNotice");function PT({attachments:e,...t}){let r=useMemo(()=>ec(),[]),n=pn({maxPerMessage:e.maxPerMessage??RT,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??CT,pick:e.pick}),[n,e.sources,e.pick]);return jsx(pf,{...t,attachments:o})}i(PT,"ComposerWithAttachments");function pf({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,m]=Qu(e,n,s);Zu(a,n===null?null:String(n),f,m);let[y,x]=useState(false),[b,C]=useState(false);useEffect(()=>{C(false);},[n]);let _=d.meta.placeholder??h.placeholder,P=o?.state.uploading??false,k=o?.state.failed??false,g=P||k,w=o?.state.attachments??kT;Er(w.length,p);let O=useCallback(()=>{if(f.trim().length===0||g||[...f].length>Lt)return;let W=o?.state.s3Keys??xT;o!==null&&W.length>0?(l(o.state.attachments.filter(ne=>ne.status==="uploaded").map(ne=>({uri:ne.previewUri,filename:ne.filename}))),e(f,{imageS3Keys:W}),o.state.clear()):e(f),m(""),C(false);},[f,e,g,o,l]),M=useCallback(()=>{t();},[t]),I=useCallback(W=>{x(false),o!==null&&(C(false),o.state.dismissRejected(),Ht(o.pick,W).then(ne=>{if(!ne.ok){C(true);return}ne.value!==null&&o.state.add(ne.value);}));},[o]),T=useMemo(()=>[...f].length>Lt,[f])||g,V=o!==null&&w.length>=o.state.maxPerMessage,j=d.slots.sendButton?.textColor??d.color.brandInk;return jsxs(View,{style:c.composerOuter,children:[o!==null&&y?jsx(Vd,{sources:o.sources,full:V,onPick:I,onClose:()=>x(false)}):null,jsxs(View,{style:c.composer,children:[o!==null?jsx(Qd,{attachments:w,rejected:b?_T:o.state.rejected,uploadFailed:k,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:W=>u({uri:W.previewUri,label:W.filename})}):null,jsxs(View,{style:c.composerRow,children:[o!==null?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:Fu(w.length,o.state.maxPerMessage),accessibilityState:{disabled:V,expanded:y},disabled:V,hitSlop:(Gt-Un)/2,style:[c.attachControl,V?c.attachControlDisabled:null],onPress:()=>x(W=>!W),children:jsx(Ed,{size:lp,color:V?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsx(Ut,{style:c.input,value:f,onChangeText:m,placeholder:_,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,onSubmitEditing:O,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(xd,{size:ap,color:j,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:O,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(kd,{size:sp,color:j,testID:"everfur-send-glyph"})})})]})]})]})}i(pf,"Composer");var kT=Object.freeze([]),xT=Object.freeze([]),_T=Object.freeze({code:"unknown",retryable:true,filename:""});function FT(e){let{runtime:t,userRef:r,scopeEpoch:n}=Y(),o=useMemo(()=>Je(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(FT,"useEverfurPetProfile");function LT(e){return createElement(un,{clientTheme:e.clientTheme??null,seams:cn,children:e.children})}i(LT,"EverfurThemeProvider");export{ti as CapabilityGate,cf as EverfurChat,Q as EverfurConfigError,$h as EverfurProvider,LT as EverfurThemeProvider,Mr as EverfurThrownError,mg as THEME_SLOT_KEYS,gt as THEME_SLOT_NAMES,ur as canonicalPetSpecies,qn as categoryFor,wf as conversationId,qf as createRnRecordsUploadTransport,S as face,Tf as isErr,Sf as isOk,$n as isRetryableCode,xf as petRef,zg as previewTheme,Pf as unwrap,Nt as useCapability,pn as useChatAttachments,ou as useEverfur,hr as useEverfurChat,FT as useEverfurPetProfile,Tn as useEverfurPets,F as useEverfurTheme,Ft as userFacingError,_f 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"),Km(r.source,l)}i(Gm,"eventSourceByteSource");async function*Km(e,t){try{yield*e;}finally{t();}}i(Km,"sourceWithCleanup");function qm(){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(qm,"createByteQueue");async function $m(e,t){let r=t.fetchImpl??sa(),n=aa(t.config.apiBaseUrl,e.path,e.query),o=la(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=ey(Wm),a=ty(s.signal,e.signal),l;try{l=await r(n,ua({...e,signal:a},o));}catch(d){return E(uo(d))}finally{s.cancel();}let u=await da(l);return l.ok?L(u):E(Qm(l.status,u,oa(l)))}i($m,"requestJson");function na(e){return {request:i(t=>$m(t,e),"request"),stream:i((t,r)=>Ym(Jm(t,r),e),"stream")}}i(na,"createHttpTransport");async function*Ym(e,t){let r=aa(t.config.apiBaseUrl,e.path,e.query),n=la(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Xm(e,n));yield*$r(Gm(l),()=>Zm(l));return}let o=t.fetchImpl??sa(),s;try{s=await o(r,ua(e,n));}catch(l){yield ea("",true,ma(l));return}let a=oa(s);if(!s.ok){let l=await da(s),u=ca(l)??ia(s.status),d=fa(l)||We(Me(u));yield ea(u,d,pa(l),a);return}if(s.body){yield*$r(Js(s.body),a);return}yield*$r(Js(null),a);}i(Ym,"streamFrames");function Xm(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Xm,"buildEventSourceInit");function Qm(e,t,r){let n=ca(t),o=n?Me(n):Fs(e),s=pa(t);return D(o,{httpStatus:e,...fa(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...ta(t)?{reasonCode:ta(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Qm,"errorFromResponse");function uo(e){return D("internalError",{retryable:true,wireMessage:ma(e)})}i(uo,"networkError");function oa(e){let t=e.headers.get(ra);return typeof t=="string"&&t.length>0?t:null}i(oa,"requestIdOf");function Zm(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(ra);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(Zm,"eventSourceRequestId");function ia(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(ia,"statusToWireCode");function ea(e,t,r,n=null){return fe({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(ea,"syntheticErrorFrame");function sa(){let e=globalThis.fetch;if(typeof e!="function")throw new ee("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(sa,"getGlobalFetch");function aa(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(aa,"buildUrl");function la(e,t,r,n){let o={...Zs(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(la,"mergeHeaders");function ua(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(ua,"buildInit");function Jm(e,t){return e.signal?e:{...e,signal:t}}i(Jm,"withSignal");function ey(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(ey,"timeoutSignal");function ty(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(ty,"mergeAbortSignals");async function da(e){try{return await e.json()}catch{return null}}i(da,"safeJson");function ta(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(ta,"extractReasonCode");function ca(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(ca,"extractWireCode");function pa(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(pa,"extractWireMessage");function fa(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(fa,"extractRetryable");function ma(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(ma,"describeCause");var ry=3e4,ny=ro*2,oy="idempotency-key",iy=new Set(["POST","PUT","PATCH","DELETE"]),sy=Object.freeze({onEvent(){}}),ay=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ly(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(ly,"seededIdempotencyKey");function Ae(e){let t=e.observer??sy,r=e.timers??ay,n=e.rng??Math.random,o=e.sleep??((f,m)=>Ry(f,r,m)),s=e.maxAttempts??rr,a=e.unaryTimeoutMs??ry,l=e.newIdempotencyKey??dy(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,y){let R=y?.maxAttempts,h=Math.max(1,R??s),C=y?.idempotent??iy.has(m.method),_=y?.idempotencyKey===void 0?null:ly(y.idempotencyKey),P=C?_??l():null,x=uy(m,P),g=0;for(;;){let w=i(W=>Object.freeze({call:f,method:m.method,path:m.path,attempt:g,...P?{idempotencyKey:P}:{},...W}),"stamp");u(w({phase:"attempt"}));let O=Ey(a,r),M=Cy(O.signal,m.signal),I;try{I=await Ks({...x,signal:M.signal},e.auth);}catch(W){I=E(uo(W));}finally{M.dispose(),O.cancel();}if(I.ok)return u(w({phase:"settled",ok:true,reason:"ok"})),I;let v=I.error,k=py(v,g,{maxAttempts:h,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...R!==void 0?{perCallMaxAttempts:R}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),V={ok:false,code:v.code,reason:k.reason,...v.httpStatus!==void 0?{httpStatus:v.httpStatus}:{},...v.requestId!==void 0?{requestId:v.requestId}:{}};if(!k.retry)return u(w({phase:"settled",...V})),E(v);if(u(w({phase:"retry",...V,delayMs:k.delayMs})),await o(k.delayMs,m.signal),m.signal?.aborted===true)return u(w({phase:"settled",...V,reason:"aborted"})),E(v);g+=1;}}i(d,"send");async function c(f){return nr(f,await vy(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 fe({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(Ae,"createRequestFunnel");function uy(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==oy&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(uy,"assembleHeaders");function dy(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(dy,"defaultIdempotencyKeyFactory");var cy=10;function py(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=fy(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!We(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(cy,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=my(e,r.now);return u!==null?u>ny?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Gr(t,r.rng)}}i(py,"decideRetry");function fy(e){let t=e.code==="unknown"?Me(by(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(fy,"throttleKind");function my(e,t){let r=gy(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=yy(e.raw);return n===null?null:Math.round(n*1e3)}i(my,"retryOverrideMs");function yy(e){for(let t of co(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(yy,"findRetryAfterSeconds");function gy(e){for(let t of co(e)){let r=t.resets_at,n=hy(r);if(n!==null)return n}return null}i(gy,"findResetsAt");function co(e){if(!ya(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];ya(n)&&t.push(n);}return t}i(co,"candidateScopes");function hy(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(hy,"parseInstantMs");function by(e){for(let t of co(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(by,"rawWireCode");function ya(e){return typeof e=="object"&&e!==null}i(ya,"isRecord");async function vy(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(vy,"resolveDeviceAuth");function Ey(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Ey,"boundedSignal");function Cy(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(Cy,"mergeSignals");function Ry(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(Ry,"delayAbortable");var Xr=Object.freeze(["better","same","worse"]),fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ga(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(ga,"invalid");function po(){return E(D("internalError",{retryable:false}))}i(po,"malformed");function ha(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):ve(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(ha,"petPath");var Ge=i(e=>typeof e=="string"?e:null,"str"),ba=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function va(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ge(t.case_id),n=Ge(t.status);if(r===null||n===null)return null;let o=Ge(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Ge(t.body_location),lastResponse:o!==null&&Xr.includes(o)?o:null,checkInDueAt:Ge(t.check_in_due_at),openedAt:Ge(t.opened_at),resolvedAt:Ge(t.resolved_at),resolutionText:Ge(t.resolution_text),checkinAskCount:ba(t.checkin_ask_count),checkinAnswerCount:ba(t.checkin_answer_count)})}i(va,"caseFromWire");function Ea(e){return {async list(t,r){let n=ha(t);if(typeof n!="string")return E(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return E(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return po();let a=s.map(va);return a.every(l=>l!==null)?L(Object.freeze(a)):po()},async checkin(t,r,n,o){let s=ha(t);if(typeof s!="string")return E(s);if(typeof r!="string"||!fo.test(r))return ga("case_id must be a UUID");if(!Xr.includes(n))return ga("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 E(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=va(l.case);return u===null?po():L(Object.freeze({case:u,ctaDeepLink:Ge(l.cta_deep_link)}))}}}i(Ea,"createCasesRepositoryOver");var Ca=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 Zr(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(Zr,"delayAbortable");function Jr(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(Jr,"mergeSignals");var mo=class mo{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?Jr(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(mo,"MediaStore");var Qr=mo;function go(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(go,"makeUser");function ho(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(ho,"makeAssistant");function sr(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(sr,"stripPending");function Sa(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(Sa,"appendText");function bo(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(bo,"finalizeAssistant");function Ta(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(Ta,"freezeSnapshot");function U(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function vo(e){let t=Me(e.code);return D(t,{retryable:e.retryable||Wr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(vo,"errorFromFrame");function Le(e){return fe({code:Sy(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Le,"synthErrorFrame");function Sy(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 nt(e)}}i(Sy,"canonicalWireCode");function Pa(e){let t=Array.isArray(e)?e:yo(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!yo(n))continue;let o=ir(n.category)??ir(n.title)??"",s=Ty(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(Pa,"parsePromptCategories");function Eo(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(Eo,"flattenPrompts");function yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(yo,"isPlainObject");function ir(e){return typeof e=="string"?e:null}i(ir,"asStr");function Ty(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(yo(r)){let n=ir(r.text)??ir(r.prompt)??ir(r.title);n!==null&&t.push(n);}return t}i(Ty,"asPromptTextList");function ka(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(ka,"defaultIdFactory");function xa(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(xa,"defaultIdempotencyFactory");var wa={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*Ia(e,t,r,n){let o=e[Symbol.asyncIterator](),s=_a(t.overallMs,n),a=_a(t.idleMs,n),l=xy(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 ky();return}if(d.tag==="idle"||d.tag==="overall"){yield Py();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(Ia,"withWatchdog");function Py(){return fe({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Py,"synthTimeoutFrame");function ky(){return fe({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(ky,"synthStreamErrorFrame");function _a(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(_a,"deadline");function xy(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(xy,"abortPromise");var _y="checkin",wy=/^\d{4}-\d{2}-\d{2}$/,en="watching";function Aa(e){return e.status!=null&&e.status!==en}i(Aa,"isCheckinSettled");function Oa(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(Oa,"isLiveAskAnswered");function Co(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==_y||n===void 0||o===void 0||!fo.test(n)||!wy.test(o)?null:{caseId:n,dueDay:o}}i(Co,"parseCheckinOrigin");function Fa(e){return Co(e)?.caseId??null}i(Fa,"parseCheckinOriginRef");function So(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return E(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||ve(o))return E(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),L(r.length?`?${r.join("&")}`:"")}i(So,"historyQuery");function lr(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(lr,"validConversationId");function Lt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(Lt,"object");function Ma(e){return e==null||typeof e=="string"&&e.length>0&&!ve(e)}i(Ma,"cursor");function ar(){return E(D("internalError",{retryable:false}))}i(ar,"malformed");function La(e){let t=Lt(e);if(!t||!Array.isArray(t.conversations)||!Ma(t.next_cursor))return ar();let r=[];for(let n of t.conversations){let o=Lt(n);if(!o||typeof o.conversation_id!="string"||!lr(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return ar();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return ar();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(La,"mapConversationPage");function Da(e){let t=Lt(e);if(!t||!Array.isArray(t.messages)||!Ma(t.next_cursor))return ar();let r=[],n=new Set;for(let o of t.messages){let s=Lt(o);if(!s||typeof s.message_id!="string"||!lr(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return ar();if(s.role!=="user"&&s.role!=="assistant"&&s.role!=="vet"||n.has(s.message_id))continue;if(n.add(s.message_id),s.role==="vet"){r.push(Iy(s,s.message_id,s.content,s.created_at));continue}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:Ay(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Oy(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(Da,"mapMessagePage");function Iy(e,t,r,n){let o=Lt(e.sender),s=Ro(o?.display_name)??Ro(e.sender_display_name),a=Ro(o?.specialty);return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:Object.freeze({displayName:s,specialty:a})})}i(Iy,"vetMessage");function Ro(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!ve(t)?t:null}i(Ro,"trimmedText");function Ay(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ay,"normalizeUrgency");function Oy(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=Lt(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(Oy,"historyCitations");var To=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Dt=4e3;var Nt=4e3;function Na(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(Na,"validateImageKeys");function ko(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>Nt?{reason:"too_long",error:U("validationFailed",false,`message is ${r} characters; the server accepts at most ${Nt}`)}:null}i(ko,"validateMessageText");function Ua(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ua,"urgencyTier");async function*ur(e){yield e;}i(ur,"singleFrameStream");async function*Va(){}i(Va,"emptyStream");var Fy=6e4,My=18e4,Ly=24,Dy=512,Ny=false;function Ba(e){return new xo(e)}i(Ba,"createChatController");var _o=class _o extends Qr{constructor(r){super(Ta({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??Ae({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=Ea(this.funnel),this.telemetry=r.telemetry??qr,this.errorPolicy=r.errorPolicy??Ds,this.timers=r.timers??wa,this.rng=r.rng??Math.random,this.newId=r.newId??ka(),this.makeIdempotencyKey=r.makeIdempotencyKey??xa(),this.budget={idleMs:r.budget?.idleMs??Fy,overallMs:r.budget?.overallMs??My};}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),()=>{}):ur(Le(u))}let a=ko(r)??Na(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),()=>{}):ur(Le(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 ur(Le(U("accessDenied",false)));let o=ko(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),ur(Le(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,go(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?sr(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(Eo(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=So(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return E(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 E(U("accessDenied",false));if(!a.ok)return a;let l=La(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 E(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?L(n):E(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return E(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):E(l.error)}async markRead(r){if(this.disposed)return E(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?E(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)):E(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return E(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||ve(r))return E(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!To.includes(n))return E(U("validationFailed",false,`feedback_type must be one of ${To.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>Dt)return E(U("validationFailed",false,`notes is over ${Dt} 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 E(U("accessDenied",false));if(!d.ok)return E(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 E(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return E(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 E(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(!lr(r))return E(U("validationFailed",false));let o=So(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return E(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?E(U("accessDenied",false)):a.ok?Da(a.value):a}async resumeConversation(r){if(this.disposed)return E(U("accessDenied",false));if(!lr(r))return E(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 E(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===en).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||Oa({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:m?en: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 E(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 E(U("accessDenied",false));if(!o.ok)return E(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 E(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 E(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 Le(n.error));}async primeConversation(r){if(this.disposed)return E(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?E(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 E(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?E(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 E(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?E(U("internalError",true)):L(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return E(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&ve(o))return E(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?E(U("accessDenied",false)):a.ok?L(Pa(a.value)):E(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=Jr(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,go(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 h=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;h.ok&&this.snapshot.conversationId===null&&this.adoptConversation(h.value);}if(u&&this.snapshot.conversationId===null){let h=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!h.ok){yield*this.emitTerminal(r,h.error,Le(h.error));return}this.adoptConversation(h.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let h=U("internalError",!0);yield*this.emitTerminal(r,h,Le(h));return}this.clearAssistantInProgress(r);let p=new AbortController,f=Jr(o.signal,p.signal),m=null;try{let h;try{h=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let _=this.authRejected();yield*this.emitTerminal(r,_,Le(_));return}if(o.signal.aborted||!this.alive(o.epoch))return;let C=this.funnel.stream("chat.send",h,f);for await(let _ of Ia(C,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(_.kind==="error"&&_.terminal){m=_;break}if(this.applyFrame(_,r),yield _,_.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 h=U("streamIncomplete",!0);yield*this.emitTerminal(r,h,Le(h));return}let y=Me(m.code);if(y==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let h=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!h){let C=this.authRejected();yield*this.emitTerminal(r,C,m);return}this.patch({reconnecting:!0});continue}if(y==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let h=this.authRejected();yield*this.emitTerminal(r,h,m);return}if(y==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,vo(m),m);return}if(Ms(y)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let R=m.retryable&&Wr(y,!0);if(Ny&&R&&s+1<this.errorPolicy.maxAttempts(y));yield*this.emitTerminal(r,vo(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 nt(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?sr(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,ho(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Dy){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);},Ly);}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?Sa(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?bo(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?sr(d):d),bo(ho(l,"",this.stamp()),r)];}let a=Eo([{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=Ua(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?sr(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(_o,"ChatControllerImpl");var xo=_o;async function ja(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),[m,y]=await Promise.all([p,f]),R=null;if(m.ok)R=m.value,s.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let x=m.error;c=x,Ha(x)?(l=true,d=x):(za(x)&&(a=true),u=true);}let h=[];y.ok?h=y.value:C(y.error);function C(x){Ha(x)?(l=true,d===null&&(d=x)):za(x)&&(a=true);}i(C,"recordAuthSignals");let _=d!==null?d.displayMessage:null;return Object.freeze({conversationId:R,petRef:n,suggestedPrompts:h,error:_,warning:_===null&&R===null&&u?Uy:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(ja,"bootstrapChat");var Uy="Chat is ready. Your first message will start the conversation.";function Ha(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(Ha,"isUnauthorized");function za(e){return e.httpStatus===403||e.code==="accessDenied"}i(za,"isForbidden");var wo=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Wa(e){return e!==wo}i(Wa,"isUploadTransportAvailable");var Vy=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var tn=10*1024*1024,rn=5,dr=120,By="/widget/v1/uploads/initiate";function Hy(e){return typeof e=="string"&&Vy.includes(e.trim().toLowerCase())}i(Hy,"isAttachmentMime");function Io(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<=dr)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,dr);let n=t.slice(r);return n.length>=dr?t.slice(0,dr):`${t.slice(0,r).slice(0,dr-n.length)}${n}`}i(Io,"sanitizeFilename");function Ao(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(Ao,"formatBytes");var cr=i(e=>Object.freeze({ok:true,value:e}),"ok"),Oe=i(e=>Object.freeze({ok:false,error:e}),"err");function le(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(le,"failure");function zy(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(zy,"attachmentSize");function jy(e){let t=Io(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!Hy(r))return Oe(le("unsupported_type",false,t));let n=zy(e);return n===null?Oe(le("unknown",false,t)):n>tn?Oe(le("too_large",false,t,{sizeBytes:n})):cr(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(jy,"validateAttachment");function Wy(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)??tn,s3_key:a,purpose:r(t.purpose)})}i(Wy,"parsePolicy");function Gy(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return le("quota_exceeded",false,t,{cause:e});case "rateLimited":return le("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return le("idempotency_conflict",true,t,{cause:e});case "validationFailed":return le("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return le("network",true,t,{cause:e});default:return r===429?le("rate_limited",true,t,{cause:e}):r===503?le("network",true,t,{cause:e}):r===void 0?le("network",true,t,{cause:e}):le("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Gy,"initiateFailure");async function Ky(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:By,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return Oe(Gy(n.error,t.filename));let o=Wy(n.value);return o===null?Oe(le("server",false,t.filename)):cr(o)}i(Ky,"initiateAttachmentUpload");async function qy(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return Oe(le("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),cr(void 0)}catch{return o()?Oe(le("cancelled",true,r.filename)):Oe(le("server",true,r.filename))}}i(qy,"uploadAttachmentBytes");var $y=2,Yy=3,Xy=Object.freeze([1e3,2e3,4e3]),Ga=0;function Qy(){return Ga+=1,`attachment-${Ga}`}i(Qy,"defaultNewId");function Ka(e){let t=Math.max(1,e.concurrency??$y),r=Math.max(1,e.maxAttempts??Yy),n=e.backoffMs??Xy,o=Math.max(1,e.maxPerMessage??rn),s=e.timers??Ra,a=e.newId??Qy,l=Wa(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),y=false,R=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(g=>{let w=u.get(g);return w===void 0?[]:[w.state]}))});for(let g of f)g();},"publish"),h=i((g,w)=>{g.state=Object.freeze({...g.state,...w}),R();},"patch"),C=i(()=>{for(;!y&&p.size<t&&c.length>0;){let g=c.shift(),w=u.get(g);w!==void 0&&(p.add(g),_(w).finally(()=>{p.delete(g),C();}));}},"pump"),_=i(async g=>{let{attachment:w}=g;for(;g.attempts<r;){if(y||g.controller.signal.aborted)return;g.attempts+=1;let O=g.controller.signal;h(g,{status:"uploading",error:null,progress:0});let M=await Ky(e.funnel,w,{signal:O});if(y||O.aborted)return;let I;if(!M.ok)I=Oe(M.error);else {let W=await qy(e.transport,M.value,w,{signal:O,onProgress:i(G=>{!O.aborted&&g.state.status==="uploading"&&h(g,{progress:Zy(G)});},"onProgress")});if(y||O.aborted)return;I=W.ok?cr(M.value.s3_key):Oe(W.error);}if(I.ok){h(g,{status:"uploaded",s3Key:I.value,error:null,progress:1});return}let v=I.error,k=v.retryable&&g.attempts<r;if(h(g,{status:k?"uploading":"failed",error:v,progress:0}),!k)return;let V=n[Math.min(g.attempts-1,n.length-1)]??0;await Zr(V,O,s);}},"run"),P=i(g=>{c.push(g.state.id),C();},"enqueue"),x={available:l,subscribe(g){return f.add(g),()=>{f.delete(g);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(g=>g.status==="uploading")},get s3Keys(){return m.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[])},add(g){let w=jy(g);if(!w.ok)return w;if(y||d.length>=o)return Oe(le("too_many",false,w.value.filename));let O=a(),M={attachment:w.value,controller:new AbortController,attempts:0,state:Object.freeze({id:O,filename:w.value.filename,previewUri:g.uri,contentType:w.value.contentType,sizeBytes:w.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(O,M),d.push(O),R(),P(M),cr(M.state)},retry(g){let w=u.get(g);w===void 0||y||w.state.status!=="failed"||(w.controller=new AbortController,w.attempts=0,h(w,{status:"uploading",error:null,progress:0,s3Key:null}),P(w));},remove(g){let w=u.get(g);if(w===void 0)return;w.controller.abort(),u.delete(g);let O=d.indexOf(g);O>=0&&d.splice(O,1);let M=c.indexOf(g);M>=0&&c.splice(M,1),R();},clear(){for(let g of [...d])x.remove(g);},dispose(){y=true;for(let g of u.values())g.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return x}i(Ka,"createAttachmentQueue");function Zy(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Zy,"clamp");var qa=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function pr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(qa,t)?qa[t]:null}i(pr,"canonicalPetSpecies");var $a=50,Jy=128,Oo=120,Ya=120,eg=2e3,Xa=120,tg=80,Ja=new Set(["male","female","unknown"]),el=new Set(["day","month","year"]),tl=new Set(["low","medium","high","athletic"]),rl=new Set(["indoor","outdoor","both"]),nl=new Set(["mild","moderate","severe"]),rg=/^(\d{4})-(\d{2})-(\d{2})$/,ol=[["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"]],il=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...ol,...il].map(([e])=>e));function ng(e){let t=rg.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(ng,"isRealDate");var mr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),og=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),on=i((e,t)=>typeof t=="string"&&ng(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),De=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(ve(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=pt(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),ig={sex:mr(Ja),spayedNeutered:og,birthDate:on,birthDatePrecision:mr(el),activityLevel:mr(tl),indoorOutdoor:mr(rl),foodBrand:De(Xa),foodType:De(Xa),microchipId:De(tg)},Fo=["ref","ref",false,De(Jy,{required:true,trimmed:true})],Mo=["notes","notes",false,De(eg,{trimmed:true})],Qa=[Fo,["name","name",true,De(Oo,{required:true,trimmed:true})],["dose","dose",false,De(Ya,{trimmed:true})],["frequency","frequency",false,De(Ya,{trimmed:true})],["startDate","start_date",false,on],["endDate","end_date",false,on],Mo],sg={allergies:[Fo,["allergen","allergen",true,De(Oo,{required:true,trimmed:true})],["severity","severity",false,mr(nl)],Mo],medications:Qa,supplements:Qa,conditions:[Fo,["conditionName","condition_name",true,De(Oo,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,on],Mo]};function ag(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 sg[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(ag,"itemToWire");function lg(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=ag(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(lg,"listToWire");function sl(e,t){let r=e,n={};for(let[a,l]of ol){let u=r[a];if(u!==void 0){if(u!==null){let d=ig[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 il){let u=r[a];if(u===void 0)continue;let d=lg(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&pr(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(sl,"petHealthToWire");var ne=i(e=>typeof e=="string"?e:null,"str"),fr=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),ug=i(e=>typeof e=="boolean"?e:null,"bool");function nn(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(nn,"itemsFromWire");function Za(e){let t=ne(e.name);return t===null||t.length===0?null:Object.freeze({ref:ne(e.ref),name:t,dose:ne(e.dose),frequency:ne(e.frequency),startDate:ne(e.start_date),endDate:ne(e.end_date),notes:ne(e.notes)})}i(Za,"medicationFromWire");function al(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:fr(Ja,e.sex),spayedNeutered:ug(e.spayed_neutered),birthDate:ne(e.birth_date),birthDatePrecision:fr(el,e.birth_date_precision),activityLevel:fr(tl,e.activity_level),indoorOutdoor:fr(rl,e.indoor_outdoor),foodBrand:ne(e.food_brand),foodType:ne(e.food_type),microchipId:ne(e.microchip_id),allergies:nn(e.allergies,r=>{let n=ne(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:ne(r.ref),allergen:n,severity:fr(nl,r.severity),notes:ne(r.notes)})}),medications:nn(e.medications,Za),supplements:nn(e.supplements,Za),conditions:nn(e.conditions,r=>{let n=ne(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:ne(r.ref),conditionName:n,diagnosedDate:ne(r.diagnosed_date),notes:ne(r.notes)})})})}i(al,"petHealthFromWire");var dl=100,cl=50,pl=100,fl=50,ml=500,dg=128,cg=6e4;function Ue(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(Ue,"invalid");function ft(e,t,r){if(typeof t!="string")return Ue(`${e} must be a string`);let n=pt(t);return n<=r?null:Ue(`${e} is ${n} characters; the server accepts at most ${r}`)}i(ft,"checkString");function sn(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Ue(`${e} must be a finite number between 0 and ${r}`)}i(sn,"outOfRange");function ll(e,t){if(typeof e!="string")return Ue("pet_ref must be a string");if(e.trim().length===0)return Ue("pet_ref must not be blank");if(ve(e))return Ue("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Ue("profile must be an object");let r=[ft("pet_ref",e,dg)];return t?.name!==void 0&&r.push(ft("name",t.name,dl)),t?.species!==void 0&&r.push(ft("species",t.species,cl)),t?.breed!==void 0&&r.push(ft("breed",t.breed,pl)),t?.ageYears!==void 0&&r.push(sn("age_years",t.ageYears,fl)),t?.weightKg!==void 0&&r.push(sn("weight_kg",t.weightKg,ml)),r.find(n=>n!==null)??null}i(ll,"validate");function yl(e,t){let r=sl(e,t);return "error"in r?{error:Ue(r.error)}:r}i(yl,"healthToWire");function pg(e){if(typeof e!="object"||e===null)return {error:Ue("patch must be an object")};let t=e,r=[["name","name",s=>ft("name",s,dl)],["species","species",s=>ft("species",s,cl)],["breed","breed",s=>ft("breed",s,pl)],["ageYears","age_years",s=>sn("age_years",s,fl)],["weightKg","weight_kg",s=>sn("weight_kg",s,ml)]],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=yl(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Ue("patch must change at least one field")}:{body:n})}i(pg,"patchToWire");function fg(e){if(e==null)return {body:{}};let t=yl(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(fg,"toWire");var Ne=i(e=>typeof e=="string"?e:null,"str"),an=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function ul(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Ne(r.pet_ref)??t,name:Ne(r.name),species:Ne(r.species),breed:Ne(r.breed),ageYears:an(r.age_years),weightKg:an(r.weight_kg)})}i(ul,"fromWire");function gl(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ne(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Ne(t.pet_id),petRef:r,name:Ne(t.name),species:Ne(t.species),breed:Ne(t.breed),ageYears:an(t.age_years),weightKg:an(t.weight_kg),updatedAt:Ne(t.updated_at)})}i(gl,"widgetPetFromWire");function mg(e){let t=gl(e);return t===null?null:Object.freeze({...t,...al(e)})}i(mg,"widgetPetProfileFromWire");function yg(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=gl(r);return n===null?[]:[n]}))}i(yg,"petListFromWire");function ot(e){return gg(Ae({auth:e}),Ae({auth:e,unaryTimeoutMs:cg}))}i(ot,"createPetsRepository");function gg(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>ll(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(yg(s.value)):E(s.error)},async registerPet(o,s,a){let l=ll(o,s);if(l!==null)return E(l);let u=fg(s);if("error"in u)return E(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(ul(p.value,o)):E(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return E(l);let u=pg(s);if("error"in u)return E(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?L(ul(d.value,o)):E(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return E(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return E(l.error);let u=mg(l.value);return u===null?E(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 E(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?L(void 0):E(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):E(s.error)}}}i(gg,"createPetsRepositoryOver");var Do=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 hg(e){return Do[e]}i(hg,"requires");function hl(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(Do))for(let a of Do[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(hl,"deniedDecisionsFor");function bl(e,t,r){let n=hg(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 Lo({name:e,enabled:false,isPending:true,limits:{}});let s=bg(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?Lo({name:e,enabled:true,isPending:false,limits:s}):Lo({name:e,enabled:false,isPending:false,limits:s,disabled:vg(n,o)})}i(bl,"decideCapability");function bg(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(bg,"mergeLimits");function vg(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:Mt("accessDenied"),level:"user_entitlement",recoverable:false})}i(vg,"disabledFor");function Lo(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(Lo,"freezeDecision");function X(e){let t=Y(e);return t===null?null:Cg(t)}i(X,"parseColor");function Y(e){if(typeof e=="number")return vl(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return No(t.slice(1));if(t.toLowerCase().startsWith("0x"))return No(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Eg(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=No(t);if(r!==null)return r}return /^\d+$/.test(t)?vl(Number.parseInt(t,10)):null}i(Y,"toRgba");function No(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Uo(t[0]),g:Uo(t[1]),b:Uo(t[2]),a:1};if(t.length===6)return {r:mt(t,0),g:mt(t,2),b:mt(t,4),a:1};if(t.length===8){let r=mt(t,0);return {r:mt(t,2),g:mt(t,4),b:mt(t,6),a:r/255}}return null}i(No,"fromHex");function Eg(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=Vo(Number(n[0])),s=Vo(Number(n[1])),a=Vo(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(Eg,"fromRgbFunc");function vl(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(vl,"argbIntToRgba");function mt(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(mt,"byte");function Uo(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Uo,"dup");function Vo(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Vo,"clampByte");function Cg(e){if(e.a>=1)return Ke(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Cg,"normalizeRgba");function Ke(e,t,r){return `#${Bo(e)}${Bo(t)}${Bo(r)}`.toUpperCase()}i(Ke,"rgbToHex");function Bo(e){return e.toString(16).padStart(2,"0")}i(Bo,"hex2");var Rg="#111111",Ut="#FFFFFF",ln="#000000";function Cl(e){let t=Y(e);if(t===null)return Ut;let r=yt(t),n=yt({r:17,g:17,b:17}),o=yt({r:255,g:255,b:255});return jo(r,o)>=jo(r,n)?Ut:Rg}i(Cl,"readableOn");function Vt(e,t){let r=Cl(e);return oe(r,e)>=t?r:oe(Ut,e)>=oe(ln,e)?Ut:ln}i(Vt,"legibleOn");function Ee(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,oe(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Ut)>=t(ln)?Ut:ln}i(Ee,"poleForGrounds");function yt(e){let t=Ho(e.r/255),r=Ho(e.g/255),n=Ho(e.b/255);return .2126*t+.7152*r+.0722*n}i(yt,"relativeLuminance");function Ho(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(Ho,"linearize");function jo(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(jo,"luminanceContrast");function oe(e,t){let r=Y(e),n=Y(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:Rl(r,o);return jo(yt(s),yt(o))}i(oe,"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 Ve(e,t){let r=Y(e),n=Y(t);if(r===null||n===null)return null;let o=r.a>=1?r:Rl(r,{...n});return Ke(o.r,o.g,o.b)}i(Ve,"flattenOnto");function Sl(e,t){let r=Y(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(Sl,"withAlpha");var El=.05;function yr(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>oe(d,c)>=n),"reads");if(Y(e)===null)return r;if(s(e))return e;let a=Ve(e,o),l=a===null?null:Y(a),u=Y(r);if(l===null||u===null)return r;for(let d=1;d<1/El;d+=1){let c=d*El,p=i((m,y)=>Math.round(m+(y-m)*c),"mix"),f=Ke(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(yr,"pushToContrast");function Tl(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(Tl,"rgbToHsl");function Wo(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:zo(c+l),g:zo(p+l),b:zo(f+l)}}i(Wo,"hslToRgb");function zo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(zo,"channel");var qe=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link"]),Sg=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Q=4.5,Tg=Object.freeze({});function Pg(e){return qe.includes(e)}i(Pg,"isSlotName");function kg(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(kg,"parseRadius");function Pl(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(!Pg(n)||o===null||typeof o!="object")continue;let s=xg(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(Pl,"parseThemeSlots");function un(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(un,"pick");function xg(e){let t={},r=X(un(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=X(un(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=kg(un(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=X(un(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(xg,"parseSlot");function dn(e,t){return t===null||Object.keys(t).length===0?e??Tg:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(dn,"mergeThemeSlots");var gr=3;function _g(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>Ve(e,r)??r)}i(_g,"seatsOf");function wg(e,t){let r=Ee(e);return e.every(n=>oe(r,n)>=t)}i(wg,"someInkReads");function Ig(e,t){let r=t[0];return r===void 0?null:Ve(e,r)}i(Ig,"collapseUnsatisfiableFill");function Ag(e){let t=Vt(e[0],Q);return e.every(r=>oe(t,r)>=Q)?t:Ee(e)}i(Ag,"inkFor");function kl(e,t){let r=false,n={};for(let o of qe){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=_g(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!wg(u,Q)){let p=Ig(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=>oe(p,f)<Q))&&(d.textColor=Ag(u),c=true);else if(p!==void 0){let f=yr(p,u,Ee(u),Q);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=yr(s.borderColor,u,Ee(u),gr);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(kl,"guardSlotContrast");function $e(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))$e(e[t]);}return e}i($e,"deepFreeze");var pn=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),_l={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},wl={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},xl={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Og={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Fg={regular:"400",medium:"500",bold:"700"},Mg={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Go=0,gt="System",Be="monospace",Lg=["content","heading","control","compact","badge"];function Dg(e){let t={};for(let r of Lg)t[r]=e;return t}i(Dg,"authoredTierSizes");function Il(){return {family:gt,mono:Be,fontUrl:null,families:{regular:gt,medium:gt,bold:gt,mono:Be,monoMedium:Be,monoBold:Be},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:xl,tierSizes:Dg(xl),lineHeight:Og,weight:Fg,letterSpacing:Mg,scale:1,maxScale:Go,scaleCaps:pn}}i(Il,"baseType");var Al={},ht=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function cn(e){return `cubic-bezier(${e.join(", ")})`}i(cn,"cssCubicBezier");var Ol={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cn(ht.standard),emphasized:cn(ht.emphasized),exit:cn(ht.exit)},reducedMotion:false},Ng={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",onDanger:"#FFFFFF",errorRed:"#CC1600",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",bubbleVet:"#FFC3BC",onBubbleVet:"#111111",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},Ce=$e({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Ng,space:_l,radius:wl,type:Il(),motion:Ol,slots:Al}),Ug={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",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#111111",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},it=$e({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Ug,space:_l,radius:wl,type:Il(),motion:Ol,slots:Al});function bt(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(bt,"textGrounds");function Fl(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(Fl,"controlGrounds");function Ko(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Ko,"linkGrounds");function Ml(e,t){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...Ll(e,t)]}i(Ml,"statusGrounds");function Ll(e,t){return [Ve(t,e.surface)??e.surface,Ve(t,e.surfaceCream)??e.surfaceCream]}i(Ll,"washGrounds");function Vg(e){return [e.composerFill,e.chatGround]}i(Vg,"composerGrounds");var Bg=new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function Dl(e,t){let r=new Set(bt(t));return bt(e).every(n=>r.has(n))}i(Dl,"onCompiledGrounds");function Nl(e){let t=e.color,r=(e.brightness==="dark"?it:Ce).color,n=(e.brightness==="dark"?Ce:it).color,o=bt(t),s=Ee(o)!==Ee(bt(r)),a=Dl(t,r),l=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,u=i((R,h,C,_,P,x)=>{let g=h===C&&(R!=="errorRed"||l);return g&&a&&Bg.has(R)?h:yr(g&&s?_:h,P,Ee(P),x)},"ink"),d=i((R,h,C)=>u(`text.${R}`,t.text[R],r.text[R],n.text[R],h,C),"text"),c=i((R,h,C,_)=>u(R,h,r[R],n[R],C,_),"token"),p=i(R=>s&&t[R]===r[R]?n[R]:t[R],"tint"),f=t.primary,m=Vt(f,Q),y=c("danger",t.danger,[...o,...Ll(t,t.badgeBgCritical)],Q);return {...t,onPrimary:m,onAccent:Vt(t.accent,Q),onDanger:oe(m,y)>=Q?m:Vt(y,Q),brandSoft:p("brandSoft"),brandSofter:p("brandSofter"),brandBorder:p("brandBorder"),borderHairlineGreen:p("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,o,Q),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,Ko(t),Q),text:{...t.text,primary:d("primary",o,Q),secondary:d("secondary",o,Q),muted:d("muted",o,Q),metaCool:d("metaCool",o,Q),timestamp:d("timestamp",o,Q),placeholder:d("placeholder",Fl(t),gr)},danger:y,errorRed:c("errorRed",t.errorRed,Ml(t,t.badgeBgCritical),Q),warningStrong:c("warningStrong",t.warningStrong,Ml(t,t.badgeBgCaution),Q),composerBorder:c("composerBorder",t.composerBorder,Vg(t),gr),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,Fl(t),gr)}}i(Nl,"guardInks");function Ul(e){let t=(e.brightness==="dark"?it:Ce).color;return e.color.brand===t.brand&&!Dl(e.color,t)}i(Ul,"everfurBrandOnPartnerGround");var Hg="#23272C",Vl=4.5,zg=.6,qo=.9,jg=.02,Wg="#FFFFFF",Gg="#111111";function Kg(e){return oe(e,Hg)>=Vl&&Math.max(oe(e,Wg),oe(e,Gg))>=Vl}i(Kg,"readsOnDark");function jl(e){let t=Y(e);if(t===null)return null;let{h:r,s:n,l:o}=Tl(t.r,t.g,t.b),s=Math.min(Math.max(o,zg),qo);for(let l=0;;l+=1){let u=s+l*jg;if(u>qo)break;let d=Wo({h:r,s:n,l:u}),c=Ke(d.r,d.g,d.b);if(Kg(c))return c}let a=Wo({h:r,s:n,l:qo});return Ke(a.r,a.g,a.b)}i(jl,"deriveDarkVariant");var qg=7,Bl=.05,$g="#000000",Hl="#FFFFFF";function Yg(e,t,r,n){let o=Ve(e,t);if(o===null)return r;if(oe(o,t)>=n)return o;let s=Y(o),a=Y(r);if(s===null||a===null)return r;for(let l=1;l<1/Bl;l+=1){let u=l*Bl,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=Ke(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(oe(c,t)>=n)return c}return r}i(Yg,"pushContrast");function Xg(e,t){let r=bt(e),n=r[0],o=zl(n);for(let s of r){let a=zl(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(Xg,"hardestGround");function zl(e){let t=Y(e);return t===null?0:yt(t)}i(zl,"luminanceOf");function st(e,t){return Ve(e,t)??X(e)??t}i(st,"solid");function Wl(e){let t=e.color,r=Ee(bt(t))===Hl,n=r?Hl:$g,o=Xg(t,r),s=i(l=>Yg(l,o,n,qg),"text"),a={...t,brandSoft:st(t.brandSoft,t.surface),brandSofter:st(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:st(t.badgeBgPositive,t.surface),badgeBgCaution:st(t.badgeBgCaution,t.surface),badgeBgCritical:st(t.badgeBgCritical,t.surface),badgeBgNeutral:st(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:st(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:st(t.checkupCardConcernBg,t.surface)};return $e({...e,highContrast:true,color:a})}i(Wl,"deriveHighContrast");var Yo=Object.freeze({cream:.03,subtle:.07,ring:.16}),Qg=Yo.cream,Zg=Yo.subtle,Jg=Yo.ring,eh=10;function $o(e,t,r){let n=Y(e),o=Y(t);if(n===null||o===null)return null;let s=i((a,l)=>Math.round(a+(l-a)*r),"at");return Ke(s(n.r,o.r),s(n.g,o.g),s(n.b,o.b))}i($o,"mix");function Gl(e){if(e===null)return {};let t=Ee([e]),r=$o(e,t,Qg),n=$o(e,t,Zg),o=$o(e,t,Jg);return r===null||n===null||o===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:o}}i(Gl,"surfaceFamily");function Kl(e){if(e===null)return {};let t=Y(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}i(Kl,"dangerFamily");function ql(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let o={};for(let[s,a]of Object.entries(r.type.size))o[s]=Math.max(eh,Math.round(a*n*10)/10);return o}i(ql,"typeSizesFor");function $l(e,t,r){if(e===null)return t;let n=e/r.space.xs,o=i(a=>Math.round(a*n),"s"),s=r.space;return {xs:o(s.xs),sm:o(s.sm),md:o(s.md),lg:o(s.lg),xl:o(s.xl),xxl:o(s.xxl)}}i($l,"spaceFor");function Yl(e,t){let r=e/t.radius.md,n=i(s=>Math.round(s*r),"s"),o=t.radius;return {tile:n(o.tile),xs:n(o.xs),sm:n(o.sm),md:n(o.md),lg:n(o.lg),xl:n(o.xl),pill:o.pill}}i(Yl,"radiiFor");var Xl=Object.freeze(["everfur","minimal","night"]),Ql=Object.freeze({everfur:Object.freeze({}),minimal:Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:Object.freeze({colorScheme:"dark"})}),br=Object.freeze({fontSizeBase:Object.freeze({min:12,max:20,default:14}),borderRadius:Object.freeze({min:0,max:32,default:14}),spacingUnit:Object.freeze({min:3,max:6,default:4})});function fn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(fn,"isRecord");function th(e){return typeof e=="string"&&Xl.includes(e.trim().toLowerCase())}i(th,"isPreset");function hr(e,t){let r=e[t];return r??void 0}i(hr,"present");var rh=16;function nh(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>rh)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}i(nh,"parsePx");var oh=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],ih=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function Xo(e){if(!fn(e))return null;let t=th(e.theme)?Ql[e.theme.trim().toLowerCase()]:{},r=fn(e.variables)?e.variables:{},n={...t};for(let[p,f]of Object.entries(r))f!=null&&(n[p]=f);let o={},s=hr(n,"colorScheme"),a=typeof s=="string"?s.trim().toLowerCase():null;(a==="light"||a==="dark"||a==="auto")&&(o.color_scheme=a);let l=a==="dark"?"_dark":"";for(let[p,f]of oh){let m=hr(n,p);m!==void 0&&(o[`${f}${l}`]=m);}let u=hr(n,"colorDanger");u!==void 0&&(o[`danger_color${l}`]=u);let d=hr(n,"fontFamily");typeof d=="string"&&d.trim().length>0&&(o.font_family=d.trim());for(let[p,f]of ih){let m=nh(hr(n,p));m!==void 0&&(o[f]=m);}let c=e.rules;if(fn(c)){let p={};for(let f of qe){let m=c[f];fn(m)&&(p[f]=m);}Object.keys(p).length>0&&(o.slots=p);}return Object.keys(o).length===0?null:Object.freeze(o)}i(Xo,"expandAppearance");var tu=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit"]),vr="slots.",ru=Object.freeze([1,2]);function yn(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(yn,"isEmptyBranding");function nu(e){let t=e?.schemaVersion??null;return t===null||ru.includes(t)}i(nu,"isKnownBrandingSchema");function ou(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(ou,"lockedFieldsOf");function sh(e){return e==="hide_powered_by"||tu.includes(e)?true:e.startsWith(vr)&&qe.includes(e.slice(vr.length))}i(sh,"isThemeLockName");function Ye(e){if(e===null||typeof e!="object")return null;let t=e,r=Zl(t),n=Xo(z(t,"appearance")),o=n===null?r:ah(Zl(n),r);return yn(o)?null:Object.freeze(o)}i(Ye,"parseClientBranding");function ah(e,t){let r={...e};for(let[o,s]of Object.entries(t))s!=null&&(r[o]=s);let n=dn(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}i(ah,"overlayFlat");function Zl(e){return {displayName:vt(z(e,"display_name","displayName")),logoUrl:vt(z(e,"logo_url","logoUrl")),primaryColor:X(z(e,"primary_color","primaryColor")),accentColor:X(z(e,"accent_color","accentColor")),brightness:ch(z(e,"brightness","color_scheme","colorScheme")),fontFamily:vt(z(e,"font_family","fontFamily")),fontUrl:vt(z(e,"font_url","fontUrl")),fonts:Jl(z(e,"fonts")),fontUrls:Jl(z(e,"font_urls","fontUrls")),placeholder:vt(z(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:lh(z(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:X(z(e,"primary_color_dark","primaryColorDark")),accentColorDark:X(z(e,"accent_color_dark","accentColorDark")),surfaceStyle:eu(z(e,"surface_style","surfaceStyle"),uh),radiusScale:eu(z(e,"radius_scale","radiusScale"),dh),logoUrlDark:vt(z(e,"logo_url_dark","logoUrlDark")),slots:Pl(z(e,"slots")),accessibilityMaxFontScale:fh(z(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:yh(z(e,"locked_fields","lockedFields")),schemaVersion:mh(z(e,"schema_version","schemaVersion")),backgroundColor:X(z(e,"background_color","backgroundColor")),backgroundColorDark:X(z(e,"background_color_dark","backgroundColorDark")),textColor:X(z(e,"text_color","textColor")),textColorDark:X(z(e,"text_color_dark","textColorDark")),dangerColor:X(z(e,"danger_color","dangerColor")),dangerColorDark:X(z(e,"danger_color_dark","dangerColorDark")),fontSizeBase:Qo(z(e,"font_size_base","fontSizeBase"),br.fontSizeBase),borderRadius:Qo(z(e,"border_radius","borderRadius"),br.borderRadius),spacingUnit:Qo(z(e,"spacing_unit","spacingUnit"),br.spacingUnit)}}i(Zl,"parseFlat");function Qo(e,t){let r=mn(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}i(Qo,"parseClamped");function lh(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(lh,"parseBool");function z(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(z,"pick");function vt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(vt,"parseNonEmptyString");var Er=["regular","medium","bold","mono","monoMedium","monoBold"];function Jl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of Er){let o=vt(z(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(Jl,"parseFaceMap");var uh=["white","cream","subtle"],dh=["sharp","default","round"];function eu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(eu,"parseEnum");function ch(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(ch,"parseBrightness");function mn(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(mn,"parseNumber");var ph=1,iu=3.1;function fh(e){let t=mn(e);return t===null?null:t<=0?0:Math.min(iu,Math.max(ph,t))}i(fh,"parseMaxFontScale");function mh(e){if(e==null)return null;let t=mn(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(mh,"parseSchemaVersion");function Zo(e){let t=e.trim();return t.startsWith(vr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Zo,"toWireName");function yh(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Zo(r);sh(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(yh,"parseLockedFields");function Jo(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Jo,"hardenHttpsUrl");function su(e,t){if(t===null||yn(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?it:Ce:e,n=r.brightness==="dark"?it:Ce,o=r.brightness==="dark",s=o?t.primaryColorDark??ei(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??ei(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&Eh(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?Y(c):null,f=i(P=>Math.round(P+(255-P)*.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?Ch(n,r.color.text):{},y=(o?t.backgroundColorDark:t.backgroundColor)??null,R=Gl(y),h={...r.color,...R},C=(o?t.textColorDark:t.textColor)??null,_={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,...R,...Kl((o?t.dangerColorDark??ei(t.dangerColor??null):t.dangerColor)??null),...C!==null?{text:{...m.text??r.color.text,primary:C}}:{},...vh(t.surfaceStyle??null,h),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:$l(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Yl(t.borderRadius,n):Sh(t.radiusScale??null,r.radius,n),type:{...r.type,...bh(r.type,t),size:ql(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:dn(r.slots,t.slots??null)};return $e(_)}i(su,"withServerBranding");var gh={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},hh=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function ti(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(ti,"isMonoFace");function bh(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of Er){let u=gh[l].map(p=>r[p]).find(p=>p!==void 0),d=ti(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 hh)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(bh,"mergeFaces");function ei(e){return e===null?null:jl(e)}i(ei,"darkVariantOf");function vh(e,t){if(e===null)return {};let r=t;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(vh,"surfaceOf");function au(e,t){return e==null?false:X(e)===X(t)}i(au,"sameColor");function Eh(e,t,r,n){return au(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&au(e.primaryColor,Ce.color.primary)}i(Eh,"isCompiledPrimary");function Ch(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(Ch,"compiledBrandFamily");var Rh={sharp:.5,default:1,round:1.5};function Sh(e,t,r){if(e===null)return t;let n=Rh[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(Sh,"radiusOf");var Th="Everfur",Ph=.5;function ri(e){let t=e?.branding??null,r=nu(t)?t:null,n=Ih(e?.clientOverride??null,ou(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=su((s==="auto"?o:s)==="dark"?it:Ce,lu(r)),d=su(u,lu(n));return Vh(d,e)}i(ri,"resolveTheme");function kh(e,t,r){return ri({...r,branding:Ye(t),clientOverride:Ye(e)})}i(kh,"previewTheme");function xh(e){return e==="placeholder"?"chat_placeholder":Zo(e)}i(xh,"wireNameOf");var _h={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function wh(e,t){return t.has(xh(e))?true:(_h[e]??[]).some(r=>t.has(r))}i(wh,"isLocked");function Ih(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(wh(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 qe){let d=o[u];d!==void 0&&(t.has(`${vr}${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 yn(s)?null:s}i(Ih,"withoutFields");function lu(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(lu,"withoutBrightness");function Ah(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(Ah,"scaledSizes");function Oh(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Ph,e)}i(Oh,"effectiveScale");var uu=["content","heading","control","compact","badge"];function Fh(e){if(!(e>0))return pn;let t={};for(let r of uu){let n=pn[r];t[r]=n===0?0:Math.min(n,e);}return t}i(Fh,"tierCaps");function Mh(e,t){return t>0?Math.min(e,t):e}i(Mh,"capped");function Lh(e,t,r,n){let o={};for(let s of uu)o[s]=n?Ah(e,Mh(t,r[s])):e;return o}i(Lh,"sizesByTier");function Dh(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Ko(e)}}i(Dh,"slotGrounds");function Nh(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Nh,"registration");function Uh(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 Er)!(o[a]===gt||o[a]===Be)&&r!==void 0&&Nh(r,o[a])===false&&(o[a]=ti(a)?Be:gt,s[a]=false),n!==null&&ti(a)&&o[a]===Be&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(Uh,"platformFaces");function Vh(e,t){let r=e.meta.displayName.trim().length===0?Th:e.meta.displayName,n=Jo(e.meta.logoUrl),o={};for(let y of Er){let R=e.type.fontUrls[y];R!==void 0&&(o[y]=Jo(R));}let s=o.regular??null,l=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,u=Number.isFinite(e.type.maxScale)?e.type.maxScale:Go,d=Oh(t?.textScale),c=Fh(u),p=Lh(e.type.size,d,c,t?.scaleTypeSizes===true),f=Nl(e),m={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:f,space:e.space,radius:e.radius,type:{...e.type,...Uh(e.type,t),fontUrl:s,fontUrls:o,size:p.content,tierSizes:p,scale:d,maxScale:u,scaleCaps:c},motion:l,slots:kl(e.slots,Dh(f))};return t?.highContrast===true?Wl($e(m)):$e(m)}i(Vh,"finalize");var du="/widget/v1/entitlements",Bh=304,Hh=Object.freeze({kind:"notModified"});async function pu(e,t={},r=Ae({auth:e})){let n=await r.send("entitlements.fetch",jh(t));return n.ok?Wh(n.value):n.error.httpStatus===Bh?Hh:{kind:"failed",error:n.error}}i(pu,"fetchEntitlements");var zh=64;function jh(e){let t={};return ni(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=zh?{method:"GET",path:du,headers:t,query:{region:e.region}}:{method:"GET",path:du,headers:t}}i(jh,"buildRequest");function Wh(e){if(e===null||typeof e!="object"||!ni(e.revision))return cu();let t=typeof e.region=="string"?e.region:"",r=ni(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Kh(e.capabilities),branding:Gh(e),livemode:e.livemode!==false})}i(Wh,"parseUpdated");function Gh(e){let t=Ye(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=Ye(r.branding);return n!==null?n:Ye(r)}return null}i(Gh,"parseBranding");function Kh(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))qh(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Kh,"mapCapabilities");function qh(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(qh,"isEnabled");function cu(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(cu,"malformed");function ni(e){return typeof e=="number"&&Number.isFinite(e)}i(ni,"isFiniteNumber");var $h=30;function fu(e){let t=e.scheduler??Yh,r=e.resolve??pu,n=Math.max(1,e.floorSeconds??$h),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(C=>{l||!a||(c=Math.max(n,C),u=t.set(()=>{u=null,h();},c*1e3));},"schedule"),y=null,R=i(async()=>{if(l)return null;let C=p;e.onFetch?.();let _=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},P;try{P=await r(e.authFor(),_);}catch(x){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Xh(x)}),!l&&C===p&&(e.onSettled?.(),m(s())),null}if(l||C!==p)return null;switch(P.kind){case "updated":d=P.revision,e.update(P.decisions,P.branding??null,P.livemode!==false),m(P.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:P.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),P},"tick"),h=i(()=>{let C=R().finally(()=>{y===C&&(y=null);});return y=C,C},"run");return {start(){a||l||(a=true,h());},prime(){return l?Promise.resolve(null):y??h()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),h());}}}i(fu,"createEntitlementPoller");var Yh={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function Xh(e){return e instanceof Error?e.message:"poll failed"}i(Xh,"describe");var mu="everfur.notifications.device";var Qh=3e3,yu=Object.freeze([mu]);function gu(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();},Qh);u.then(p,p);})}i(gu,"startBeforeLogoutHooks");function hu(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(hu,"graceAuth");async function bu(e,t){if(yu.length===0)return;let r=await Promise.allSettled(yu.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(bu,"sweepPerUserKv");function Zh(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Zh,"compiledDefaultDecisions");function oi(e=Zh){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,...o.livemode===false?{livemode:false}:{}}),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(oi,"createEntitlementStore");function ii(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(ii,"notConfiguredError");function vu(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 Qs(r,t===void 0?void 0:{platform:t})}i(vu,"tryResolveClient");function Eu(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Eu,"guardTelemetry");var Jh=Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${Yr} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Cu(e,t,r=ao){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. `+Jh[r]);}i(Cu,"reportConfigFailure");function si(e){return Object.freeze({request(){return Promise.resolve(E(ii(e)))},stream(t,r){let n=fe({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(si,"refusingTransport");function Ru(){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(Ru,"createInMemoryKv");var Su=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function ku(e,t){return new li(e,t)}i(ku,"createEverfurRuntime");var eb=6e4,ui=class ui{constructor(t,r){this.sessionId=io();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 ee("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?Eu(n.telemetry):qr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=lo(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=si(s);else if(n.transport!==void 0)l=n.transport;else {let c=vu(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=na({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=si(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&Cu(s,this.telemetry,r?.platform),this.errorPolicy=n.errorPolicy,this.camera=n.camera??Ns,this.upload=n.upload??Ca,this.uploadTransport=n.uploadTransport??wo,this.imageCache=n.imageCache??Su,this.kv=n.storage??Ru(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?oi():oi(()=>hl("sdk_config",Mt("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",ai(c),()=>this.buildChatController(c),Tu),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${ai(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=Gs(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-eb,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 fu({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n,o)=>this.updateEntitlements({decisions:r,isPending:false,branding:n,...o===false?{livemode:o}:{}}),"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=ja(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=io(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await bu(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 gu({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>hu({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?E(Pu(t)):r(ot(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?Pu("prepare"):n===null?null:ii(n),s=this.identity,[a,l,u]=await Promise.all([o?E(o):s===null?L(void 0):s.currentToken().then(()=>L(void 0),()=>E(D("authRejected",{retryable:false}))),o?E(o):this.primeEntitlements(),t===null?void 0:o?E(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"?E(t.error):L(void 0):E(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",ai(r),()=>this.buildChatController(r),Tu,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?E(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(ui,"EverfurRuntimeImpl");var li=ui;function ai(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(ai,"chatScopeKey");function Tu(e){e.dispose();}i(Tu,"disposeChat");function Pu(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Pu,"disposedError");var xu=Symbol.for("@everfur/sdk#EverfurContext@v1"),_u=globalThis,gn=_u[xu]??(_u[xu]=createContext(null));gn.displayName??="EverfurContext";function Z(){let e=useContext(gn);if(e===null)throw new ee("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Z,"useEverfurContext");function wu(){return Z().handle}i(wu,"useEverfur");var Iu=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Au=globalThis,Cr=Au[Iu]??(Au[Iu]=createContext(Ce));Cr.displayName??="EverfurThemeContext";function F(){return useContext(Cr)}i(F,"useEverfurTheme");function hn(e){let{runtime:t}=Z(),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?ab(e.clientTheme):"",f=useMemo(()=>e.clientTheme?Ye(e.clientTheme):null,[p]),m=n.branding??null,y=useMemo(()=>ri({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(Cr.Provider,{value:y},e.children)}i(hn,"EverfurThemeProviderCore");function ab(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(ab,"stableKey");function Du(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(k=>k+1,0),m=useRef(null),y=useRef(void 0),R=r?.userRef??null;y.current!==R&&(y.current!==void 0&&(m.current=null),y.current=R);let h=m.current!==null?m.current.user:r??null,C=useRef(null),_=useRef(void 0),P=n??null;_.current!==P&&(_.current!==void 0&&(C.current=null),_.current=P);let x=C.current!==null?C.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:ku({config:l.withDefaults?l.withDefaults(t):t,user:h,activePet:x,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let g=d.current.runtime,w=useRef(null);useEffect(()=>{let k=d.current?.runtime;k===void 0||!k.isDisposed||w.current!==k&&(w.current=k,f());}),useEffect(()=>{let k=c.current;k!==null&&(c.current=null,k.dispose());});let O=h?.userRef??null;useLayoutEffect(()=>{g.setUser(h);},[g,O]),useLayoutEffect(()=>{g.setActivePet(x);},[g,x]),useEffect(()=>()=>g.dispose(),[g]),useEffect(()=>{s==="onMount"&&g.prepare(x===null?{}:{petRef:x});},[g,s,O,x]);let M=useMemo(()=>({setUser:i(k=>{m.current={user:k},g.setUser(k),f();},"setUser"),setActivePet:i(k=>{C.current={pet:k},g.setActivePet(k),f();},"setActivePet"),open:i(k=>g.open(k),"open"),prepare:i(k=>g.prepare(k),"prepare"),registerPet:i((k,V)=>g.registerPet(k,V),"registerPet"),updatePet:i((k,V)=>g.updatePet(k,V),"updatePet"),deletePet:i(k=>g.deletePet(k),"deletePet"),eraseUserData:i(()=>g.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let k=g.logout();return f(),k},"logout")}),[g,f]),I=useMemo(()=>({runtime:g,handle:M,userRef:O,activePet:x,scopeEpoch:g.scopeEpoch}),[g,M,O,x,p]),v=createElement(hn,{clientTheme:o??null,seams:l.theme,children:a});return createElement(gn.Provider,{value:I},l.wrap?l.wrap(v):v)}i(Du,"EverfurProviderCore");var db=2;function cb(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<db)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(cb,"readEventSourceResponseHeader");function Nu(){let e=ub;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=>cb(n,o),"getResponseHeader")})}}i(Nu,"createRnEventSourceFactory");function yb(){let e=useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(yb,"useRnColorScheme");function gb(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(gb,"isThenable");function hb(){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(hb,"useRnReducedMotion");function Bu(){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(Bu,"readFontScale");function bb(e){let t=Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(Dimensions,"change",e);return ()=>r?.remove?.()}i(bb,"subscribeFontScale");function vb(){return useSyncExternalStore(bb,Bu,Bu)}i(vb,"useRnTextScale");function Wu(){try{let e=Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i(Wu,"platformOS");function Eb(){return Wu()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(Eb,"contrastSignal");function Cb(){let[e,t]=useState(false);return useEffect(()=>{let r=true,{query:n,event:o}=Eb(),a=AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(AccessibilityInfo);gb(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(Cb,"useRnHighContrast");function Rb(){return Wu()==="ios"?"Menlo":Be}i(Rb,"rnPlatformMonoFamily");function Sb(){return globalThis.__DEV__!==false}i(Sb,"isDevelopment");var Hu=new Set;function Tb(e){if(!Sb()||Hu.has(e))return;Hu.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(Tb,"warnUnregisteredFace");function Pb(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||Tb(e),o}i(Pb,"rnIsFontRegistered");var vn=Object.freeze({useColorScheme:yb,useReducedMotion:hb,useTextScale:vb,useHighContrast:Cb,scaleTypeSizes:false,platformMonoFamily:Rb,isFontRegistered:Pb});function xb(e){return createElement(SafeAreaProvider,null,e)}i(xb,"wrapInSafeArea");var _b=Object.freeze({platform:"react-native",eventSourceFactory:Nu(),wrap:xb,theme:vn});function wb(e){return createElement(Du,{...e,seams:_b})}i(wb,"EverfurProvider");function Bt(e){let{runtime:t}=Z(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>bl(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Bt,"useCapability");function Lb(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Lb,"tierMultiplier");function S({tier:e="content",...t}){let{type:r}=F(),n=Lb(r,e);return createElement(Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(S,"Text");var Ht=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Db=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function T(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Db[t]]}}i(T,"face");var ci=class ci 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(ci,"HostRenderBoundary");var di=ci;function Ub({render:e}){return e()}i(Ub,"RenderHost");function Rt({render:e,fallback:t,resetKey:r}){return createElement(di,{fallback:t,resetKey:r,children:createElement(Ub,{render:e})})}i(Rt,"HostRender");var Vb=48;function Bb(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Bb,"selectView");function mi(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Bt(t),l=useMemo(()=>Bb(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsx(Rt,{render:o,fallback:jsx(Yu,{capability:t,style:s})}):jsx(Yu,{capability:t,style:s});case "disabled":return n?jsx(Rt,{render:()=>n(a),fallback:jsx(Xu,{decision:a,style:s}),resetKey:a}):jsx(Xu,{decision:a,style:s});default:return nt(l)}}i(mi,"CapabilityGate");function Yu({capability:e,style:t}){let r=F(),n=useMemo(()=>Qu(r),[r]);return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:n.skeletonBar})})}i(Yu,"PendingSkeleton");function Xu({decision:e,style:t}){let r=F(),n=useMemo(()=>Qu(r),[r]),o=e.disabled?.reason??"";return jsx(View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsx(S,{style:n.offstateText,children:o}):null})}i(Xu,"OffState");function Qu(e){let{color:t,space:r,radius:n,type:o}=e;return StyleSheet.create({offstate:{minHeight:Vb,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...T(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(Qu,"makeStyles");var b=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",senderVet:"Your vet",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 q(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(q,"fillCopy");var yi=Object.freeze([Object.freeze({key:"inaccurate",label:b.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:b.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:b.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:b.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:b.feedbackReasonOther,feedbackType:"not_helpful"})]),Zu=Object.freeze([Object.freeze({sentiment:"up",label:b.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:b.feedbackNeutral}),Object.freeze({sentiment:"down",label:b.feedbackNotHelpful})]);function Hb(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Hb,"sentimentToFeedbackType");function Ju(e,t){if(e==="down"&&t!==null){let r=yi.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Hb(e)}i(Ju,"feedbackTypeFor");var Gb=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function Rr(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=Z(),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 I=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=I,d({scope:l,controller:I}),()=>{p.current=null,d(v=>v?.controller===I?null:v),t.registry.releaseChat(I);}},[t,r,s,a,o,l]);let f=useCallback(I=>c?c.subscribe(I):Kb,[c]),m=useCallback(()=>c?c.getSnapshot():Gb,[c]),y=useSyncExternalStore(f,m,m),R=useCallback((I,v)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?hi(c,c.send(I,v?.imageS3Keys===void 0?{}:{imageS3Keys:v.imageS3Keys}),()=>p.current===c):Promise.resolve(bi()),[c]),h=useCallback(I=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?hi(c,c.askEverfur(I),()=>p.current===c):Promise.resolve(bi()),[c]),C=useCallback(()=>c&&p.current===c?hi(c,c.retryLast(),()=>p.current===c):Promise.resolve(bi()),[c]),_=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),P=useCallback(()=>{c&&p.current===c&&c.newConversation();},[c]),[x,g]=useState({controller:null,byMessage:{}}),w=x.controller===c?x.byMessage:qb,O=useCallback(async(I,v,k,V)=>{if(!c||p.current!==c)return E(D("accessDenied"));let W=String(I),G=x.controller===c?x.byMessage[W]:void 0;if(G===v&&k==null)return g(be=>{let Ie={...be.controller===c?be.byMessage:{}};return delete Ie[W],{controller:c,byMessage:Ie}}),L(Object.freeze({feedbackId:""}));g(be=>({controller:c,byMessage:{...be.controller===c?be.byMessage:{},[W]:v}}));let ae=await c.submitFeedback(I,Ju(v,k??null),V??null);return p.current!==c?E(D("accessDenied")):(ae.ok||g(be=>{let Ie={...be.controller===c?be.byMessage:{}};return G===void 0?delete Ie[W]:Ie[W]=G,{controller:c,byMessage:Ie}}),ae)},[c,x]),M=useMemo(()=>{let I=i(async v=>{if(!c||p.current!==c)return E(D("accessDenied"));let k=await v(c);return p.current===c?k:E(D("accessDenied"))},"run");return {listConversations:i(v=>I(k=>k.listConversations({...s?{petRef:s}:{},...v})),"listConversations"),getMessages:i((v,k)=>I(V=>V.getMessages(v,k)),"getMessages"),resumeConversation:i(v=>I(k=>k.resumeConversation(v)),"resumeConversation"),loadOlderMessages:i(()=>I(v=>v.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>I(v=>v.markRead()),"markRead"),refreshActiveThread:i(()=>I(v=>v.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((v,k)=>I(V=>V.answerCheckin(v,k)),"answerCheckin"),openCheckin:i(v=>I(k=>k.openCheckin(v)),"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,...M,suggestedPrompts:y.suggestedPrompts,unreadCount:y.unreadCount,hasUnreadThreads:y.hasUnreadThreads??false,newConversation:P,sentimentByMessage:w,feedback:O,send:R,askEverfur:h,retryLast:C,stop:_}),[y,s,R,h,C,_,M,P,w,O])}i(Rr,"useEverfurChat");var Kb=i(()=>{},"NOOP_UNSUBSCRIBE"),qb=Object.freeze({});async function hi(e,t,r){for await(let o of t);if(!r())return E(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?E(n.error):L($b(n.messages))}i(hi,"driveToResult");function $b(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($b,"lastAssistantResponseId");function bi(){return E(D("internalError",{retryable:true}))}i(bi,"notReadyError");function nd(e){switch(e.code){case "too_large":return q(b.attachmentTooLarge,{max:Ao(tn),filename:e.filename,size:Ao(e.sizeBytes??0)});case "too_many":return q(b.attachmentTooMany,{max:rn});case "unsupported_type":return q(b.attachmentUnsupported,{filename:e.filename});case "network":return b.attachmentNetwork;case "server":return q(b.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return b.attachmentCancelled;case "rate_limited":return b.attachmentRateLimited;case "quota_exceeded":return b.attachmentQuota;case "idempotency_conflict":return b.attachmentConflict;case "unknown":return b.attachmentUnknown}}i(nd,"attachmentErrorMessage");function od(e,t){return q(e>=t?b.attachmentsFull:b.addAttachment,{used:e,total:t})}i(od,"attachControlLabel");var Zb=Object.freeze({attachments:Object.freeze([])});function En(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=Z(),o=e.maxPerMessage??rn,s=useCallback(()=>{let{services:g}=t.registry;return Ka({funnel:Ae({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,()=>Zb),[f,m]=useState(null),y=useCallback(g=>{let O=(Array.isArray(g)?g:[g]).map(I=>c.add(I)),M=O.find(I=>!I.ok);return M!==void 0&&!M.ok&&m(M.error),O},[c,m]),R=useCallback(g=>c.retry(g),[c]),h=useCallback(g=>c.remove(g),[c]),C=useCallback(()=>c.clear(),[c]),_=useCallback(()=>m(null),[m]),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:y,retry:R,remove:h,clear:C,dismissRejected:_}),[c.available,p,o,P,x,f,y,R,h,C,_])}i(En,"useChatAttachments");var tv="pet_not_registered";function ad(e){return e!=null&&e.reasonCode===tv}i(ad,"isPetNotRegistered");var rv=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function ld(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=Z(),a=useCallback(()=>ot(n.registry.services.authFor(o)),[n,o,s]),l=useMemo(()=>t===void 0?null:Ei(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 R=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(h=>{R===c.current&&(h.ok?(d({key:f,status:"registered",error:null,registered:h.value}),p.current?.()):d({key:f,status:"failed",error:h.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?rv: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(ld,"useChatPetRegistration");function Ei(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Ei).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)}:${Ei(n)}`).join(",")}}`}i(Ei,"stableKey");var Ci=Object.freeze({});function dd(e){let[t,r]=useState(Ci),n=useRef(null),o=useRef([]);o.current=e.map(a=>a.id),useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===Ci?u:Ci);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(dd,"useSentImages");var lv=500;function Ri(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,lv):null}i(Ri,"sanitizeSeedPrompt");function pd(e,t,r){let n=Ri(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(pd,"useInitialAsk");function uv(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(uv,"isCoalesced");function fd(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"}:uv(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(fd,"decideChatRefresh");function Si(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Si,"reportHostFailure");function dv(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(dv,"isThenable");function $(e,...t){if(typeof e=="function")try{let r=e(...t);return dv(r)&&Promise.resolve(r).then(void 0,Si),r}catch(r){Si(r);return}}i($,"callHost");var md=new WeakMap;function yd(e){if(typeof e!="function")return;let t=md.get(e);if(t!==void 0)return t;let r=i((...n)=>{$(e,...n);},"guarded");return md.set(e,r),r}i(yd,"guardHost");function jt(e,...t){let r;try{r=e(...t);}catch(n){return Si(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(jt,"callHostAsync");function hd(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),s=e?.isOffline===void 0?false:$(()=>e.isOffline?.()===!0)===true,a=useRef(()=>{});a.current=l=>{let{conversationId:u,isTurnInFlight:d,refresh:c}=r.current,p=fd(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=$(()=>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)$(d);}},[e]);}i(hd,"useChatLifecycle");function pv(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(pv,"targetKey");function vd(e,t){let r=pv(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(vd,"useCheckinTarget");function Rd(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(Rd,"useChatDraft");function Sd(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 jt(()=>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??""}`||$(()=>e.write(t,r));},[e,t,r,a]);}i(Sd,"usePersistedDraft");var te=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 Rn(e){let t=e?.replace(/\s+/g," ").trim();return t||te.untitled}i(Rn,"conversationTitle");function Pd(e){return `${e.unreadCount!==null&&e.unreadCount>0?te.unreadPrefix:""}${te.openConversation} ${Rn(e.title)}`}i(Pd,"openConversationLabel");function Td(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Td,"normalizeForSearch");function bv(e,t){let r=Td(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=Td(Rn(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(bv,"filterConversations");function ki(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(ki,"fresh");function kd(e){let[t,r]=useState(false),[n,o]=useState(""),s=e.listConversations,a=useRef(0),[l,u]=useState(()=>ki(s)),d=l.scope===s?l:ki(s);useEffect(()=>(a.current+=1,r(false),o(""),u(ki(s)),()=>{a.current+=1;}),[s]);let c=useCallback(async P=>{let x=++a.current,g=P!==void 0;u(O=>({...O,scope:s,loading:!g,loadingMore:g,error:null}));let w=await e.listConversations(P?{cursor:P}:void 0);if(x===a.current){if(!w.ok){u(O=>({...O,loading:false,loadingMore:false,error:w.error.displayMessage}));return}u(O=>{let M=P&&O.scope===s?O.rows:[],I=new Set(M.map(v=>v.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...M,...w.value.conversations.filter(v=>!I.has(v.id))],cursor:w.value.nextCursor===P?null:w.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async P=>{let x=++a.current;u(w=>({...w,loading:true,error:null}));let g=await e.resumeConversation(P);x===a.current&&(u(w=>({...w,loading:false,error:g.ok?null:g.error.displayMessage})),g.ok&&r(false));},"resume"),y=i(async()=>{let P=a.current,x=await e.loadOlderMessages();P===a.current&&!x.ok&&u(g=>({...g,error:x.error.displayMessage}));},"earlier"),R=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),h=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),C=useMemo(()=>bv(d.rows,n),[d.rows,n]),_=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:y,newConversation:R,loadMore:h,query:n,setQuery:o,searching:_,filtered:C,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(kd,"useHistoryPanel");var Sn="#111111",Tn="#FFFFFF",Cv=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Sn,pillColor:Tn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Sn,pillColor:Tn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Sn,pillColor:Tn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Sn,pillColor:Tn,showsVetAction:false})});function Rv(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(Rv,"urgencySignature");function Sv(e){return q(b.urgencyGeneralReason,{petName:e?.trim()||b.emptyTitlePetFallback})}i(Sv,"generalUrgencyReason");function wd(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:Tv(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Sv(t)}:null}return null}i(wd,"latestUrgencySource");function Tv(e){return typeof e=="string"&&e.trim().length>0?e:null}i(Tv,"shownReason");function Id(e){let t=e===null?null:Rv(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:Cv[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:q(b.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Id,"useUrgencySurface");function Ad(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Ad,"selectView");function Pv(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Pv,"needsNewConversation");function Od(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=Pv(t);return {tone:"error",title:r?b.turnUnreachableTitle:b.turnFailedTitle,body:t.displayMessage,actionLabel:r?b.turnStartNewChat:b.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:b.turnStoppedTitle,body:b.turnStoppedBody,actionLabel:b.turnRetry,action:"retry"}:null}i(Od,"turnNotice");function Fd(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(Fd,"awaitingAssistant");var kv=3,xv=Object.freeze([]);function Md(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return xv;let r=new Set,n=[];for(let o of e.suggestedPrompts){let s=o.trim(),a=s.replace(/\s+/g," ").toLowerCase();if(!(a.length===0||r.has(a))&&(r.add(a),n.push(s),n.length===kv))break}return Object.freeze(n)}i(Md,"visibleFollowUps");function Ld(e){return e.sender?.displayName??b.senderVet}i(Ld,"vetSenderLabel");function Dd(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(Dd,"buildChatOpts");var Sr=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 Vd(e){let t=F(),r=useMemo(()=>Iv(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${Sr.title}. ${Sr.body}`,children:[jsx(S,{style:r.title,children:Sr.title}),jsx(S,{style:r.body,children:Sr.body})]})}i(Vd,"ClinicalDisclaimer");function Iv(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:{...T(e,"bold"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{...T(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.snug),color:t.text.muted}})}i(Iv,"makeStyles");var ue={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function ie(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(ie,"box");function me(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(me,"stroke");function Bd({size:e,color:t,strokeWidth:r}){let n=me(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxs(View,{style:[ie(e),{gap:e*.22}],...ue,children:[jsx(View,{style:o}),jsx(View,{style:o}),jsx(View,{style:o})]})}i(Bd,"MenuGlyph");function Hd({size:e,color:t,strokeWidth:r,rotate:n}){let o=me(e,r),s=e*.78;return jsxs(View,{style:[ie(e),{transform:[{rotate:n}]}],...ue,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(Hd,"Cross");function zd(e){return jsx(Hd,{...e,rotate:"0deg"})}i(zd,"PlusGlyph");function St(e){return jsx(Hd,{...e,rotate:"45deg"})}i(St,"CloseGlyph");function lt({size:e,color:t,strokeWidth:r}){let n=me(e,r);return jsx(View,{style:ie(e),...ue,children:jsx(View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(lt,"CheckGlyph");var Fv={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=me(e,r),s=e*.46,a=Fv[n];return jsx(View,{style:ie(e),...ue,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 jd({size:e,color:t,strokeWidth:r}){let n=me(e,r),o={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};return jsxs(View,{style:[ie(e),{flexDirection:"row",gap:1}],...ue,children:[jsx(View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsx(View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(jd,"BookGlyph");function Wd({size:e,color:t,strokeWidth:r}){let n=me(e,r),o=e*.5;return jsxs(View,{style:ie(e),...ue,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(Wd,"ArrowUpRightGlyph");function Gd({size:e,color:t,strokeWidth:r}){let n=me(e,r),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:n,borderColor:t,borderRadius:e*.14};return jsxs(View,{style:ie(e),...ue,children:[jsx(View,{style:[s,{top:0,left:0}]}),jsx(View,{style:[s,{bottom:0,right:0}]})]})}i(Gd,"CopyGlyph");function kn({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=me(e,r),a=n?t:"transparent";return jsxs(View,{style:[ie(e),{transform:[{rotate:o}]}],...ue,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(kn,"ThumbGlyph");function Kd({size:e,color:t,strokeWidth:r}){let n=me(e,r);return jsxs(View,{style:[ie(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...ue,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(Kd,"InfoGlyph");function qd({size:e,color:t,strokeWidth:r}){let n=me(e,r),o=e*.34;return jsxs(View,{style:ie(e),...ue,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(qd,"UploadGlyph");function $d({size:e,color:t,strokeWidth:r}){let n=me(e,r);return jsxs(View,{style:[ie(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...ue,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($d,"PhotoGlyph");function Yd({size:e,color:t,strokeWidth:r}){let n=me(e,r);return jsxs(View,{style:ie(e),...ue,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(Yd,"CameraGlyph");function Xd({size:e,color:t,strokeWidth:r}){let n=me(e,r),o=e*.66;return jsxs(View,{style:ie(e),...ue,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(Xd,"SearchGlyph");function Qd({size:e,color:t,strokeWidth:r}){let n=me(e,r);return jsxs(View,{style:ie(e),...ue,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(Qd,"EditGlyph");function Zd({size:e,color:t,strokeWidth:r}){let n=me(e,r),o=e*.62;return jsxs(View,{style:ie(e),...ue,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(Zd,"MapPinGlyph");function Jd({size:e,color:t,testID:r}){let n=e*.36;return jsx(View,{style:ie(e),testID:r,...ue,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(Jd,"SendGlyph");function ec({size:e,color:t,testID:r}){return jsx(View,{style:ie(e),testID:r,...ue,children:jsx(View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(ec,"StopGlyph");function xn({size:e,strokeWidth:t,color:r,children:n}){return jsx(View,{style:[ie(e),{borderRadius:e/2,borderWidth:t??StyleSheet.hairlineWidth,borderColor:r}],children:n})}i(xn,"Ring");var Tr=Object.freeze({standard:ht.standard,emphasized:ht.emphasized,exit:ht.exit,outQuad:Object.freeze([.25,.46,.45,.94])});var tc=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}),Mv=Object.freeze({...tc,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 rc(e){return e.motion.reducedMotion?Mv:tc}i(rc,"chatMotion");function _n(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(_n,"followUpDelayMs");function nc(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(nc,"nextRevealLength");function J(){let e=F();return rc(e)}i(J,"useChatMotion");var Bv=8;function ic(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(ic,"bezierComponent");function Hv(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(Hv,"bezierSlope");function wn(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<Bv;l+=1){let u=Hv(a,t,n);if(u===0)break;a-=(ic(a,t,n)-s)/u;}return ic(Math.min(1,Math.max(0,a)),r,o)}}i(wn,"bezierEasing");var xi=wn(Tr.standard),zv=wn(Tr.outQuad);function Ai(e){let t=useRef(null);return t.current===null&&(t.current=new Animated.Value(e)),t.current}i(Ai,"useAnimatedValue");function Tt(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=Ai(e>0?0:1);return useEffect(()=>{if(e<=0)return;let s=Animated.timing(o,{toValue:1,duration:e,easing:zv,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(Tt,"useFadeIn");function Oi({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=useState(e),l=Ai(e&&t<=0?1:0);return useEffect(()=>{if(e){a(true);let d=Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:xi,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:xi,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(Oi,"FadePresence");var jv=12;function H({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=J(),u=Ai(1),d=useCallback(c=>{l.pressMs<=0||l.pressScale===1||Animated.timing(u,{toValue:c,duration:l.pressMs,easing:xi,useNativeDriver:true}).start();},[u,l.pressMs,l.pressScale]);return jsx(Pressable,{...a,hitSlop:s??jv,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(H,"PressScale");function lc(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=>nc(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(lc,"useRevealedText");var sc=false;function Wv(e){e.layoutMs<=0||(sc||(sc=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(Wv,"animateLayout");function Pr(e,t){let r=useRef(e);r.current!==e&&(r.current=e,Wv(t));}i(Pr,"useAnimateLayoutOn");var Fi=36,Qv=22,Zv=12,Jv=12,eE=16,tE="#000",rE="rgba(0,0,0,0.45)";function uc({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:b.closePreview,style:In.backdrop,onPress:r,children:jsx(Image,{source:{uri:e},style:In.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsx(View,{pointerEvents:"box-none",style:[In.closeWrap,{top:o.top+Jv}],children:jsx(H,{accessibilityRole:"button",accessibilityLabel:b.closePreview,hitSlop:Zv,style:In.closeButton,onPress:r,children:jsx(St,{size:Qv,color:n.color.surface,strokeWidth:2})})})]})}i(uc,"AttachmentImageLightbox");var In=StyleSheet.create({backdrop:{flex:1,backgroundColor:tE,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:eE},closeButton:{width:Fi,height:Fi,borderRadius:Fi/2,backgroundColor:rE,alignItems:"center",justifyContent:"center"}});var An=12,aE=80,Mi=44,dc=22,lE=.14,uE=18,dE=8,cc=Object.freeze({photo:b.attachmentPhoto,camera:b.attachmentCamera});function pc({sources:e,full:t,onPick:r,onClose:n}){let o=F(),s=useMemo(()=>cE(o),[o]);return jsxs(View,{style:s.anchor,pointerEvents:"box-none",children:[jsx(Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:b.closeAttachmentPicker,onPress:n}),jsxs(View,{style:s.bubble,children:[jsx(View,{style:s.tilesRow,children:e.map(a=>jsxs(H,{accessibilityRole:"button",accessibilityLabel:cc[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($d,{size:dc,color:o.color.brandInk,strokeWidth:1.5}):jsx(Yd,{size:dc,color:o.color.brandInk,strokeWidth:1.5})}),jsx(S,{tier:"control",style:s.tileLabel,children:cc[a]})]},a))}),jsx(View,{style:s.tail}),jsx(View,{style:s.tailFill})]})]})}i(pc,"AttachmentPickerPopover");function cE(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:lE,shadowRadius:uE,shadowOffset:{width:0,height:dE},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:aE,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Mi,height:Mi,borderRadius:Mi/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...T(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-An/2,width:An,height:An,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:An+4,height:2,backgroundColor:t.surfaceCream}})}i(cE,"makeStyles");var xe=Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var mc=56,yc=12,mE=14,yE=10,gE=.45,hE="rgba(7,193,104,0.55)",bE="rgba(185,28,28,0.55)",vE=200,EE=300,Sc=20,Di=22,CE=12,RE="rgba(0,0,0,0.78)",gc=220,hc=100,bc="rgba(255,255,255,0.15)";function Tc({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=F(),l=useMemo(()=>kc(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(SE,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsx(S,{style:l.rejected,accessibilityRole:"alert",children:b.attachmentsFailedBlocked}):null,t!==null?jsx(S,{style:l.rejected,accessibilityRole:"alert",children:nd(t)}):null]})}i(Tc,"AttachmentStrip");function SE({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?q(b.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(TE,{styles:t,onDone:()=>p(false)}):null]})}),l?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:q(b.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsx(View,{style:t.failedInner,children:jsx(St,{size:Sc,color:s.color.surface,strokeWidth:2})})}):null,jsx(H,{accessibilityRole:"button",accessibilityLabel:q(b.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsx(St,{size:CE,color:s.color.surface,strokeWidth:1.5})})]})}i(SE,"PreviewCard");function TE({styles:e,onDone:t}){let r=F(),n=J(),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:vE,useNativeDriver:true}),Animated.delay(n.uploadFlashMs),Animated.timing(s,{toValue:0,duration:EE,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(lt,{size:Sc,color:r.color.surface,strokeWidth:2})})}i(TE,"SuccessFlash");function Pc({images:e,onPreview:t}){let r=F(),n=useMemo(()=>kc(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:q(b.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(Pc,"SentImages");function kc(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:mc,height:mc,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:yc,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...xe,alignItems:"center",justifyContent:"center",backgroundColor:Sl(e.color.brandInk,gE)??e.color.brandSofter},successOverlay:{...xe,alignItems:"center",justifyContent:"center",backgroundColor:hE},failedOverlay:{...xe,borderRadius:yc,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:bE},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:Di,height:Di,borderRadius:Di/2,backgroundColor:RE,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...T(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:gc,height:gc,borderRadius:mE,backgroundColor:bc},gridImage:{width:hc,height:hc,borderRadius:yE,backgroundColor:bc}})}i(kc,"makeStyles");var PE="chat attachment upload: the file handle has no uri",kE="chat attachment upload failed";function xE(e){return {uri:e.uri,name:Io(e.name),type:e.mimeType}}i(xE,"filePartOf");function xc(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(PE));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(kE)),"failed");return o?.aborted===true?a():Kr({url:t.upload_url,fields:t.upload_fields,file:xE(r),signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(xc,"createRnChatAttachmentTransport");function On(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=Z(),o=useMemo(()=>ot(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(On,"useEverfurPets");function _c(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(_c,"headerPetOf");function pe(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(pe,"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 Se(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Se,"slotText");var wc=Object.freeze({visitButton:"Talk to a vet"});var Ic=Symbol.for("@everfur/sdk/televet");function Qe(){let e=globalThis,t=e[Ic];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[Ic]=r,r}i(Qe,"televetGlobal");function Fn(e){let t=Qe();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Fn,"publish");function Ac(e){let t=Qe().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(Ac,"callTelevetPresenter");function Oc(e){let t=Qe();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(Oc,"subscribeTelevetExperience");function Hi(){return Qe().snapshot}i(Hi,"televetExperienceSnapshot");function OE(){return Qe().hosts.length>0}i(OE,"hasTelevetHost");function Fc(e){if(!OE())return false;let t=Object.freeze({...e});return Fn({request:t,serial:Qe().snapshot.serial+1}),true}i(Fc,"presentTelevetExperience");function zi(){Qe().snapshot.request!==null&&Fn({request:null});}i(zi,"dismissTelevetExperience");function Mc(){let e=Qe(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Fn({activeHost:e.hosts[0]??null}),t}i(Mc,"claimTelevetHost");function Lc(e){let t=Qe();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Fn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(Lc,"releaseTelevetHost");var Dc=false;function Mn(e,t){return t!==void 0?($(t,e),"onStartInApp"):Ac(e)==="presented"?"presenter":Fc(e)?"experience":(Dc||(Dc=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(Mn,"openVetVisitInApp");function Vc(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(Vc,"memoizeTelevetLoader");function Bc(e){let[t,r]=useState(null);useEffect(()=>{let d=Mc();return r(d),()=>{Lc(d);}},[]);let n=useSyncExternalStore(Oc,Hi,Hi),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),zi());}),()=>{d=false;}},[u,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:zi}}i(Bc,"useTelevetExperienceHost");var ME=Vc(()=>import('@everfur/sdk/televet/booking'));function xr(){let e=Bc(ME);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(xr,"EverfurTelevetHost");var ji=Object.freeze(["visit","join","summary","messages"]);function Wi(e){return typeof e=="string"&&ji.includes(e)}i(Wi,"isVetVisitIntent");var DE="/widget/v1/televet/handoffs",NE="/widget/v1/televet/availability",UE="/widget/v1/televet/chat-entry",VE=/^[a-z0-9][a-z0-9_-]{0,39}$/,BE=/^[A-Za-z0-9_-]{22}$/;var Hc=32,zc=128,jc=64;function Ki(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(Ki,"vetVisitErrorReasonOf");function Wc(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(Wc,"invalid");function Gi(e){return E(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Gi,"unusable");function HE(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!VE.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>jc)return {ok:false,message:`visitRef must be 1..${jc} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Wi(a))return {ok:false,message:`intent must be one of ${ji.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(HE,"handoffBody");function zE(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Wi(r)?null:Object.freeze({visitRef:t,intent:r})}i(zE,"parseVisitEcho");function Kc(e){let t=e.funnel??Ae({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(Gc(r,"televet.visit.handoff_failed",{reason:Ki(o)}),E(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let h=typeof o=="string"?[...o].length:0;if(h<1||h>zc)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${zc} characters`}));a=o;}let l=HE(a,s);if(!l.ok){let h=Wc(l.message);return h.ok?h:n(h.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:DE,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=jE(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!BE.test(f))){let h=Gi("the handoff response carried no usable return flow id");return h.ok?h:n(h.error)}let m=u.visit_ref!==void 0,y=m?zE(d.value?.visit):null;if(m&&y===null){let h=Gi("the handoff response did not confirm the visit it opens");return h.ok?h:n(h.error)}let R=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...y!==null?{visit:y}:{}});return R===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Gc(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),L(R))},async checkAvailability(o){if(typeof o!="string"||o.length>Hc)return Wc(`state must be at most ${Hc} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:NE,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return E(s.error);let a=s.value?.available;return typeof a!="boolean"?Gi("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:UE},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(Kc,"createVetVisitController");function jE(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||!qE(t)?null:Object.freeze({url:t,expiresAt:r})}i(jE,"parseHandoff");var WE=new Set(["localhost","127.0.0.1","[::1]"]),GE=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,KE=/[\s\u0000-\u001f\u007f]/;function qE(e){if(KE.test(e))return false;let t=GE.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"&&WE.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(qE,"isOpenableVisitUrl");function Gc(e,t,r){if(e)try{e.track(t,r);}catch{}}i(Gc,"safeTrack");var qi=Object.freeze({status:"idle",error:null,errorReason:null});function YE(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(YE,"usePreflight");var XE=Object.freeze({status:"opening",error:null,errorReason:null});function Yc(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=Z(),s=Bt("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:k}=r.registry;return Kc({auth:k.authFor(n),telemetry:k.telemetry,...k.errorPolicy?{errorPolicy:k.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=YE(f,a,{usState:l,chat:u,scope:m}),R=a&&(y===null||y.open)&&(!u||d!==null),h=t.returnTo??null,[C,_]=useState(qi),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 w=useRef(R);w.current=R;let O=useCallback((k,V)=>{if(P.current)return P.current;let W=i((ye,rt)=>(_({status:ye==="cancelled"?"idle":"error",error:rt,errorReason:ye==="cancelled"?null:ye}),Object.freeze({opened:false,reason:ye,error:rt})),"fail");if(!w.current)return Promise.resolve(W("unavailable",null));let G=e.prepare();if(!G.ok)return Promise.resolve(W(G.reason,null));let ae=x.current,be=g.current;_(XE);let ct=(async()=>{let ye,rt={...h!==null?{returnTo:h}:{},...u?{entry:"chat"}:{},...V!==null?{visitRef:V.visitRef}:{},...V!==null&&V.intent!==null&&V.intent!==void 0?{intent:V.intent}:{}},Dr=Object.keys(rt).length===0?void 0:rt,Nr=k===void 0?d:k;try{ye=await(Dr===void 0?be.createHandoff(Nr):be.createHandoff(Nr,Dr));}catch{return e.abandon(G.value),W("unknown",null)}let Ot=x.current;if(Ot.runtime!==ae.runtime||Ot.userRef!==ae.userRef||Ot.scopeEpoch!==ae.scopeEpoch)return e.abandon(G.value),W("cancelled",null);if(!ye.ok)return e.abandon(G.value),W(Ki(ye.error),ye.error);let Jt=await e.finish(G.value,ye.value);return Jt!==null?W(Jt,null):(_(qi),Object.freeze(ye.value.flowId===void 0?{opened:true}:{opened:true,flowId:ye.value.flowId}))})().finally(()=>{P.current===ct&&(P.current=null);});return P.current=ct,ct},[e,d,h,u]),M=useCallback((k,V)=>{if(!w.current)return _({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let W=k===void 0?d:k,G={...W!==null?{petRef:W}:{},...l!==null?{usState:l}:{},...V!==null?{visitRef:V.visitRef,intent:V.intent}:{}};return Mn(G)===null?(_({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(_(qi),Promise.resolve(Object.freeze({opened:true})))},[d,l]),I=useCallback(k=>c?O(k,null):M(k,null),[c,O,M]),v=useCallback((k,V)=>c?O(void 0,{visitRef:k,intent:V??null}):M(void 0,{visitRef:k,intent:V??null}),[c,O,M]);return {available:R,isPending:s.isPending||(y?.pending??false),status:C.status,error:C.error,errorReason:C.errorReason,open:I,openVisit:v}}i(Yc,"useVetVisitWith");var JE=i(e=>Linking.openURL(e),"defaultOpenUrl");function Dn(e={}){let{openUrl:t,...r}=e,n=useMemo(()=>{let o=t??JE;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 Yc(n,r)}i(Dn,"useVetVisit");var Xc=44,oC=.6;function Kt(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:R}=e,h=R==="redirect",C=Dn({...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:h?"redirect":"in-app"}),_=F(),P=useMemo(()=>iC(_),[_]),x=useRef(false);if(!C.available)return jsxs(Fragment,{children:[null,jsx(xr,{})]});let g=C.status==="opening",w=r??wc.visitButton;return jsxs(Fragment,{children:[jsx(Pressable,{onPress:i(()=>{if(!(g||x.current)){if(!h){let M={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...f!=null?{visitRef:f,intent:m??null}:{}};Mn(M,y)===null&&$(s,"unavailable",null);return}x.current=true,(f==null?C.open():C.openVisit(f,m??null)).then(M=>{M.opened?$(o,M.flowId??null):M.reason!=="cancelled"&&$(s,M.reason,M.error);}).finally(()=>{x.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:w,accessibilityState:{busy:g,disabled:g},style:[P.button,g?P.busy:null,a],children:jsx(S,{style:[P.label,l],children:w})}),jsx(xr,{})]})}i(Kt,"VetVisitButton");function iC(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return StyleSheet.create({button:{minHeight:Xc,minWidth:Xc,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...pe(s.vetVisitButton)},busy:{opacity:oC},label:{...T(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...Se(s.vetVisitButton)}})}i(iC,"makeStyles");function $i(e){return pr(e)==="cat"?"cat":"dog"}i($i,"speciesOf");function Yi(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(Yi,"petAgeYears");function ep(e){let t=Yi(e.ageYears),r=$i(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(ep,"formatPetMeta");var Jc=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 sC(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Jc[t%Jc.length]}i(sC,"pickInitialsPalette");function Xi(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(Xi,"getInitial");function tp(e){return {...sC(e.petRef),initial:Xi(e.name)}}i(tp,"petInitials");function dC(e){return Math.max(12,Math.round(e*.42))}i(dC,"letterSize");function wr({pet:e,size:t,ringStroke:r}){let n=F(),o=useMemo(()=>cC(n),[n]),s=t-r*2,a=e===null?null:tp(e),l=dC(s);return jsx(xn,{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(S,{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?Xi(null):a.initial})})})}i(wr,"PetDisc");function cC(e){return StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...T(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(cC,"makeStyles");var Zi=48,op=2,hC=320,bC="80%",vC="rgba(17,17,17,0.45)",EC=18,rp=22,CC=12,np=.4,RC=44;function Ji(e){return e?.name?.trim()||b.yourPet}i(Ji,"petDisplayName");function ip({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=F(),l=useMemo(()=>SC(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:xe,onPress:s,accessibilityRole:"button",accessibilityLabel:b.close,children:jsx(View,{style:l.backdrop})}),jsxs(View,{style:l.panel,accessibilityViewIsModal:true,children:[jsx(S,{tier:"heading",style:l.title,accessibilityRole:"header",children:b.yourPets}),jsx(ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(u=>{let d=u.petRef===r,c=Ji(u),p=ep(u);return jsxs(H,{accessibilityRole:"button",accessibilityLabel:q(d?b.petCurrentlyActive:b.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsx(wr,{pet:u,size:Zi,ringStroke:op}),jsxs(View,{style:l.copy,children:[jsx(S,{style:l.name,numberOfLines:1,children:c}),jsx(S,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${b.activePrefix}${p}`:p})]}),d?jsx(lt,{size:EC,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxs(H,{accessibilityRole:"button",accessibilityLabel:b.addAnotherPet,style:l.addRow,onPress:o,children:[jsx(View,{style:l.addDisc,children:jsx(S,{tier:"control",style:l.addPlus,children:"+"})}),jsx(S,{style:l.addLabel,children:b.addAnotherPet})]}):null,jsx(H,{accessibilityRole:"button",accessibilityLabel:b.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsx(S,{tier:"control",style:l.closeText,children:b.close})})]})]})}):null}i(ip,"PetSwitcherSheet");function SC(e){let t=e.color,r=e.radius;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:vC},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:rp,borderTopRightRadius:rp,gap:14,maxHeight:bC},title:{...T(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:hC,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:RC,paddingHorizontal:8},addDisc:{width:Zi,height:Zi,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:op,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...T(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...T(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:{...T(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...T(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:np},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:CC,backgroundColor:t.brandSoft},closeText:{...T(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:np}})}i(SC,"makeStyles");var kC=44,Un=36,xC=22,es=9,_C=1.5,ap=6,kt=35,Vn=1.75,ts=12.4,wC=.5,IC=8,AC=28,OC=160;function ns(e,t){return _c(e,t)}i(ns,"headerPet");function up({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=F(),u=useMemo(()=>MC(l),[l]),[d,c]=useState(false),p=ns(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,y=Ji(p),R=i(C=>{c(false),e.setActivePet(C),$(o,C);},"select"),h=s===void 0?null:()=>{c(false),$(s);};return jsxs(View,{style:u.row,children:[jsxs(H,{accessibilityRole:"button",accessibilityLabel:r?b.openMenuUnread:b.openMenu,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsx(Bd,{size:xC,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(FC,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsx(Kt,{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(H,{accessibilityRole:"button",accessibilityLabel:q(b.switchActivePet,{name:y}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsx(wr,{pet:p,size:kt,ringStroke:Vn}),jsx(View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsx(zd,{size:IC,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsx(View,{style:u.avatarWrap,accessible:true,accessibilityLabel:b.yourPet,children:jsx(xn,{size:kt,strokeWidth:Vn,color:l.color.success,children:jsx(View,{style:u.placeholderDisc})})}):jsx(View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?b.yourPet:y,children:jsx(wr,{pet:p,size:kt,ringStroke:Vn})})}),jsx(ip,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:R,onAddPet:h,onClose:()=>c(false)})]})}i(up,"ChatHeader");function FC({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(FC,"BrandLogo");function MC(e){let t=e.color,r=kt-Vn*2;return StyleSheet.create({vetEntry:{minHeight:kC,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...T(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:Un/2},iconButton:{width:Un,height:Un,borderRadius:Un/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:ap,right:ap,width:es,height:es,borderRadius:es,backgroundColor:t.danger,borderWidth:_C,borderColor:t.surface},center:{...xe,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:AC,width:OC},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:kt/2},avatarWrap:{width:kt,height:kt,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ts,height:ts,borderRadius:ts/2,borderWidth:wC,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(MC,"makeStyles");var pp=44,VC="rgba(17,17,17,0.55)",fp=26,BC=36,mp=4,os=20,is=38,HC=18,zC=12;function yp({visible:e,onSubmit:t,onSkip:r}){let n=F(),o=useMemo(()=>jC(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"),R=i(async()=>{if(d)return;c(true),f(false);let C=l.trim();await t(s,C.length>0?C:null)?m():(c(false),f(true));},"submit");if(!e)return null;let h=[...l].length>Dt;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:b.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(kn,{size:HC,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxs(View,{style:o.headerText,children:[jsx(S,{tier:"heading",style:o.title,accessibilityRole:"header",children:b.feedbackTitle}),jsx(S,{style:o.subtitle,children:b.feedbackSubtitle})]})]}),jsx(View,{style:o.options,children:yi.map(C=>{let _=s===C.key;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:C.label,accessibilityState:{selected:_},style:[o.option,_?o.optionSelected:null],onPress:()=>a(P=>P===C.key?null:C.key),children:[jsx(S,{style:[o.optionLabel,_?o.optionLabelSelected:null],children:C.label}),jsx(View,{style:[o.radio,_?o.radioSelected:null],children:_?jsx(lt,{size:zC,color:n.color.surface,strokeWidth:2}):null})]},C.key)})}),jsxs(View,{style:o.inputWrap,children:[jsx(Ht,{style:o.input,placeholder:b.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:b.feedbackNotesPlaceholder,value:l,onChangeText:u,multiline:true,editable:!d}),l.length>0?jsx(S,{tier:"compact",style:[o.counter,h?o.counterOver:null],children:`${[...l].length}/${Dt}`}):null]}),p?jsx(S,{style:o.failed,accessibilityRole:"alert",children:b.feedbackFailed}):null,jsxs(View,{style:o.actions,children:[jsx(H,{accessibilityRole:"button",accessibilityLabel:b.feedbackSubmit,accessibilityState:{busy:d,disabled:d||h},disabled:d||h,style:[o.submit,d||h?o.submitDisabled:null],onPress:()=>{R();},children:jsx(S,{tier:"control",style:o.submitLabel,children:b.feedbackSubmit})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:b.feedbackSkipA11y,hitSlop:8,onPress:y,style:o.skip,children:jsx(S,{tier:"control",style:o.skipLabel,children:b.feedbackSkip})})]})]})]})})}i(yp,"FeedbackReasons");function jC(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...xe,backgroundColor:VC},sheet:{backgroundColor:t.surface,borderTopLeftRadius:fp,borderTopRightRadius:fp,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:BC,height:mp,borderRadius:mp/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:is,height:is,borderRadius:is/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...T(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...T(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:{...T(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:os,height:os,borderRadius:os/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,...T(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...T(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...T(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:pp,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...pe(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...T(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...Se(o.primaryButton)},skip:{minHeight:pp,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...T(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(jC,"makeStyles");var oR=.88,iR=420,sR=58,aR="rgba(17,17,17,0.28)",lR=.08,uR=.1,dR=.08,cR=.18,pR=.78,fR=.7,ss=36,mR=10,yR=14,gR=12,hR=16,bR=14,as=8,vR=1.5,ER=.5,CR=wn(Tr.standard);function RR(e){return Math.min(Math.round(e*oR),iR)}i(RR,"drawerPanelWidth");function gp({chat:e,history:t}){let[r,n]=useState(t.open),o=useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsx(SR,{chat:e,history:t,onHidden:o}):null}i(gp,"HistoryDrawer");function SR({chat:e,history:t,onHidden:r}){let n=F(),o=useMemo(()=>PR(n),[n]),s=J(),a=useSafeAreaInsets(),{width:l}=useWindowDimensions(),u=RR(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 C=Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:CR,useNativeDriver:true});return C.start(({finished:_})=>{_&&!d&&r();}),()=>C.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,y=t.rows.length===0,R=y&&t.loading?jsxs(View,{style:o.emptyCard,accessibilityLabel:te.loading,accessibilityState:{busy:true},children:[jsx(ActivityIndicator,{color:o.emptyTitle.color}),jsx(S,{style:o.emptyBody,children:te.loading})]}):y&&t.error!==null?jsxs(View,{style:o.emptyCard,children:[jsx(S,{style:o.emptyTitle,accessibilityRole:"alert",children:te.loadFailed}),jsx(S,{style:o.emptyBody,children:t.error}),jsx(H,{accessibilityRole:"button",accessibilityLabel:te.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsx(S,{tier:"control",style:o.retryText,children:te.retry})})]}):jsxs(View,{style:o.emptyCard,children:[jsx(S,{style:o.emptyTitle,children:t.emptyKind==="empty"?te.empty:te.noMatch}),jsx(S,{style:o.emptyBody,children:t.emptyKind==="empty"?te.emptyBody:te.noMatchBody})]}),h=!t.searching&&t.loadingMore?jsx(View,{style:o.loadMoreFooter,children:jsx(S,{style:o.loadMoreLabel,children:te.loadingMore})}):null;return jsx(Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxs(View,{style:o.root,children:[jsx(Pressable,{style:xe,onPress:t.close,accessibilityRole:"button",accessibilityLabel:te.closeA11y,children:jsx(Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsx(Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(sR,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(Xd,{size:bR,color:n.color.text.muted,strokeWidth:1.5}),jsx(Ht,{value:t.query,onChangeText:C=>t.setQuery(C.replace(/^\s+/,"")),style:o.searchInput,placeholder:te.search,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:te.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsx(H,{accessibilityRole:"button",accessibilityLabel:te.newConversation,style:o.newButton,onPress:t.newConversation,children:jsx(Qd,{size:hR,color:n.color.text.primary,strokeWidth:1.5})})]}),jsx(S,{tier:"heading",style:o.heading,accessibilityRole:"header",children:te.heading}),t.error!==null&&!y?jsx(View,{style:o.errorCard,children:jsx(S,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsx(FlatList,{data:m,keyExtractor:C=>C.id,renderItem:({item:C})=>jsx(TR,{row:C,active:C.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(C.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:R,ListFooterComponent:h,onEndReached:t.loadMore,onEndReachedThreshold:ER})]})})]})})}i(SR,"DrawerModal");function TR({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0;return jsx(H,{accessibilityRole:"button",accessibilityLabel:Pd(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(S,{style:[n.itemTitle,s?n.itemTitleUnread:null],numberOfLines:1,children:Rn(e.title)}),s?jsx(View,{style:n.unreadDot}):null]})})}i(TR,"Row");function zn(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(zn,"inkWash");function PR(e){let t=e.color,r=e.slots,n=!Ul(e),o=n?t.onPrimary:t.text.primary;return StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:aR},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:n?t.brand:t.surface,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:zn(o,uR)},searchInput:{...T(e,"regular"),flex:1,fontSize:13,lineHeight:16,color:t.text.primary,padding:0},newButton:{width:ss,height:ss,borderRadius:ss/2,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},heading:{...T(e,"bold"),fontSize:14,lineHeight:17,color:o,marginTop:4},list:{gap:10,paddingBottom:28},listEmpty:{flexGrow:1},item:{paddingVertical:12,paddingHorizontal:4,borderRadius:mR},itemActive:{backgroundColor:zn(o,lR)},itemRow:{flexDirection:"row",alignItems:"center",gap:8},itemTitle:{...T(e,"regular"),flex:1,fontSize:14,lineHeight:18,color:o},itemTitleUnread:T(e,"bold"),unreadDot:{width:as,height:as,borderRadius:as/2,backgroundColor:t.danger,borderWidth:vR,borderColor:o},errorCard:{borderRadius:gR,borderWidth:.5,borderColor:t.danger,backgroundColor:t.surface,padding:12},errorText:{...T(e,"regular"),fontSize:11,lineHeight:16,color:t.danger},emptyCard:{borderRadius:yR,padding:14,gap:6,backgroundColor:zn(o,dR),borderWidth:.5,borderColor:zn(o,cR)},emptyTitle:{...T(e,"bold"),fontSize:12,lineHeight:15,color:o},emptyBody:{...T(e,"regular"),fontSize:11,lineHeight:17,color:o,opacity:pR},retrySlot:{marginTop:8,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:7,borderWidth:1,borderColor:o,...pe(r.primaryButton)},retryText:{...T(e,"bold"),fontSize:12,lineHeight:15,color:o,...Se(r.primaryButton)},loadMoreFooter:{paddingVertical:14,alignItems:"center"},loadMoreLabel:{...T(e,"regular"),fontSize:11,lineHeight:14,color:o,opacity:fR}})}i(PR,"makeStyles");var AR=Object.freeze({}),OR=100,FR=20;function MR(e,t,r,n){return ![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}i(MR,"readWindowTops");function hp(e,t){let r=typeof e=="number"&&Number.isFinite(e),n=useRef(null),[o,s]=useState(null),a=useRef(null),l=useRef(null),u=useRef(true),d=useCallback(()=>{l.current!==null&&clearTimeout(l.current),l.current=null;},[]);useEffect(()=>(u.current=true,()=>{u.current=false,d();}),[d]);let c=useCallback(i(function f(m){n.current?.measureInWindow((y,R)=>{let h=a.current;if(!u.current||h===null)return;let C=MR(R,h.y,h.height,Dimensions.get("window").height);if(C!==null){s(_=>_!==null&&_.chatTop===C.chatTop&&_.parentTop===C.parentTop?_:C);return}m>=FR||(l.current=setTimeout(()=>{l.current=null,f(m+1);},OR));});},"measureAt"),[]),p=useCallback(f=>{let{y:m,height:y}=f.nativeEvent.layout;a.current={y:m,height:y},d(),c(0);},[c,d]);return useMemo(()=>{if(!t)return {avoidingProps:r?{keyboardVerticalOffset:e}:AR,probeRef:null,topInWindow:null};let f=o?.parentTop??0;return {avoidingProps:r?{keyboardVerticalOffset:e,onLayout:p}:f>0?{keyboardVerticalOffset:f,onLayout:p}:{onLayout:p},probeRef:n,topInWindow:o?.chatTop??null}},[t,r,e,o,p])}i(hp,"useChatKeyboardOffset");function bp({probeRef:e}){return e===null?null:jsx(View,{ref:e,collapsable:false,pointerEvents:"none",style:LR})}i(bp,"KeyboardOffsetProbe");var LR=Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function vp(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(vp,"chatVetVisitOptions");var BR=16,HR=.75,us=12,Ep=15,zR=18,Wn=22,jR=14,WR=8,GR=20,KR=10,qR=13;function Rp({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=F(),a=useMemo(()=>$R(s),[s]),l=J(),u=e.tier,d=e.source;return jsxs(Fragment,{children:[jsx(Oi,{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(S,{tier:"compact",style:[a.label,{color:u.textColor}],children:u.label}),d.reason!==null?jsx(S,{style:[a.reason,{color:u.reasonColor}],children:d.reason}):null,e.showVetAction?r!==void 0?jsx(Rt,{render:()=>r(u.level),fallback:jsx(Cp,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}),resetKey:u.level}):jsx(Cp,{tier:u,petRef:t,onFindVet:n,vet:o,styles:a}):null,e.dismissLabel!==null?jsx(H,{accessibilityRole:"button",accessibilityLabel:e.dismissLabel,hitSlop:WR,containerStyle:a.closeSlot,style:a.closeButton,onPress:e.dismiss,children:jsx(St,{size:jR,color:u.textColor,strokeWidth:1.5})}):null]}):null}),jsx(Oi,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsx(H,{accessibilityRole:"button",accessibilityLabel:b.showLatestVetAlert,hitSlop:KR,onPress:e.expand,children:jsx(Kd,{size:GR,color:s.color.text.muted,strokeWidth:2})})})]})}i(Rp,"UrgencyBanner");function Cp({tier:e,petRef:t,onFindVet:r,vet:n,styles:o}){let s=F(),a=Dn(vp(t,n)),l=a.status==="opening",u=a.available?()=>{a.open();}:r!==void 0?()=>{$(r,e.level);}:null;if(u===null)return null;let d=Bi(s.slots.vetVisitButton)?.textColor??e.textColor;return jsxs(H,{accessibilityRole:"button",accessibilityLabel:b.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(Zd,{size:qR,color:d,strokeWidth:1.5}),jsx(S,{tier:"control",style:[o.findVetLabel,{color:d}],children:b.findVet})]})}i(Cp,"VetAction");function $R(e){let t=Bi(e.slots.vetVisitButton);return StyleSheet.create({pinned:{marginTop:0,marginBottom:4,paddingHorizontal:e.space.lg},card:{borderRadius:BR,borderWidth:HR,paddingHorizontal:14,paddingVertical:8,gap:2},label:{...T(e,"monoBold"),fontSize:us,lineHeight:Ep},reason:{...T(e,"regular"),fontSize:us,lineHeight:zR,paddingRight:Wn},findVetSlot:{alignSelf:"flex-start",marginTop:6},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...pe(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...T(e,"monoBold"),fontSize:us,lineHeight:Ep},closeSlot:{position:"absolute",top:6,right:6},closeButton:{width:Wn,height:Wn,borderRadius:Wn/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:16,paddingTop:2,paddingBottom:4}})}i($R,"makeStyles");function Sp(){let e=On(),{handle:t}=Z(),r=useCallback(n=>t.setActivePet(n),[t]);return useMemo(()=>({...e,setActivePet:r}),[e,r])}i(Sp,"useChatPets");var Ap=300,Op=3e3,Pp=120,$t=44,JR=120,eS="86%",cs=15,kp=22,Or=.5,tS=.04,rS=8,nS=2,oS=1,iS=.6,sS=22,aS=48,xp=1.25,lS=14,uS=18,dS=6,cS=14,pS=.04,fS=12,mS=2,yS=2,_p=36,wp=20,qt=36,Yt=($t-qt)/2,Fp=24,Mp=22,gS=.4,Gn=30,Lp=20,hS=.4,bS=480,vS=8,Ip=14,ES=10,CS=14,RS=12,SS=13,TS=18,PS="12%";function Pe(){let e=F(),t=useMemo(()=>kS(e),[e]);return {theme:e,styles:t}}i(Pe,"useChatTheme");function kS(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=o.size.body/Ce.type.size.body,a=s===1?kp:Math.round(kp*s),l=s===1?wp:Math.round(wp*s),u=e.slots;return StyleSheet.create({container:{flex:1,minHeight:Pp,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Pp,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"center",justifyContent:"flex-start",paddingTop:PS,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:bS,gap:18},errorText:{...T(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:$t,minWidth:$t,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...pe(u.primaryButton)},retryLabel:{...T(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...Se(u.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...T(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:{...T(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...T(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:$t,justifyContent:"center"},turnNoticeActionLabel:{...T(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...T(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...T(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:eS},bubbleUser:{padding:cs,backgroundColor:t.bubbleUser,borderRadius:n.xl,borderBottomRightRadius:n.sm,borderWidth:Or,borderColor:t.accentEdge,shadowColor:t.brand,shadowOpacity:tS,shadowRadius:rS,shadowOffset:{width:0,height:nS},elevation:oS,...pe(u.userBubble,Or)},bubbleAssistant:u.assistantBubble?.backgroundColor===void 0?{...pe(u.assistantBubble,Or)}:{padding:cs,borderRadius:n.xl,...pe(u.assistantBubble,Or)},bubbleVet:{padding:cs,backgroundColor:t.bubbleVet,borderRadius:n.xl,borderBottomLeftRadius:n.sm,...pe(u.vetBubble,Or)},bubblePending:{opacity:iS},bubbleTextUser:{...T(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:a,...Se(u.userBubble)},bubbleTextAssistant:{...T(e,"medium"),color:t.text.primary,fontSize:o.size.body,lineHeight:a,...Se(u.assistantBubble)},bubbleTextVet:{...T(e,"medium"),color:t.onBubbleVet,fontSize:o.size.body,lineHeight:a,...Se(u.vetBubble)},vetSender:{...T(e,"bold"),color:t.onBubbleVet,fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.normal),marginBottom:r.xs,...Se(u.vetBubble)},bubbleBold:T(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:T(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.sm,gap:vS},followUpSlot:{alignSelf:"stretch",borderRadius:Ip},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:RS,paddingVertical:ES,paddingHorizontal:CS,borderRadius:Ip,backgroundColor:t.brandSoft},followUpText:{...T(e,"medium"),flex:1,color:t.text.primary,fontSize:SS,lineHeight:TS},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,marginBottom:r.sm,minHeight:aS,justifyContent:"center",paddingLeft:lS,paddingRight:uS,paddingVertical:dS,backgroundColor:t.composerFill,borderWidth:xp,borderColor:t.composerBorder,borderRadius:sS,shadowColor:t.shadow,shadowOpacity:pS,shadowRadius:fS,shadowOffset:{width:0,height:mS},elevation:yS,...pe(u.composerInput,xp)},composerRow:{flexDirection:"row",alignItems:"center",gap:cS,minHeight:_p},attachControl:{width:Gn,height:Gn,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:hS},input:{flex:1,minHeight:_p,maxHeight:JR,paddingHorizontal:0,paddingVertical:0,...T(e,"regular"),fontSize:o.size.body,lineHeight:l,color:t.text.primary,...Se(u.composerInput)},sendControl:{minHeight:qt,minWidth:qt,alignItems:"center",justifyContent:"center"},sendDisc:{width:qt,height:qt,borderRadius:qt/2,alignItems:"center",justifyContent:"center",...pe(u.sendButton)},sendControlDisabled:{opacity:gS},poweredBy:{...T(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(kS,"makeStyles");var xS=Object.freeze({kind:"live"}),_S=Object.freeze({kind:"folded"});function ps(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=Co(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(ps,"askOf");function Np(e){let t=new Map,r=new Map;for(let o of e){let s=ps(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=ps(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,xS),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,_S);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(Np,"placeCheckins");var Dp=864e5,wS=365;function Kn(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/Dp)-Math.floor(r/Dp);return o<1||o>wS?null:o}i(Kn,"checkinDayNumber");function Up(e){return ps(e)?.dueDay||null}i(Up,"checkinDueDay");var _e=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"})}),Vp=Object.freeze(Xr.map(e=>Object.freeze({answer:e,label:_e.answers[e]})));function Bp(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:!Aa(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(Bp,"useCheckinCard");var jp=44,OS=.6;function Gp({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s,onLayout:a}){let l=F(),u=useMemo(()=>FS(l),[l]),d=Bp(t,r),c=d.answer!==null||d.pending!==null,p=r!==null&&d.answerable,f=Kn(t.openedAt,Up(e));return jsxs(View,{style:u.card,accessibilityLabel:_e.eyebrow,onLayout:a,children:[jsxs(View,{style:u.head,children:[jsx(S,{tier:"compact",style:u.eyebrow,children:_e.eyebrow}),f!==null?jsx(S,{tier:"compact",style:u.headDay,children:q(_e.day,{day:f})}):null]}),jsx(S,{style:u.question,accessibilityRole:"text",children:e.text}),p?jsx(View,{style:[u.row,d.pending?u.rowPending:null],children:Vp.map(({answer:m,label:y})=>{let R=(d.pending??d.answer)===m;return jsx(Pressable,{onPress:()=>d.choose(m),disabled:c,accessibilityRole:"button",accessibilityLabel:y,accessibilityState:{selected:R,disabled:c,busy:d.pending===m},style:[u.pill,R?u.pillSelected:null],children:jsx(S,{tier:"control",style:[u.pillLabel,R?u.pillLabelSelected:null],children:y})},m)})}):null,d.answer!==null?jsx(S,{style:u.logged,children:_e.logged}):null,d.escalated?o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:_e.findVet,style:u.findVet,children:jsx(S,{tier:"control",style:u.findVetLabel,children:_e.findVet})}):n?jsx(Kt,{entry:"chat",petRef:n,label:_e.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(S,{style:u.resolution,children:t.resolutionText}):null,d.error?jsx(S,{style:u.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}i(Gp,"CheckinCard");function FS(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:{...T(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...T(e,"bold"),color:t.text.primary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...T(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:OS},pill:{flex:1,minHeight:jp,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...T(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...T(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...T(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...T(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:jp,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...T(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(FS,"makeStyles");var DS=1.5,NS=3;function qp({text:e,runDueDays:t,openedAt:r,onLayout:n}){let o=F(),s=useMemo(()=>US(o),[o]),a=t.map(u=>Kn(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(S,{tier:"compact",style:s.days,children:a.map(u=>q(_e.day,{day:u})).join(_e.daySeparator)}):null,l?null:jsx(S,{style:s.question,accessibilityRole:"text",children:e})]})]})}i(qp,"CheckinPastAsk");function US(e){let t=e.color,r=e.space,n=e.type;return StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:DS,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:NS},days:{...T(e,"monoMedium"),fontSize:n.size.nano,letterSpacing:n.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},question:{...T(e,"regular"),fontSize:n.size.bodyTight,lineHeight:n.size.bodyTight*n.lineHeight.normal,color:t.text.muted}})}i(US,"makeStyles");var VS=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),$p="#C8BEB4";function BS(e){return e?VS[e.toUpperCase()]??$p:$p}i(BS,"tierColor");function HS(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(HS,"tierLabel");function je(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(je,"text");function zS(e){let t=je(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(zS,"httpsUrl");function jS(e,t){let r=je(e.source_name)??je(e.sourceName),n=je(e.section),o=je(e.authority_tier)??je(e.authorityTier),s=HS(o),a=r??je(e.title)??`Source ${t+1}`,l=je(e.monograph_chunk_id)??je(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:zS(e.url),excerpt:je(e.excerpt),tierColor:BS(o),key:`${a}-${l??"none"}-${t}`})}i(jS,"toCitationCard");function Yp(e){return e===void 0||e.length===0?WS:Object.freeze(e.map((t,r)=>jS(t,r)))}i(Yp,"toCitationCards");var WS=Object.freeze([]);function hs(e){return e===1?`1 ${b.sourceSingular}`:`${e} ${b.sourcePlural}`}i(hs,"sourcesLabel");function Xp(e,t){return `${t?b.hideSources:b.showSources} ${hs(e)}`}i(Xp,"sourcesToggleLabel");function Qp(e){return [e.url!==null?`${b.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(Qp,"citationA11yLabel");var YS=244,Jp=8,ef=13,XS=14,QS=.3,ZS=-0.24,JS=22,eT=10,tT=15;function tf({citations:e,onOpenUrl:t}){let r=F(),n=useMemo(()=>oT(r),[r]),o=useMemo(()=>Yp(e),[e]),[s,a]=useState(false);if(o.length===0)return null;let l=o.length;return jsxs(View,{style:n.block,children:[jsxs(H,{accessibilityRole:"button",accessibilityLabel:Xp(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(u=>!u),children:[jsx(jd,{size:ef,color:r.color.brandInk,strokeWidth:1.5}),jsx(S,{tier:"compact",style:n.toggleLabel,children:hs(l)}),jsx(Pn,{size:ef,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsx(rT,{cards:o,styles:n,open:t}):null]})}i(tf,"CitationCards");function rT({cards:e,styles:t,open:r}){let n=J(),o=Tt(n.citationsInMs,{risePx:n.citationsRisePx});return jsx(Animated.View,{style:o,children:jsx(ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsx(nT,{card:s,styles:t,open:r},s.key))})})}i(rT,"Deck");function nT({card:e,styles:t,open:r}){let n=F(),o=e.url!==null&&r!==void 0,s=Qp(o?e:{...e,url:null}),a=jsxs(Fragment,{children:[jsxs(View,{style:t.cardHeader,children:[jsx(View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsx(S,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsx(Wd,{size:XS,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsx(S,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsx(S,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let l=e.url;return jsx(H,{accessibilityRole:"link",accessibilityLabel:s,style:t.card,onPress:()=>r(l),children:a})}return jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}i(nT,"Card");function oT(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:{...T(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:QS,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:YS,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:Jp,height:Jp,borderRadius:n.pill},cardTitle:{...T(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:JS,color:t.text.primary,letterSpacing:ZS},cardTitleLink:{color:t.linkInk},cardMeta:{...T(e,"monoMedium"),fontSize:o.nano,lineHeight:eT,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...T(e,"regular"),fontSize:o.tiny,lineHeight:tT,color:t.text.muted}})}i(oT,"makeStyles");function rf(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(rf,"formatMessageTime");var Fr=15,dT=15,cT=6,pT=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function lf({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=F(),a=useMemo(()=>fT(s),[s]),l=J(),u=e.role==="user",d=useMemo(()=>rf(e.createdAt),[e.createdAt]),c=t!==void 0&&e.role!=="vet"&&e.text.length>0,p=e.role==="assistant"&&n!==void 0&&e.responseId!==void 0,[f,m]=useState(false),y=useRef(null);useEffect(()=>()=>{y.current&&clearTimeout(y.current);},[]);let R=i(()=>{t!==void 0&&(jt(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(S,{tier:"compact",style:a.timestamp,children:d}):null,c?jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:f?b.copied:u?b.copyUserMessage:b.copyAssistantMessage,hitSlop:dT,onPress:R,style:a.iconHit,children:f?jsx(lt,{size:Fr,color:s.color.success,strokeWidth:2}):jsx(Gd,{size:Fr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?Zu.map(({sentiment:h,label:C})=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:C,accessibilityState:{selected:r===h},hitSlop:cT,onPress:()=>n?.(h),style:a.iconHit,children:jsx(kn,{size:Fr,color:s.color.sentiment[h],active:r===h,rotate:pT[h],strokeWidth:1.5})},h)):null]}),o?jsx(S,{style:a.thanks,accessibilityLiveRegion:"polite",children:b.feedbackThanks}):null]})}i(lf,"MessageFooter");function fT(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:{...T(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:Fr,height:Fr,alignItems:"center",justifyContent:"center"},thanks:{...T(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(fT,"makeStyles");var uf="#10462E",df="#000000",mT="#83E0B4",yT=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:mT,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:uf,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})]),gT=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function hT(e){return e==null?e:e.replace(gT,"").trim()}i(hT,"formatBreedForPrompt");var bT=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 vT(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return bT.has(t)}i(vT,"isUninformativeBreed");function ET(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(ET,"unspecifiedBreedLabel");function CT(e,t){return vT(e)?ET(t):String(e).replace(/\s+/gu," ").trim()}i(CT,"resolveBreedLabel");function cf(e){let t=e?.name?.trim()||b.emptyTitlePetFallback;return q(b.emptyTitle,{petName:t})}i(cf,"emptyStateTitle");function pf(e,t=uf){let r=$i(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=CT(hT(e?.breed),r)||null,l=Yi(e?.ageYears),u=l===null?null:String(l);return Object.freeze(yT.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=q(m,{petName:s,breed:a??n,species:r,ageYears:u??""}),R=!o&&m.startsWith("{petName}")?y.charAt(0).toUpperCase()+y.slice(1):y;return Object.freeze({id:d.id,intent:d.intent,label:R,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(pf,"resolveQuickPrompts");var ST=36,yf=4,TT=340;function gf({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=F(),a=useMemo(()=>kT(s),[s]),l=useMemo(()=>pf(e,s.color.brandInk),[e,s.color.brandInk]),u=cf(e);return jsxs(View,{style:a.block,children:[jsx(S,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsx(View,{style:a.list,children:l.map((d,c)=>jsx(PT,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(gf,"QuickPrompts");function PT({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=J(),d=Tt(u.followUpInMs,{delayMs:_n(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(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:yf,style:[l.chip,c],onPress:()=>{$(s,r);},children:jsx(S,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsx(Animated.View,{style:d,children:jsx(Kt,{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(H,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:yf,style:[l.chip,c],onPress:()=>o(e.label),children:jsx(S,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(PT,"Chip");function kT(e){let t=e.color;return StyleSheet.create({block:{gap:18,alignItems:"center",width:"100%"},title:{...T(e,"bold"),fontSize:28,lineHeight:34,color:t.text.primary,letterSpacing:-0.8,textAlign:"center",maxWidth:TT},list:{width:"100%",gap:12,alignItems:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:14,paddingVertical:9,minHeight:ST,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipLabel:{...T(e,"bold"),fontSize:12,lineHeight:14,color:df,textAlign:"center"}})}i(kT,"makeStyles");var vs=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hf(e){return e.includes("*")||e.includes("`")}i(hf,"hasInlineMarkup");function bf(e){let t=[],r=0;vs.lastIndex=0;for(let n=vs.exec(e);n!==null;n=vs.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(bf,"tokenizeInlineMarkdown");function vf(e,t){return hf(e)?bf(e).map((r,n)=>{switch(r.kind){case "bold":return jsx(S,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx(S,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx(S,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(vf,"renderInlineMarkdown");var Rf=6,Pf=520,OT=Math.round(Pf*.18),Sf=.44,FT=.5,Tf=[0,.5,1],MT=[0,1,2];function kf(){let e=F(),t=useMemo(()=>DT(e),[e]),r=!e.motion.reducedMotion;return jsx(View,{style:t.card,accessible:true,accessibilityRole:"text",accessibilityLabel:b.typing,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:MT.map(n=>r?jsx(LT,{index:n,style:t.dot},n):jsx(View,{style:[t.dot,t.dotStatic]},n))})}i(kf,"TypingIndicator");function LT({index:e,style:t}){let r=useRef(new Animated.Value(0)).current;useEffect(()=>{let s=Animated.sequence([Animated.delay(e*OT),Animated.loop(Animated.timing(r,{toValue:1,duration:Pf,useNativeDriver:true}))]);return s.start(),()=>s.stop()},[r,e]);let n=r.interpolate({inputRange:Tf,outputRange:[Sf,1,Sf]}),o=r.interpolate({inputRange:Tf,outputRange:[0,-3.5,0]});return jsx(Animated.View,{style:[t,{opacity:n,transform:[{translateY:o}]}]})}i(LT,"AnimatedDot");function DT(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:Rf,height:Rf,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:FT}})}i(DT,"makeStyles");function xf(e,t,r){let n=e-r,o=t!=null?Math.min(n,t):n;return Math.max(0,o)}i(xf,"resolveTurnScrollTarget");function _f(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(_f,"latestTurn");function wf(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(wf,"nextFollowOffset");function If(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=_f(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 w=u.current.get(c);if(w===void 0)return;let O=p===null?null:u.current.get(p)??null;x=xf(w,O,96);}let g=wf(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 m=useCallback(P=>{a.current=P.nativeEvent.layout.height,f();},[f]),y=useCallback((P,x)=>{l.current=x,a.current>0&&(s.current=Math.min(s.current,Math.max(0,x-a.current))),f();},[f]),R=useCallback(P=>{s.current=P.nativeEvent.contentOffset.y;},[]),h=useCallback(()=>{n.current=false;},[]),C=useCallback(P=>{let{contentOffset:x,contentSize:g,layoutMeasurement:w}=P.nativeEvent;s.current=x.y,n.current=g.height-x.y-w.height<=24;},[]),_=useCallback(P=>x=>{u.current.set(P,x.nativeEvent.layout.y),(P===c||P===p)&&f();},[c,p,f]);return {ref:r,onLayout:m,onContentSizeChange:y,onScroll:R,onScrollBeginDrag:h,onScrollEnd:C,rowLayout:_}}i(If,"useThreadFollow");function Lf(e,t,r){switch(e){case "loading":return r.renderPending?jsx(Rt,{render:r.renderPending,fallback:jsx(Of,{})}):jsx(Of,{});case "empty":return jsx(WT,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsx(qT,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsx($T,{messages:t.messages,prompts:Md(t),onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,thanksFor:r.thanksFor,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl});default:return nt(e)}}i(Lf,"renderView");function Of(){let{theme:e,styles:t}=Pe(),[r,n]=useState(false);return useEffect(()=>{let o=setTimeout(()=>n(true),Ap);return ()=>clearTimeout(o)},[]),jsx(View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:b.loading,children:r?jsx(ActivityIndicator,{color:e.color.brandInk}):null})}i(Of,"LoadingState");function WT({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:o}){let{styles:s}=Pe();return jsx(ScrollView,{contentContainerStyle:s.emptyContent,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,accessibilityLabel:b.empty,children:jsx(gf,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o})})}i(WT,"EmptyState");function GT({prompts:e,onSelectPrompt:t}){let{styles:r}=Pe();return e.length===0?null:jsx(View,{style:r.followUps,children:e.map((n,o)=>jsx(KT,{prompt:n,index:o,onSelectPrompt:t},n))})}i(GT,"FollowUps");function KT({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=Pe(),s=J(),a=Tt(s.followUpInMs,{delayMs:_n(s,t)});return jsx(Animated.View,{style:a,children:jsxs(H,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:o.followUpSlot,style:o.followUpRow,children:[jsx(S,{style:o.followUpText,children:e}),jsx(Pn,{size:ZT,color:n.color.brandInk,direction:"right"})]})})}i(KT,"FollowUpRow");function qT({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Pe(),o=ad(e)?yd(r):void 0;return jsxs(View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsx(S,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:b.addPet,style:n.retryButton,children:jsx(S,{tier:"control",style:n.retryLabel,children:b.addPet})}):null,e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:b.retry,style:n.retryButton,children:jsx(S,{tier:"control",style:n.retryLabel,children:b.retry})}):null]})}i(qT,"ErrorState");function $T({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:R,onFindVet:h,vet:C,onOpenUrl:_}){let{styles:P}=Pe(),x=J();Pr(e.length,x);let g=useMemo(()=>Np(e),[e]),w=Fd(e,n),O=e[e.length-1],M=useMemo(()=>e.filter(v=>!(v.checkin&&g.get(v.id)?.kind==="folded")),[e,g]),I=If(M,n);return jsxs(ScrollView,{ref:I.ref,style:P.list,contentContainerStyle:P.listContent,accessibilityLabel:b.transcript,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,onLayout:I.onLayout,onContentSizeChange:I.onContentSizeChange,onScroll:I.onScroll,scrollEventThrottle:QT,onScrollBeginDrag:I.onScrollBeginDrag,onScrollEndDrag:I.onScrollEnd,onMomentumScrollEnd:I.onScrollEnd,children:[e.map(v=>{let k=v.checkin?g.get(v.id):void 0;return k?.kind==="folded"?null:k?.kind==="past"?jsx(qp,{text:v.text,runDueDays:k.runDueDays,openedAt:v.checkin?.openedAt,onLayout:I.rowLayout(v.id)},v.id):v.checkin&&k!==void 0?jsx(Gp,{message:v,checkin:v.checkin,onAnswer:o,petRef:R,onFindVet:h,vet:C,onLayout:I.rowLayout(v.id)},v.id):jsx(JT,{onLayout:I.rowLayout(v.id),message:v,revealing:n&&v===O&&v.role==="assistant",onCopy:s,sentiment:v.responseId===void 0?null:a[String(v.responseId)]??null,onSentiment:l,thanks:u!==null&&v.responseId!==void 0&&String(v.responseId)===u,images:d[v.id]??XT,onPreview:c,onOpenUrl:_},v.id)}),f?jsx(S,{tier:"compact",style:P.reconnectingCaption,accessibilityRole:"text",children:b.reconnecting}):null,w?jsx(kf,{}):null,p!==null?jsx(YT,{notice:p,onRetry:m,onStartNew:y}):null,jsx(GT,{prompts:t,onSelectPrompt:r})]})}i($T,"PopulatedState");function YT({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Pe(),o=e.tone==="error";return jsxs(View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsx(S,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsx(S,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsx(Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Yt,style:n.turnNoticeAction,children:jsx(S,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(YT,"TurnNoticeCard");var XT=Object.freeze([]),QT=16,ZT=14;function JT({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l,onOpenUrl:u,onLayout:d}){let{styles:c}=Pe(),p=J(),f=Tt(p.messageInMs),m=lc(e.text,t,p),y=e.role==="user",R=e.role==="vet",h=y?b.senderUser:R?Ld(e):b.senderAssistant,C=useCallback(P=>o(e,P),[o,e]),_=e.pending!==true;return jsxs(Animated.View,{style:[c.rowBlock,y?c.rowBlockUser:c.rowBlockAssistant,f],onLayout:d,children:[jsx(View,{style:[c.row,y?c.rowUser:c.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${h}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxs(View,{style:[c.bubble,y?c.bubbleUser:R?c.bubbleVet:c.bubbleAssistant,e.pending?c.bubblePending:null],children:[y&&a.length>0?jsx(Pc,{images:a,onPreview:P=>l({uri:P.uri,label:P.filename})}):null,R?jsx(S,{style:c.vetSender,children:h}):null,jsx(S,{style:y?c.bubbleTextUser:R?c.bubbleTextVet:c.bubbleTextAssistant,children:e.role==="assistant"?vf(m,{bold:c.bubbleBold,italic:c.bubbleItalic,code:c.bubbleCode}):e.text})]})}),e.role==="assistant"&&!t?jsx(tf,{citations:e.citations,onOpenUrl:u}):null,_?jsx(lf,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:C,thanks:s}):null]})}i(JT,"MessageRow");var oP=Object.freeze(["photo"]),iP=1;function Nf(e){let{style:t,renderPending:r}=e;return jsx(mi,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsx(sP,{...e})})}i(Nf,"EverfurChat");function sP({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:R,draftStore:h,vetReturnTo:C,vetUsState:_,vetPrefer:P,onOpenUrl:x,keyboardVerticalOffset:g}){let{theme:w,styles:O}=Pe(),M=J(),I=useMemo(()=>Dd(e,t),[e,t]),v=Rr(I),k=Ad(v),V=Sp(),W=kd(v),G=useSafeAreaInsets(),ae=Od(v),be=useMemo(()=>l===void 0?void 0:()=>{$(l,"emergency");},[l]),Ie=useMemo(()=>C===void 0&&_===void 0&&P===void 0?void 0:{returnTo:C,usState:_,prefer:P},[C,_,P]),ct=ns(V.pets,v.petRef),ye=useMemo(()=>wd(v.messages,ct?.name??null),[v.messages,ct?.name]),rt=Id(ye);Pr(rt.showBanner,M),vd(v.openCheckin,f),pd(v.askEverfur,v.isBootstrapping,m);let Dr=useMemo(()=>Ri(y),[y]);hd(R,{conversationId:v.conversationId===null?null:String(v.conversationId),isTurnInFlight:v.isStreaming,refresh:v.refreshActiveThread});let Nr=(v.hasUnreadThreads??false)||W.rows.some(ke=>ke.unreadCount!==null&&ke.unreadCount>0)||(v.unreadCount??0)>0,Ot=dd(v.messages),[Jt,Qn]=useState(null),Vf=useCallback(()=>Qn(null),[]),[er,Zn]=useState(null),[Bf,Ss]=useState(null),Ft=useRef(null);useEffect(()=>()=>{Ft.current&&clearTimeout(Ft.current);},[]);let Ts=useCallback(ke=>{Ss(String(ke)),Ft.current&&clearTimeout(Ft.current),Ft.current=setTimeout(()=>{Ss(null),Ft.current=null;},Op);},[]),Hf=useCallback((ke,Vr)=>{let tr=ke.responseId;if(tr===void 0)return;let qf=v.sentimentByMessage[String(tr)];v.feedback(tr,Vr),Vr==="down"&&qf!=="down"&&Zn(tr);},[v]),zf=useCallback(async(ke,Vr)=>er===null||!(await v.feedback(er,"down",ke??"other",Vr)).ok?false:(Zn(null),Ts(er),true),[v,er,Ts]),jf=useCallback(()=>Zn(null),[]),Wf=useCallback(ke=>{v.send(ke);},[v.send]),Gf=useMemo(()=>x===void 0?void 0:ke=>{$(x,ke,"citation");},[x]),Ps=Platform.OS==="ios"?"padding":void 0,Ur=hp(g,Ps!==void 0),Kf=Ur.topInWindow===null?G.top:Math.max(0,G.top-Ur.topInWindow),ks={send:v.send,stop:v.stop,isStreaming:v.isStreaming,conversationId:v.conversationId,seed:Dr,draftStore:h,onStage:Ot.stage,onPreview:Qn};return jsxs(KeyboardAvoidingView,{style:[O.container,{paddingTop:Kf},r],behavior:Ps,...Ur.avoidingProps,children:[jsx(bp,{probeRef:Ur.probeRef}),jsx(up,{pets:V,petRef:v.petRef,historyUnread:Nr,onOpenHistory:W.show,onPetChange:s,onAddPet:p,vet:Ie}),c!==void 0?jsx(aP,{petRef:e??null,pet:c,onRegistered:V.refresh}):null,jsx(Rp,{surface:rt,petRef:v.petRef,renderVetAction:u,onFindVet:l,vet:Ie}),jsx(View,{style:O.body,children:Lf(k,v,{notice:ae,vet:Ie,onCheckinFindVet:be,onSelectPrompt:Wf,renderPending:n,shownPet:ct,onVetPrep:a,onCopy:o,onSentiment:Hf,thanksFor:Bf,imagesByMessage:Ot.byMessage,onPreview:Qn,onAddPet:p,onOpenUrl:Gf})}),d!==void 0?jsx(lP,{...ks,attachments:d}):jsx(Uf,{...ks,attachments:null}),jsx(Vd,{}),w.meta.hidePoweredBy?null:jsx(S,{tier:"compact",style:O.poweredBy,accessibilityRole:"text",accessibilityLabel:b.poweredBy,children:b.poweredBy}),jsx(gp,{chat:v,history:W}),jsx(yp,{visible:er!==null,onSubmit:zf,onSkip:jf}),jsx(uc,{uri:Jt?.uri??null,label:Jt?.label??"",onClose:Vf}),jsx(xr,{})]})}i(sP,"ChatBody");function aP({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Pe(),o=ld(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs(View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsx(S,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsx(Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:b.retry,hitSlop:Yt,children:jsx(S,{tier:"control",style:n.setupNoticeAction,children:b.retry})})]})}i(aP,"PetSetupNotice");function lP({attachments:e,...t}){let r=useMemo(()=>xc(),[]),n=En({maxPerMessage:e.maxPerMessage??iP,transport:r}),o=useMemo(()=>({state:n,sources:e.sources??oP,pick:e.pick}),[n,e.sources,e.pick]);return jsx(Uf,{...t,attachments:o})}i(lP,"ComposerWithAttachments");function Uf({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:u}){let{theme:d,styles:c}=Pe(),p=J(),[f,m]=Rd(e,n,s);Sd(a,n===null?null:String(n),f,m);let[y,R]=useState(false),[h,C]=useState(false);useEffect(()=>{C(false);},[n]);let _=d.meta.placeholder??b.placeholder,P=o?.state.uploading??false,x=o?.state.failed??false,g=P||x,w=o?.state.attachments??uP;Pr(w.length,p);let O=useCallback(()=>{if(f.trim().length===0||g||[...f].length>Nt)return;let G=o?.state.s3Keys??dP;o!==null&&G.length>0?(l(o.state.attachments.filter(ae=>ae.status==="uploaded").map(ae=>({uri:ae.previewUri,filename:ae.filename}))),e(f,{imageS3Keys:G}),o.state.clear()):e(f),m(""),C(false);},[f,e,g,o,l]),M=useCallback(()=>{t();},[t]),I=useCallback(G=>{R(false),o!==null&&(C(false),o.state.dismissRejected(),jt(o.pick,G).then(ae=>{if(!ae.ok){C(true);return}ae.value!==null&&o.state.add(ae.value);}));},[o]),k=useMemo(()=>[...f].length>Nt,[f])||g,V=o!==null&&w.length>=o.state.maxPerMessage,W=d.slots.sendButton?.textColor??d.color.brandInk;return jsxs(View,{style:c.composerOuter,children:[o!==null&&y?jsx(pc,{sources:o.sources,full:V,onPick:I,onClose:()=>R(false)}):null,jsxs(View,{style:c.composer,children:[o!==null?jsx(Tc,{attachments:w,rejected:h?cP: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:od(w.length,o.state.maxPerMessage),accessibilityState:{disabled:V,expanded:y},disabled:V,hitSlop:($t-Gn)/2,style:[c.attachControl,V?c.attachControlDisabled:null],onPress:()=>R(G=>!G),children:jsx(qd,{size:Lp,color:V?d.color.text.muted:d.color.brandInk,strokeWidth:1.75})}):null,jsx(Ht,{style:c.input,value:f,onChangeText:m,placeholder:_,placeholderTextColor:d.slots.composerInput?.textColor??d.color.text.placeholder,onSubmitEditing:O,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsx(Pressable,{onPress:M,accessibilityRole:"button",accessibilityLabel:b.stop,hitSlop:Yt,style:c.sendControl,children:jsx(View,{style:c.sendDisc,testID:"everfur-stop-disc",children:jsx(ec,{size:Mp,color:W,testID:"everfur-stop-glyph"})})}):jsx(Pressable,{onPress:O,disabled:k,accessibilityRole:"button",accessibilityLabel:b.send,accessibilityState:{disabled:k,busy:P},hitSlop:Yt,style:[c.sendControl,k?c.sendControlDisabled:null],children:jsx(View,{style:c.sendDisc,testID:"everfur-send-disc",children:jsx(Jd,{size:Fp,color:W,testID:"everfur-send-glyph"})})})]})]})]})}i(Uf,"Composer");var uP=Object.freeze([]),dP=Object.freeze([]),cP=Object.freeze({code:"unknown",retryable:true,filename:""});function gP(e){let{runtime:t,userRef:r,scopeEpoch:n}=Z(),o=useMemo(()=>ot(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(gP,"useEverfurPetProfile");function bP(e){return createElement(hn,{clientTheme:e.clientTheme??null,seams:vn,children:e.children})}i(bP,"EverfurThemeProvider");export{Ql as APPEARANCE_PRESETS,Xl as APPEARANCE_PRESET_NAMES,br as APPEARANCE_SIZE_RANGES,mi as CapabilityGate,Nf as EverfurChat,ee as EverfurConfigError,wb as EverfurProvider,bP as EverfurThemeProvider,Br as EverfurThrownError,Sg as THEME_SLOT_KEYS,qe as THEME_SLOT_NAMES,pr as canonicalPetSpecies,eo as categoryFor,tm as conversationId,vm as createRnRecordsUploadTransport,Xo as expandAppearance,T as face,Xf as isErr,Yf as isOk,to as isRetryableCode,Jf as petRef,kh as previewTheme,Qf as unwrap,Bt as useCapability,En as useChatAttachments,wu as useEverfur,Rr as useEverfurChat,gP as useEverfurPetProfile,On as useEverfurPets,F as useEverfurTheme,Mt as userFacingError,em as userRef};
|