@everfur/sdk 1.5.3 → 1.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.
Files changed (74) hide show
  1. package/chat-cards/package.json +8 -0
  2. package/dist/{Chat.d-BCfyvzX8.d.ts → Chat.d-B4GybUU4.d.ts} +1 -1
  3. package/dist/{Chat.d-Od44h51D.d.cts → Chat.d-DPM2ncxi.d.cts} +1 -1
  4. package/dist/chat/index.cjs +174 -174
  5. package/dist/chat/index.d.cts +4 -4
  6. package/dist/chat/index.d.ts +4 -4
  7. package/dist/chat/index.js +340 -340
  8. package/dist/chat/lite/index.cjs +174 -174
  9. package/dist/chat/lite/index.d.cts +4 -4
  10. package/dist/chat/lite/index.d.ts +4 -4
  11. package/dist/chat/lite/index.js +339 -339
  12. package/dist/chat-cards/index.cjs +18 -0
  13. package/dist/chat-cards/index.d.cts +15 -0
  14. package/dist/chat-cards/index.d.ts +15 -0
  15. package/dist/chat-cards/index.js +18 -0
  16. package/dist/{chatHandoffToken.d-BjfmIxXk.d.cts → chatHandoffToken.d-Cap2z62P.d.cts} +1 -1
  17. package/dist/{chatHandoffToken.d-CFiI6IMc.d.ts → chatHandoffToken.d-zdp23Ukr.d.ts} +1 -1
  18. package/dist/{checkin.d-CokpahFL.d.ts → checkin.d-BoZXWjxX.d.ts} +8 -0
  19. package/dist/{checkin.d-BP3ZWBfX.d.cts → checkin.d-CuIUahcd.d.cts} +8 -0
  20. package/dist/{chunk-CFEHTNKX.js → chunk-6AIEUA4V.js} +1 -1
  21. package/dist/{chunk-OU5RMGKD.js → chunk-BN7OAFBS.js} +18 -18
  22. package/dist/{chunk-ZGL2GEEI.js → chunk-IXHLESYC.js} +1 -1
  23. package/dist/{chunk-XGF2HYNN.js → chunk-LMIBOI3I.js} +16 -16
  24. package/dist/client/index.cjs +1 -1
  25. package/dist/client/index.d.cts +1 -1
  26. package/dist/client/index.d.ts +1 -1
  27. package/dist/client/index.js +1 -1
  28. package/dist/{context.d-DS1GXUEY.d.ts → context.d-D7zX6Q0J.d.ts} +1 -1
  29. package/dist/{context.d-Bj6-xYPA.d.cts → context.d-guaLkx5t.d.cts} +1 -1
  30. package/dist/core/index.cjs +2 -2
  31. package/dist/core/index.d.cts +4 -4
  32. package/dist/core/index.d.ts +4 -4
  33. package/dist/core/index.js +2 -2
  34. package/dist/index.cjs +354 -354
  35. package/dist/index.d.cts +7 -7
  36. package/dist/index.d.ts +7 -7
  37. package/dist/index.js +364 -364
  38. package/dist/notifications/index.d.cts +3 -3
  39. package/dist/notifications/index.d.ts +3 -3
  40. package/dist/records/index.cjs +1 -1
  41. package/dist/records/index.js +1 -1
  42. package/dist/{route.d-DtuKY5dM.d.ts → route.d-B3u14HJT.d.ts} +1 -1
  43. package/dist/{route.d-Nt-r-7IO.d.cts → route.d-QBCoO62z.d.cts} +1 -1
  44. package/dist/{runtimeTypes.d-CL4l7ta4.d.cts → runtimeTypes.d-BSxuUCOX.d.cts} +1 -1
  45. package/dist/{runtimeTypes.d-BzUig75K.d.ts → runtimeTypes.d-hjN6xvxm.d.ts} +1 -1
  46. package/dist/server/events/index.cjs +1 -1
  47. package/dist/server/events/index.js +1 -1
  48. package/dist/server/index.cjs +1 -1
  49. package/dist/server/index.js +1 -1
  50. package/dist/testing/rn/index.d.cts +2 -2
  51. package/dist/testing/rn/index.d.ts +2 -2
  52. package/dist/testing/web/index.d.cts +2 -2
  53. package/dist/testing/web/index.d.ts +2 -2
  54. package/dist/{useUnread.d-CedFK4k6.d.ts → useUnread.d-4SbFChbd.d.ts} +30 -3
  55. package/dist/{useUnread.d-DST1GMmL.d.cts → useUnread.d-B0YhhR_D.d.cts} +30 -3
  56. package/dist/web/health-plan/index.cjs +1 -1
  57. package/dist/web/health-plan/index.js +1 -1
  58. package/dist/web/index.cjs +3 -3
  59. package/dist/web/index.d.cts +7 -7
  60. package/dist/web/index.d.ts +7 -7
  61. package/dist/web/index.js +3 -3
  62. package/dist/web/notifications/index.d.cts +2 -2
  63. package/dist/web/notifications/index.d.ts +2 -2
  64. package/dist/web/records-sheet/index.cjs +1 -1
  65. package/dist/web/records-sheet/index.js +1 -1
  66. package/dist/web/shop/index.cjs +1 -1
  67. package/dist/web/shop/index.js +1 -1
  68. package/dist/web/televet/booking/index.cjs +1 -1
  69. package/dist/web/televet/booking/index.js +1 -1
  70. package/dist/web/televet/call/index.cjs +1 -1
  71. package/dist/web/televet/call/index.js +1 -1
  72. package/dist/web/ui/index.cjs +1 -1
  73. package/dist/web/ui/index.js +32 -32
  74. package/package.json +16 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- import{z as e}from"zod";import{createContext,forwardRef as t,createElement as r,useEffect as n,useState as l,useSyncExternalStore as i,useContext as o,useMemo as a,useCallback as s,useRef as u,useReducer as c,useLayoutEffect as d,Component as f,Fragment as h}from"react";import*as p from"react-native";import{Platform as g,TextInput as b,StyleSheet as m,AccessibilityInfo as y,useColorScheme as v,Dimensions as k,PixelRatio as w,View as C,AppState as S,Text as x,Linking as _,KeyboardAvoidingView as R,Pressable as T,Keyboard as I,Modal as z,ScrollView as P,ActivityIndicator as O,Image as E,UIManager as j,LayoutAnimation as F,Animated as A,useWindowDimensions as D,FlatList as M}from"react-native";import{SafeAreaProvider as L,useSafeAreaInsets as B}from"react-native-safe-area-context";import H from"react-native-sse";import{jsx as U,jsxs as N,Fragment as $}from"react/jsx-runtime";import*as W from"@everfur/sdk/televet/booking";import*as V from"@everfur/sdk/texting";function q(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))return true;t+=1}else if(r>=56320&&r<=57343)return true}return false}function G(e){return[...e].length}function ok(e,t){/* @__PURE__ */
2
+ import{z as e}from"zod";import{createContext,forwardRef as t,createElement as r,useEffect as n,useState as l,useSyncExternalStore as i,useContext as o,useMemo as a,lazy as s,useCallback as u,useRef as c,useReducer as d,useLayoutEffect as f,Component as h,Fragment as p,Suspense as g}from"react";import*as b from"react-native";import{Platform as m,TextInput as y,StyleSheet as v,AccessibilityInfo as k,useColorScheme as w,Dimensions as C,PixelRatio as S,View as x,AppState as _,Text as R,Linking as T,KeyboardAvoidingView as I,Pressable as z,Keyboard as P,Modal as O,ScrollView as E,ActivityIndicator as j,Image as F,UIManager as A,LayoutAnimation as D,Animated as M,useWindowDimensions as L,FlatList as B}from"react-native";import{SafeAreaProvider as H,useSafeAreaInsets as U}from"react-native-safe-area-context";import N from"react-native-sse";import{jsx as $,jsxs as W,Fragment as V}from"react/jsx-runtime";import*as q from"@everfur/sdk/televet/booking";import*as G from"@everfur/sdk/texting";function K(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))return true;t+=1}else if(r>=56320&&r<=57343)return true}return false}function Y(e){return[...e].length}function ok(e,t){/* @__PURE__ */
3
3
  return Object.freeze({ok:true,value:e})}function err(e){/* @__PURE__ */
4
- return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var K=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new K(e.error)}var Y=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var Q=128,J=128,X=/[\u0000-\u001F\u007F]/,Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=G(t);if(r===0||r>J)throw new Y("invalid-argument",`petRef must be 1..${J} characters`);if(X.test(t))throw new Y("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=G(t);if(r===0||r>Q)throw new Y("invalid-argument",`userRef must be 1..${Q} characters`);if(t.includes("@"))throw new Y("invalid-argument","userRef must not contain '@'");if(X.test(t))throw new Y("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!Z.test(e))throw new Y("invalid-argument","conversationId must be a UUID");return e}var ee=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],te=/* @__PURE__ */Object.freeze(ee.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(te.map(e=>e.wireCode));var re=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),ne=/* @__PURE__ */Object.freeze(te.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:re[e.wireCode]}))),le=new Map(ne.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ie=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(ne.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...ie]){let t=le.get(e+r);if(t)return t}}var oe=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return oe[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var ae=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return ae.has(e)}var se=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||se.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var ue=500,ce=8e3,de=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(ue*2**r,ce);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var fe="This feature isn't available on your account right now.",he="Something in that request was not right. Check the details and try again.",pe=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:fe,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:he,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:fe,runtimeDisposed:he,unknown:"Something went wrong. Please try again."}),ge="This session has ended. Please sign in again.",be="linked_account_read_only";function me(e,t,r){return e==="conflict"&&r===be?fe:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?ge:userFacingError(e)}function userFacingError(e){return pe[e]}function ye(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var ve=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===be,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:me(e,t?.wireCode,n?be:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&ve.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&ye(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ye(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var ke=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function we(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return _e(e)}var Ce=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,Se=/[\s\u0000-\u001f\u007f\\]/,xe={"http:":"80","https:":"443"};function _e(e,t){let r=e.trim();let n=Se.test(r)?null:Ce.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===xe[f]?"":String(h),g=xe[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var Re="application/pdf",Te=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Ie=e=>Te.includes(e);function ze(e,t){return e===Re||t!==void 0&&Ie(e)&&t.includes(e)}var Pe=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function Oe(e){return ze(e,Te)?Pe[e]:Pe["application/pdf"]}var Ee="file",je="multipart upload failed";function Fe(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Ee,e.file)}catch{return Promise.reject(new Error(je))}return e.fetch!==void 0?Me(e.fetch,e.url,t,e.signal):De(e.url,t,e.signal)}function Ae(e){return e>=200&&e<300}function De(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(je));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(je))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Ae(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function Me(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var Le="records upload: the file handle has no uri",Be="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
5
- return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Le));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(Be));return l?.aborted===true?o():Fe({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:Oe(r.mimeType),type:He(r.mimeType)},signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}function He(e){return ze(e,Te)?e:"application/pdf"}var Ue=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var Ne=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<de},maxAttempts(){return de}});var $e=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(e,t,r){let n;try{n=t()}catch(t){return Ve(`optional peer '${e}' is not installed: ${qe(t)}`)}let l=We(n);return l==null?Ve(`optional peer '${e}' resolved to no module`):r&&!r(l)?Ve(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:l})}function We(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function Ve(e){/* @__PURE__ */
6
- return Object.freeze({available:false,module:null,reason:e})}function qe(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function acceptedFrame(e,t,r=null){/* @__PURE__ */
4
+ return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var Q=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new Q(e.error)}var J=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var X=128,Z=128,ee=/[\u0000-\u001F\u007F]/,te=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=Y(t);if(r===0||r>Z)throw new J("invalid-argument",`petRef must be 1..${Z} characters`);if(ee.test(t))throw new J("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=Y(t);if(r===0||r>X)throw new J("invalid-argument",`userRef must be 1..${X} characters`);if(t.includes("@"))throw new J("invalid-argument","userRef must not contain '@'");if(ee.test(t))throw new J("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!te.test(e))throw new J("invalid-argument","conversationId must be a UUID");return e}var re=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],ne=/* @__PURE__ */Object.freeze(re.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(ne.map(e=>e.wireCode));var le=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),ie=/* @__PURE__ */Object.freeze(ne.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:le[e.wireCode]}))),oe=new Map(ie.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ae=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(ie.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...ae]){let t=oe.get(e+r);if(t)return t}}var se=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return se[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var ue=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return ue.has(e)}var ce=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||ce.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var de=500,fe=8e3,he=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(de*2**r,fe);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var pe="This feature isn't available on your account right now.",ge="Something in that request was not right. Check the details and try again.",be=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:pe,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:ge,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:pe,runtimeDisposed:ge,unknown:"Something went wrong. Please try again."}),me="This session has ended. Please sign in again.",ye="linked_account_read_only";function ve(e,t,r){return e==="conflict"&&r===ye?pe:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?me:userFacingError(e)}function userFacingError(e){return be[e]}function ke(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var we=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===ye,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:ve(e,t?.wireCode,n?ye:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&we.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&ke(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ke(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var Ce=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Se(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return Te(e)}var xe=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,_e=/[\s\u0000-\u001f\u007f\\]/,Re={"http:":"80","https:":"443"};function Te(e,t){let r=e.trim();let n=_e.test(r)?null:xe.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===Re[f]?"":String(h),g=Re[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var Ie="application/pdf",ze=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Pe=e=>ze.includes(e);function Oe(e,t){return e===Ie||t!==void 0&&Pe(e)&&t.includes(e)}var Ee=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function je(e){return Oe(e,ze)?Ee[e]:Ee["application/pdf"]}var Fe="file",Ae="multipart upload failed";function De(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Fe,e.file)}catch{return Promise.reject(new Error(Ae))}return e.fetch!==void 0?Be(e.fetch,e.url,t,e.signal):Le(e.url,t,e.signal)}function Me(e){return e>=200&&e<300}function Le(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(Ae));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(Ae))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Me(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function Be(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var He="records upload: the file handle has no uri",Ue="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
5
+ return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(He));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(Ue));return l?.aborted===true?o():De({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:je(r.mimeType),type:Ne(r.mimeType)},signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}function Ne(e){return Oe(e,ze)?e:"application/pdf"}var $e=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var We=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<he},maxAttempts(){return he}});var Ve=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(e,t,r){let n;try{n=t()}catch(t){return Ge(`optional peer '${e}' is not installed: ${Ke(t)}`)}let l=qe(n);return l==null?Ge(`optional peer '${e}' resolved to no module`):r&&!r(l)?Ge(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:l})}function qe(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function Ge(e){/* @__PURE__ */
6
+ return Object.freeze({available:false,module:null,reason:e})}function Ke(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function acceptedFrame(e,t,r=null){/* @__PURE__ */
7
7
  return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}function heartbeatFrame(e,t=null){/* @__PURE__ */
8
8
  return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}function deltaFrame(e,t,r=null){/* @__PURE__ */
9
9
  return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}function doneFrame(e,t=null){/* @__PURE__ */
@@ -11,377 +11,377 @@ return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,
11
11
  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,...e.freeCap?{freeCap:/* @__PURE__ */Object.freeze({...e.freeCap})}:{}})}function analysisStartedFrame(e,t,r=null){/* @__PURE__ */
12
12
  return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
13
13
  return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
14
- return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var Ge="/widget/v1/anon-identity",Ke="x-everfur-anon-token",Ye="anonTokenInvalid";function Qe(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let l=null,i=null,o=null,a=null,s=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs-2592e5),d=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,a={method:"POST",path:Ge,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},s=await e.request(a),u=s.ok?s.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(l={token:c,mintedAtMs:n(),ttlMs:Qe(u?.expires_at,i)},o=null,c)}catch{return o=n(),d()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(a,3e4)?Promise.resolve(l?.token??null):(a=n(),l=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function Je(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function Xe(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let l=null,i=false,o=null,a=false,s=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new Y("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:Ze(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(a)throw new Y("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:s()},hasToken(){return!a&&l!==null},clear(){a=true,l=null},reportRejected(){a||i||(i=true,n?.())}}}function Ze(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[Ke]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...et(e.headers),...authHeaders(t)}}}function et(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===Ke||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await Je(t),n=await t.transport.request(withAuthHeaders(e,tt(t,r)));if(n.ok||nt(n.error.raw)!==Ye||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,tt(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(Xe(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(Xe(e,{wireCode:nt(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(rt(i.error))):i}function tt(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function rt(e){let t=e.raw,r=nt(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function nt(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var lt="DAILY_QUOTA_EXCEEDED",it=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function ot(e,t){if(!it.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?lt:e}var at="free_cap_reached";function st(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function ut(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==at&&n.code!==at)return null;let l=st(n.limit),i=st(n.used);if(l===null||i===null)return null;let o=n.resets_at,a=n.emergency_guidance;/* @__PURE__ */
15
- return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ct(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:ut(t)}function dt(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function ft(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):dt()}var ht=`\n\n`,pt=1048576,gt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),bt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=ft(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(ht,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+ht.length),o=0;let r=mt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>pt){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=mt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function mt(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=gt.safeParse(l);return i.success?yt(i.data,r,t):null}function yt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:vt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:vt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:ut(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:vt(e.conversation_id)??"",messageId:vt(e.message_id),title:vt(e.title),followUpQuestions:St(e.follow_up_questions),citations:_t(e.citations),citationStatus:vt(e.citation_status),urgencyLevel:wt(e.urgency_level),urgencyReason:vt(e.urgency_reason),urgencyProvided:Ct(e),resultId:vt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(vt(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=vt(e.delta)??vt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(vt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:vt(e.result_id),analysisType:vt(e.analysis_type),modelVersion:vt(e.model_version),confidence:kt(e.confidence),detections:_t(e.detections),interpretation:vt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function vt(e){return typeof e=="string"?e:null}function kt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function wt(e){return typeof e=="string"&&bt.includes(e)?e:null}function Ct(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||wt(t)!==null}function St(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e){return Array.isArray(e)?e.filter(xt):[]}function Rt(e,t,r){return{...e,surface:t,requestId:r||null}}var Tt=64,It=/^[A-Za-z0-9._+() -]+$/;function zt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Tt?null:It.test(t)?t:null}var Pt="1.5.3";var Ot="react-native",Et="2026-09-19",jt="EVERFUR_API_BASE_URL";function Ft(e,t){/* @__PURE__ */
14
+ return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var Ye="/widget/v1/anon-identity",Qe="x-everfur-anon-token",Je="anonTokenInvalid";function Xe(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let l=null,i=null,o=null,a=null,s=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs-2592e5),d=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,a={method:"POST",path:Ye,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},s=await e.request(a),u=s.ok?s.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(l={token:c,mintedAtMs:n(),ttlMs:Xe(u?.expires_at,i)},o=null,c)}catch{return o=n(),d()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(a,3e4)?Promise.resolve(l?.token??null):(a=n(),l=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function Ze(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function et(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let l=null,i=false,o=null,a=false,s=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new J("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:tt(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(a)throw new J("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:s()},hasToken(){return!a&&l!==null},clear(){a=true,l=null},reportRejected(){a||i||(i=true,n?.())}}}function tt(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[Qe]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...rt(e.headers),...authHeaders(t)}}}function rt(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===Qe||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await Ze(t),n=await t.transport.request(withAuthHeaders(e,nt(t,r)));if(n.ok||it(n.error.raw)!==Je||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,nt(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(et(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(et(e,{wireCode:it(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(lt(i.error))):i}function nt(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function lt(e){let t=e.raw,r=it(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function it(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var ot="DAILY_QUOTA_EXCEEDED",at=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function st(e,t){if(!at.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?ot:e}var ut="free_cap_reached";function ct(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function dt(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==ut&&n.code!==ut)return null;let l=ct(n.limit),i=ct(n.used);if(l===null||i===null)return null;let o=n.resets_at,a=n.emergency_guidance;/* @__PURE__ */
15
+ return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ft(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:dt(t)}function ht(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function pt(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ht()}var gt=`\n\n`,bt=1048576,mt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),yt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=pt(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(gt,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+gt.length),o=0;let r=vt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>bt){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=vt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function vt(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=mt.safeParse(l);return i.success?kt(i.data,r,t):null}function kt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:wt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:wt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:dt(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:wt(e.conversation_id)??"",messageId:wt(e.message_id),title:wt(e.title),followUpQuestions:_t(e.follow_up_questions),citations:Tt(e.citations),citationStatus:wt(e.citation_status),urgencyLevel:St(e.urgency_level),urgencyReason:wt(e.urgency_reason),urgencyProvided:xt(e),resultId:wt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(wt(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=wt(e.delta)??wt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(wt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:wt(e.result_id),analysisType:wt(e.analysis_type),modelVersion:wt(e.model_version),confidence:Ct(e.confidence),detections:Tt(e.detections),interpretation:wt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function wt(e){return typeof e=="string"?e:null}function Ct(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function St(e){return typeof e=="string"&&yt.includes(e)?e:null}function xt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||St(t)!==null}function _t(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(e){return Array.isArray(e)?e.filter(Rt):[]}function It(e,t,r){return{...e,surface:t,requestId:r||null}}var zt=64,Pt=/^[A-Za-z0-9._+() -]+$/;function Ot(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>zt?null:Pt.test(t)?t:null}var Et="1.6.0";var jt="react-native",Ft="2026-09-19",At="EVERFUR_API_BASE_URL";function Dt(e,t){/* @__PURE__ */
16
16
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
17
- return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||Et,o=zt(e.appVersion);/* @__PURE__ */
18
- return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:Pt,platform:t?.platform??Ot,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:Ut(jt);return r?Bt(r):Ft("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${jt}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function At(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function Dt(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function Mt(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Dt(t)}function Lt(e,t){return`${e}://${t}`}function Bt(e){let t=e.trim(),r=ke.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Ft("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=At(r[2]);if(l.length===0)return Ft("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=Mt(t,l)?`: ${Lt(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&Ht(l)))return n==="http"?Ft("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):Ft("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
19
- return Object.freeze({ok:true,value:o})}function Ht(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function Ut(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Nt(e,t){if(e.status!==429&&e.status!==503)return t;let r=Wt(e.headers.get($t),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&Vt(n)?t:{...n??{},retry_after_seconds:r}}var $t="retry-after";function Wt(e,t){if(e===null)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r);let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):null}function Vt(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var qt=3e4,Gt="x-request-id";async function*fetchByteSource(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)break;r&&r.length>0&&(yield r)}}finally{await(t.cancel?.())}}function eventSourceByteSource(e){let t=new TextEncoder,r=Yt(),n=false,l=e=>{let n="";e.lastEventId&&(n+=`id: ${e.lastEventId}\n`);let l=e.data??"";for(let e of l.split(`\n`))n+=`data: ${e}\n`;n+=`\n`,r.push(t.encode(n))},i=()=>{a(),r.end()},o=e=>{let n=typeof e.xhrStatus=="number"?e.xhrStatus:0;if(n>=400){let l=tr(e.message);if(l!==null){let e={type:"error",code:at,retryable:false,limit:l.limit,used:l.used,resets_at:l.resetsAt,emergency_guidance:l.emergencyGuidance};r.push(t.encode(`data: ${JSON.stringify(e)}\n\n`))}else{let e=Zt(n),l=isAutoRetryable(fromWire(e));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:e,retryable:l})}\n\n`))}}a(),r.end()};e.addEventListener("message",l),e.addEventListener("done",i),e.addEventListener("error",o);function a(){if(!n){n=true,e.removeEventListener("message",l),e.removeEventListener("done",i),e.removeEventListener("error",o);try{e.close()}catch{}}}return Kt(r.source,a)}async function*Kt(e,t){try{yield*e}finally{t()}}function Yt(){let e=[],t=false,r=null,n=()=>{if(r){let e=r;r=null,e()}};async function*l(){for(;;){let n=e.shift();if(n!==void 0){yield n;continue}if(t)return;await new Promise(e=>{r=e})}}return{source:l(),push:t=>{e.push(t),n()},end:()=>{t=true,n()}}}async function requestJson(e,t){let r=t.fetchImpl??getGlobalFetch(),n=rr(t.config.apiBaseUrl,e.path,e.query),l=nr(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),i=or(qt),o=ar(i.signal,e.signal),a;try{a=await r(n,lr({...e,signal:o},l))}catch(e){return err(networkError(e))}finally{i.cancel()}if(e.onResponseHeaders)try{e.onResponseHeaders(e=>a.headers.get(e))}catch{}if(e.rawText&&a.ok)try{return ok(Number(a.headers.get("content-length"))>e.rawText?null:await a.text())}catch(e){return err(networkError(e))}let s=await sr(a);return a.ok?ok(s):err(errorFromResponse(a.status,Nt(a,s),requestIdOf(a)))}function createHttpTransport(e){return{request:t=>requestJson(t,e),stream:(t,r)=>Qt(ir(t,r),e)}}async function*Qt(e,t){let r=rr(t.config.apiBaseUrl,e.path,e.query),n=nr(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Jt(e,n));yield*parseSse(eventSourceByteSource(l),()=>eventSourceRequestId(l));return}let l=t.fetchImpl??getGlobalFetch(),i;try{i=await l(r,lr(e,n))}catch(e){yield er("",true,hr(e));return}let o=requestIdOf(i);if(!i.ok){let e=await sr(i),t=cr(e)??Zt(i.status),r=fr(e)||isAutoRetryable(fromWire(t));yield er(t,r,dr(e),o,ut(e));return}if(i.body){yield*parseSse(fetchByteSource(i.body),o);return}yield*parseSse(fetchByteSource(null),o)}function Jt(e,t){return{method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}function errorFromResponse(e,t,r){let n=cr(t),l=n?fromWire(n):fromHttpStatus(e),i=dr(t);return makeEverfurError(l,{httpStatus:e,...fr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...ur(t)?{reasonCode:ur(t)}:{},...Xt(t)!==null?{retryAfterSeconds:Xt(t)}:{},...i?{wireMessage:i}:{},...t!=null?{raw:t}:{}})}function Xt(e){let t=e,r=t?.retry_after_seconds??t?.error?.retry_after_seconds;return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null}function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:hr(e)})}function requestIdOf(e){let t=e.headers.get(Gt);return typeof t=="string"&&t.length>0?t:null}function eventSourceRequestId(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Gt)}catch{return null}return typeof t=="string"&&t.length>0?t:null}function Zt(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}function er(e,t,r,n=null,l=null){return errorFrame({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n,freeCap:l})}function tr(e){if(typeof e!="string"||e.length===0)return null;try{return ut(JSON.parse(e))}catch{return null}}function getGlobalFetch(){let e=globalThis.fetch;if(typeof e!="function")throw new Y("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}function rr(e,t,r){let n=t.startsWith("/")?t:`/${t}`,l=`${e}${n}`;if(r){let e=Object.entries(r).filter(e=>e[1]!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");e&&(l+=`?${e}`)}return l}function nr(e,t,r,n){let l={...buildBaseHeaders(e),accept:r};return n&&(l["content-type"]="application/json"),t&&Object.assign(l,t),l}function lr(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}function ir(e,t){return e.signal?e:{...e,signal:t}}function or(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function ar(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}async function sr(e){try{return await e.json()}catch{return null}}function ur(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}function cr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?ot(r,e):ut(e)!==null?at:null}function dr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}function fr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}function hr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var pr=3e4,gr=ce*2,br="idempotency-key",mr=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),yr=/* @__PURE__ */Object.freeze({onEvent(){}}),vr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function kr(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??yr,r=e.timers??vr,n=e.rng??Math.random,l=e.sleep??((e,t)=>Dr(e,r,t)),i=e.maxAttempts??de,o=e.unaryTimeoutMs??pr,a=e.newIdempotencyKey??Cr(),s=e=>{try{t.onEvent(e)}catch{}};async function u(t,u,c){let d=c?.maxAttempts,f=Math.max(1,d??i),h=c?.idempotent??mr.has(u.method),p=c?.idempotencyKey===void 0?null:kr(c.idempotencyKey),g=h?p??a():null,b=wr(u,g),m=0;for(;;){let i=e=>/* @__PURE__ */Object.freeze({call:t,method:u.method,path:u.path,attempt:m,...g?{idempotencyKey:g}:{},...e});s(i({phase:"attempt"}));let a=Fr(o,r),c=Ar(a.signal,u.signal),h;try{h=await authedSend({...b,signal:c.signal},e.auth)}catch(e){h=err(networkError(e))}finally{c.dispose(),a.cancel()}if(h.ok)return s(i({phase:"settled",ok:true,reason:"ok"})),h;let p=h.error,y=xr(p,m,{maxAttempts:f,rng:n,now:r.now(),aborted:u.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:p.code,reason:y.reason,...p.httpStatus!==void 0?{httpStatus:p.httpStatus}:{},...p.requestId!==void 0?{requestId:p.requestId}:{}};if(!y.retry)return s(i({phase:"settled",...v})),err(p);if(s(i({phase:"retry",...v,delayMs:y.delayMs})),await l(y.delayMs,u.signal),u.signal?.aborted===true)return s(i({phase:"settled",...v,reason:"aborted"})),err(p);m+=1}}async function c(t){return withAuthHeaders(t,await jr(e.auth))}async function*d(t,r,n){s(
17
+ return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||Ft,o=Ot(e.appVersion);/* @__PURE__ */
18
+ return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:Et,platform:t?.platform??jt,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:$t(At);return r?Ut(r):Dt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${At}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function Mt(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function Lt(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function Bt(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Lt(t)}function Ht(e,t){return`${e}://${t}`}function Ut(e){let t=e.trim(),r=Ce.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Dt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=Mt(r[2]);if(l.length===0)return Dt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=Bt(t,l)?`: ${Ht(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&Nt(l)))return n==="http"?Dt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):Dt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
19
+ return Object.freeze({ok:true,value:o})}function Nt(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function $t(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Wt(e,t){if(e.status!==429&&e.status!==503)return t;let r=qt(e.headers.get(Vt),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&Gt(n)?t:{...n??{},retry_after_seconds:r}}var Vt="retry-after";function qt(e,t){if(e===null)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r);let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):null}function Gt(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var Kt=3e4,Yt="x-request-id";async function*fetchByteSource(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)break;r&&r.length>0&&(yield r)}}finally{await(t.cancel?.())}}function eventSourceByteSource(e){let t=new TextEncoder,r=Jt(),n=false,l=e=>{let n="";e.lastEventId&&(n+=`id: ${e.lastEventId}\n`);let l=e.data??"";for(let e of l.split(`\n`))n+=`data: ${e}\n`;n+=`\n`,r.push(t.encode(n))},i=()=>{a(),r.end()},o=e=>{let n=typeof e.xhrStatus=="number"?e.xhrStatus:0;if(n>=400){let l=nr(e.message);if(l!==null){let e={type:"error",code:ut,retryable:false,limit:l.limit,used:l.used,resets_at:l.resetsAt,emergency_guidance:l.emergencyGuidance};r.push(t.encode(`data: ${JSON.stringify(e)}\n\n`))}else{let e=tr(n),l=isAutoRetryable(fromWire(e));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:e,retryable:l})}\n\n`))}}a(),r.end()};e.addEventListener("message",l),e.addEventListener("done",i),e.addEventListener("error",o);function a(){if(!n){n=true,e.removeEventListener("message",l),e.removeEventListener("done",i),e.removeEventListener("error",o);try{e.close()}catch{}}}return Qt(r.source,a)}async function*Qt(e,t){try{yield*e}finally{t()}}function Jt(){let e=[],t=false,r=null,n=()=>{if(r){let e=r;r=null,e()}};async function*l(){for(;;){let n=e.shift();if(n!==void 0){yield n;continue}if(t)return;await new Promise(e=>{r=e})}}return{source:l(),push:t=>{e.push(t),n()},end:()=>{t=true,n()}}}async function requestJson(e,t){let r=t.fetchImpl??getGlobalFetch(),n=lr(t.config.apiBaseUrl,e.path,e.query),l=ir(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),i=sr(Kt),o=ur(i.signal,e.signal),a;try{a=await r(n,or({...e,signal:o},l))}catch(e){return err(networkError(e))}finally{i.cancel()}if(e.onResponseHeaders)try{e.onResponseHeaders(e=>a.headers.get(e))}catch{}if(e.rawText&&a.ok)try{return ok(Number(a.headers.get("content-length"))>e.rawText?null:await a.text())}catch(e){return err(networkError(e))}let s=await cr(a);return a.ok?ok(s):err(errorFromResponse(a.status,Wt(a,s),requestIdOf(a)))}function createHttpTransport(e){return{request:t=>requestJson(t,e),stream:(t,r)=>Xt(ar(t,r),e)}}async function*Xt(e,t){let r=lr(t.config.apiBaseUrl,e.path,e.query),n=ir(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Zt(e,n));yield*parseSse(eventSourceByteSource(l),()=>eventSourceRequestId(l));return}let l=t.fetchImpl??getGlobalFetch(),i;try{i=await l(r,or(e,n))}catch(e){yield rr("",true,gr(e));return}let o=requestIdOf(i);if(!i.ok){let e=await cr(i),t=fr(e)??tr(i.status),r=pr(e)||isAutoRetryable(fromWire(t));yield rr(t,r,hr(e),o,dt(e));return}if(i.body){yield*parseSse(fetchByteSource(i.body),o);return}yield*parseSse(fetchByteSource(null),o)}function Zt(e,t){return{method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}function errorFromResponse(e,t,r){let n=fr(t),l=n?fromWire(n):fromHttpStatus(e),i=hr(t);return makeEverfurError(l,{httpStatus:e,...pr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...dr(t)?{reasonCode:dr(t)}:{},...er(t)!==null?{retryAfterSeconds:er(t)}:{},...i?{wireMessage:i}:{},...t!=null?{raw:t}:{}})}function er(e){let t=e,r=t?.retry_after_seconds??t?.error?.retry_after_seconds;return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null}function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:gr(e)})}function requestIdOf(e){let t=e.headers.get(Yt);return typeof t=="string"&&t.length>0?t:null}function eventSourceRequestId(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Yt)}catch{return null}return typeof t=="string"&&t.length>0?t:null}function tr(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}function rr(e,t,r,n=null,l=null){return errorFrame({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n,freeCap:l})}function nr(e){if(typeof e!="string"||e.length===0)return null;try{return dt(JSON.parse(e))}catch{return null}}function getGlobalFetch(){let e=globalThis.fetch;if(typeof e!="function")throw new J("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}function lr(e,t,r){let n=t.startsWith("/")?t:`/${t}`,l=`${e}${n}`;if(r){let e=Object.entries(r).filter(e=>e[1]!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");e&&(l+=`?${e}`)}return l}function ir(e,t,r,n){let l={...buildBaseHeaders(e),accept:r};return n&&(l["content-type"]="application/json"),t&&Object.assign(l,t),l}function or(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}function ar(e,t){return e.signal?e:{...e,signal:t}}function sr(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function ur(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}async function cr(e){try{return await e.json()}catch{return null}}function dr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}function fr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?st(r,e):dt(e)!==null?ut:null}function hr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}function pr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}function gr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var br=3e4,mr=fe*2,yr="idempotency-key",vr=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),kr=/* @__PURE__ */Object.freeze({onEvent(){}}),wr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Cr(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??kr,r=e.timers??wr,n=e.rng??Math.random,l=e.sleep??((e,t)=>Lr(e,r,t)),i=e.maxAttempts??he,o=e.unaryTimeoutMs??br,a=e.newIdempotencyKey??xr(),s=e=>{try{t.onEvent(e)}catch{}};async function u(t,u,c){let d=c?.maxAttempts,f=Math.max(1,d??i),h=c?.idempotent??vr.has(u.method),p=c?.idempotencyKey===void 0?null:Cr(c.idempotencyKey),g=h?p??a():null,b=Sr(u,g),m=0;for(;;){let i=e=>/* @__PURE__ */Object.freeze({call:t,method:u.method,path:u.path,attempt:m,...g?{idempotencyKey:g}:{},...e});s(i({phase:"attempt"}));let a=Dr(o,r),c=Mr(a.signal,u.signal),h;try{h=await authedSend({...b,signal:c.signal},e.auth)}catch(e){h=err(networkError(e))}finally{c.dispose(),a.cancel()}if(h.ok)return s(i({phase:"settled",ok:true,reason:"ok"})),h;let p=h.error,y=Rr(p,m,{maxAttempts:f,rng:n,now:r.now(),aborted:u.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:p.code,reason:y.reason,...p.httpStatus!==void 0?{httpStatus:p.httpStatus}:{},...p.requestId!==void 0?{requestId:p.requestId}:{}};if(!y.retry)return s(i({phase:"settled",...v})),err(p);if(s(i({phase:"retry",...v,delayMs:y.delayMs})),await l(y.delayMs,u.signal),u.signal?.aborted===true)return s(i({phase:"settled",...v,reason:"aborted"})),err(p);m+=1}}async function c(t){return withAuthHeaders(t,await Ar(e.auth))}async function*d(t,r,n){s(
20
20
  /* @__PURE__ */Object.freeze({call:t,phase:"stream.open",method:r.method,path:r.path,attempt:0}));try{yield*e.auth.transport.stream(r,n)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null})}}/* @__PURE__ */
21
- return Object.freeze({send:u,authorize:c,stream:d})}function wr(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==br&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function Cr(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var Sr=10;function xr(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=_r(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=n==="burst"?"burst-throttle":"retryable-code";if((()=>{if(r.policy===void 0)return false;try{return!r.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let i=()=>{if(r.policy===void 0)return null;let t;try{t=r.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Sr,Math.floor(t)))},o=r.perCallMaxAttempts??i()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let a=Rr(e,r.now);return a!==null?a>gr?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:a}:{retry:true,reason:l,delayMs:backoffDelayMs(t,r.rng)}}function _r(e){let t=e.code==="unknown"?fromWire(Or(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function Rr(e,t){let r=Ir(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=Tr(e.raw);return n===null?null:Math.round(n*1e3)}function Tr(e){for(let t of zr(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Ir(e){for(let t of zr(e)){let e=t.resets_at,r=Pr(e);if(r!==null)return r}return null}function zr(e){if(!Er(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];Er(n)&&t.push(n)}return t}function Pr(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function Or(e){for(let t of zr(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function Er(e){return typeof e=="object"&&e!==null}async function jr(e){if(e.mode==="anonymous"){let t=await Je(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function Fr(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function Ar(e,t){let r=()=>{};if(!t)return{signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let l=()=>n.abort();return e.addEventListener("abort",l,{once:true}),t.addEventListener("abort",l,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",l),t.removeEventListener("abort",l)}}}function Dr(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let l=t.setTimeout(()=>{r?.removeEventListener("abort",i),n()},e),i=()=>{t.clearTimeout(l),n()};r?.addEventListener("abort",i,{once:true})})}var Mr=/* @__PURE__ */Object.freeze(["better","same","worse"]),Lr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Br(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Hr(){return err(makeEverfurError("internalError",{retryable:false}))}function Ur(e){return typeof e!="string"||e.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):q(e)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}var Nr=e=>typeof e=="string"?e:null,$r=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Wr(e){if(typeof e!="object"||e===null)return null;let t=e,r=Nr(t.case_id),n=Nr(t.status);if(r===null||n===null)return null;let l=Nr(t.last_response);/* @__PURE__ */
22
- return Object.freeze({caseId:r,status:n,bodyLocation:Nr(t.body_location),lastResponse:l!==null&&Mr.includes(l)?l:null,checkInDueAt:Nr(t.check_in_due_at),openedAt:Nr(t.opened_at),resolvedAt:Nr(t.resolved_at),resolutionText:Nr(t.resolution_text),checkinAskCount:$r(t.checkin_ask_count),checkinAnswerCount:$r(t.checkin_answer_count)})}function Vr(e){return{async list(t,r){let n=Ur(t);if(typeof n!="string")return err(n);let l=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!l.ok)return err(l.error);let i=typeof l.value=="object"&&l.value!==null?l.value.cases:null;if(!Array.isArray(i))return Hr();let o=i.map(Wr);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):Hr()},async checkin(t,r,n,l){let i=Ur(t);if(typeof i!="string")return err(i);if(typeof r!="string"||!Lr.test(r))return Br("case_id must be a UUID");if(!Mr.includes(n))return Br("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${i}/${r}/checkin`,body:{response:n},...l?.signal?{signal:l.signal}:{}});if(!o.ok)return err(o.error);let a=typeof o.value=="object"&&o.value!==null?o.value:{},s=Wr(a.case);return s===null?Hr():ok(/* @__PURE__ */Object.freeze({case:s,ctaDeepLink:Nr(a.cta_deep_link)}))}}}function qr(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}function Gr(e,t){let r=t.activeConversationId===null||t.activeConversationId.length===0?null:t.activeConversationId;return r===null&&t.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:qr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var Kr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var Yr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Qr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let l={handle:void 0},i=()=>{r.clearTimeout(l.handle),t.removeEventListener("abort",i),n()};l.handle=r.setTimeout(i,e),t.addEventListener("abort",i,{once:true})})}function Jr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}var Xr=class{constructor(e){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...e})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){return this.snapshot}patch(e){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...e});for(let e of this.listeners)e()}beginOperation(e){this.inFlight?.abort();let t=new AbortController;this.inFlight=t;let r=this.epoch;return{signal:e?Jr(t.signal,e):t.signal,epoch:r,settle:()=>{this.inFlight===t&&(this.inFlight=null)}}}alive(e){return e===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear()}};function Zr(e,t,r){/* @__PURE__ */
23
- return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function en(e,t,r){/* @__PURE__ */
24
- return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function tn(e){/* @__PURE__ */
25
- return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function rn(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),/* @__PURE__ */Object.freeze(r)}function nn(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,/* @__PURE__ */Object.freeze(r)}function ln(e){/* @__PURE__ */
26
- return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function on(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function an(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function sn(e){return errorFrame({code:un(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function un(e){switch(e){case"authExpired":return"AUTH_EXPIRED";case"authRejected":return"AuthorizationException";case"sessionRequired":return"session_required";case"accessDenied":return"ACCESS_DENIED";case"paymentRequired":return"TIER_UPGRADE_REQUIRED";case"quotaExceeded":return"QUOTA_EXCEEDED";case"rateLimited":return"RATE_LIMITED";case"validationFailed":return"ValidationException";case"sdkUpdateRequired":return"invalidRequest";case"conflict":return"ConflictException";case"idempotencyConflict":return"IDEMPOTENCY_CONFLICT";case"idempotencyInFlight":return"IDEMPOTENCY_KEY_IN_FLIGHT";case"conversationNotFound":return"CONVERSATION_NOT_FOUND";case"petNotFound":return"PET_NOT_FOUND";case"resourceNotFound":return"ResourceNotFoundException";case"streamTimeout":return"STREAM_TIMEOUT";case"mediaUploadFailed":return"MEDIA_UPLOAD_FAILED";case"moderationBlocked":return"MODERATION_BLOCKED";case"upstreamLlmTimeout":return"UPSTREAM_LLM_TIMEOUT";case"internalError":return"INTERNAL_ERROR";case"notImplemented":return"NotImplementedException";case"serviceUnavailable":return"ServiceUnavailableException";case"streamIncomplete":return"STREAM_INCOMPLETE";case"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function cn(e){let t=Array.isArray(e)?e:fn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!fn(e))continue;let t=hn(e.category)??hn(e.title)??"",n=pn(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
27
- return Object.freeze(r)}function dn(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hn(e){return typeof e=="string"?e:null}function pn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(fn(r)){let e=hn(r.text)??hn(r.prompt)??hn(r.title);e!==null&&t.push(e)}return t}function gn(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function bn(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function mn(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function yn(e){let t=e,r=mn(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let l=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof l=="function"){let t=l.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var vn={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*kn(e,t,r,n){let l=yn(e);if(l===null){yield Cn();return}let i=Sn(t.overallMs,n),o=Sn(t.idleMs,n),a=xn(r);try{for(;;){if(r.aborted)return;let e=l.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),i.promise.then(()=>({tag:"overall"})),a.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield Cn();return}if(n.tag==="idle"||n.tag==="overall"){yield wn();return}let s=n.value;if(s.done||(o.reset(t.idleMs),yield s.value,s.value.terminal))return}}finally{o.cancel(),i.cancel(),Promise.resolve(l.return?.(void 0)).catch(()=>{})}}function wn(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Cn(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Sn(e,t){let r=()=>{},n=new Promise(e=>{r=e}),l=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(l),l=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(l)}}}function xn(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var _n="checkin",Rn=/^\d{4}-\d{2}-\d{2}$/,Tn="watching";function In(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function zn(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,l=t.question,i=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof l!="string"||l.trim().length===0)return null;let o=typeof i=="string"&&i.length>0?i:null,a=On(o),s=a===null?null:/* @__PURE__ */Object.freeze({caseId:a.caseId,answer:null,resolutionText:null,status:null}),u=typeof t.created_at=="string"?t.created_at:"",c=/* @__PURE__ */Object.freeze({id:n,role:"assistant",text:l,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...s===null?{}:{checkin:s}});/* @__PURE__ */
28
- return Object.freeze({conversationId:r,message:c,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==Tn}function Pn(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}function On(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==_n||n===void 0||l===void 0||!Lr.test(n)||!Rn.test(l)?null:{caseId:n,dueDay:l}}function En(e){return On(e)?.caseId??null}function jn(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||q(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function Fn(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function An(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Dn(e){return e==null||typeof e=="string"&&e.length>0&&!q(e)}function Mn(){return err(makeEverfurError("internalError",{retryable:false}))}function Ln(e){let t=An(e);if(!t||!Array.isArray(t.conversations)||!Dn(t.next_cursor))return Mn();let r=[];for(let e of t.conversations){let t=An(e);if(!t||typeof t.conversation_id!="string"||!Fn(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return Mn();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return Mn();let l=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...l.length>0?{preview:l}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Bn(e){let t=An(e);if(!t||!Array.isArray(t.messages)||!Dn(t.next_cursor))return Mn();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=An(e);if(!t||typeof t.message_id!="string"||!Fn(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return Mn();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Hn(t,t.message_id,t.content,t.created_at));continue}let l=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,i=t.role==="assistant"?En(l):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:Nn(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:$n(t.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...i!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:i,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Hn(e,t,r,n){let l=An(e.sender),i=Un(l?.display_name)??Un(e.sender_display_name),o=Un(l?.specialty);/* @__PURE__ */
29
- return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function Un(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!q(t)?t:null}function Nn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function $n(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
30
- return Object.freeze(e.flatMap(e=>{let r=An(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function Wn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Vn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),qn=4e3;var Gn=4e3;function Kn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:on("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:on("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Yn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:on("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Gn?{reason:"too_long",error:on("validationFailed",false,`message is ${r} characters; the server accepts at most ${Gn}`)}:null}function Qn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Jn(e){yield e}async function*Xn(){}var Zn=6e4,el=18e4,tl=24,rl=512,nl=false;function createChatController(e){return new al(e)}function ll(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function il(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function ol(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var al=class extends Xr{constructor(e){super(ln({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Vr(this.funnel),this.telemetry=e.telemetry??Ue,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??Ne,this.timers=e.timers??vn,this.rng=e.rng??Math.random,this.newId=e.newId??gn(),this.makeIdempotencyKey=e.makeIdempotencyKey??bn(),this.budget={idleMs:e.budget?.idleMs??Zn,overallMs:e.budget?.overallMs??el}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=on(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Jn(sn(e))}let l=Yn(e)??Kn(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Jn(sn(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Jn(sn(on("accessDenied",false)));let r=Yn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Jn(sn(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):Xn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Zr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?tn(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(dn(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=jn(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(on("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(on("accessDenied",false));if(!l.ok)return l;let i=Ln(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,i.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return i}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=zn(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),il(n.error)?n.error:null;if(n.error.category==="notFound"&&ol(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=In(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}ll(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(on("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(on("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(on("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(on("accessDenied",false));if(typeof e!="string"||e.trim().length===0||q(e))return err(on("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Vn.includes(t))return err(on("validationFailed",false,`feedback_type must be one of ${Vn.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>qn)return err(on("validationFailed",false,`notes is over ${qn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(on("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(on("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(on("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(on("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!Fn(e))return err(on("validationFailed",false));let r=jn(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(on("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(on("accessDenied",false)):l.ok?Bn(l.value):l}async resumeConversation(e){if(this.disposed)return err(on("accessDenied",false));if(!Fn(e))return err(on("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(on("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===Tn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||Pn({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
31
- return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?Tn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(on("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(on("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(on("accessDenied",false));if(!i.ok)return err(i.error);let o=Wn(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&il(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(on("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(on("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield sn(t.error))}async primeConversation(e){if(this.disposed)return err(on("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(on("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(on("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(on("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(on("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(on("accessDenied",false));let r=e?.petRef??null;if(r!==null&&q(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(on("accessDenied",false)):l.ok?ok(cn(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=Jr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Zr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,sn(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=on("internalError",!0);yield*this.emitTerminal(e,t,sn(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=Jr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,sn(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Ke]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of kn(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=on("streamIncomplete",!0);yield*this.emitTerminal(e,t,sn(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===Ye||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,an(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(nl&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,an(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?tn(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,en(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=rl){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},tl)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?rn(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?nn(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?tn(e):e),nn(en(r,"",this.stamp()),e)]}let l=dn([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=Qn(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?tn(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?on("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,ul(e)?(a=true,u=e):(cl(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){ul(e)?(a=true,u===null&&(u=e)):cl(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
32
- return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:b,error:y,warning:y===null&&g===null&&s?sl:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...i]),sawForbidden:o,sawUnauthorized:a,sawConversationInitFailure:s})})}var sl="Chat is ready. Your first message will start the conversation.";function ul(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function cl(e){return e.httpStatus===403||e.code==="accessDenied"}var dl=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function fl(e){return e!==dl}var hl=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var pl=10*1024*1024,gl=5,bl=120,ml="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&hl.includes(e.trim().toLowerCase())}function sanitizeFilename(e){if(!e)return"attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return"attachment";if(t.length<=bl)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,bl);let n=t.slice(r);return n.length>=bl?t.slice(0,bl):`${t.slice(0,r).slice(0,bl-n.length)}${n}`}function formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}var yl=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),vl=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function kl(e,t,r,n){/* @__PURE__ */
33
- return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return vl(kl("unsupported_type",false,t));let n=attachmentSize(e);return n===null?vl(kl("unknown",false,t)):n>pl?vl(kl("too_large",false,t,{sizeBytes:n})):yl(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function wl(e){if(typeof e!="object"||e===null)return null;let t=e,r=e=>typeof e=="string"&&e.length>0?e:null,n=e=>typeof e=="number"&&Number.isFinite(e)?e:null,l=r(t.upload_id),i=r(t.upload_url),o=r(t.s3_key);if(l===null||i===null||o===null)return null;let a={},s=t.upload_fields;if(typeof s=="object"&&s!==null)for(let[e,t]of Object.entries(s))typeof t=="string"&&(a[e]=t);/* @__PURE__ */
34
- return Object.freeze({upload_id:l,upload_url:i,upload_fields:/* @__PURE__ */Object.freeze(a),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??pl,s3_key:o,purpose:r(t.purpose)})}function Cl(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return kl("quota_exceeded",false,t,{cause:e});case"rateLimited":return kl("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return kl("idempotency_conflict",true,t,{cause:e});case"validationFailed":return kl("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return kl("network",true,t,{cause:e});default:return r===429?kl("rate_limited",true,t,{cause:e}):r===503?kl("network",true,t,{cause:e}):r===void 0?kl("network",true,t,{cause:e}):kl("server",e.retryable,t,{httpStatus:r,cause:e})}}async function initiateAttachmentUpload(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:ml,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return vl(Cl(n.error,t.filename));let l=wl(n.value);return l===null?vl(kl("server",false,t.filename)):yl(l)}async function uploadAttachmentBytes(e,t,r,n){let l=()=>n?.signal?.aborted===true;if(l())return vl(kl("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),yl(void 0)}catch{return l()?vl(kl("cancelled",true,r.filename)):vl(kl("server",true,r.filename))}}var Sl=2,xl=3,_l=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Rl=0;function Tl(){return Rl+=1,`attachment-${Rl}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??Sl),r=Math.max(1,e.maxAttempts??xl),n=e.backoffMs??_l,l=Math.max(1,e.maxPerMessage??gl),i=e.timers??Yr,o=e.newId??Tl,a=fl(e.transport),s=/* @__PURE__ */new Map,u=[],c=[],d=/* @__PURE__ */new Set,f=/* @__PURE__ */new Set,h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),p=false,g=()=>{h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(u.flatMap(e=>{let t=s.get(e);return t===void 0?[]:[t.state]}))});for(let e of f)e()},b=(e,t)=>{e.state=/* @__PURE__ */Object.freeze({...e.state,...t}),g()},m=()=>{for(;!p&&d.size<t&&c.length>0;){let e=c.shift(),t=s.get(e);t!==void 0&&(d.add(e),y(t).finally(()=>{d.delete(e),m()}))}},y=async t=>{let{attachment:l}=t;for(;t.attempts<r;){if(p||t.controller.signal.aborted)return;t.attempts+=1;let o=t.controller.signal;b(t,{status:"uploading",error:null,progress:0});let a=await initiateAttachmentUpload(e.funnel,l,{signal:o});if(p||o.aborted)return;let s;if(!a.ok)s=vl(a.error);else{let r=await uploadAttachmentBytes(e.transport,a.value,l,{signal:o,onProgress:e=>{!o.aborted&&t.state.status==="uploading"&&b(t,{progress:Il(e)})}});if(p||o.aborted)return;s=r.ok?yl(a.value.s3_key):vl(r.error)}if(s.ok){b(t,{status:"uploaded",s3Key:s.value,error:null,progress:1});return}let u=s.error,c=u.retryable&&t.attempts<r;if(b(t,{status:c?"uploading":"failed",error:u,progress:0}),!c)return;let d=n[Math.min(t.attempts-1,n.length-1)]??0;await Qr(d,o,i)}},v=e=>{c.push(e.state.id),m()},k={available:a,subscribe(e){return f.add(e),()=>{f.delete(e)}},getSnapshot:()=>h,get uploading(){return h.attachments.some(e=>e.status==="uploading")},get s3Keys(){return h.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[])},add(e){let t=validateAttachment(e);if(!t.ok)return t;if(p||u.length>=l)return vl(kl("too_many",false,t.value.filename));let r=o(),n={attachment:t.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:r,filename:t.value.filename,previewUri:e.uri,contentType:t.value.contentType,sizeBytes:t.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return s.set(r,n),u.push(r),g(),v(n),yl(n.state)},retry(e){let t=s.get(e);t===void 0||p||t.state.status!=="failed"||(t.controller=new AbortController,t.attempts=0,b(t,{status:"uploading",error:null,progress:0,s3Key:null}),v(t))},remove(e){let t=s.get(e);if(t===void 0)return;t.controller.abort(),s.delete(e);let r=u.indexOf(e);r>=0&&u.splice(r,1);let n=c.indexOf(e);n>=0&&c.splice(n,1),g()},clear(){for(let e of[...u])k.remove(e)},dispose(){p=true;for(let e of s.values())e.controller.abort();s.clear(),u.length=0,c.length=0,f.clear(),h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return k}function Il(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var zl=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(zl,t)?zl[t]:null}var Pl=50,Ol=128,El=120,jl=120,Fl=2e3,Al=120,Dl=80,Ml=/* @__PURE__ */new Set(["male","female","unknown"]),Ll=/* @__PURE__ */new Set(["day","month","year"]),Bl=/* @__PURE__ */new Set(["low","medium","high","athletic"]),Hl=/* @__PURE__ */new Set(["indoor","outdoor","both"]),Ul=/* @__PURE__ */new Set(["mild","moderate","severe"]),Nl=/^(\d{4})-(\d{2})-(\d{2})$/,$l=[["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"]],Wl=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...$l,...Wl].map(([e])=>e));function Vl(e){let t=Nl.exec(e);if(t===null)return false;let[r,n,l]=[Number(t[1]),Number(t[2]),Number(t[3])],i=new Date(Date.UTC(r,n-1,l));return i.getUTCFullYear()===r&&i.getUTCMonth()===n-1&&i.getUTCDate()===l}var ql=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,Gl=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,Kl=(e,t)=>typeof t=="string"&&Vl(t)?null:`${e} must be a real date written YYYY-MM-DD`,Yl=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(q(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let l=t.trimmed?n.trim():n;if(t.required&&l.length===0)return`${r} is required and must not be blank`;let i=G(l);return i<=e?null:`${r} is ${i} characters; the server accepts at most ${e}`},Ql={sex:ql(Ml),spayedNeutered:Gl,birthDate:Kl,birthDatePrecision:ql(Ll),activityLevel:ql(Bl),indoorOutdoor:ql(Hl),foodBrand:Yl(Al),foodType:Yl(Al),microchipId:Yl(Dl)},Jl=["ref","ref",false,Yl(Ol,{required:true,trimmed:true})],Xl=["notes","notes",false,Yl(Fl,{trimmed:true})],Zl=[Jl,["name","name",true,Yl(El,{required:true,trimmed:true})],["dose","dose",false,Yl(jl,{trimmed:true})],["frequency","frequency",false,Yl(jl,{trimmed:true})],["startDate","start_date",false,Kl],["endDate","end_date",false,Kl],Xl],ei={allergies:[Jl,["allergen","allergen",true,Yl(El,{required:true,trimmed:true})],["severity","severity",false,ql(Ul)],Xl],medications:Zl,supplements:Zl,conditions:[Jl,["conditionName","condition_name",true,Yl(El,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Kl],Xl]};function ti(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return{error:`${n} must be an object`};let l=r,i={};for(let[t,r,o,a]of ei[e]){let e=l[t];if(e==null){if(o)return{error:`${n}.${t} is required`};e===null&&(i[r]=null);continue}let s=a(`${n}.${t}`,e);if(s!==null)return{error:s};i[r]=e}let o=i.start_date,a=i.end_date;return typeof o=="string"&&typeof a=="string"&&a<o?{error:`${n}.endDate must not be before startDate`}:{item:i}}function ri(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>Pl)return{error:`${e} has ${t.length} items; the server accepts at most ${Pl}`};let r=[],n=/* @__PURE__ */new Set;for(let l=0;l<t.length;l+=1){let i=ti(e,l,t[l]);if("error"in i)return i;let o=i.item.ref;if(typeof o=="string"){let t=o.trim();if(n.has(t))return{error:`${e}: ref ${JSON.stringify(t)} is used twice; a ref names one item`};n.add(t)}r.push(i.item)}return{items:r}}function ni(e,t){let r=e,n={};for(let[e,t]of $l){let l=r[e];if(l!==void 0){if(l!==null){let t=Ql[e](e,l);if(t!==null)return{error:t}}n[t]=l}}let l=r.birthDate!==void 0,i=r.birthDatePrecision!==void 0;if(l!==i||l&&r.birthDate===null!=(r.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[e,t]of Wl){let l=r[e];if(l===void 0)continue;let i=ri(e,l);if("error"in i)return i;n[t]=i.items}return Object.keys(n).length>0&&t!==void 0&&canonicalPetSpecies(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}var li=e=>typeof e=="string"?e:null,ii=(e,t)=>typeof t=="string"&&e.has(t)?t:null,oi=e=>typeof e=="boolean"?e:null;function ai(e,t){return Array.isArray(e)?/* @__PURE__ */Object.freeze(e.flatMap(e=>{if(typeof e!="object"||e===null||Array.isArray(e))return[];let r=t(e);return r===null?[]:[r]})):/* @__PURE__ */Object.freeze([])}function si(e){let t=li(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:li(e.ref),name:t,dose:li(e.dose),frequency:li(e.frequency),startDate:li(e.start_date),endDate:li(e.end_date),notes:li(e.notes)})}function ui(e){let t=e.profile_version;/* @__PURE__ */
35
- return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:ii(Ml,e.sex),spayedNeutered:oi(e.spayed_neutered),birthDate:li(e.birth_date),birthDatePrecision:ii(Ll,e.birth_date_precision),activityLevel:ii(Bl,e.activity_level),indoorOutdoor:ii(Hl,e.indoor_outdoor),foodBrand:li(e.food_brand),foodType:li(e.food_type),microchipId:li(e.microchip_id),allergies:ai(e.allergies,e=>{let t=li(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:li(e.ref),allergen:t,severity:ii(Ul,e.severity),notes:li(e.notes)})}),medications:ai(e.medications,si),supplements:ai(e.supplements,si),conditions:ai(e.conditions,e=>{let t=li(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:li(e.ref),conditionName:t,diagnosedDate:li(e.diagnosed_date),notes:li(e.notes)})})})}var ci=100,di=50,fi=100,hi=50,pi=500,gi=128,bi=6e4;function mi(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function yi(e,t,r){if(typeof t!="string")return mi(`${e} must be a string`);let n=G(t);return n<=r?null:mi(`${e} is ${n} characters; the server accepts at most ${r}`)}function vi(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:mi(`${e} must be a finite number between 0 and ${r}`)}function ki(e,t){if(typeof e!="string")return mi("pet_ref must be a string");if(e.trim().length===0)return mi("pet_ref must not be blank");if(q(e))return mi("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return mi("profile must be an object");let r=[yi("pet_ref",e,gi)];return t?.name!==void 0&&r.push(yi("name",t.name,ci)),t?.species!==void 0&&r.push(yi("species",t.species,di)),t?.breed!==void 0&&r.push(yi("breed",t.breed,fi)),t?.ageYears!==void 0&&r.push(vi("age_years",t.ageYears,hi)),t?.weightKg!==void 0&&r.push(vi("weight_kg",t.weightKg,pi)),r.find(e=>e!==null)??null}function wi(e,t){let r=ni(e,t);return"error"in r?{error:mi(r.error)}:r}function Ci(e){if(typeof e!="object"||e===null)return{error:mi("patch must be an object")};let t=e,r=[["name","name",e=>yi("name",e,ci)],["species","species",e=>yi("species",e,di)],["breed","breed",e=>yi("breed",e,fi)],["ageYears","age_years",e=>vi("age_years",e,hi)],["weightKg","weight_kg",e=>vi("weight_kg",e,pi)]],n={};for(let[e,l,i]of r){let r=t[e];if(r!==void 0){if(r!==null){let e=i(r);if(e!==null)return{error:e}}n[l]=r}}let l=wi(t,t.species);return"error"in l?l:(Object.assign(n,l.body),Object.keys(n).length===0?{error:mi("patch must change at least one field")}:{body:n})}function Si(e){if(e==null)return{body:{}};let t=wi(e,e.species);return"error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}var xi=e=>typeof e=="string"?e:null,_i=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Ri(e,t){let r=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
36
- return Object.freeze({petRef:xi(r.pet_ref)??t,name:xi(r.name),species:xi(r.species),breed:xi(r.breed),ageYears:_i(r.age_years),weightKg:_i(r.weight_kg)})}function widgetPetFromWire(e){if(typeof e!="object"||e===null)return null;let t=e,r=xi(t.pet_ref);return r===null||r.length===0?null:/* @__PURE__ */Object.freeze({petId:xi(t.pet_id),petRef:r,name:xi(t.name),species:xi(t.species),breed:xi(t.breed),ageYears:_i(t.age_years),weightKg:_i(t.weight_kg),updatedAt:xi(t.updated_at)})}function Ti(e){let t=widgetPetFromWire(e);return t===null?null:/* @__PURE__ */Object.freeze({...t,...ui(e)})}function Ii(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];/* @__PURE__ */
37
- return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return zi(createRequestFunnel({auth:e}),createRequestFunnel({auth:e,unaryTimeoutMs:bi}))}function zi(e,t=e){let r=(e,t)=>t?{...e,signal:t}:e,n=e=>ki(e,void 0)??`/widget/v1/pets/${encodeURIComponent(e)}`;return{async list(t){let n=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},t?.signal));return n.ok?ok(Ii(n.value)):err(n.error)},async registerPet(t,r,n){let l=ki(t,r);if(l!==null)return err(l);let i=Si(r);if("error"in i)return err(i.error);let o={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(t)}`,body:i.body},a=await e.send("pets.registerPet",n?.signal?{...o,signal:n.signal}:o);return a.ok?ok(Ri(a.value,t)):err(a.error)},async updatePet(t,l,i){let o=n(t);if(typeof o!="string")return err(o);let a=Ci(l);if("error"in a)return err(a.error);let s=await e.send("pets.updatePet",r({method:"PATCH",path:o,body:a.body},i?.signal));return s.ok?ok(Ri(s.value,t)):err(s.error)},async getPetProfile(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.getPetProfile",r({method:"GET",path:`${i}/profile`},l?.signal));if(!o.ok)return err(o.error);let a=Ti(o.value);return a===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(a)},async deletePet(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.deletePet",r({method:"DELETE",path:i},l?.signal));return o.ok?ok(void 0):err(o.error)},async eraseUserData(e){let n=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},e?.signal),{maxAttempts:1});return n.ok?ok(void 0):err(n.error)}}}var Pi=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(e){return Pi[e]}function deniedDecisionsFor(e,t){let r=/* @__PURE__ */Object.freeze({reason:t,level:e,recoverable:false}),n=[],l=/* @__PURE__ */new Set;for(let e of Object.keys(Pi))for(let t of Pi[e])l.has(t)||(l.add(t),n.push(/* @__PURE__ */Object.freeze({resource:t,granted:false,disabled:r}))/* @__PURE__ */);return Object.freeze(n)}function decideCapability(e,t,r){let n=requires(e),l=/* @__PURE__ */new Map;for(let e of t)l.set(e.resource,e);if(r?.isPending===true&&n.some(e=>!l.has(e)))return ji({name:e,enabled:false,isPending:true,limits:{}});let i=Oi(n,l);return n.filter(e=>l.get(e)?.granted!==true).length===0?ji({name:e,enabled:true,isPending:false,limits:i}):ji({name:e,enabled:false,isPending:false,limits:i,disabled:Ei(n,l)})}function Oi(e,t){let r={};for(let n of e){let e=t.get(n)?.limits;if(e)for(let[t,n]of Object.entries(e)){let e=r[t];r[t]=e===void 0?n:Math.min(e,n)}}return r}function Ei(e,t){for(let r of e){let e=t.get(r)?.disabled;if(e)/* @__PURE__ */
21
+ return Object.freeze({send:u,authorize:c,stream:d})}function Sr(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==yr&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function xr(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var _r=10;function Rr(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=Tr(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=n==="burst"?"burst-throttle":"retryable-code";if((()=>{if(r.policy===void 0)return false;try{return!r.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let i=()=>{if(r.policy===void 0)return null;let t;try{t=r.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(_r,Math.floor(t)))},o=r.perCallMaxAttempts??i()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let a=Ir(e,r.now);return a!==null?a>mr?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:a}:{retry:true,reason:l,delayMs:backoffDelayMs(t,r.rng)}}function Tr(e){let t=e.code==="unknown"?fromWire(jr(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function Ir(e,t){let r=Pr(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=zr(e.raw);return n===null?null:Math.round(n*1e3)}function zr(e){for(let t of Or(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Pr(e){for(let t of Or(e)){let e=t.resets_at,r=Er(e);if(r!==null)return r}return null}function Or(e){if(!Fr(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];Fr(n)&&t.push(n)}return t}function Er(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function jr(e){for(let t of Or(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function Fr(e){return typeof e=="object"&&e!==null}async function Ar(e){if(e.mode==="anonymous"){let t=await Ze(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function Dr(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function Mr(e,t){let r=()=>{};if(!t)return{signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let l=()=>n.abort();return e.addEventListener("abort",l,{once:true}),t.addEventListener("abort",l,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",l),t.removeEventListener("abort",l)}}}function Lr(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let l=t.setTimeout(()=>{r?.removeEventListener("abort",i),n()},e),i=()=>{t.clearTimeout(l),n()};r?.addEventListener("abort",i,{once:true})})}var Br=/* @__PURE__ */Object.freeze(["better","same","worse"]),Hr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ur(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Nr(){return err(makeEverfurError("internalError",{retryable:false}))}function $r(e){return typeof e!="string"||e.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):K(e)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}var Wr=e=>typeof e=="string"?e:null,Vr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function qr(e){if(typeof e!="object"||e===null)return null;let t=e,r=Wr(t.case_id),n=Wr(t.status);if(r===null||n===null)return null;let l=Wr(t.last_response);/* @__PURE__ */
22
+ return Object.freeze({caseId:r,status:n,bodyLocation:Wr(t.body_location),lastResponse:l!==null&&Br.includes(l)?l:null,checkInDueAt:Wr(t.check_in_due_at),openedAt:Wr(t.opened_at),resolvedAt:Wr(t.resolved_at),resolutionText:Wr(t.resolution_text),checkinAskCount:Vr(t.checkin_ask_count),checkinAnswerCount:Vr(t.checkin_answer_count)})}function Gr(e){return{async list(t,r){let n=$r(t);if(typeof n!="string")return err(n);let l=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!l.ok)return err(l.error);let i=typeof l.value=="object"&&l.value!==null?l.value.cases:null;if(!Array.isArray(i))return Nr();let o=i.map(qr);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):Nr()},async checkin(t,r,n,l){let i=$r(t);if(typeof i!="string")return err(i);if(typeof r!="string"||!Hr.test(r))return Ur("case_id must be a UUID");if(!Br.includes(n))return Ur("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${i}/${r}/checkin`,body:{response:n},...l?.signal?{signal:l.signal}:{}});if(!o.ok)return err(o.error);let a=typeof o.value=="object"&&o.value!==null?o.value:{},s=qr(a.case);return s===null?Nr():ok(/* @__PURE__ */Object.freeze({case:s,ctaDeepLink:Wr(a.cta_deep_link)}))}}}function Kr(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}function Yr(e,t){let r=t.activeConversationId===null||t.activeConversationId.length===0?null:t.activeConversationId;return r===null&&t.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:Kr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var Qr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var Jr=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Xr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let l={handle:void 0},i=()=>{r.clearTimeout(l.handle),t.removeEventListener("abort",i),n()};l.handle=r.setTimeout(i,e),t.addEventListener("abort",i,{once:true})})}function Zr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}var en=class{constructor(e){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...e})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){return this.snapshot}patch(e){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...e});for(let e of this.listeners)e()}beginOperation(e){this.inFlight?.abort();let t=new AbortController;this.inFlight=t;let r=this.epoch;return{signal:e?Zr(t.signal,e):t.signal,epoch:r,settle:()=>{this.inFlight===t&&(this.inFlight=null)}}}alive(e){return e===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear()}};function tn(e,t,r){/* @__PURE__ */
23
+ return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function rn(e,t,r){/* @__PURE__ */
24
+ return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function nn(e){/* @__PURE__ */
25
+ return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function ln(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),/* @__PURE__ */Object.freeze(r)}function on(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,/* @__PURE__ */Object.freeze(r)}function an(e){/* @__PURE__ */
26
+ return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function sn(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function un(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function cn(e){return errorFrame({code:dn(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function dn(e){switch(e){case"authExpired":return"AUTH_EXPIRED";case"authRejected":return"AuthorizationException";case"sessionRequired":return"session_required";case"accessDenied":return"ACCESS_DENIED";case"paymentRequired":return"TIER_UPGRADE_REQUIRED";case"quotaExceeded":return"QUOTA_EXCEEDED";case"rateLimited":return"RATE_LIMITED";case"validationFailed":return"ValidationException";case"sdkUpdateRequired":return"invalidRequest";case"conflict":return"ConflictException";case"idempotencyConflict":return"IDEMPOTENCY_CONFLICT";case"idempotencyInFlight":return"IDEMPOTENCY_KEY_IN_FLIGHT";case"conversationNotFound":return"CONVERSATION_NOT_FOUND";case"petNotFound":return"PET_NOT_FOUND";case"resourceNotFound":return"ResourceNotFoundException";case"streamTimeout":return"STREAM_TIMEOUT";case"mediaUploadFailed":return"MEDIA_UPLOAD_FAILED";case"moderationBlocked":return"MODERATION_BLOCKED";case"upstreamLlmTimeout":return"UPSTREAM_LLM_TIMEOUT";case"internalError":return"INTERNAL_ERROR";case"notImplemented":return"NotImplementedException";case"serviceUnavailable":return"ServiceUnavailableException";case"streamIncomplete":return"STREAM_INCOMPLETE";case"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function fn(e){let t=Array.isArray(e)?e:pn(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!pn(e))continue;let t=gn(e.category)??gn(e.title)??"",n=bn(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
27
+ return Object.freeze(r)}function hn(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gn(e){return typeof e=="string"?e:null}function bn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(pn(r)){let e=gn(r.text)??gn(r.prompt)??gn(r.title);e!==null&&t.push(e)}return t}function mn(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function yn(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function vn(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function kn(e){let t=e,r=vn(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let l=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof l=="function"){let t=l.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var wn={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*Cn(e,t,r,n){let l=kn(e);if(l===null){yield xn();return}let i=_n(t.overallMs,n),o=_n(t.idleMs,n),a=Rn(r);try{for(;;){if(r.aborted)return;let e=l.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),i.promise.then(()=>({tag:"overall"})),a.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield xn();return}if(n.tag==="idle"||n.tag==="overall"){yield Sn();return}let s=n.value;if(s.done||(o.reset(t.idleMs),yield s.value,s.value.terminal))return}}finally{o.cancel(),i.cancel(),Promise.resolve(l.return?.(void 0)).catch(()=>{})}}function Sn(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function xn(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function _n(e,t){let r=()=>{},n=new Promise(e=>{r=e}),l=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(l),l=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(l)}}}function Rn(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var Tn="checkin",In=/^\d{4}-\d{2}-\d{2}$/,zn="watching";function Pn(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function On(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,l=t.question,i=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof l!="string"||l.trim().length===0)return null;let o=typeof i=="string"&&i.length>0?i:null,a=jn(o),s=a===null?null:/* @__PURE__ */Object.freeze({caseId:a.caseId,answer:null,resolutionText:null,status:null}),u=typeof t.created_at=="string"?t.created_at:"",c=/* @__PURE__ */Object.freeze({id:n,role:"assistant",text:l,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...s===null?{}:{checkin:s}});/* @__PURE__ */
28
+ return Object.freeze({conversationId:r,message:c,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==zn}function En(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}function jn(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==Tn||n===void 0||l===void 0||!Hr.test(n)||!In.test(l)?null:{caseId:n,dueDay:l}}function Fn(e){return jn(e)?.caseId??null}function An(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||K(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function Dn(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ln(e){return e==null||typeof e=="string"&&e.length>0&&!K(e)}function Bn(){return err(makeEverfurError("internalError",{retryable:false}))}function Hn(e){let t=Mn(e);if(!t||!Array.isArray(t.conversations)||!Ln(t.next_cursor))return Bn();let r=[];for(let e of t.conversations){let t=Mn(e);if(!t||typeof t.conversation_id!="string"||!Dn(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return Bn();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return Bn();let l=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...l.length>0?{preview:l}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Un(e){let t=Mn(e);if(!t||!Array.isArray(t.messages)||!Ln(t.next_cursor))return Bn();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=Mn(e);if(!t||typeof t.message_id!="string"||!Dn(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return Bn();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Nn(t,t.message_id,t.content,t.created_at));continue}let l=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,i=t.role==="assistant"?Fn(l):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:Wn(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Vn(t.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...i!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:i,answer:null,resolutionText:null,status:null})}:{},...t.a2ui?{a2ui:[t.a2ui]}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Nn(e,t,r,n){let l=Mn(e.sender),i=$n(l?.display_name)??$n(e.sender_display_name),o=$n(l?.specialty);/* @__PURE__ */
29
+ return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function $n(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!K(t)?t:null}function Wn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function Vn(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
30
+ return Object.freeze(e.flatMap(e=>{let r=Mn(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function qn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Gn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Kn=4e3;var Yn=4e3;function Qn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:sn("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:sn("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Jn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:sn("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Yn?{reason:"too_long",error:sn("validationFailed",false,`message is ${r} characters; the server accepts at most ${Yn}`)}:null}function Xn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Zn(e){yield e}async function*el(){}var tl=6e4,rl=18e4,nl=24,ll=512,il=false;function createChatController(e){return new ul(e)}function ol(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function al(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function sl(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var ul=class extends en{constructor(e){super(an({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Gr(this.funnel),this.telemetry=e.telemetry??$e,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??We,this.timers=e.timers??wn,this.rng=e.rng??Math.random,this.newId=e.newId??mn(),this.makeIdempotencyKey=e.makeIdempotencyKey??yn(),this.budget={idleMs:e.budget?.idleMs??tl,overallMs:e.budget?.overallMs??rl}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=sn(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Zn(cn(e))}let l=Jn(e)??Qn(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Zn(cn(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Zn(cn(sn("accessDenied",false)));let r=Jn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Zn(cn(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):el()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,tn(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?nn(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(hn(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=An(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(sn("accessDenied",false));if(!l.ok)return l;let i=Hn(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,i.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return i}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=On(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),al(n.error)?n.error:null;if(n.error.category==="notFound"&&sl(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=Pn(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}ol(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(sn("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(sn("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(sn("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(sn("accessDenied",false));if(typeof e!="string"||e.trim().length===0||K(e))return err(sn("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Gn.includes(t))return err(sn("validationFailed",false,`feedback_type must be one of ${Gn.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>Kn)return err(sn("validationFailed",false,`notes is over ${Kn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(sn("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(sn("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(sn("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(sn("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!Dn(e))return err(sn("validationFailed",false));let r=An(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(sn("accessDenied",false)):l.ok?Un(l.value):l}async resumeConversation(e){if(this.disposed)return err(sn("accessDenied",false));if(!Dn(e))return err(sn("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===zn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||En({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
31
+ return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?zn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(sn("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(!i.ok)return err(i.error);let o=qn(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&al(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(sn("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(sn("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield cn(t.error))}async primeConversation(e){if(this.disposed)return err(sn("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(sn("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(sn("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(sn("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(sn("accessDenied",false));let r=e?.petRef??null;if(r!==null&&K(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(sn("accessDenied",false)):l.ok?ok(fn(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=Zr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,tn(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,cn(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=sn("internalError",!0);yield*this.emitTerminal(e,t,cn(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=Zr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,cn(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Qe]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of Cn(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=sn("streamIncomplete",!0);yield*this.emitTerminal(e,t,cn(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===Je||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,un(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(il&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,un(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?nn(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,rn(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=ll){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},nl)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?ln(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?on(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?nn(e):e),on(rn(r,"",this.stamp()),e)]}let l=hn([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=Xn(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?nn(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?sn("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,dl(e)?(a=true,u=e):(fl(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){dl(e)?(a=true,u===null&&(u=e)):fl(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
32
+ return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:b,error:y,warning:y===null&&g===null&&s?cl:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...i]),sawForbidden:o,sawUnauthorized:a,sawConversationInitFailure:s})})}var cl="Chat is ready. Your first message will start the conversation.";function dl(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function fl(e){return e.httpStatus===403||e.code==="accessDenied"}var hl=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function pl(e){return e!==hl}var gl=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var bl=10*1024*1024,ml=5,yl=120,vl="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&gl.includes(e.trim().toLowerCase())}function sanitizeFilename(e){if(!e)return"attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return"attachment";if(t.length<=yl)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,yl);let n=t.slice(r);return n.length>=yl?t.slice(0,yl):`${t.slice(0,r).slice(0,yl-n.length)}${n}`}function formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}var kl=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),wl=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function Cl(e,t,r,n){/* @__PURE__ */
33
+ return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return wl(Cl("unsupported_type",false,t));let n=attachmentSize(e);return n===null?wl(Cl("unknown",false,t)):n>bl?wl(Cl("too_large",false,t,{sizeBytes:n})):kl(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function Sl(e){if(typeof e!="object"||e===null)return null;let t=e,r=e=>typeof e=="string"&&e.length>0?e:null,n=e=>typeof e=="number"&&Number.isFinite(e)?e:null,l=r(t.upload_id),i=r(t.upload_url),o=r(t.s3_key);if(l===null||i===null||o===null)return null;let a={},s=t.upload_fields;if(typeof s=="object"&&s!==null)for(let[e,t]of Object.entries(s))typeof t=="string"&&(a[e]=t);/* @__PURE__ */
34
+ return Object.freeze({upload_id:l,upload_url:i,upload_fields:/* @__PURE__ */Object.freeze(a),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??bl,s3_key:o,purpose:r(t.purpose)})}function xl(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return Cl("quota_exceeded",false,t,{cause:e});case"rateLimited":return Cl("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return Cl("idempotency_conflict",true,t,{cause:e});case"validationFailed":return Cl("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return Cl("network",true,t,{cause:e});default:return r===429?Cl("rate_limited",true,t,{cause:e}):r===503?Cl("network",true,t,{cause:e}):r===void 0?Cl("network",true,t,{cause:e}):Cl("server",e.retryable,t,{httpStatus:r,cause:e})}}async function initiateAttachmentUpload(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:vl,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return wl(xl(n.error,t.filename));let l=Sl(n.value);return l===null?wl(Cl("server",false,t.filename)):kl(l)}async function uploadAttachmentBytes(e,t,r,n){let l=()=>n?.signal?.aborted===true;if(l())return wl(Cl("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),kl(void 0)}catch{return l()?wl(Cl("cancelled",true,r.filename)):wl(Cl("server",true,r.filename))}}var _l=2,Rl=3,Tl=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Il=0;function zl(){return Il+=1,`attachment-${Il}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??_l),r=Math.max(1,e.maxAttempts??Rl),n=e.backoffMs??Tl,l=Math.max(1,e.maxPerMessage??ml),i=e.timers??Jr,o=e.newId??zl,a=pl(e.transport),s=/* @__PURE__ */new Map,u=[],c=[],d=/* @__PURE__ */new Set,f=/* @__PURE__ */new Set,h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),p=false,g=()=>{h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(u.flatMap(e=>{let t=s.get(e);return t===void 0?[]:[t.state]}))});for(let e of f)e()},b=(e,t)=>{e.state=/* @__PURE__ */Object.freeze({...e.state,...t}),g()},m=()=>{for(;!p&&d.size<t&&c.length>0;){let e=c.shift(),t=s.get(e);t!==void 0&&(d.add(e),y(t).finally(()=>{d.delete(e),m()}))}},y=async t=>{let{attachment:l}=t;for(;t.attempts<r;){if(p||t.controller.signal.aborted)return;t.attempts+=1;let o=t.controller.signal;b(t,{status:"uploading",error:null,progress:0});let a=await initiateAttachmentUpload(e.funnel,l,{signal:o});if(p||o.aborted)return;let s;if(!a.ok)s=wl(a.error);else{let r=await uploadAttachmentBytes(e.transport,a.value,l,{signal:o,onProgress:e=>{!o.aborted&&t.state.status==="uploading"&&b(t,{progress:Pl(e)})}});if(p||o.aborted)return;s=r.ok?kl(a.value.s3_key):wl(r.error)}if(s.ok){b(t,{status:"uploaded",s3Key:s.value,error:null,progress:1});return}let u=s.error,c=u.retryable&&t.attempts<r;if(b(t,{status:c?"uploading":"failed",error:u,progress:0}),!c)return;let d=n[Math.min(t.attempts-1,n.length-1)]??0;await Xr(d,o,i)}},v=e=>{c.push(e.state.id),m()},k={available:a,subscribe(e){return f.add(e),()=>{f.delete(e)}},getSnapshot:()=>h,get uploading(){return h.attachments.some(e=>e.status==="uploading")},get s3Keys(){return h.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[])},add(e){let t=validateAttachment(e);if(!t.ok)return t;if(p||u.length>=l)return wl(Cl("too_many",false,t.value.filename));let r=o(),n={attachment:t.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:r,filename:t.value.filename,previewUri:e.uri,contentType:t.value.contentType,sizeBytes:t.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return s.set(r,n),u.push(r),g(),v(n),kl(n.state)},retry(e){let t=s.get(e);t===void 0||p||t.state.status!=="failed"||(t.controller=new AbortController,t.attempts=0,b(t,{status:"uploading",error:null,progress:0,s3Key:null}),v(t))},remove(e){let t=s.get(e);if(t===void 0)return;t.controller.abort(),s.delete(e);let r=u.indexOf(e);r>=0&&u.splice(r,1);let n=c.indexOf(e);n>=0&&c.splice(n,1),g()},clear(){for(let e of[...u])k.remove(e)},dispose(){p=true;for(let e of s.values())e.controller.abort();s.clear(),u.length=0,c.length=0,f.clear(),h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return k}function Pl(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var Ol=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Ol,t)?Ol[t]:null}var El=50,jl=128,Fl=120,Al=120,Dl=2e3,Ml=120,Ll=80,Bl=/* @__PURE__ */new Set(["male","female","unknown"]),Hl=/* @__PURE__ */new Set(["day","month","year"]),Ul=/* @__PURE__ */new Set(["low","medium","high","athletic"]),Nl=/* @__PURE__ */new Set(["indoor","outdoor","both"]),$l=/* @__PURE__ */new Set(["mild","moderate","severe"]),Wl=/^(\d{4})-(\d{2})-(\d{2})$/,Vl=[["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"]],ql=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...Vl,...ql].map(([e])=>e));function Gl(e){let t=Wl.exec(e);if(t===null)return false;let[r,n,l]=[Number(t[1]),Number(t[2]),Number(t[3])],i=new Date(Date.UTC(r,n-1,l));return i.getUTCFullYear()===r&&i.getUTCMonth()===n-1&&i.getUTCDate()===l}var Kl=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,Yl=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,Ql=(e,t)=>typeof t=="string"&&Gl(t)?null:`${e} must be a real date written YYYY-MM-DD`,Jl=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(K(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let l=t.trimmed?n.trim():n;if(t.required&&l.length===0)return`${r} is required and must not be blank`;let i=Y(l);return i<=e?null:`${r} is ${i} characters; the server accepts at most ${e}`},Xl={sex:Kl(Bl),spayedNeutered:Yl,birthDate:Ql,birthDatePrecision:Kl(Hl),activityLevel:Kl(Ul),indoorOutdoor:Kl(Nl),foodBrand:Jl(Ml),foodType:Jl(Ml),microchipId:Jl(Ll)},Zl=["ref","ref",false,Jl(jl,{required:true,trimmed:true})],ei=["notes","notes",false,Jl(Dl,{trimmed:true})],ti=[Zl,["name","name",true,Jl(Fl,{required:true,trimmed:true})],["dose","dose",false,Jl(Al,{trimmed:true})],["frequency","frequency",false,Jl(Al,{trimmed:true})],["startDate","start_date",false,Ql],["endDate","end_date",false,Ql],ei],ri={allergies:[Zl,["allergen","allergen",true,Jl(Fl,{required:true,trimmed:true})],["severity","severity",false,Kl($l)],ei],medications:ti,supplements:ti,conditions:[Zl,["conditionName","condition_name",true,Jl(Fl,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ql],ei]};function ni(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return{error:`${n} must be an object`};let l=r,i={};for(let[t,r,o,a]of ri[e]){let e=l[t];if(e==null){if(o)return{error:`${n}.${t} is required`};e===null&&(i[r]=null);continue}let s=a(`${n}.${t}`,e);if(s!==null)return{error:s};i[r]=e}let o=i.start_date,a=i.end_date;return typeof o=="string"&&typeof a=="string"&&a<o?{error:`${n}.endDate must not be before startDate`}:{item:i}}function li(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>El)return{error:`${e} has ${t.length} items; the server accepts at most ${El}`};let r=[],n=/* @__PURE__ */new Set;for(let l=0;l<t.length;l+=1){let i=ni(e,l,t[l]);if("error"in i)return i;let o=i.item.ref;if(typeof o=="string"){let t=o.trim();if(n.has(t))return{error:`${e}: ref ${JSON.stringify(t)} is used twice; a ref names one item`};n.add(t)}r.push(i.item)}return{items:r}}function ii(e,t){let r=e,n={};for(let[e,t]of Vl){let l=r[e];if(l!==void 0){if(l!==null){let t=Xl[e](e,l);if(t!==null)return{error:t}}n[t]=l}}let l=r.birthDate!==void 0,i=r.birthDatePrecision!==void 0;if(l!==i||l&&r.birthDate===null!=(r.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[e,t]of ql){let l=r[e];if(l===void 0)continue;let i=li(e,l);if("error"in i)return i;n[t]=i.items}return Object.keys(n).length>0&&t!==void 0&&canonicalPetSpecies(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}var oi=e=>typeof e=="string"?e:null,ai=(e,t)=>typeof t=="string"&&e.has(t)?t:null,si=e=>typeof e=="boolean"?e:null;function ui(e,t){return Array.isArray(e)?/* @__PURE__ */Object.freeze(e.flatMap(e=>{if(typeof e!="object"||e===null||Array.isArray(e))return[];let r=t(e);return r===null?[]:[r]})):/* @__PURE__ */Object.freeze([])}function ci(e){let t=oi(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:oi(e.ref),name:t,dose:oi(e.dose),frequency:oi(e.frequency),startDate:oi(e.start_date),endDate:oi(e.end_date),notes:oi(e.notes)})}function di(e){let t=e.profile_version;/* @__PURE__ */
35
+ return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:ai(Bl,e.sex),spayedNeutered:si(e.spayed_neutered),birthDate:oi(e.birth_date),birthDatePrecision:ai(Hl,e.birth_date_precision),activityLevel:ai(Ul,e.activity_level),indoorOutdoor:ai(Nl,e.indoor_outdoor),foodBrand:oi(e.food_brand),foodType:oi(e.food_type),microchipId:oi(e.microchip_id),allergies:ui(e.allergies,e=>{let t=oi(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:oi(e.ref),allergen:t,severity:ai($l,e.severity),notes:oi(e.notes)})}),medications:ui(e.medications,ci),supplements:ui(e.supplements,ci),conditions:ui(e.conditions,e=>{let t=oi(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:oi(e.ref),conditionName:t,diagnosedDate:oi(e.diagnosed_date),notes:oi(e.notes)})})})}var fi=100,hi=50,pi=100,gi=50,bi=500,mi=128,yi=6e4;function vi(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function ki(e,t,r){if(typeof t!="string")return vi(`${e} must be a string`);let n=Y(t);return n<=r?null:vi(`${e} is ${n} characters; the server accepts at most ${r}`)}function wi(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:vi(`${e} must be a finite number between 0 and ${r}`)}function Ci(e,t){if(typeof e!="string")return vi("pet_ref must be a string");if(e.trim().length===0)return vi("pet_ref must not be blank");if(K(e))return vi("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return vi("profile must be an object");let r=[ki("pet_ref",e,mi)];return t?.name!==void 0&&r.push(ki("name",t.name,fi)),t?.species!==void 0&&r.push(ki("species",t.species,hi)),t?.breed!==void 0&&r.push(ki("breed",t.breed,pi)),t?.ageYears!==void 0&&r.push(wi("age_years",t.ageYears,gi)),t?.weightKg!==void 0&&r.push(wi("weight_kg",t.weightKg,bi)),r.find(e=>e!==null)??null}function Si(e,t){let r=ii(e,t);return"error"in r?{error:vi(r.error)}:r}function xi(e){if(typeof e!="object"||e===null)return{error:vi("patch must be an object")};let t=e,r=[["name","name",e=>ki("name",e,fi)],["species","species",e=>ki("species",e,hi)],["breed","breed",e=>ki("breed",e,pi)],["ageYears","age_years",e=>wi("age_years",e,gi)],["weightKg","weight_kg",e=>wi("weight_kg",e,bi)]],n={};for(let[e,l,i]of r){let r=t[e];if(r!==void 0){if(r!==null){let e=i(r);if(e!==null)return{error:e}}n[l]=r}}let l=Si(t,t.species);return"error"in l?l:(Object.assign(n,l.body),Object.keys(n).length===0?{error:vi("patch must change at least one field")}:{body:n})}function _i(e){if(e==null)return{body:{}};let t=Si(e,e.species);return"error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}var Ri=e=>typeof e=="string"?e:null,Ti=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Ii(e,t){let r=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
36
+ return Object.freeze({petRef:Ri(r.pet_ref)??t,name:Ri(r.name),species:Ri(r.species),breed:Ri(r.breed),ageYears:Ti(r.age_years),weightKg:Ti(r.weight_kg)})}function widgetPetFromWire(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ri(t.pet_ref);return r===null||r.length===0?null:/* @__PURE__ */Object.freeze({petId:Ri(t.pet_id),petRef:r,name:Ri(t.name),species:Ri(t.species),breed:Ri(t.breed),ageYears:Ti(t.age_years),weightKg:Ti(t.weight_kg),updatedAt:Ri(t.updated_at)})}function zi(e){let t=widgetPetFromWire(e);return t===null?null:/* @__PURE__ */Object.freeze({...t,...di(e)})}function Pi(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];/* @__PURE__ */
37
+ return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return Oi(createRequestFunnel({auth:e}),createRequestFunnel({auth:e,unaryTimeoutMs:yi}))}function Oi(e,t=e){let r=(e,t)=>t?{...e,signal:t}:e,n=e=>Ci(e,void 0)??`/widget/v1/pets/${encodeURIComponent(e)}`;return{async list(t){let n=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},t?.signal));return n.ok?ok(Pi(n.value)):err(n.error)},async registerPet(t,r,n){let l=Ci(t,r);if(l!==null)return err(l);let i=_i(r);if("error"in i)return err(i.error);let o={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(t)}`,body:i.body},a=await e.send("pets.registerPet",n?.signal?{...o,signal:n.signal}:o);return a.ok?ok(Ii(a.value,t)):err(a.error)},async updatePet(t,l,i){let o=n(t);if(typeof o!="string")return err(o);let a=xi(l);if("error"in a)return err(a.error);let s=await e.send("pets.updatePet",r({method:"PATCH",path:o,body:a.body},i?.signal));return s.ok?ok(Ii(s.value,t)):err(s.error)},async getPetProfile(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.getPetProfile",r({method:"GET",path:`${i}/profile`},l?.signal));if(!o.ok)return err(o.error);let a=zi(o.value);return a===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(a)},async deletePet(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.deletePet",r({method:"DELETE",path:i},l?.signal));return o.ok?ok(void 0):err(o.error)},async eraseUserData(e){let n=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},e?.signal),{maxAttempts:1});return n.ok?ok(void 0):err(n.error)}}}var Ei=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(e){return Ei[e]}function deniedDecisionsFor(e,t){let r=/* @__PURE__ */Object.freeze({reason:t,level:e,recoverable:false}),n=[],l=/* @__PURE__ */new Set;for(let e of Object.keys(Ei))for(let t of Ei[e])l.has(t)||(l.add(t),n.push(/* @__PURE__ */Object.freeze({resource:t,granted:false,disabled:r}))/* @__PURE__ */);return Object.freeze(n)}function decideCapability(e,t,r){let n=requires(e),l=/* @__PURE__ */new Map;for(let e of t)l.set(e.resource,e);if(r?.isPending===true&&n.some(e=>!l.has(e)))return Ai({name:e,enabled:false,isPending:true,limits:{}});let i=ji(n,l);return n.filter(e=>l.get(e)?.granted!==true).length===0?Ai({name:e,enabled:true,isPending:false,limits:i}):Ai({name:e,enabled:false,isPending:false,limits:i,disabled:Fi(n,l)})}function ji(e,t){let r={};for(let n of e){let e=t.get(n)?.limits;if(e)for(let[t,n]of Object.entries(e)){let e=r[t];r[t]=e===void 0?n:Math.min(e,n)}}return r}function Fi(e,t){for(let r of e){let e=t.get(r)?.disabled;if(e)/* @__PURE__ */
38
38
  return Object.freeze({reason:e.reason,level:e.level,recoverable:e.recoverable})}/* @__PURE__ */
39
- return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function ji(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function Fi(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,Ai)}catch(e){Ai(e)}}function Ai(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var Di=/* @__PURE__ */new WeakMap,Mi=/* @__PURE__ */new Map;function Li(e,t){Di.set(e,t)}function Bi(e,t,r,n){let l=Di.get(e);if(l===void 0)return null;let i;if(t.mode==="personalized"&&typeof t.userRef=="string")i=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")i=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${l}|${i}|${r}|${Ui(n)}`}function Hi(e,t){if(e===null)return t();let r=Mi.get(e);if(r!==void 0)return r;let n=t().finally(()=>{Mi.get(e)===n&&Mi.delete(e)});return Mi.set(e,n),n}function Ui(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(Ui).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Ui(t)}`).join(",")}}`}var Ni=/* @__PURE__ */new WeakMap;function $i(e,t){let r=Ni.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,Ni.set(e,r)),r.add(t),()=>{r?.delete(t)}}function Wi(e){let t=Ni.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var Vi=/* @__PURE__ */new Map;function qi(e,t){return()=>{let r=Vi.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let l=n.finally(()=>{Vi.get(e)===l&&Vi.delete(e)});return Vi.set(e,l),l}}function parseColor(e){let t=Gi(e);return t===null?null:eo(t)}function Gi(e){if(typeof e=="number")return Qi(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Ki(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Ki(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Yi(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=Ki(t);if(e!==null)return e}return/^\d+$/.test(t)?Qi(Number.parseInt(t,10)):null}function Ki(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:Xi(t[0]),g:Xi(t[1]),b:Xi(t[2]),a:1};if(t.length===6)return{r:Ji(t,0),g:Ji(t,2),b:Ji(t,4),a:1};if(t.length===8){let e=Ji(t,0);return{r:Ji(t,2),g:Ji(t,4),b:Ji(t,6),a:e/255}}return null}function Yi(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(e=>e.trim());if(n.length<3)return null;let l=Zi(Number(n[0])),i=Zi(Number(n[1])),o=Zi(Number(n[2]));if(l===null||i===null||o===null)return null;let a=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;a=Math.min(1,Math.max(0,e))}return{r:l,g:i,b:o,a:a}}function Qi(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return{r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}function Ji(e,t){return Number.parseInt(e.slice(t,t+2),16)}function Xi(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function Zi(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function eo(e){if(e.a>=1)return to(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function to(e,t,r){return`#${ro(e)}${ro(t)}${ro(r)}`.toUpperCase()}function ro(e){return e.toString(16).padStart(2,"0")}var no="#111111",lo="#FFFFFF",io="#000000";function readableOn(e){let t=Gi(e);if(t===null)return lo;let r=so(t),n=so({r:17,g:17,b:17}),l=so({r:255,g:255,b:255});return co(r,l)>=co(r,n)?lo:no}function oo(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(lo,e)>=contrastRatio(io,e)?lo:io}function ao(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(lo)>=t(io)?lo:io}function so(e){let t=uo(e.r/255),r=uo(e.g/255),n=uo(e.b/255);return.2126*t+.7152*r+.0722*n}function uo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function co(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=Gi(e),n=Gi(t);if(r===null||n===null)return 1;let l=n.a>=1?n:{...n},i=r.a>=1?r:fo(r,l);return co(so(i),so(l))}function fo(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function ho(e,t){let r=Gi(e),n=Gi(t);if(r===null||n===null)return null;let l=r.a>=1?r:fo(r,{...n});return to(l.r,l.g,l.b)}function po(e,t){let r=Gi(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var go=.05;function bo(e,t,r,n){let l=t[0];if(l===void 0)return r;let i=e=>t.every(t=>contrastRatio(e,t)>=n);if(Gi(e)===null)return r;if(i(e))return e;let o=ho(e,l),a=o===null?null:Gi(o),s=Gi(r);if(a===null||s===null)return r;for(let e=1;e<1/go;e+=1){let t=e*go,r=(e,r)=>Math.round(e+(r-e)*t),n=to(r(a.r,s.r),r(a.g,s.g),r(a.b,s.b));if(i(n))return n}return r}function mo(e,t,r){let n=e/255,l=t/255,i=r/255,o=Math.max(n,l,i),a=Math.min(n,l,i),s=(o+a)/2;if(o===a)return{h:0,s:0,l:s};let u=o-a,c=u/(1-Math.abs(2*s-1)),d;return o===n?(d=(l-i)/u*60,d<0&&(d=d+360)):o===l?d=((i-n)/u+2)*60:d=((n-l)/u+4)*60,{h:d,s:c,l:s}}function yo(e){let{h:t,s:r,l:n}=e,l=(1-Math.abs(2*n-1))*r,i=t/60,o=l*(1-Math.abs(i%2-1)),a=n-l/2,s=Math.floor(i)%6,u=[[l,o,0],[o,l,0],[0,l,o],[0,o,l],[o,0,l],[l,0,o]],[c,d,f]=u[s];return{r:vo(c+a),g:vo(d+a),b:vo(f+a)}}function vo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var ko=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),wo=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Co=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return Co[e]??wo}var So=4.5,xo=/* @__PURE__ */Object.freeze({});function _o(e){return ko.includes(e)}function Ro(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,l]of Object.entries(e)){if(!_o(n)||l===null||typeof l!="object")continue;let e=zo(l);if(e===null)continue;let i=To(n,e);i!==null&&(t[n]=i,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function To(e,t){let r=Co[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function Io(e,t,r){return e[t]!==void 0?e[t]:e[r]}function zo(e){let t={},r=parseColor(Io(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(Io(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let l=Ro(Io(e,"border_radius","borderRadius"));l!==null&&(t.borderRadius=l);let i=parseColor(Io(e,"text_color","textColor"));return i!==null&&(t.textColor=i),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??xo:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function Po(e){let t=Gi(e);return t!==null&&t.a>=1}var Oo=3,Eo=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function jo(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function Fo(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>ho(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=Oo))return null;let l=[...t,...n,...r];return bo(n[0],l,ao(l),Oo)}function Ao(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>ho(e,t)??t)}function Do(e,t){let r=ao(e);return e.every(e=>contrastRatio(r,e)>=t)}function Mo(e,t){let r=t[0];return r===void 0?null:ho(e,r)}function Lo(e){let t=oo(e[0],So);return e.every(e=>contrastRatio(t,e)>=So)?t:ao(e)}function Bo(e,t,r,n,l){return Eo.has(e)?false:l?true:r!==void 0&&jo(t,r)?false:!(n!==void 0&&r!==void 0&&Po(r))}function guardSlotContrast(e,t,r){let n=false,l={};for(let i of ko){let o=e[i];if(o===void 0)continue;let a=o.backgroundColor,s=t?.[i]??[],u=Ao(a,s),c={...o},d=false;if(a!==void 0&&u.length>1&&!Do(u,So)){let e=Mo(a,s);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[i],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&Po(h)&&Fo(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(a!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<So))&&(c.textColor=Lo(u),d=true);else if(e!==void 0){let t=bo(e,u,ao(u),So);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&Bo(i,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=bo(o.borderColor,e,ao(e),Oo);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=Fo(h,f,u);e!==null&&(c.borderColor=e,d=true)}l[i]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(l):e}var Ho=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),Uo=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var No=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){No(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var $o=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Wo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),Vo={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},qo={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Go={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},Ko={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Yo={regular:"400",medium:"500",bold:"700"},Qo={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},Jo=0,Xo="System",Zo="monospace",ea=["content","heading","control","compact","badge"];function ta(e){let t={};for(let r of ea)t[r]=e;return t}var ra=[];function na(){return{family:Xo,mono:Zo,fontUrl:null,families:{regular:Xo,medium:Xo,bold:Xo,mono:Zo,monoMedium:Zo,monoBold:Zo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Go,tierSizes:ta(Go),lineHeight:Ko,weight:Yo,letterSpacing:Qo,scale:1,maxScale:Jo,scaleCaps:$o,headingFamily:null,headingWeight:null,fontSources:ra,roles:Uo,typeScale:1}}var la={},ia=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(e){return`cubic-bezier(${e.join(", ")})`}var oa={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(ia.standard),emphasized:cssCubicBezier(ia.emphasized),exit:cssCubicBezier(ia.exit)},reducedMotion:false},aa={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},sa=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:aa,space:Vo,radius:qo,type:na(),motion:oa,slots:la}),ua={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},ca=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:ua,space:Vo,radius:qo,type:na(),motion:oa,slots:la});function da(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function fa(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function ha(e){return fa(e).every(t=>contrastRatio(e.brand,t)>=Oo)}function pa(e){return[e.chatGround,e.surface,e.surfaceCream]}function ga(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...ba(e,t)]}function ba(e,t){return[ho(t,e.surface)??e.surface,ho(t,e.surfaceCream)??e.surfaceCream]}function ma(e){return[e.composerFill,e.chatGround]}var ya=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function va(e,t){let r=new Set(da(t));return da(e).every(e=>r.has(e))}function ka(e){let t=e.color,r=(e.brightness==="dark"?ca:sa).color,n=(e.brightness==="dark"?sa:ca).color,l=da(t),i=ao(l)!==ao(da(r)),o=va(t,r),a=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,s=(e,t,r,n,l,s)=>{let u=t===r&&(e!=="errorRed"||a);return u&&o&&ya.has(e)?t:bo(u&&i?n:t,l,ao(l),s)},u=(e,l,i)=>s(`text.${e}`,t.text[e],r.text[e],n.text[e],l,i),c=(e,t,l,i)=>s(e,t,r[e],n[e],l,i),d=e=>i&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=oo(f,So),p=c("danger",t.danger,[...l,...ba(t,t.badgeBgCritical)],So),g={...t,onPrimary:h,onAccent:oo(t.accent,So),onDanger:contrastRatio(h,p)>=So?h:oo(p,So),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,l,So),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,pa(t),So),text:{...t.text,primary:u("primary",l,So),secondary:u("secondary",l,So),muted:u("muted",l,So),metaCool:u("metaCool",l,So),timestamp:u("timestamp",l,So),placeholder:u("placeholder",fa(t),Oo)},danger:p,errorRed:c("errorRed",t.errorRed,ga(t,t.badgeBgCritical),So),warningStrong:c("warningStrong",t.warningStrong,ga(t,t.badgeBgCaution),So),composerBorder:c("composerBorder",t.composerBorder,ma(t),Oo),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,fa(t),Oo)},b={...g,...Ia(g,r,o)};return{...b,...wa(t,b,r)}}function wa(e,t,r){let n={},l=(e,t,r)=>bo(e,t,ao(t),r);if((!_a(e.success,r.success)||!_a(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=l(e.success,ga(t,e.badgeBgPositive),So)),(!_a(e.cautionAccent,r.cautionAccent)||!_a(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=l(e.cautionAccent,ga(t,e.badgeBgCaution),So)),Ca(e,r)){n.info=l(e.info,ga(t,e.badgeBgInfo),So);let r=[t.surface,t.chatGround,...ba(t,e.badgeBgInfo)];n.infoEdge=l(e.infoEdge,r,Oo)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function Ca(e,t){return!_a(e.info,t.info)||!_a(e.badgeBgInfo,t.badgeBgInfo)}var Sa=.24,xa=.3;function _a(e,t){return parseColor(e)===parseColor(t)}function Ra(e,t){return _a(e.accent,t.accent)?_a(e.brand,t.brand)?null:e.brand:e.accent}function Ta(e,t,r){let n=po(e,r);return(n===null?null:ho(n,t))??t}function Ia(e,t,r){let n=Ra(e,t),l=fa(e),i=ao(l),o=ao([e.surface])===lo,a=n===null&&r,s;a?s=t.highlight:n===null?s=o?Ta(sa.color.highlight,e.surface,xa):sa.color.highlight:s=Ta(n,e.surface,o?xa:Sa);let u=a?t.onHighlight:bo(e.text.primary,[s],ao([s]),So),c=n===null?t.mark:bo(n,l,i,Oo),d=ha(e)?e.brand:i,f=(e,t,n)=>r&&_a(e,t)?n:bo(e,l,d,Oo),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=Oo)?e.primary:bo(e.primary,h,ao(h),Oo);return{highlight:s,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var za=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Pa(e,t){let r=(e.brightness==="dark"?ca:sa).color,n=e.color,l=t.color,i=[],o=(e,t,r,n)=>{i.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},a=(e,t)=>!za(e,t);a(n.text.primary,r.text.primary)&&!za(l.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,l.text.primary),a(n.brand,r.brand)&&(za(l.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,l.brandInk),za(l.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,l.primaryEdge),!za(l.controlEdge,n.brandBorder)&&!ha({...l,brand:n.brand})&&o("primary_color","control outline",n.brand,l.controlEdge)),a(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!za(l.linkInk,n.accent)&&o("accent_color","link text",n.accent,l.linkInk),a(n.danger,r.danger)&&!za(l.danger,n.danger)&&o("danger_color","error text",n.danger,l.danger),a(n.success,r.success)&&!za(l.success,n.success)&&o("success_color","positive status",n.success,l.success),a(n.warningStrong,r.warningStrong)&&!za(l.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,l.warningStrong),a(n.cautionAccent,r.cautionAccent)&&!za(l.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,l.cautionAccent),(a(n.info,r.info)||a(n.badgeBgInfo,r.badgeBgInfo))&&(za(l.info,n.info)||o("info_color","information text",n.info,l.info),za(l.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,l.infoEdge));for(let r of ko){let n=e.slots[r],l=t.slots[r];n===void 0||l===void 0||n===l||(l.backgroundColor!==void 0&&!za(l.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,l.backgroundColor),n.textColor!==void 0&&l.textColor!==void 0&&!za(l.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,l.textColor),l.borderColor!==void 0&&!za(l.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,l.borderColor))}/* @__PURE__ */
40
- return Object.freeze(i)}var Oa=/* @__PURE__ */new Set;function Ea(e){if(e.length===0)return;let t=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(Oa.has(t))return;Oa.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var ja="#23272C",Fa=4.5,Aa=.6,Da=.9,Ma=.02,La="#FFFFFF",Ba="#111111";function Ha(e){return contrastRatio(e,ja)>=Fa&&Math.max(contrastRatio(e,La),contrastRatio(e,Ba))>=Fa}function deriveDarkVariant(e){let t=Gi(e);if(t===null)return null;let{h:r,s:n,l:l}=mo(t.r,t.g,t.b),i=Math.min(Math.max(l,Aa),Da);for(let e=0;;e+=1){let t=i+e*Ma;if(t>Da)break;let l=yo({h:r,s:n,l:t}),o=to(l.r,l.g,l.b);if(Ha(o))return o}let o=yo({h:r,s:n,l:Da});return to(o.r,o.g,o.b)}var Ua=7,Na=.05,$a="#000000",Wa="#FFFFFF";function Va(e,t,r,n){let l=ho(e,t);if(l===null)return r;if(contrastRatio(l,t)>=n)return l;let i=Gi(l),o=Gi(r);if(i===null||o===null)return r;for(let e=1;e<1/Na;e+=1){let r=e*Na,l=(e,t)=>Math.round(e+(t-e)*r),a=to(l(i.r,o.r),l(i.g,o.g),l(i.b,o.b));if(contrastRatio(a,t)>=n)return a}return r}function qa(e,t){let r=da(e),n=r[0],l=Ga(n);for(let e of r){let r=Ga(e);(t?r>l:r<l)&&(n=e,l=r)}return n}function Ga(e){let t=Gi(e);return t===null?0:so(t)}function Ka(e,t){return ho(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=ao(da(t))===Wa,n=r?Wa:$a,l=qa(t,r),i=e=>Va(e,l,n,Ua),o={...t,brandSoft:Ka(t.brandSoft,t.surface),brandSofter:Ka(t.brandSofter,t.surface),brandBorder:i(t.brandBorder),borderHairlineGreen:i(t.borderHairlineGreen),brandBorderStrong:i(t.brandBorderStrong),controlEdge:i(t.controlEdge),structureEdge:i(t.structureEdge),brandInk:i(t.brandInk),linkInk:i(t.linkInk),borderRingCream:i(t.borderRingCream),composerBorder:i(t.composerBorder),text:{primary:i(t.text.primary),secondary:i(t.text.secondary),muted:i(t.text.muted),placeholder:i(t.text.placeholder),onBrand:t.text.onBrand,metaCool:i(t.text.metaCool),timestamp:i(t.text.timestamp)},badgeBgPositive:Ka(t.badgeBgPositive,t.surface),badgeBgCaution:Ka(t.badgeBgCaution,t.surface),badgeBgCritical:Ka(t.badgeBgCritical,t.surface),badgeBgNeutral:Ka(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Ka(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Ka(t.checkupCardConcernBg,t.surface),info:i(t.info),infoEdge:i(t.infoEdge),badgeBgInfo:Ka(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var Ya=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),Qa=Ya.cream,Ja=Ya.subtle,Xa=Ya.ring,Za=10;function es(e,t,r){let n=Gi(e),l=Gi(t);if(n===null||l===null)return null;let i=(e,t)=>Math.round(e+(t-e)*r);return to(i(n.r,l.r),i(n.g,l.g),i(n.b,l.b))}function ts(e){if(e===null)return{};let t=ao([e]),r=es(e,t,Qa),n=es(e,t,Ja),l=es(e,t,Xa);return r===null||n===null||l===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:l}}function rs(e){if(e===null)return{};let t=Gi(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function ns(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let l={};for(let[e,t]of Object.entries(r.type.size))l[e]=Math.max(Za,Math.round(t*n*10)/10);return l}function ls(e,t,r){if(e===null)return t;let n=e/r.space.xs,l=e=>Math.round(e*n),i=r.space;return{xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),xxl:l(i.xxl)}}function is(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),l=t.radius;return{tile:n(l.tile),xs:n(l.xs),sm:n(l.sm),md:n(l.md),lg:n(l.lg),xl:n(l.xl),pill:l.pill}}var os=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function as(e,t){let r=Gi(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function ss(e,t){if(e===null)return{};let r=as(e,t?os.success.dark:os.success.light),n=as(e,t?os.successCard.dark:os.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function us(e,t){if(e===null)return{};let r=as(e,t?os.warning.dark:os.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function cs(e,t){if(e===null)return{};let r=as(e,t?os.info.dark:os.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function ds(e,t,r){if(e===null)return t;let n=r.type.lineHeight,l=e/n.normal;if(l===1)return n;let i=e=>Math.round(e*l*100)/100;return{tight:i(n.tight),snug:i(n.snug),normal:i(n.normal),relaxed:i(n.relaxed)}}function fs(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:pa(e),header:[e.surface,e.background,e.chatGround],banner:[ho(e.badgeBgInfo,e.surface)??e.surface,ho(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function hs(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var gs=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),bs=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),ms=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function ys(e){return typeof e=="string"&&gs.includes(e.trim().toLowerCase())}function vs(e,t){let r=e[t];return r??void 0}var ks=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>ks)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var ws=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],Cs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],Ss=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],xs=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],_s=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!ps(e))return null;let t=ys(e.theme)?bs[e.theme.trim().toLowerCase()]:{},r=ps(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let l={},i=vs(n,"colorScheme"),o=typeof i=="string"?i.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(l.color_scheme=o);let a=o==="dark"?"_dark":"";for(let[e,t]of ws){let r=vs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of Cs){let r=vs(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of xs){let r=vs(n,e);typeof r=="string"&&r.trim().length>0&&(l[t]=r.trim())}for(let[e,t]of _s){let r=parsePx(vs(n,e));r!==void 0&&(l[t]=r)}for(let[e,t]of Ss){let r=vs(n,e);(typeof r=="number"||typeof r=="string")&&(l[t]=r)}let s=e.fonts;Array.isArray(s)&&s.length>0&&(l.font_sources=s);let u=e.rules;if(ps(u)){let e={};for(let t of ko){let r=u[t];ps(r)&&(e[t]=r)}Object.keys(e).length>0&&(l.slots=e)}return Object.keys(l).length===0?null:/* @__PURE__ */Object.freeze(l)}var Rs="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function Ts(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var Is=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?Ts(__EVERFUR_BRAND_CDN_ORIGIN__):Rs;var zs=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),Ps=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),Os=Object.keys(Ps),Es="presentation",js="presentation.";function isPresentationLockName(e){if(e===Es)return true;if(!e.startsWith(js))return false;let t=e.slice(js.length);return Object.values(Ps).includes(t)}var Fs={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},As=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function Ds(e,t){if(t==null)return;let r=Fs[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:As.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Os){let n=Ps[e],l=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],i=Ds(e,l);i!==void 0&&(r[e]=i)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${js}${Ps[e]}`;for(let e of t)if(e===Es||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,l=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},i=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,a={};for(let e of Os){let t=l[e],r=isPresentationFieldLocked(e,o)?void 0:i[e];a[e]=r??t??zs[e]}/* @__PURE__ */
41
- return Object.freeze(a)}var Ms=4,Ls=/* @__PURE__ */Object.freeze({min:1,max:2}),Bs=100,Hs=2048,Us=["100","200","300","400","500","600","700","800","900"];function Ns(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim().length===0||e.length>16)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function $s(e){let t=Ns(e);if(t===null)return null;let r=String(t);return Us.includes(r)?r:null}function Ws(e){let t=Ns(e);return t===null?null:Math.min(Ls.max,Math.max(Ls.min,t))}function Vs(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Hs?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(t)?t:null}function qs(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Bs||/[\u0000-\u001F\u007F]/.test(t)?null:t}function Gs(e,...t){for(let r of t)if(e[r]!==void 0&&e[r]!==null)return e[r]}function Ks(e){if(!ps(e))return null;let t=qs(e.family);if(t===null)return null;let r=Gs(e,"src"),n=Gs(e,"cssSrc","css_src");if(r===void 0==(n===void 0))return null;if(n!==void 0){let e=Vs(n);return e===null?null:/* @__PURE__ */Object.freeze({family:t,cssSrc:e})}let l=Vs(r);if(l===null)return null;let i={family:t,src:l},o=$s(e.weight);o!==null&&(i.weight=o);let a=typeof e.style=="string"?e.style.trim().toLowerCase():null;return(a==="normal"||a==="italic")&&(i.style=a),/* @__PURE__ */Object.freeze(i)}function Ys(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=Ms)break;let e=Ks(r);e!==null&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}var Qs=/* @__PURE__ */Object.freeze({size:/* @__PURE__ */Object.freeze({min:8,max:48}),letterSpacing:/* @__PURE__ */Object.freeze({min:-.1,max:.3}),typeScale:/* @__PURE__ */Object.freeze({min:.8,max:1.3})}),Js=["content","heading","control","compact","badge"],Xs=["sans","heading","mono"],Zs=/* @__PURE__ */Object.freeze({min:1,max:3.1});function eu(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e.trim().replace(/px$/i,"")):Number.NaN;return Number.isFinite(t)?t:null}function tu(e,t){return Math.min(t.max,Math.max(t.min,e))}function ru(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==void 0)return e[r]}function lu(e){let t=eu(e);return t===null?null:tu(t,Qs.typeScale)}function iu(e){if(!ru(e))return null;let t={};for(let r of Js){let n=eu(nu(e,r));n!==null&&(t[r]=n<=0?0:tu(n,Zs))}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function ou(e){if(!ru(e))return null;let t={},r=eu(nu(e,"size","fontSize","font_size"));r!==null&&(t.size=tu(r,Qs.size));let n=Ws(nu(e,"lineHeight","line_height"));n!==null&&(t.lineHeight=n);let l=$s(nu(e,"weight","fontWeight","font_weight"));l!==null&&(t.weight=l);let i=nu(e,"face");typeof i=="string"&&Xs.includes(i.trim())&&(t.face=i.trim());let o=eu(nu(e,"letterSpacing","letter_spacing"));o!==null&&(t.letterSpacing=tu(o,Qs.letterSpacing));let a=nu(e,"uppercase");return typeof a=="boolean"&&(t.uppercase=a),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function au(e){if(!ru(e))return null;let t={};for(let r of Ho){let n=ou(nu(e,r));n!==null&&(t[r]=n)}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}var su=e=>Math.round(e*10)/10,uu=e=>Math.round(e*100)/100;function cu(e,t,r,n){if(t===null&&r===null&&n===null)return e;let l=t===null?null:t/Uo.body.size,i=r===null?null:r/Uo.body.lineHeight,o={};for(let t of Ho){let r=e[t],a=Uo[t];o[t]=/* @__PURE__ */Object.freeze({...r,...l===null?{}:{size:su(a.size*l)},...i===null?{}:{lineHeight:uu(a.lineHeight*i)},...n?.[t]??{}})}/* @__PURE__ */
42
- return Object.freeze(o)}function du(e,t){let r=false,n={};for(let l of Ho){let i=e[l],o=t(i);o===1?n[l]=i:(r=true,n[l]=/* @__PURE__ */Object.freeze({...i,size:su(i.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function fu(e,t,r){return{nano:su(e.nano*r),small:su(e.small*r),micro:su(e.micro*r),tiny:su(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:su(e.verdict*r)}}var hu=/* @__PURE__ */Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),pu="slots.",gu=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}function isKnownBrandingSchema(e){let t=e?.schemaVersion??null;return t===null||gu.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
43
- return new Set(["hide_powered_by",...e?.lockedFields??[]])}function bu(e){return e==="hide_powered_by"||hu.includes(e)||isPresentationLockName(e)?true:e.startsWith(pu)&&ko.includes(e.slice(pu.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=yu(t),n=expandAppearance(wu(t,"appearance")),l=n===null?r:mu(yu(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function mu(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function yu(e){return{displayName:Cu(wu(e,"display_name","displayName")),logoUrl:Cu(wu(e,"logo_url","logoUrl")),primaryColor:parseColor(wu(e,"primary_color","primaryColor")),accentColor:parseColor(wu(e,"accent_color","accentColor")),brightness:Iu(wu(e,"brightness","color_scheme","colorScheme")),fontFamily:Cu(wu(e,"font_family","fontFamily")),fontUrl:Cu(wu(e,"font_url","fontUrl")),fonts:xu(wu(e,"fonts")),fontUrls:xu(wu(e,"font_urls","fontUrls")),placeholder:Cu(wu(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:ku(wu(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(wu(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(wu(e,"accent_color_dark","accentColorDark")),surfaceStyle:Tu(wu(e,"surface_style","surfaceStyle"),_u),radiusScale:Tu(wu(e,"radius_scale","radiusScale"),Ru),logoUrlDark:Cu(wu(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(wu(e,"slots")),accessibilityMaxFontScale:Eu(wu(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Au(wu(e,"locked_fields","lockedFields")),presentation:parsePresentation(wu(e,"presentation")),schemaVersion:ju(wu(e,"schema_version","schemaVersion")),backgroundColor:parseColor(wu(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(wu(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(wu(e,"text_color","textColor")),textColorDark:parseColor(wu(e,"text_color_dark","textColorDark")),dangerColor:parseColor(wu(e,"danger_color","dangerColor")),dangerColorDark:parseColor(wu(e,"danger_color_dark","dangerColorDark")),fontSizeBase:vu(wu(e,"font_size_base","fontSizeBase"),ms.fontSizeBase),borderRadius:vu(wu(e,"border_radius","borderRadius"),ms.borderRadius),spacingUnit:vu(wu(e,"spacing_unit","spacingUnit"),ms.spacingUnit),successColor:parseColor(wu(e,"success_color","successColor")),successColorDark:parseColor(wu(e,"success_color_dark","successColorDark")),warningColor:parseColor(wu(e,"warning_color","warningColor")),warningColorDark:parseColor(wu(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(wu(e,"info_color","infoColor")),infoColorDark:parseColor(wu(e,"info_color_dark","infoColorDark")),headingFontFamily:Cu(wu(e,"heading_font_family","headingFontFamily")),fontWeightBody:$s(wu(e,"font_weight_body","fontWeightBody")),fontWeightHeading:$s(wu(e,"font_weight_heading","fontWeightHeading")),lineHeight:Ws(wu(e,"line_height","lineHeight")),fontSources:Ys(wu(e,"font_sources","fontSources")),assistantAvatarUrl:Cu(wu(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:iu(wu(e,"text_scale_caps","textScaleCaps")),typeScale:lu(wu(e,"type_scale","typeScale")),typeRoles:au(wu(e,"type_roles","typeRoles"))}}function vu(e,t){let r=zu(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function ku(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}function wu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function Cu(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var Su=["regular","medium","bold","mono","monoMedium","monoBold"];function xu(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Su){let n=Cu(wu(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var _u=["white","cream","subtle"],Ru=["sharp","default","round"];function Tu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function Iu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function zu(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}var Pu=1,Ou=3.1;function Eu(e){let t=zu(e);return t===null?null:t<=0?0:Math.min(Ou,Math.max(Pu,t))}function ju(e){if(e==null)return null;let t=zu(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Fu(e){let t=e.trim();return t.startsWith(pu)?t:t.startsWith(js)?js+t.slice(js.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Au(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=Fu(r);bu(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var Du=/* @__PURE__ */new RegExp(`^${Is}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&Du.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?ca:sa:e,n=r.brightness==="dark"?ca:sa,l=r.brightness==="dark",i=l?t.primaryColorDark??Uu(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??Uu(t.accentColor):t.accentColor,a=i??r.color.primary,s=o??r.color.accent,u=i!==null&&Wu(t,a,n,l),c=u?n.color.primary:a,d=i!==null&&!u?Gi(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?Vu(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=ts(p),b={...r.color,...g},m=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??Uu(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...rs(y(t.dangerColor,t.dangerColorDark)),...ss(y(t.successColor,t.successColorDark),l),...us(y(t.warningColor,t.warningColorDark),l),...cs(y(t.infoColor,t.infoColorDark),l),...m!==null?{text:{...h.text??r.color.text,primary:m}}:{},...Nu(t.surfaceStyle??null,b),primary:c,accent:s,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:ls(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?is(t.borderRadius,n):Gu(t.radiusScale??null,r.radius,n),type:{...r.type,...Hu(r.type,t),size:ns(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:ds(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:cu(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var Mu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Lu=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Bu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function Hu(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of Su){let a=Mu[e].map(e=>r[e]).find(e=>e!==void 0),s=Bu(e)?null:t.fontFamily;a!==void 0?(l[e]=a,i[e]=true):s!==null&&(l[e]=s,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:a!==void 0&&delete o[e]}for(let e of Lu)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function Uu(e){return e===null?null:deriveDarkVariant(e)}function Nu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function $u(e,t){return e==null?false:parseColor(e)===parseColor(t)}function Wu(e,t,r,n){return $u(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&$u(e.primaryColor,sa.color.primary)}function Vu(e,t){let r=e.color;return{text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}var qu={sharp:.5,default:1,round:1.5};function Gu(e,t,r){if(e===null)return t;let n=qu[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var Ku="Everfur",Yu=.5;function resolveTheme(e){return dc(Qu(e),e)}function themeAdjustments(e){let t=Qu(e);return Pa(t,dc(t,{...e,highContrast:false}))}function Qu(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=ec(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=rc((i==="auto"?l:i)==="dark"?ca:sa,e?.typeProfile),a=withServerBranding(o,tc(r));return withServerBranding(a,tc(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Ju(e){return e==="placeholder"?"chat_placeholder":Fu(e)}var Xu={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function Zu(e,t){return t.has(Ju(e))?true:(Xu[e]??[]).some(e=>t.has(e))}function ec(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(Zu(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of ko){let n=l[r];n!==void 0&&(t.has(`${pu}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function tc(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function rc(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:Wo}})}function nc(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function lc(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Yu,e)}var ic=["content","heading","control","compact","badge"];function oc(e,t){let r={};for(let n of ic){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:$o[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return ic.every(e=>r[e]===$o[e])?$o:r}function ac(e,t){return t>0?Math.min(e,t):e}function sc(e,t,r,n){let l={};for(let i of ic)l[i]=n?nc(e,ac(t,r[i])):e;return l}function uc(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function cc(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return{family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces,headingFamily:e.headingFamily};let l=e.headingFamily!==null&&r!==void 0&&uc(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of Su)!(i[e]===Xo||i[e]===Zo)&&r!==void 0&&uc(r,i[e])===false&&(i[e]=Bu(e)?Zo:Xo,o[e]=false),n!==null&&Bu(e)&&i[e]===Zo&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function dc(e,t){let r=e.meta.displayName.trim().length===0?Ku:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of Su){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.regular??null,o=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,a=Number.isFinite(e.type.maxScale)?e.type.maxScale:Jo,s=lc(t?.textScale),u=oc(e.type.scaleCaps,a),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=du(e.type.roles,()=>d),h=c?du(f,e=>ac(s,u[e.tier])):f,p=t?.typeProfile==="phone"?fu(e.type.size,f,d):nc(e.type.size,d),g=sc(p,s,u,c),b=ka(e),m={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:b,space:e.space,radius:e.radius,type:{...e.type,...cc(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:s,maxScale:a,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,fs(b),hs(b))};return t?.highContrast===true?deriveHighContrast(deepFreeze(m)):deepFreeze(m)}var fc="/widget/v1/entitlements",hc=304,pc=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",bc(t));return n.ok?mc(n.value):n.error.httpStatus===hc?pc:{kind:"failed",error:n.error}}var gc=64;function bc(e){let t={};return Sc(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=gc?{method:"GET",path:fc,headers:t,query:{region:e.region}}:{method:"GET",path:fc,headers:t}}function mc(e){if(e===null||typeof e!="object"||!Sc(e.revision))return Cc();let t=typeof e.region=="string"?e.region:"",r=Sc(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
44
- return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:kc(e.capabilities),branding:vc(e),livemode:e.livemode!==false,...yc(e)})}function yc(e){let t=e.render_hints,r=e.sms_profile_public??(t!==null&&typeof t=="object"?t.sms_profile_public:void 0);return r!==null&&typeof r=="object"?{smsProfilePublic:r}:{}}function vc(e){let t=parseClientBranding(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let e=parseClientBranding(r.branding);return e!==null?e:parseClientBranding(r)}return null}function kc(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))wc(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
45
- return Object.freeze(t)}function wc(e){return typeof e=="object"&&e!==null&&e.enabled===true}function Cc(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function Sc(e){return typeof e=="number"&&Number.isFinite(e)}var xc=30;function createEntitlementPoller(e){let t=e.scheduler??_c,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??xc),l=e.rng??Math.random,i=()=>n+l()*n,o=false,a=false,s=null,u=null,c=n,d=0,f=()=>{s!==null&&(t.clear(s),s=null)},h=e=>{a||!o||(c=Math.max(n,e),s=t.set(()=>{s=null,b()},c*1e3))},p=null,g=async()=>{if(a)return null;let t=d;e.onFetch?.();let n=e.region?{cachedRevision:u,region:e.region}:{cachedRevision:u},l;try{l=await r(e.authFor(),n)}catch(r){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Rc(r)}),!a&&t===d&&(e.onSettled?.(),h(i())),null}if(a||t!==d)return null;switch(l.kind){case"updated":u=l.revision,l.smsProfilePublic!==void 0?e.update(l.decisions,l.branding??null,l.livemode!==false,l.smsProfilePublic):e.update(l.decisions,l.branding??null,l.livemode!==false),h(l.ttlSeconds);break;case"notModified":h(c);break;case"failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:l.error.code}),h(i());break;default:h(i())}return e.onSettled?.(),l},b=()=>{let e=g().finally(()=>{p===e&&(p=null)});return p=e,e};return{start(){o||a||(o=true,b())},prime(){return a?Promise.resolve(null):p??b()},stop(){a||(a=true,d++,f())},refresh(){a||!o||(d++,u=null,f(),b())}}}var _c={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function Rc(e){return e instanceof Error?e.message:"poll failed"}var Tc=20;function Ic(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map,n=e=>{let t=e??"",n=r.get(t);return n===void 0&&(n=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:e}),r.set(t,n)),n},l=/* @__PURE__ */new Map,i=/* @__PURE__ */new Set,o=0,a=/* @__PURE__ */new Map,s=(r,l)=>{let o=r??"",a=t.get(o)??n(r);if(!(a.hasUnread===l.hasUnread&&a.unreadCount===l.unreadCount&&a.conversationId===l.conversationId)){t.set(o,l);for(let e of[...i])e();i.size>0&&l.hasUnread!==null&&l.unreadCount!==null&&e.emit({type:"unread_changed",petRef:r,conversationId:l.conversationId,unreadCount:l.unreadCount,hasUnread:l.hasUnread})}},u=(e,t)=>{a.set(e??"",t);let r=0,n=null;for(let e of t){let t=e.unreadCount??0;r+=t,t>0&&n===null&&(n=e.id)}s(e,/* @__PURE__ */Object.freeze({hasUnread:r>0,unreadCount:r,conversationId:n??t[0]?.id??null,petRef:e}))},c=(e,t,r)=>{if(t.some(e=>e.unreadCount===null)){a.delete(e??""),s(e,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:t[0]?.id??null,petRef:e}));return}let n=t.slice(0,Tc).map(e=>/* @__PURE__ */Object.freeze({id:e.id,unreadCount:e.unreadCount}));if(r||n.length===0){u(e,n);return}let l=new Set(n.map(e=>e.id)),i=(a.get(e??"")??[]).filter(e=>!l.has(e.id));u(e,[...n,...i].slice(0,Tc))};return{subscribe(e){return i.add(e),()=>{i.delete(e)}},get(e){return t.get(e??"")??n(e)},refresh(t){let r=t??"",n=l.get(r);if(n!==void 0)return n;let i=e.read(t);if(i===null)return Promise.resolve();let a=o,s=i.then(e=>{a!==o||!e.ok||c(t,e.value.conversations,true)},()=>{}).finally(()=>{l.get(r)===s&&l.delete(r)});return l.set(r,s),s},reportPage(e,t){c(e,t,false)},reportHead(e,t){c(e,t===null?[]:[t],false)},reportRead(e){for(let r of[...t.values()]){let t=a.get(r.petRef??"");t===void 0||!t.some(t=>t.id===e&&(t.unreadCount??0)>0)||u(r.petRef,t.map(t=>t.id===e?/* @__PURE__ */Object.freeze({id:t.id,unreadCount:0}):t))}},reset(){if(o+=1,l.clear(),a.clear(),t.size!==0){t.clear();for(let e of[...i])e()}}}}function zc(e,t,r){let n=jn({...t===null?{}:{petRef:t},limit:Tc},100);return n.ok?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${n.value}`},{maxAttempts:1}).then(e=>e.ok?Ln(e.value):err(e.error)):Promise.resolve(err(n.error))}var Pc="everfur.notifications.device";var Oc="everfur.slots.v2",Ec="everfur.slots.installId.v2";var jc=3e3,Fc=/* @__PURE__ */Object.freeze([Pc,Oc,Ec]);function Ac(e){let{leaving:t,identity:r,hooks:n,telemetry:l}=e;if(t===null||r===null||n.size===0)return null;let i=/* @__PURE__ */Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),o=[...n].map(e=>{try{return Promise.resolve(e(i))}catch(e){return Promise.reject(e)}}),a=(e,t)=>{try{l.track("sdk.logout.hookFailed",{reason:e,count:t,totalCount:o.length})}catch{}},s=Promise.allSettled(o).then(e=>{let t=e.filter(e=>e.status==="rejected").length;t>0&&a("failed",t)});return new Promise(e=>{let t=false,r=()=>{t||(t=true,clearTimeout(n),e())},n=setTimeout(()=>{t||a("timeout",o.length),r()},jc);s.then(r,r)})}function Dc(e){let{leaving:t,identity:r,transport:n,sessionId:l}=e,i=r.currentToken();i.catch(()=>{});let o={userRef:t.userRef,currentToken:()=>i,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:n,identity:o,userRef:t.userRef,sessionId:l}}async function Mc(e,t){if(Fc.length===0)return;let r=await Promise.allSettled(Fc.map(t=>e.removeItem(t))),n=r.filter(e=>e.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length})}function Lc(){/* @__PURE__ */
46
- return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function Bc(e=Lc){let t=/* @__PURE__ */new Set,r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:null}),n=()=>{for(let e of t)e()};return{subscribe(e){return t.add(e),()=>{t.delete(e)}},getSnapshot(){return r},set(e){r=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...e.decisions]),isPending:e.isPending,branding:e.branding??null,...e.livemode===false?{livemode:false}:{},...e.smsProfilePublic!==void 0&&e.smsProfilePublic!==null?{smsProfilePublic:e.smsProfilePublic}:{}}),n()},reset(t){r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:t?.keepBranding===true?r.branding??null:null,...t?.keepBranding===true&&r.smsProfilePublic!==void 0?{smsProfilePublic:r.smsProfilePublic}:{}}),n()},setPending(e){r.isPending!==e&&(r=/* @__PURE__ */Object.freeze({...r,isPending:e}),n())}}}var Hc="everfur.branding.v1.";function Uc(e){let t=[];for(let r of e){let e=r.codePointAt(0);e<128?t.push(e):e<2048?t.push(192|e>>6,128|e&63):e<65536?t.push(224|e>>12,128|e>>6&63,128|e&63):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63)}return t}function Nc(e){let t=3421674724,r=2216829733;for(let n of Uc(e)){r=(r^n)>>>0;let e=r*435,l=Math.floor(e/4294967296),i=e>>>0;t=t*435+l+r*256>>>0,r=i}return t.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")}function $c(e){return`${Hc}${Nc(e)}`}function Wc(e){return e?JSON.stringify(e):null}async function Vc(e,t){try{let r=await e.getItem($c(t));if(r===null)return null;let n=parseClientBranding(JSON.parse(r));return n===null?null:/* @__PURE__ */Object.freeze({...n,logoUrl:hardenBrandAssetUrl(n.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(n.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(n.assistantAvatarUrl??null)})}catch{return null}}async function qc(e,t,r){try{r===null?await e.removeItem($c(t)):await e.setItem($c(t),r)}catch{}}function Gc(e,t){let r;return{restore(r){Vc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let l=Wc(n);l!==r&&(r=l,qc(e,t,l))}}}function Kc(){let e=null,t=/* @__PURE__ */new Set;return{get:()=>e,subscribe(e){return t.add(e),()=>{t.delete(e)}},set(r){if(r!==e){e=r;for(let e of[...t])try{e()}catch{}}}}}function Yc(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:Kc(),store:null,disposed:false}}function Qc(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function Jc(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{},...e.appVersion!==void 0?{appVersion:e.appVersion}:{}};return tryResolveClientConfig(r,t===void 0?void 0:{platform:t})}function Xc(e,t){/* @__PURE__ */
47
- return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:Zc(r,n,t))}catch{}}})}function Zc(e,t,r){let n=e.indexOf("."),l=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",i=typeof t?.requestId=="string"?t.requestId:null;return{...Rt(r,l,i),...t}}function ed(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(l,i)=>n.call(e,l,i??Rt(t,r,l.requestId))}:{}}}var td=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${jt} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function rd(e,t,r=Ot){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+td[r])}function nd(e){/* @__PURE__ */
48
- return Object.freeze({request(){return Promise.resolve(err(Qc(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return async function*(){r.aborted||(yield n)}()}})}var ld=/* @__PURE__ */new WeakSet;function id(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return ld.add(t),t}var od=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new sd(e,t)}var ad=6e4,sd=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new Y("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:Pt,platform:t?.platform??Ot,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:zt(r?.appVersion)}),this.telemetry=r.telemetry?Xc(r.telemetry,this.errorContext):Ue,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=nd(l);else if(r.transport!==void 0)o=r.transport;else{let e=Jc(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=nd(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Li(this,this.mintScope),this.transport=o,l!==null&&(rd(l,this.telemetry,t?.platform),this.emit({type:"error",code:Qc(l).code,requestId:null,context:Rt(this.errorContext,"runtime",null)})),this.errorPolicy=ed(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??$e,this.upload=r.upload??Kr,this.uploadTransport=r.uploadTransport??dl,this.imageCache=r.imageCache??od,this.kv=r.storage??id(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Bc():Bc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",ud(e),()=>this.buildChatController(e),cd),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${ud(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=Ic({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:zc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Gc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?Yc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=qi(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-ad,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Fi(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&Wc(l)===Wc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:ed(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await Mc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return Ac({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>Dc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>Hi(Bi(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(dd(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&Wi(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?dd("prepare"):r===null?null:Qc(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(Xe(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}if(s==="ready")this.emit({type:"ready"});else if(s==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:Rt(this.errorContext,"runtime",e)})}/* @__PURE__ */
49
- return Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",ud(t),()=>this.buildChatController(t),cd,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function ud(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function cd(e){e.dispose()}function dd(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function fd(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function hd(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function pd(e){return e.ok?e:err(hd(e.error))}function gd(e){return{send:async(...t)=>pd(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var bd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),md=globalThis,yd=md[bd]??(md[bd]=createContext(null));yd.displayName??="EverfurContext";function vd(){let e=o(yd);if(e===null)throw new Y("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return vd().handle}var kd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),wd=globalThis,Cd=wd[kd]??(wd[kd]=createContext(sa));Cd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(Cd)}var Sd=()=>()=>{},xd=()=>null;function _d(e,t){return i(t?.subscribe??Sd,t?.get??xd,t?.get??xd)??e}function EverfurThemeProviderCore(e){let{runtime:t}=vd(),l=t.entitlements,o=i(l.subscribe,l.getSnapshot,l.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),c=e.seams.useTextScale(),d=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,h=e.seams.typeProfile,p=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,b=e.clientTheme?Rd(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=_d(o.branding??null,t.sdkConfigHost?.branding),v=a(()=>resolveTheme({branding:y,clientOverride:m,colorScheme:s,reducedMotion:u,textScale:c,scaleTypeSizes:f,highContrast:d,...h===void 0?{}:{typeProfile:h},...p===void 0?{}:{platformMonoFamily:p},...g===void 0?{}:{isFontRegistered:g}}),[y,m,s,u,c,f,h,d,p,g]);e.seams.useResolvedTheme?.(v);let k=e.seams.isDevelopment;return n(()=>{k===void 0||!Td(k)||Ea(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(Cd.Provider,{value:v},e.children)}function Rd(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function Td(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:l,activePet:i,theme:o,warmUp:s,children:f,seams:h}=e,p=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=u(null),b=u(null),m=u(t?.onEvent);m.current=t?.onEvent;let y=u(e=>{m.current?.(e)}),[v,k]=c(e=>e+1,0),w=u(null),C=u(void 0),S=l?.userRef??null;C.current!==S&&(C.current!==void 0&&(w.current=null),C.current=S);let x=w.current!==null?w.current.user:l??null,_=u(null),R=u(void 0),T=i??null;R.current!==T&&(R.current!==void 0&&(_.current=null),R.current=T);let I=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==p||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(b.current=g.current.runtime),g.current={key:p,runtime:createEverfurRuntime({config:Id(h.withDefaults?h.withDefaults(t):t,y.current),user:x,activePet:I,theme:o??null},{platform:h.platform,...h.eventSourceFactory?{eventSourceFactory:h.eventSourceFactory}:{}})});let z=g.current.runtime,P=u(null);n(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||P.current!==e&&(P.current=e,k())}),n(()=>{let e=b.current;e!==null&&(b.current=null,e.dispose())});let O=x?.userRef??null;d(()=>{z.setUser(x)},[z,O]),d(()=>{z.setActivePet(I)},[z,I]);let E=u(null);n(()=>(E.current===z&&(E.current=null),()=>{E.current=z,zd(()=>{E.current===z&&(E.current=null,z.dispose())})}),[z]),n(()=>{s==="onMount"&&z.prepare(I===null?{}:{petRef:I})},[z,s,O,I]);let j=a(()=>({setUser:e=>{w.current={user:e},z.setUser(e),k()},setActivePet:e=>{_.current={pet:e},z.setActivePet(e),k()},open:e=>z.open(e),prepare:e=>z.prepare(e),registerPet:(e,t)=>z.registerPet(e,t),updatePet:(e,t)=>z.updatePet(e,t),deletePet:e=>z.deletePet(e),eraseUserData:()=>z.eraseUserData(),logout:()=>{w.current={user:null};let e=z.logout();return k(),e}}),[z,k]),F=a(()=>({runtime:z,handle:j,userRef:O,activePet:I,scopeEpoch:z.scopeEpoch,publishableKey:Pd(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:f});return r(yd.Provider,{value:F},h.wrap?h.wrap(A):A)}function Id(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function zd(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Pd(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Od=2;function Ed(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Od)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function jd(){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:e=>Ed(n,e)})}}function Fd(){let e=v();return e==="dark"?"dark":e==="light"?"light":null}function Ad(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Dd(){let[e,t]=l(false);return n(()=>{let e=true,r=y?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(y);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=y?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Md(){let e=w?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(w);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function Ld(e){let t=k?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(k,"change",e);return()=>r?.remove?.()}function Bd(){return i(Ld,Md,Md)}function Hd(){try{let e=g?.OS;return typeof e=="string"?e:null}catch{return null}}function Ud(){return Hd()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function Nd(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=Ud(),l=y?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(y);Ad(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=y?.addEventListener,o=typeof i=="function"?i.call(y,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function $d(){return Hd()==="ios"?"Menlo":Zo}function Wd(){return globalThis.__DEV__!==false}var Vd=/* @__PURE__ */new Set;function qd(e){if(!Wd()||Vd.has(e))return;Vd.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function Gd(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t)}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let l=n.includes(e);return l||qd(e),l}var Kd=/* @__PURE__ */new Set;function Yd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var Qd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Jd(e){if(!Wd())return;let t=Yd(e).filter(e=>!Kd.has(e));if(t.length===0)return;for(let e of t)Kd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Qd[e]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function Xd(e){n(()=>{try{Jd(e)}catch{}},[e])}var Zd=/* @__PURE__ */Object.freeze({useColorScheme:Fd,useReducedMotion:Dd,useTextScale:Bd,useHighContrast:Nd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:$d,isFontRegistered:Gd,useResolvedTheme:Xd,isDevelopment:Wd});function ef(e){return r(L,null,e)}var tf=/* @__PURE__ */Object.freeze({platform:"react-native",...g.OS==="web"?{}:{eventSourceFactory:jd()},wrap:ef,theme:Zd});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:tf})}function useCapability(e){let{runtime:t}=vd(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function rf(e){let{runtime:t}=vd(),r=t.entitlements,n=s(e=>r===void 0?()=>{}:r.subscribe(e),[r]),l=s(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return i(n,l,l)}var nf=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[nf[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[nf[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function lf(e){return e<=450?"regular":e<=650?"medium":"bold"}var of={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=af.get(e);r===void 0&&(r=/* @__PURE__ */new Map,af.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=sf(e,t);return r.set(t,l),l}var af=/* @__PURE__ */new WeakMap;function sf(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=lf(Number(n)),i=r.face==="mono"?face(e,of[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,a=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},s=r.size,u={...a,fontSize:s,lineHeight:Math.round(s*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(s*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function uf(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:t,...n}){let l=useEverfurTheme(),i=t===void 0?void 0:l.type.roles[t],o=uf(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(x,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var cf=t(function(e,t){return r(b,{...e,...t===null?{}:{ref:t}})});var df=class extends f{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:t,resetKey:n}){return r(df,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var ff=48;function hf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:l,style:i}=e,o=useCapability(t),s=a(()=>hf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */U(HostRender,{render:l,fallback:/* @__PURE__ */U(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */U(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */U(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */U(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */U(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>pf(r),[r]);/* @__PURE__ */
50
- return U(C,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */U(C,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>pf(r),[r]),l=e.disabled?.reason??"";/* @__PURE__ */
51
- return U(C,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:l,children:l.length>0?/* @__PURE__ */U(Text,{style:n.offstateText,children:l}):null})}function pf(e){let{color:t,space:r,radius:n,type:l}=e;return m.create({offstate:{minHeight:ff,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:m.hairlineWidth,borderColor:t.brandBorder},offstateText:{...face(e,"regular"),fontSize:l.size.body,lineHeight:Math.round(l.size.body*l.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}var gf=createContext(null);function TelevetHostOutlet(){let e=o(gf);return e===null?null:/* @__PURE__ */U(e,{})}var bf=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function mf(){let e=globalThis,t=e[bf];if(t!==void 0)return t;let r={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return e[bf]=r,r}function yf(e){let t=mf();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function vf(e){let t=mf().presenter;if(t===null)return"absent";try{return t(e)===!1?"declined":"presented"}catch(e){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",e),"threw"}}function kf(e){let t=mf();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function wf(){return mf().snapshot}function Cf(){return mf().hosts.length>0}function Sf(e){if(!Cf())return false;let t=/* @__PURE__ */Object.freeze({...e});return yf({request:t,serial:mf().snapshot.serial+1}),true}function xf(){mf().snapshot.request!==null&&yf({request:null})}function _f(){let e=mf(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],yf({activeHost:e.hosts[0]??null}),t}function Rf(e){let t=mf();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;yf(r===null?{activeHost:r,request:null}:{activeHost:r})}function Tf(e){let t=null;return()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null)}),r}}function If(e){let[t,r]=l(null);n(()=>{let e=_f();return r(e),()=>{Rf(e)}},[]);let o=i(kf,wf,wf),a=t!==null&&o.activeHost===t?o.request:null,[s,u]=l(null),c=a!==null&&s===null;return n(()=>{if(!c)return;let t=true;return e().then(e=>{t&&u(()=>e)},e=>{t&&(console.warn("[everfur] The in-app vet visit could not load its screens.",e),xf())}),()=>{t=false}},[c,e]),a===null||s===null?null:{module:s,request:a,serial:o.serial,dismiss:xf}}var zf=Tf(()=>Promise.resolve(W));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let l=If(zf);if(l===null)return null;let{EverfurTelevetModal:i}=l.module;/* @__PURE__ */
52
- return U(i,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var Pf=640,Of=600,Ef=/* @__PURE__ */Object.freeze({width:0,height:0}),jf="useWindowDimensions"in p&&typeof p.useWindowDimensions=="function"?p.useWindowDimensions:()=>Ef,Ff=/* @__PURE__ */Object.freeze({width:"100%",maxWidth:Pf,alignSelf:"center"});/* @__PURE__ */Object.freeze({...Ff,flex:1});var Af=/* @__PURE__ */Object.freeze({...Ff,flexGrow:1,flexShrink:1});function Df(){return jf().width>=Of}function Mf(e="flow"){let{width:t}=jf();if(t<Of)return null;if(e==="flow")return Ff;let r=Math.max(0,Math.round((t-Pf)/2));return{left:r,right:r}}function Lf(e,t){return t===null?e:[e,t]}var Bf=/* @__PURE__ */Symbol.for("@everfur/sdk#InSdkColumn@v1"),Hf=globalThis,Uf=Hf[Bf]??(Hf[Bf]=createContext(false));Uf.displayName??="EverfurInSdkColumn";function SdkTabletColumn({children:e,style:t,testID:r}){let n=Df(),l=o(Uf);return!n||l?e:/* @__PURE__ */U(C,{style:t===void 0?Af:[Af,t],testID:r??"everfur-tablet-column",children:/* @__PURE__ */U(Uf.Provider,{value:true,children:e})})}var Nf="Go to the nearest emergency vet now.";var $f=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",sourcesHeading:"Sources",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:Nf,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",capReached:"You've used your {cap} free messages this month.",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function Wf(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function Vf(e){return e?.trim()||$f.emptyTitlePetFallback}function qf(e,t){return Wf(e,{petName:Vf(t)})}var Gf="tel:+18884264435";var Kf=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function Yf(e){let t=Kf(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var Qf=6;function Jf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function Xf(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let l of e){if(n.length>=r)break;if(l===null||typeof l!="object"||Array.isArray(l))continue;let e=t(l);e!==null&&n.push(e)}/* @__PURE__ */
53
- return Object.freeze(n)}function Zf(e){let t=Kf(e.title,80),r=Kf(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function eh(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=[];if(Array.isArray(t.gallery))for(let e of t.gallery){let t=Yf(e);t!==null&&r.length<Qf&&r.push(t)}let n=Xf(t.doses,e=>{let t=Kf(e.label,60),r=Kf(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:Jf(e.minLb??e.min_lb),maxLb:Jf(e.maxLb??e.max_lb)})},Qf),l=Xf(t.details,Zf,Qf),i=t.fit,o=i!==null&&typeof i=="object"&&!Array.isArray(i)?Zf(i):null,a=o!==null&&i.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,s=/* @__PURE__ */Object.freeze({kicker:Kf(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:l,fine:Kf(t.fine,300),fit:a});return s.kicker===null&&r.length===0&&n.length===0&&l.length===0&&s.fine===null&&a===null?void 0:s}var th=128;var rh=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),nh=/* @__PURE__ */new Set(["y","c","g","r"]),lh=/* @__PURE__ */new Set(["done","now","next"]),ih=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,oh=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,ah=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,sh=e=>typeof e=="string"&&rh.has(e)?e:null;function uh(e){let t=oh(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var ch=e=>typeof e=="number"&&Number.isInteger(e)?String(e):oh(e,th);function dh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function fh(e){/* @__PURE__ */
54
- return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function hh(e,t,r=20){if(!Array.isArray(e))return null;let n=[];for(let l of e){if(n.length>=r)break;let e=t(l);e!==null&&n.push(e)}return n.length===0?null:/* @__PURE__ */Object.freeze(n)}var ph=(e,t=12,r=300)=>hh(e,e=>oh(e,r),t);function gh(e){let t=ih(e),r=oh(t?.kicker,120),n=oh(t?.title,300);if(t===null||r===null||n===null)return null;let l=ih(t.risk),i=ih(t.odds),o=ih(t.quote),a=ih(t.jump);return fh({kicker:r,title:n,sources:hh(t.sources,e=>{let t=oh(ih(e)?.label,60);return t===null?null:fh({label:t,kind:ah(ih(e)?.kind)})},6),risk:oh(l?.lead,300)===null?null:fh({lead:oh(l?.lead,300),body:oh(l?.body),kind:ah(l?.kind)}),odds:oh(i?.label,120)===null||oh(i?.from,20)===null||oh(i?.to,20)===null?null:fh({label:oh(i?.label,120),tag:oh(i?.tag,40),from:oh(i?.from,20),to:oh(i?.to,20),toLabel:oh(i?.toLabel,120)}),quote:oh(o?.text)===null?null:fh({kicker:oh(o?.kicker,120),tag:oh(o?.tag,40),text:oh(o?.text)}),jump:oh(a?.title,300)===null||oh(a?.go,60)===null?null:fh({title:oh(a?.title,300),go:oh(a?.go,60)}),report:bh(t.report)})}function bh(e){let t=ih(e),r=oh(t?.label,120),n=oh(t?.text,1200);return r===null||n===null?null:fh({label:r,text:n,actions:ph(t?.actions,5,300)})}function mh(e){let t=ih(e),r=oh(t?.title,300),n=hh(t?.steps,e=>{let t=ih(e),r=oh(t?.title,300),n=t?.tone;return r===null?null:fh({title:r,body:oh(t?.body),source:oh(t?.source,200),tone:typeof n=="string"&&nh.has(n)?n:null,icon:sh(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:fh({title:r,label:oh(t?.label,60),steps:n})}function yh(e){let t=ih(e),r=oh(t?.title,300);if(t===null||r===null)return null;let n=ih(t.rating),l=ih(t.reviews),i=ih(t.why),o=ih(i?.score),a=ih(t.dose),s=ih(t.ingredients),u=hh(l?.items,e=>{let t=ih(e),r=t?.stars,n=oh(t?.text),l=oh(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||l===null?null:fh({stars:Math.round(r),text:n,by:l})},5),c=hh(i?.rows,e=>{let t=ih(e),r=oh(t?.chip,40),n=oh(t?.title,300);return r===null||n===null?null:fh({chip:r,kind:ah(t?.kind),title:n,body:oh(t?.body)})}),d=hh(a?.stats,e=>{let t=ih(e),r=oh(t?.value,40),n=oh(t?.label,120),l=t?.kind;return r===null||n===null?null:fh({value:r,label:n,kind:l==="weight"||l==="dose"||l==="days"?l:null})},6),f=ph(s?.items,12,80);return fh({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:ch(t.productId),partnerSku:oh(t.partnerSku,200),rating:oh(n?.value,20)===null?null:fh({value:oh(n?.value,20),label:oh(n?.label,120)}),line:oh(t.line),reviews:oh(l?.label,200)===null||u===null?null:fh({label:oh(l?.label,200),items:u}),checkoutLine:oh(t.checkoutLine,300),why:oh(i?.title,200)===null||c===null?null:fh({title:oh(i?.title,200),rows:c,score:oh(o?.text,200)===null||oh(o?.value,20)===null?null:fh({text:oh(o?.text,200),value:oh(o?.value,20)})}),dose:oh(a?.title,200)===null||d===null?null:fh({title:oh(a?.title,200),stats:d,note:oh(a?.note)}),doseLabel:oh(t.doseLabel,120),ingredients:f===null?null:fh({label:oh(s?.label,200),items:f}),proof:oh(t.proof,300),trust:hh(t.trust,e=>{let t=ih(e),r=sh(t?.icon),n=oh(t?.label,120);return r===null||n===null?null:fh({icon:r,label:n})},6),more:oh(t.more,120),fine:oh(t.fine),checkin:oh(t.checkin,200),detail:eh(t.detail)??null})}function vh(e){let t=ih(e),r=oh(t?.title,200),n=hh(t?.items,e=>{let t=ih(e),r=oh(t?.title,300),n=oh(t?.body);return r===null||n===null?null:fh({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:fh({title:r,items:n})}function kh(e){let t=ih(e),r=oh(t?.title,200),n=ph(t?.questions,12,300),l=oh(t?.add,80),i=oh(t?.added,80);return r===null||n===null||l===null||i===null?null:fh({title:r,questions:n,add:l,added:i})}function wh(e){let t=ih(e),r=oh(t?.title,200),n=hh(t?.items,e=>{let t=ih(e),r=oh(t?.key,th),n=oh(t?.title,300),l=oh(t?.action,80),i=ch(t?.productId),o=oh(t?.added,80)??(i!==null?l:null);return r===null||n===null||l===null||o===null?null:fh({key:r,productId:i,title:n,body:oh(t?.body),price:oh(t?.price,40),was:oh(t?.was,40),tag:oh(t?.tag,40),imageUrl:uh(t?.imageUrl),icon:sh(t?.icon),kind:ah(t?.kind),action:l,added:o,owned:t?.owned===true?true:null,detail:eh(t?.detail)??null})},6);return r===null||n===null?null:fh({title:r,items:n})}function Ch(e){let t=ih(e),r=oh(t?.kicker,120),n=oh(t?.title,120);return t===null||r===null||n===null?null:fh({kicker:r,title:n,icon:sh(t.icon),track:hh(t.track,e=>{let t=ih(e),r=oh(t?.title,120),n=t?.state;return r===null?null:fh({title:r,detail:oh(t?.detail,120),state:typeof n=="string"&&lh.has(n)?n:null,tag:oh(t?.tag,40)})},6),heading:oh(t.heading,200),rows:hh(t.rows,e=>{let t=ih(e),r=sh(t?.icon),n=oh(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return fh({icon:r,label:n,text:"",fromVet:true});let l=oh(t?.text,300);return l===null?null:fh({icon:r,label:n,text:l})},6),note:oh(t.note,300),action:oh(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=ih(e),r=oh(t?.title,300),n=yh(t?.pick);if(t===null||r===null||n===null)return null;let l=ih(t.byline);return fh({eyebrow:oh(t.eyebrow,120),title:r,subtitle:oh(t.subtitle,300),subtitleNoRecords:oh(t.subtitleNoRecords,300),headImageUrl:uh(t.headImageUrl),byline:oh(l?.name,120)===null?null:fh({name:oh(l?.name,120),role:oh(l?.role,120),imageUrl:uh(l?.imageUrl),shortName:oh(l?.shortName,60)}),focus:gh(t.focus),routine:mh(t.routine),pick:n,signs:vh(t.signs),checkup:kh(t.checkup),extras:wh(t.extras),wait:Ch(t.wait),fine:oh(t.fine),checkoutRows:hh(t.checkoutRows,e=>{let t=ih(e),r=sh(t?.icon),n=oh(t?.label,60),l=oh(t?.value,200);return r===null||n===null||l===null?null:fh({icon:r,label:n,value:l})},6)})}function healthPlanPageFromWire(e,t){let r=ih(e);if(r===null||!("page"in r))return null;let n=ih(r.pet),l=n?.sex;/* @__PURE__ */
55
- return Object.freeze({petRef:oh(r.pet_ref,th)??t,pet:/* @__PURE__ */Object.freeze({name:oh(n?.name,120),species:oh(n?.species,60),sex:l==="female"||l==="male"?l:null,breed:oh(n?.breed,120),weightKg:dh(n?.weight_kg),weightLb:dh(n?.weight_lb)}),checkout:r.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(r.page),vetReviewed:r.vet_reviewed===true,trackingTextsEnabled:r.tracking_texts_enabled===true})}function Sh(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function xh(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function _h(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}var Rh=e=>typeof e=="string"&&e.length>0&&e.length<=th;function Th(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function Ih(e,t,r){if(!Rh(t))return err(Sh("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${Th(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let l=healthPlanPageFromWire(n.value,t);return l===null?err(xh("healthPlan.page.read")):ok(l)}var zh=/* @__PURE__ */new WeakMap;function Ph(e){let t=zh.get(e);if(t!==void 0)return t;let r=Oh(e);return zh.set(e,r),r}function Oh(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(_h("getPage")));let{services:n}=e.registry,l=gd(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return Ih(l,t,r)}}}function Eh(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function jh(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Fh(e,...t){if(typeof e=="function")try{let r=e(...t);return jh(r)&&Promise.resolve(r).then(void 0,Eh),r}catch(e){Eh(e);return}}var Ah=/* @__PURE__ */new WeakMap;function Dh(e){if(typeof e!="function")return;let t=Ah.get(e);if(t!==void 0)return t;let r=(...t)=>{Fh(e,...t)};return Ah.set(e,r),r}function Mh(e,...t){let r;try{r=e(...t)}catch(e){return Eh(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var Lh=6e4;function Bh({lifecycle:e,refreshKey:t,readyAt:r,revalidate:l,refresh:i,now:o=Date.now}){let a=u({readyAt:r,revalidate:l,refresh:i??l,now:o});a.current={readyAt:r,revalidate:l,refresh:i??l,now:o},n(()=>{if(e==null)return;let t=Fh(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=a.current;e!==null&&r()-e>=Lh&&t()}));return()=>{typeof t=="function"&&Fh(t)}},[e]);let s=u(t);n(()=>{Object.is(s.current,t)||(s.current=t,a.current.refresh())},[t])}var Hh=Lh,Uh=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function Nh(){let e=globalThis,t=e[Uh];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[Uh]=r,r}function $h(e,t,r,n,l){let i=Nh(),o=i.get(t);o===void 0&&(o=/* @__PURE__ */new Map,i.set(t,o));let a=o,s=`${r}\0${n}`,u=a.get(s);if(!l&&u!==void 0&&(u.at===null||Date.now()-u.at<Hh))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(a.get(s)===c&&(e.ok||fd(e.error)?c.at=Date.now():a.delete(s)),e))};return a.set(s,c),c.promise}function useHealthPlanPage(e){let{userRef:t,runtime:r}=vd(),i=a(()=>Ph(r),[r]),o=e.repository,c=o??i,d=s((e,n)=>o!==void 0||t==null?c.getPage(e):$h(i,r,t,e,n),[o,c,i,r,t]),{petRef:f}=e,h=e.enabled!==false&&t!=null&&f!==null,[p,g]=l({phase:"idle",petRef:null,page:null,error:null}),b=u(0),m=u(0),y=s(async e=>{let t=++b.current;if(!h||f===null){g(e=>e.phase==="idle"&&e.petRef===null?e:{phase:"idle",petRef:null,page:null,error:null});return}g(e=>({phase:"loading",petRef:f,page:e.petRef===f?e.page:null,error:null}));let r=await d(f,e);t===b.current&&(r.ok?g({phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}):fd(r.error)?g({phase:"ready",petRef:f,page:null,error:null,missing:true,readyAt:Date.now()}):g({phase:"failed",petRef:f,page:null,error:r.error}))},[h,f,d]),v=s(()=>y(true),[y]),k=p.phase==="ready"&&p.petRef===f,w=s(async()=>{if(!h||f===null||!k)return;let e=b.current,t=++m.current,r=await d(f,true);e!==b.current||t!==m.current||!r.ok||g(e=>e.phase==="ready"&&e.petRef===f?{phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}:e)},[h,f,k,d]);Bh({lifecycle:e.lifecycle,refreshKey:e.refreshKey,readyAt:k?p.readyAt??null:null,revalidate:()=>{w()},refresh:()=>{k?w():v()}}),n(()=>(y(false),()=>{b.current+=1}),[y]);let C=h&&p.petRef!==f;return a(()=>({phase:C?"loading":p.phase,page:C?null:p.page,error:C?null:p.error,missing:!C&&p.missing===true,refresh:v}),[C,p,v])}var Wh=/* @__PURE__ */Object.freeze({branding:null}),Vh=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>Wh});function qh(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function Gh(e){let{runtime:t}=vd(),r=t?.entitlements??Vh,n=s(()=>r.getSnapshot()?.branding??null,[r]),l=_d(i(r.subscribe,n,n),t?.sdkConfigHost?.branding),o=qh(e);return a(()=>{let t=l?.lockedFields??null;return{presentation:resolvePresentation({server:l?.presentation??null,locked:t,client:e??null}),isLocked:e=>isPresentationFieldLocked(e,t)}},[l,o])}function Kh(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function Yh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function Qh(e){let t=ct(e);return t===null?null:{reached:$f.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function Jh(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function Xh(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=Jh(r),n=t==="web",l=Qh(r);return{tone:"error",title:l!==null?l.reached:e?$f.turnUnreachableTitle:n?$f.turnFailedTitleWeb:$f.turnFailedTitle,body:r.displayMessage,actionLabel:e?$f.turnStartNewChat:n?$f.retry:$f.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:$f.turnStoppedTitle,body:$f.turnStoppedBody,actionLabel:$f.turnRetry,action:"retry"}:null}function Zh(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var ep=3,tp=/* @__PURE__ */Object.freeze([]);function rp(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return tp;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),l=e.replace(/\s+/g," ").toLowerCase();if(!(l.length===0||r.has(l))&&(r.add(l),n.push(e),n.length===ep))break}/* @__PURE__ */
56
- return Object.freeze(n)}var np=5;function lp(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function ip(e,t){if(t===void 0)return rp(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return tp;let n=Math.max(1,Math.min(np,Math.floor(t.count??ep))),l=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){l=r.text;break}}let i=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(l===null?[]:[i(l)]),a=[],s=e=>{let r=e.trim(),l=i(r);a.length>=n||l.length===0||o.has(l)||lp(t.exclude,r)||(o.add(l),a.push(r))};for(let t of e.suggestedPrompts)s(t);let u=[];try{u=typeof t.fill=="function"?t.fill(l):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&s(e);/* @__PURE__ */
57
- return Object.freeze(a)}function op(e){return e.sender?.displayName??$f.senderVet}function ap(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var sp=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function up(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function cp(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===ep&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>sp.test(e)||up(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var dp="pet_not_registered";function fp(e){return e!=null&&e.reasonCode===dp}var hp=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function pp(e,t,r){let{runtime:i,userRef:o,scopeEpoch:c}=vd(),d=s((e,t)=>{let r=i.registry.services.authFor(o);return Hi(Bi(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,c]),f=a(()=>t===void 0?null:Ui(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=u(0),b=u(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${c}|${e}|${f}`,y=s(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=s(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?hp:h.key!==m?{status:"registering",error:null,registered:null,retry:v}:{status:h.status,error:h.error,registered:h.registered,retry:v},[m,h,v])}var gp=/* @__PURE__ */Object.freeze({});function bp(e){let[t,r]=l(gp),i=u(null),o=u([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===gp?e:gp);return}let t=i.current;if(t===null)return;let n=e.find(e=>e.role==="user"&&!t.known.has(e.id));n!==void 0&&(i.current=null,r(e=>({...e,[n.id]:t.images})))},[e]);let c=s(e=>{i.current=e.length===0?null:{images:e,known:new Set(o.current)}},[]);return a(()=>({byMessage:t,stage:c}),[t,c])}var mp=/* @__PURE__ */new WeakSet;function yp(){let e=makeEverfurError("internalError",{retryable:true});return mp.add(e),err(e)}function vp(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&mp.has(t)}var kp=500;function wp(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,kp):null}function Cp(e,t,r,l){let i=wp(r),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=u(e);a.current=e;let s=u(null),c=u(null),d=u(o);d.current=o,n(()=>{if(i===null||o===null||t||s.current===o||c.current===o)return;let e=a.current;if(e===void 0)return;c.current=o;let r=e=>{c.current===o&&(c.current=null),!vp(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var Sp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),xp=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),_p=/* @__PURE__ */Object.freeze({...Sp,markRead:true}),Rp=/* @__PURE__ */Object.freeze({...xp,markRead:true});function Tp(e,t){return e?t?_p:Sp:t?Rp:xp}function Ip(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:Fh(()=>r()!==!1)===true}function zp(e,t){let r=u({target:e,isVisible:t});r.current={target:e,isVisible:t};let l=u(e.isStreaming);n(()=>{let t=l.current;if(l.current=e.isStreaming,!t||e.isStreaming)return;let{target:n,isVisible:i}=r.current;n.status!=="complete"||n.conversationId===null||n.unreadCount===null||!i()||n.markRead()},[e.isStreaming])}var Pp=3e5;function Op(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function Ep(e,t,r){let l=u(t);l.current=t;let i=u(null),o=u(null),a=u(false),s=u(0),c=u(0),d=u(3e4),f=()=>e?.isOffline===void 0?false:Fh(()=>e.isOffline?.()===!0)===true,h=f(),p=u(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:u}=l.current,h=Gr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:u===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,Op(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,Pp),c.current=Date.now()+s.current):(s.current=0,c.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},n(()=>{if(t.isTurnInFlight||h)return;let e=o.current;e!==null&&p.current(e)},[t.isTurnInFlight,h]),n(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=Fh(()=>e(()=>{p.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)Fh(e)}},[e]);let g=r?.intervalMs??null,b=r?.isVisibleFallback;n(()=>{if(e===void 0||g===null||!Number.isFinite(g)||g<=0)return;d.current=g;let t=setInterval(()=>{Date.now()<c.current||Ip(e,b)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var jp=/^efch_[A-Za-z0-9_-]{43}$/,Fp="efch";function Ap(e){return typeof e=="string"&&jp.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${Fp}=`))continue;let e=r.slice(Fp.length+1);return Ap(e)?e:null}return null}var Dp=128,Mp=/[\u0000-\u001f\u007f]/;function Lp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Bp(e){return typeof e!="string"||e.length===0||e.length>Dp||Mp.test(e)||e.includes("://")?null:e}function Hp(e){if(e===null)return null;let t=e.conversation_id,r=Bp(e.pet_ref);return typeof t!="string"||!Fn(t)||r===null?null:{conversationId:t,petRef:r}}function Up(e,t,r){return Ap(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(Hp(Lp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(on("internalError",false))):Promise.resolve(ok(null))}function Np(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=Ap(e)?e:null,a=o===null||i===null?null:`${String(i)}|${o}`,[s,u]=l(null);return n(()=>{if(a===null||o===null||i===null||r===null)return;let e=true,t=r.registry.services;return Up(t.authFor(i),o,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||u({key:a,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[a,r,o,i]),s!==null&&s.key===a?s.target:void 0}function $p(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function Wp(e,t,r){let l=$p(t),i=t?.kind==="chat",o=t?.petRef??null,a=i&&!r.pinned&&o!==null&&r.petRef!==null&&o!==r.petRef,s=u({openCheckin:e,target:t,selectPet:r.selectPet});s.current={openCheckin:e,target:t,selectPet:r.selectPet};let c=u(null),d=u(null),f=r.petRef;n(()=>{if(l===null||c.current===l)return;let{openCheckin:e,target:t,selectPet:n}=s.current;if(a&&o!==null){if(d.current?.key!==l){d.current={key:l,from:f},n(o);return}f!==d.current.from&&(c.current=l);return}i&&!r.ready||(c.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,f,r.ready])}var Vp=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function qp(e){let t=e?.replace(/\s+/g," ").trim();return t||Vp.untitled}function Gp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function Kp(e){let t=Gp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?Vp.newReply.replace("{date}",t):t}function Yp(e,t){return t?`${Vp.countLabel}${Vp.countSeparator}${e}`:Vp.countLabel}function Qp(e){return`${e.unreadCount!==null&&e.unreadCount>0?Vp.unreadPrefix:""}${Vp.openConversation} ${qp(e.title)}`}function Jp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function Xp(e,t){let r=Jp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=Jp(qp(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function Zp(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function eg(e){let[t,r]=l(false),[i,o]=l(""),c=e.listConversations,d=u(0),[f,h]=l(()=>Zp(c)),p=f.scope===c?f:Zp(c);n(()=>(d.current+=1,r(false),o(""),h(Zp(c)),()=>{d.current+=1}),[c]);let g=s(async t=>{let r=++d.current,n=t!==void 0;h(e=>({...e,scope:c,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===d.current){if(!l.ok){h(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}h(e=>{let r=t&&e.scope===c?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:c,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,c]),b=()=>{r(true),o(""),g()},m=()=>{d.current+=1,r(false)},y=async t=>{let n=++d.current;h(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);n===d.current&&(h(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&r(false))},v=async()=>{let t=d.current,r=await e.loadOlderMessages();t===d.current&&!r.ok&&h(e=>({...e,error:r.error.displayMessage}))},k=()=>{e.newConversation(),d.current+=1,r(false)},w=()=>{p.cursor===null||p.loading||p.loadingMore||i.trim().length>0||g(p.cursor)},C=a(()=>Xp(p.rows,i),[p.rows,i]),S=i.trim().length>0;return{...p,open:t,show:b,close:m,load:g,resume:y,earlier:v,newConversation:k,loadMore:w,query:i,setQuery:o,searching:S,filtered:C,emptyKind:p.rows.length===0?"empty":"noMatch"}}var tg="#111111",rg="#FFFFFF",ng=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:tg,pillColor:rg,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:tg,pillColor:rg,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:tg,pillColor:rg,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:tg,pillColor:rg,showsVetAction:false})});function lg(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function ig(e){return Wf($f.urgencyGeneralReason,{petName:e?.trim()||$f.emptyTitlePetFallback})}function og(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:ag(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:ig(t)}:null}return null}function ag(e){return typeof e=="string"&&e.trim().length>0?e:null}function sg(e){let t=e===null?null:lg(e),[r,i]=l(null),[o,u]=l(false);n(()=>u(false),[t]);let c=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:ng[e.level],f=e!==null&&!c&&e.level!=="general",h=s(()=>{t!==null&&i(t),u(false)},[t]),p=s(()=>u(true),[]);return a(()=>({source:e,tier:d,signature:t,showBanner:c,showCompactIcon:f,showVetAction:c&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:Wf($f.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var ug="everfur.com",cg=2048,dg=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function fg(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&dg.test(e)&&t.add(e)}/* @__PURE__ */
58
- return Object.freeze([...t])}function hg(e,t){if(e===ug||e.endsWith(`.${ug}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function pg(e,t){if(typeof e!="string"||e.length===0||e.length>cg||!/^https:\/\//i.test(e))return null;let r=we(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:hg(r.hostname,t)?r.href:null}function gg(e){try{Promise.resolve(_.openURL(e)).catch(()=>{})}catch{}}var bg=createContext(null);function mg(){return o(bg)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:t,children:n}){let l=e===false?null:Array.isArray(e)?e.join(`\n`):"",i=a(()=>{if(l===null)return null;let e=fg(l===""?[]:l.split(`\n`));/* @__PURE__ */
59
- return Object.freeze({hosts:e,open:t!==void 0?e=>{Fh(t,e,"message")}:gg})},[l,t]);return r(bg.Provider,{value:i},n)}var yg={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function vg(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function kg(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l={width:e*.82,height:n,borderRadius:n,backgroundColor:t};/* @__PURE__ */
60
- return N(C,{style:[vg(e),{gap:e*.22}],...yg,children:[
61
- /* @__PURE__ */U(C,{style:l}),
62
- /* @__PURE__ */U(C,{style:l}),
63
- /* @__PURE__ */U(C,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=kg(e,r),i=e*.78;/* @__PURE__ */
64
- return N(C,{style:[vg(e),{transform:[{rotate:n}]}],...yg,children:[
65
- /* @__PURE__ */U(C,{style:{position:"absolute",width:i,height:l,borderRadius:l,backgroundColor:t}}),
66
- /* @__PURE__ */U(C,{style:{position:"absolute",width:l,height:i,borderRadius:l,backgroundColor:t}})]})}function PlusGlyph(e){/* @__PURE__ */
67
- return U(Cross,{...e,rotate:"0deg"})}function CloseGlyph(e){/* @__PURE__ */
68
- return U(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r);/* @__PURE__ */
69
- return U(C,{style:vg(e),...yg,children:/* @__PURE__ */U(C,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}var wg={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:e,color:t,strokeWidth:r,direction:n}){let l=kg(e,r),i=e*.46,o=wg[n];/* @__PURE__ */
70
- return U(C,{style:vg(e),...yg,children:/* @__PURE__ */U(C,{style:{width:i,height:i,borderRightWidth:l,borderBottomWidth:l,borderColor:t,marginTop:i*o.marginTop,marginLeft:i*o.marginLeft,transform:[{rotate:o.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};/* @__PURE__ */
71
- return N(C,{style:[vg(e),{flexDirection:"row",gap:1}],...yg,children:[
72
- /* @__PURE__ */U(C,{style:[l,{borderTopLeftRadius:e*.2}]}),
73
- /* @__PURE__ */U(C,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l=e*.5;/* @__PURE__ */
74
- return N(C,{style:vg(e),...yg,children:[
75
- /* @__PURE__ */U(C,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),
76
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l=e*.6,i={position:"absolute",width:l,height:l,borderWidth:n,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
77
- return N(C,{style:vg(e),...yg,children:[
78
- /* @__PURE__ */U(C,{style:[i,{top:0,left:0}]}),
79
- /* @__PURE__ */U(C,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=kg(e,r),o=n?t:"transparent";/* @__PURE__ */
80
- return N(C,{style:[vg(e),{transform:[{rotate:l}]}],...yg,children:[
81
- /* @__PURE__ */U(C,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),
82
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),
83
- /* @__PURE__ */U(C,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r);/* @__PURE__ */
84
- return N(C,{style:[vg(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...yg,children:[
85
- /* @__PURE__ */U(C,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),
86
- /* @__PURE__ */U(C,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l=e*.34;/* @__PURE__ */
87
- return N(C,{style:vg(e),...yg,children:[
88
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.06,width:l,height:l,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),
89
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),
90
- /* @__PURE__ */U(C,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r);/* @__PURE__ */
91
- return N(C,{style:[vg(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...yg,children:[
92
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),
93
- /* @__PURE__ */U(C,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r);/* @__PURE__ */
94
- return N(C,{style:vg(e),...yg,children:[
95
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),
96
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */U(C,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l=e/24,i=16*l+n,o=11*l-i/2,a=11+8/Math.SQRT2,s=(21-a)*Math.SQRT2*l,u=(a+21)/2*l;/* @__PURE__ */
97
- return N(C,{style:vg(e),...yg,children:[
98
- /* @__PURE__ */U(C,{style:{position:"absolute",top:o,left:o,width:i,height:i,borderRadius:i,borderWidth:n,borderColor:t}}),
99
- /* @__PURE__ */U(C,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r);/* @__PURE__ */
100
- return N(C,{style:vg(e),...yg,children:[
101
- /* @__PURE__ */U(C,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),
102
- /* @__PURE__ */U(C,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l=e*.62;/* @__PURE__ */
103
- return N(C,{style:vg(e),...yg,children:[
104
- /* @__PURE__ */U(C,{style:{position:"absolute",top:0,width:l,height:l,borderRadius:l,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */U(C,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),
105
- /* @__PURE__ */U(C,{style:{position:"absolute",bottom:e*.04,width:l*.5,height:l*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:e,color:t,testID:r}){let n=e*.36;/* @__PURE__ */
106
- return U(C,{style:vg(e),testID:r,...yg,children:/* @__PURE__ */U(C,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:r}){/* @__PURE__ */
107
- return U(C,{style:vg(e),testID:r,...yg,children:/* @__PURE__ */U(C,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=kg(e,r);/* @__PURE__ */
108
- return N(C,{style:vg(e),testID:n,...yg,children:[
109
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.08,width:e*.26,height:e*.48,borderWidth:l,borderColor:t,borderRadius:e*.13}}),
110
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.38,width:e*.56,height:e*.36,borderBottomWidth:l,borderLeftWidth:l,borderRightWidth:l,borderColor:t,borderBottomLeftRadius:e*.28,borderBottomRightRadius:e*.28}}),
111
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.74,width:l,height:e*.18,backgroundColor:t}})]})}function Ring({size:e,strokeWidth:t,color:r,children:n}){/* @__PURE__ */
112
- return U(C,{style:[vg(e),{borderRadius:e/2,borderWidth:t??m.hairlineWidth,borderColor:r}],children:n})}function ArrowUpGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=kg(e,r),i=e*.46;/* @__PURE__ */
113
- return N(C,{style:vg(e),testID:n,...yg,children:[
114
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.16,bottom:e*.12,width:l,borderRadius:l,backgroundColor:t}}),
115
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r);/* @__PURE__ */
116
- return N(C,{style:vg(e),...yg,children:[
117
- /* @__PURE__ */U(C,{style:{width:e*.8,height:e*.6,marginTop:-e*.12,borderWidth:n,borderColor:t,borderRadius:e*.14}}),
118
- /* @__PURE__ */U(C,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=kg(e,r),l=e*.72,i=e/2;/* @__PURE__ */
119
- return N(C,{style:vg(e),...yg,children:[
120
- /* @__PURE__ */U(C,{style:{width:l,height:l,borderRadius:l/2,borderWidth:n,borderColor:t,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
121
- /* @__PURE__ */U(C,{style:{position:"absolute",top:e*.16,left:e*.12,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}}),
122
- /* @__PURE__ */U(C,{style:{position:"absolute",top:i-e*.2,left:i-n/2,width:n,height:e*.2+n/2,borderRadius:n,backgroundColor:t}}),
123
- /* @__PURE__ */U(C,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var Cg=/* @__PURE__ */Object.freeze({standard:ia.standard,emphasized:ia.emphasized,exit:ia.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var Sg=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),xg=/* @__PURE__ */Object.freeze({...Sg,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function _g(e){return e.motion.reducedMotion?xg:Sg}function Rg(e,t){return Math.max(0,t)*e.followUpStaggerMs}function Tg(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}function Ig(){let e=useEverfurTheme();return _g(e)}var zg=8;function Pg(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function Og(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function Eg(e){let[t,r,n,l]=e;return e=>{if(e<=0)return 0;if(e>=1)return 1;let i=e;for(let r=0;r<zg;r+=1){let r=Og(i,t,n);if(r===0)break;i-=(Pg(i,t,n)-e)/r}return Pg(Math.min(1,Math.max(0,i)),r,l)}}var jg=Eg(Cg.standard),Fg=Eg(Cg.outQuad),Ag=Eg(Cg.out);function Dg(e){let t=u(null);return t.current===null&&(t.current=new A.Value(e)),t.current}function Mg(e,t={}){let r=t.risePx??0,l=t.delayMs??0,i=Dg(e>0?0:1);return n(()=>{if(e<=0){i.setValue(1);return}let t=A.timing(i,{toValue:1,duration:e,easing:Fg,useNativeDriver:true}),r=l>0?A.sequence([A.delay(l),t]):t;return r.start(),()=>r.stop()},[i,e,l]),a(()=>({opacity:i,transform:[{translateY:i.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[i,r])}function FadePresence({visible:e,inMs:t,outMs:r,style:i,children:o}){let[a,s]=l(e),u=Dg(e&&t<=0?1:0);return n(()=>{if(e){s(true);let e=A.timing(u,{toValue:1,duration:Math.max(0,t),easing:jg,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(r<=0){s(false);return}let n=A.timing(u,{toValue:0,duration:r,easing:jg,useNativeDriver:true});return n.start(({finished:e})=>{e&&s(false)}),()=>n.stop()},[e,a,t,r,u]),!a&&!e?null:/* @__PURE__ */U(A.View,{style:[i,{opacity:u}],children:o})}var Lg=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function Bg(e,t){let[r]=l(()=>e?t.bubbleInMs:0),i=r>0,o=Dg(i?0:1);n(()=>{if(r<=0)return;let e=A.timing(o,{toValue:1,duration:r,easing:Ag,useNativeDriver:true});return e.start(),()=>e.stop()},[r,o]);let s=t.bubbleFromScale,u=t.bubbleRisePx;return a(()=>i?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[u,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:Lg,[i,o,u,s])}function Hg(e){let t=u(null),r=u(null),n=e[0]?.id??null;if(t.current===null||r.current!==n){let l=t.current===null;t.current=new Map(e.map(e=>[e.id,l&&e.pending===true])),r.current=n}let l=t.current;for(let t of e)l.has(t.id)||l.set(t.id,true);return s(e=>l.get(e)===true,[l])}var Ug=12;function PressScale({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:l,hitSlop:i,...o}){let a=Ig(),u=Dg(1),c=s(e=>{a.pressMs<=0||a.pressScale===1||A.timing(u,{toValue:e,duration:a.pressMs,easing:jg,useNativeDriver:true}).start()},[u,a.pressMs,a.pressScale]);/* @__PURE__ */
124
- return U(T,{...o,hitSlop:i??Ug,style:t,onPressIn:e=>{c(a.pressScale),n?.(e)},onPressOut:e=>{c(1),l?.(e)},children:/* @__PURE__ */U(A.View,{style:[e,{transform:[{scale:u}]}],children:r})})}function Ng(e,t,r){let i=t&&r.revealTickMs>0,[o,a]=l(0),s=u(e);return s.current=e,n(()=>{if(!i)return;let e=setInterval(()=>{a(e=>Tg(r,e,s.current.length))},r.revealTickMs);return()=>clearInterval(e)},[i,r]),i?e.slice(0,Math.min(o,e.length)):e}var $g=false;function Wg(e){e.layoutMs<=0||($g||($g=true,g.OS==="android"&&typeof j.setLayoutAnimationEnabledExperimental=="function"&&j.setLayoutAnimationEnabledExperimental(true)),F.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function Vg(e,t){let r=u(e);r.current!==e&&(r.current=e,Wg(t))}var qg=36,Gg=22,Kg=12,Yg=12,Qg=16,Jg="#000",Xg="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:r}){let n=useEverfurTheme(),l=B();return e===null?null:/* @__PURE__ */N(z,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[
125
- /* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:$f.closePreview,style:Zg.backdrop,onPress:r,children:/* @__PURE__ */U(E,{source:{uri:e},style:Zg.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
126
- /* @__PURE__ */U(C,{pointerEvents:"box-none",style:[Zg.closeWrap,{top:l.top+Yg}],children:/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:$f.closePreview,hitSlop:Kg,style:Zg.closeButton,onPress:r,children:/* @__PURE__ */U(CloseGlyph,{size:Gg,color:n.color.surface,strokeWidth:2})})})]})}var Zg=m.create({backdrop:{flex:1,backgroundColor:Jg,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:Qg},closeButton:{width:qg,height:qg,borderRadius:qg/2,backgroundColor:Xg,alignItems:"center",justifyContent:"center"}});var eb=()=>{};function tb(){try{return S.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let r=S.currentState==="background";t=S.addEventListener("change",t=>{t==="background"?r=!0:t==="active"&&r&&(r=!1,e())})}catch{return eb}return()=>t.remove()},isVisible:tb}}function rb(e,t){if(e===void 0)return{};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}function nb(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function lb(e){return e?.textColor===void 0?{}:{color:e.textColor}}function ib(e){switch(e.code){case"too_large":return Wf($f.attachmentTooLarge,{max:formatBytes(pl),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return Wf($f.attachmentTooMany,{max:gl});case"unsupported_type":return Wf($f.attachmentUnsupported,{filename:e.filename});case"network":return $f.attachmentNetwork;case"server":return Wf($f.attachmentServer,{status:""});case"cancelled":return $f.attachmentCancelled;case"rate_limited":return $f.attachmentRateLimited;case"quota_exceeded":return $f.attachmentQuota;case"idempotency_conflict":return $f.attachmentConflict;case"unknown":return $f.attachmentUnknown}}function ob(e,t){return Wf(e>=t?$f.attachmentsFull:$f.addAttachment,{used:e,total:t})}var ab=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:t,userRef:r,scopeEpoch:o}=vd(),c=e.maxPerMessage??gl,d=s(()=>{let{services:n}=t.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:n.authFor(r),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}),transport:e.transport??n.uploadTransport,maxPerMessage:c})},[t,r,o,c,e.transport]),f=a(()=>e.queue??d(),[e.queue,d]),h=u(/* @__PURE__ */new WeakSet),[p,g]=l(null),b=p!==null&&p.of===f?p.queue:f;n(()=>{if(b!==e.queue){if(h.current.has(b)){g({of:f,queue:d()});return}return()=>{b.dispose(),h.current.add(b)}}},[b,f,d,e.queue]);let m=i(b.subscribe,b.getSnapshot,()=>ab),[y,v]=l(null),k=s(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>b.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&v(r.error),t},[b,v]),w=s(e=>b.retry(e),[b]),C=s(e=>b.remove(e),[b]),S=s(()=>b.clear(),[b]),x=s(()=>v(null),[v]),_=m.attachments.some(e=>e.status==="uploading"),R=m.attachments.some(e=>e.status==="failed");return a(()=>({available:b.available,attachments:m.attachments,maxPerMessage:c,uploading:_,failed:R,blocked:_||R,s3Keys:m.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:y,add:k,retry:w,remove:C,clear:S,dismissRejected:x}),[b.available,m,c,_,R,y,k,w,C,S,x])}var sb=6e3;function ub(e,t,r){let n=t.trim();if(!n)return e;let l=e===""||/\s$/.test(e)?"":" ",i=`${e}${l}${n}`;return typeof r=="number"&&r>0?i.slice(0,r):i}function cb(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${r}:${n.toString().padStart(2,"0")}`}function db(e){switch(e){case"permissionDenied":return $f.micBlocked;case"noSpeech":return $f.noSpeech;case"unavailable":return $f.dictationUnavailable}}function fb(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var hb=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function pb(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...hb]){let e=(n??"").trim();if(!e)continue;let l=e.toLowerCase();if(!t.has(l)&&(t.add(l),r.push(e),r.length>=100))break}return r}function gb(e,t,r){let[i,o]=l({send:e,conversationId:t,text:r??"",seeded:r??null}),a=i.send===e&&(i.conversationId===null||i.conversationId===t);n(()=>{o(n=>{let l=n.send===e&&(n.conversationId===null||n.conversationId===t),i=l?n.text:"",o=l?n.seeded:null,a=r!=null&&r!==o&&i.length===0;return{send:e,conversationId:t,text:a?r:i,seeded:a?r:o}})},[e,t,r]);let u=s(r=>o(n=>({send:e,conversationId:t,text:r,seeded:n.seeded})),[e,t]);return[a?i.text:"",u]}function bb(e,t,r,i,o=false){let a=u({draft:r,setDraft:i});a.current={draft:r,setDraft:i};let s=u(null),[c,d]=l(null);n(()=>{if(e===void 0)return;let r=`${t??""}`;if(s.current===r)return;s.current=r;let n=true;return(async()=>{let l=await Mh(()=>e.read(t));if(!n)return;let i=l.ok&&typeof l.value=="string"?l.value:"";i.length>0&&a.current.draft.length===0&&a.current.setDraft(i),d(r)})(),()=>{n=false}},[e,t]),n(()=>{e===void 0||o||c!==`${t??""}`||Fh(()=>e.write(t,r))},[e,t,r,c,o])}function mb(e){if(!(g.OS!=="ios"||e===""))try{let t=y?.announceForAccessibility;typeof t=="function"&&t.call(y,e)}catch{}}function AnnounceLine({line:e}){return n(()=>{mb(e)},[e]),null}var yb=12,vb=80,kb=44,wb=22,Cb=.14,Sb=18,xb=8,_b=/* @__PURE__ */Object.freeze({photo:$f.attachmentPhoto,camera:$f.attachmentCamera});function AttachmentPickerPopover({sources:e,full:t,onPick:r,onClose:n}){let l=useEverfurTheme(),i=a(()=>Rb(l),[l]);/* @__PURE__ */
127
- return N(C,{style:i.anchor,pointerEvents:"box-none",children:[
128
- /* @__PURE__ */U(T,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:$f.closeAttachmentPicker,onPress:n}),
129
- /* @__PURE__ */N(C,{style:i.bubble,children:[
130
- /* @__PURE__ */U(C,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */N(PressScale,{accessibilityRole:"button",accessibilityLabel:_b[e],accessibilityState:{disabled:t},disabled:t,containerStyle:i.tile,style:i.tileInner,onPress:()=>r(e),children:[
131
- /* @__PURE__ */U(C,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */U(PhotoGlyph,{size:wb,color:l.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */U(CameraGlyph,{size:wb,color:l.color.brandInk,strokeWidth:1.5})}),
132
- /* @__PURE__ */U(Text,{tier:"control",style:i.tileLabel,children:_b[e]})]},e))}),
133
- /* @__PURE__ */U(C,{style:i.tail}),
134
- /* @__PURE__ */U(C,{style:i.tailFill})]})]})}function Rb(e){let t=e.color,r=e.radius;return m.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:Cb,shadowRadius:Sb,shadowOffset:{width:0,height:xb},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:vb,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:kb,height:kb,borderRadius:kb/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-yb/2,width:yb,height:yb,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:yb+4,height:2,backgroundColor:t.surfaceCream}})}var Tb=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var Ib=56,zb=12,Pb=14,Ob=10,Eb=.45,jb="rgba(7,193,104,0.55)",Fb="rgba(185,28,28,0.55)",Ab=200,Db=300,Mb=20,Lb=22,Bb=12,Hb="rgba(0,0,0,0.78)",Ub=220,Nb=100,$b="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:l,onPreview:i,style:o}){let s=useEverfurTheme(),u=a(()=>Wb(s),[s]);return e.length===0&&t===null?null:/* @__PURE__ */N(C,{style:[u.strip,o],children:[e.length>0?/* @__PURE__ */U(C,{style:u.cards,children:e.map(e=>/* @__PURE__ */U(PreviewCard,{row:e,styles:u,onRetry:n,onRemove:l,onPreview:i},e.id))}):null,r?/* @__PURE__ */U(Text,{style:u.rejected,accessibilityRole:"alert",children:$f.attachmentsFailedBlocked}):null,t!==null?/* @__PURE__ */U(Text,{style:u.rejected,accessibilityRole:"alert",children:ib(t)}):null]})}function PreviewCard({row:e,styles:t,onRetry:r,onRemove:i,onPreview:o}){let a=useEverfurTheme(),s=e.status==="uploading",c=e.status==="failed",d=e.status==="uploaded",f=u(e.status),[h,p]=l(false);return n(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */N(C,{style:t.card,children:[
135
- /* @__PURE__ */U(T,{accessibilityRole:d?"button":"image",accessibilityLabel:d?Wf($f.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:s,disabled:!d},disabled:!d,style:t.thumbHit,onPress:()=>o(e),children:/* @__PURE__ */N(C,{style:t.thumb,children:[
136
- /* @__PURE__ */U(E,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */U(C,{style:t.uploadingOverlay,children:/* @__PURE__ */U(O,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */U(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:Wf($f.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:/* @__PURE__ */U(C,{style:t.failedInner,children:/* @__PURE__ */U(CloseGlyph,{size:Mb,color:a.color.surface,strokeWidth:2})})}):null,
137
- /* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:Wf($f.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>i(e.id),children:/* @__PURE__ */U(CloseGlyph,{size:Bb,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:t}){let r=useEverfurTheme(),l=Ig(),i=u(null);i.current===null&&(i.current=new A.Value(0));let o=i.current;return n(()=>{let e=A.sequence([A.timing(o,{toValue:1,duration:Ab,useNativeDriver:true}),A.delay(l.uploadFlashMs),A.timing(o,{toValue:0,duration:Db,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&t()}),()=>e.stop()},[o,l.uploadFlashMs,t]),/* @__PURE__ */U(A.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:o}],children:/* @__PURE__ */U(CheckGlyph,{size:Mb,color:r.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:t}){let r=useEverfurTheme(),n=a(()=>Wb(r),[r]);if(e.length===0)return null;let l=e.length===1;/* @__PURE__ */
138
- return U(C,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:Wf($f.attachedImage,{filename:e.filename}),onPress:()=>t(e),children:/* @__PURE__ */U(E,{source:{uri:e.uri},style:l?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${r}`))})}function Wb(e){let t=e.color,r=e.type;return m.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:Ib,height:Ib,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:zb,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:m.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Tb,alignItems:"center",justifyContent:"center",backgroundColor:po(e.color.brandInk,Eb)??e.color.brandSofter},successOverlay:{...Tb,alignItems:"center",justifyContent:"center",backgroundColor:jb},failedOverlay:{...Tb,borderRadius:zb,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:Fb},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:Lb,height:Lb,borderRadius:Lb/2,backgroundColor:Hb,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:Ub,height:Ub,borderRadius:Pb,backgroundColor:$b},gridImage:{width:Nb,height:Nb,borderRadius:Ob,backgroundColor:$b}})}var Vb="chat attachment upload: the file handle has no uri",qb="chat attachment upload failed";function Gb(e){return{uri:e.uri,name:sanitizeFilename(e.name),type:e.mimeType}}function createRnChatAttachmentTransport(e={}){/* @__PURE__ */
139
- return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Vb));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(qb));return l?.aborted===true?o():Fe({url:t.upload_url,fields:t.upload_fields,file:Gb(r),signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}var Kb=300,Yb=3e3,Qb=120,Jb=44,Xb=120,Zb="88%",em=520,tm=2,rm=.5,nm=1.5,lm=1.6,im=.6,om=56,am=1.5,sm=5,um=5,cm=36,dm=20,fm=14,hm=Jb,pm=4,gm=24,bm=22,mm=.4,ym=Jb,vm=20,km=.4,wm=480,Cm=12,Sm=.72,xm=48,_m=1.5,Rm=1.3,Tm=1,Im=1,zm="12%",Pm=14,Om=16,Em=28,jm=18,Fm="84%",Am=10,Dm=15,Mm=1.42,Lm=4,Bm=3,Hm=14,Um=20;function Nm(){let e=useEverfurTheme(),t=a(()=>$m(e),[e]);return{theme:e,styles:t}}function $m(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=Math.round(l.size.body*nm),o=Math.round(l.size.body*lm),a=Math.round(dm*l.size.body/fm),s=t.borderRingCream,u=e.slots;return m.create({container:{flex:1,minHeight:Qb,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Qb,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:zm,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:wm,gap:r.lg},errorText:{...face(e,"regular"),fontSize:l.size.subtitle,lineHeight:l.size.subtitle*l.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Jb,minWidth:Jb,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...rb(u.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,...lb(u.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.md,backgroundColor:t.surfaceCream,borderWidth:Im,borderColor:t.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal},turnNoticeAction:{minHeight:Jb,justifyContent:"center"},turnNoticeActionLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight},setupNoticeAction:{...face(e,"medium"),color:t.brandInk,fontSize:l.size.caption},reconnectingCaption:{...face(e,"medium"),color:t.text.secondary,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:r.xs,paddingVertical:r.md,paddingHorizontal:r.md+r.xs/2,backgroundColor:t.surfaceSubtle,borderRadius:n.md},readingDot:{width:6,height:6,borderRadius:n.pill,backgroundColor:t.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:Bm,minHeight:Hm},readingDotInline:{width:Lm,height:Lm,borderRadius:n.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:Jb,justifyContent:"center",paddingHorizontal:r.md+r.xs/2},earlierLabel:{...face(e,"monoBold"),color:t.linkInk,fontSize:l.size.caption},listContent:{padding:r.lg,gap:r.xl},listContentCards:{paddingTop:Pm,paddingHorizontal:Om,paddingBottom:Em,gap:jm},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:Zb,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:em,paddingVertical:r.md,paddingHorizontal:r.lg+tm,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:rm,borderColor:t.primaryEdge}:{},borderRadius:n.lg,borderBottomRightRadius:n.xs,...rb(u.userBubble,rm)},bubbleAssistant:u.assistantBubble?.backgroundColor===void 0?{...rb(u.assistantBubble,rm)}:{paddingVertical:r.md,paddingHorizontal:r.lg+tm,borderRadius:n.lg,...rb(u.assistantBubble,rm)},bubbleVet:{maxWidth:em,paddingVertical:r.md,paddingHorizontal:r.lg+tm,backgroundColor:t.bubbleVet,borderRadius:n.lg,borderTopLeftRadius:n.xs,...rb(u.vetBubble,rm)},bubbleCards:{maxWidth:Fm},bubbleUserCards:{paddingVertical:Am,paddingHorizontal:Dm},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*Mm)},bubblePending:{opacity:im},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:l.size.body,lineHeight:i,...lb(u.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:o,...lb(u.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:l.size.body,lineHeight:i,...lb(u.vetBubble)},assistantName:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,marginBottom:r.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:r.sm,marginBottom:r.xs},assistantAvatar:{width:Um,height:Um,borderRadius:Um/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:r.sm,marginBottom:r.xs},vetSender:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},vetTime:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption},bubbleBold:face(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.md},followUpsHeading:{...face(e,"monoBold"),color:t.text.muted,fontSize:Cm,textTransform:"uppercase",letterSpacing:Sm,paddingBottom:r.sm,borderBottomWidth:Tm,borderBottomColor:s},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:Tm,borderTopColor:s},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,minHeight:xm,paddingVertical:r.sm+tm,...u.chip?.backgroundColor!==void 0||u.chip?.borderColor!==void 0?{paddingHorizontal:r.md}:{},...rb(u.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:l.size.bodyTight,...lb(u.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,marginTop:r.md},askChip:{minHeight:Jb,maxWidth:"100%",justifyContent:"center",paddingVertical:r.sm,paddingHorizontal:r.lg,borderRadius:n.pill,borderWidth:_m,borderColor:t.brandInk,backgroundColor:t.chatGround,...rb(u.chip,_m)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*Rm),...lb(u.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:r.md,marginTop:r.xs},composer:{marginHorizontal:r.md,marginTop:r.xs,minHeight:om,justifyContent:"center",paddingLeft:r.sm,paddingRight:sm,paddingVertical:um,backgroundColor:t.composerFill,borderWidth:am,borderColor:t.composerBorder,borderRadius:n.pill,...rb(u.composerInput,am)},composerRow:{flexDirection:"row",alignItems:"center",gap:r.xs,minHeight:cm},dictationError:{...face(e,"regular"),fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,color:t.danger,paddingHorizontal:r.xs},attachControl:{width:ym,height:ym,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:km},input:{flex:1,minHeight:cm,maxHeight:Xb,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:l.size.body,lineHeight:a,color:t.text.primary,...lb(u.composerInput)},sendControl:{minHeight:hm,minWidth:hm,alignItems:"center",justifyContent:"center"},sendDisc:{width:hm,height:hm,borderRadius:hm/2,alignItems:"center",justifyContent:"center",...rb(u.sendButton)},sendControlDisabled:{opacity:mm},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.micro,textAlign:"center",paddingBottom:r.xs}})}var Wm=18,Vm=28,qm=6,Gm=1200,Km=.4,Ym=.4;function DictationButton({active:e,listening:t,elapsedMs:r,disabled:l=false,onToggle:i}){let o=useEverfurTheme(),s=a(()=>Qm(o),[o]);return n(()=>{if(t)try{y.announceForAccessibility($f.listening)}catch{}},[t]),/* @__PURE__ */N(C,{style:s.wrap,children:[t?/* @__PURE__ */U(Text,{style:s.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:cb(r)}):null,
140
- /* @__PURE__ */U(T,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?$f.stopDictation:$f.dictate,accessibilityState:{selected:e,disabled:l},style:[s.button,l?s.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */N($,{children:[
141
- /* @__PURE__ */U(Pulse,{style:s.pulse,reduced:o.motion.reducedMotion}),
142
- /* @__PURE__ */U(StopGlyph,{size:Vm,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */U(MicGlyph,{size:Wm,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=u(new A.Value(1)).current;return n(()=>{if(t)return;let e=A.loop(A.sequence([A.timing(r,{toValue:Km,duration:Gm/2,useNativeDriver:true}),A.timing(r,{toValue:1,duration:Gm/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */U(A.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function Qm(e){let t=e.color,r=e.type.tierSizes.compact.micro;return m.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:Jb,height:Jb,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:Ym},pulse:{position:"absolute",top:qm,right:qm,bottom:qm,left:qm,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var Jm=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function Xm(){let e=globalThis,t=e[Jm];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[Jm]=r,r}function registerEverfurDictation(e){let t=Xm();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function Zm(){return Xm().version??0}function ey(e){let t=Xm(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function ty(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function ry(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function ny(){let e=Xm();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||g.OS!=="ios"&&g.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:ry(t())}),e=>typeof e=="object"&&e!==null&&ty(e.box));return r.available&&(e.memo=r.module.box),e.memo}function ly(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function iy(){try{return Intl.DateTimeFormat().resolvedOptions().locale||ay}catch{return ay}}function oy(e){return e.replace(/_/g,"-").toLowerCase()}var ay="en-US";function sy(e=iy()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return ay;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:ay}function uy(e,t){if(t.length===0)return null;let r=e=>t.find(t=>oy(t)===oy(e));return r(e)??r(ay)??t.find(e=>oy(e).startsWith("en-"))??null}async function cy(e,t){if(g.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return uy(t,r??[])??t}catch{return t}}async function dy(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(g.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=oy(t);return(r??[]).some(e=>oy(e)===n)?"on_device":"network"}catch{return"network"}}function fy(){return g.OS!=="android"?true:Number(g.Version)>=hy}var hy=33;function py(e,t,r){return{lang:t,interimResults:true,continuous:fy(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var gy=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),by=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function my(e){return by.has(e)}var yy=600,vy=3;function ky(e,t,r){if(gy.has(r))return null;let n=my(r)?yy:0;return r==="language-not-supported"&&oy(t)!==oy(ay)?{mode:"network",lang:ay,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function wy(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Cy(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Sy=55e3,xy=3e3,_y=1e3;function Ry(e){return Ty.has(e)||my(e)}var Ty=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),Iy=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function zy(e){return e.replace(/\s+/g," ").trim()}function Py(e,t,r){let n=zy(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function Oy(e){return zy([...e.committed,e.interim].join(" "))}function Ey(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,a=e=>i!==null&&i.token===e?i:null;function s(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){s(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&Oy(e.transcript)===""&&e.launchedAt-o<_y}function d(e){return e.mode??"none"}function f(e,t){fb(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){fb(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(a(e.token)===null)return;u(e);let r=Oy(e.transcript),n=e.errorCode;if(n!==null&&!(r&&Ry(n))){h(e,wy(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{a(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),fb(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(a(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=Py(l.transcript,r,e?.isFinal===true),t.onText(Oy(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||my(t)))return;let r=Oy(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<vy?ky(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(a(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){b(l,e.mode);return}s(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(a(l.token)===null||l.userStopped)&&b(l,e.mode)},e.delayMs);return}p(l)}})]}function b(t,r){s(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=Iy,t.errorCode=null,g(t);try{e.start(py(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function m(t){let r=await Cy(e);if(a(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await cy(e,t.lang),a(t.token)===null)return;let n=await dy(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Sy),b(t,n))}function y(r){if(!(a(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),xy);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:sy(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:Iy,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),m(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,a=Oy(r.transcript);if(u(r),t.onStatus("idle"),!!l){a&&f(r,a),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function jy({enabled:e,input:t,setInput:r,phrases:o,maxLength:c,telemetry:d}){let f=i(ey,Zm,Zm),h=a(()=>e?ny():null,[e,f]),p=a(()=>ly(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=u(t);w.current=t;let C=u(r);C.current=r;let x=u(d);x.current=d;let _=u(""),R=u(c);R.current=c;let T=u(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:Ey(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>C.current(ub(_.current,e,R.current)),onError:e=>{y(e),b("error")}},()=>x.current)});let I=h===null?null:T.current?.controller??null,z=s(()=>{I?.cancel()},[I]),P=s(()=>{if(I!==null){if(I.isActive()){I.stop();return}y(null),k(0),_.current=w.current,I.start(o)}},[I,o]);n(()=>{if(g!=="listening")return;let e=Date.now();k(0);let t=setInterval(()=>k(Date.now()-e),1e3);return()=>clearInterval(t)},[g]),n(()=>{if(g!=="error")return;let e=setTimeout(()=>{y(null),b("idle")},sb);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=S.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var Fy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function Ay(){let e=globalThis,t=e[Fy];if(t!==void 0)return t;let r=createContext(true);return e[Fy]=r,r}var Dy=Ay();function My(){return o(Dy)}var Ly=/* @__PURE__ */Object.freeze(["photo"]),By=52,Hy=1.5,Uy=10,Ny=14,$y=10,Wy=40,Vy=20,qy=.3,Gy=2.5,Ky=1,Yy=1.5,Qy=38,Jy=22,Xy=3;function Zy(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?qf($f.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):qf($f.placeholder,t):n==="urgent"?$f.placeholderUrgentWeb:n==="followUp"?$f.placeholderFollowUpWeb:qf($f.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??gl,transport:r}),l=a(()=>({state:n,sources:e.sources??Ly,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
143
- return U(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:c,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:w=false}){let{theme:S,styles:x}=Nm(),_=a(()=>iv(S),[S]),R=a(()=>ov(S),[S]),I=Ig(),[z,P]=gb(e,i,c),[O,E]=l(false),[j,F]=l(false),A=s(()=>F(true),[]),D=s(()=>F(false),[]),[M,L]=l(false);n(()=>{L(false)},[i]);let B=Zy(S.meta.placeholder,p,k,b,S.meta.placeholderFillsPet===true),H=a(()=>pb({name:p,breed:g}),[p,g]),W=jy({enabled:m,input:z,setInput:P,phrases:H,maxLength:Gn,telemetry:y}),V=W.cancel,q=W.active;bb(d,i===null?null:String(i),z,P,q);let G=u(i);n(()=>{G.current!==i&&(G.current=i,V())},[i,V]);let K=My();n(()=>{K||V()},[K,V]);let Y=o?.state.uploading??false,Q=o?.state.failed??false,J=Y||Q,X=o?.state.attachments??ev;Vg(X.length,I);let Z=s(()=>{let t=z.trim();if(t.length===0||J||[...t].length>Gn)return;q&&V();let r=o?.state.s3Keys??tv;o!==null&&r.length>0?(f(o.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),o.state.clear()):e(t),P(""),L(false)},[z,e,J,q,V,o,f]),ee=s(e=>{q&&V(),P(e)},[q,V,P]),te=s(()=>{t()},[t]),re=s(e=>{E(false),o!==null&&(L(false),o.state.dismissRejected(),Mh(o.pick,e).then(e=>{if(!e.ok){L(true);return}e.value!==null&&o.state.add(e.value)}))},[o]),ne=a(()=>[...z.trim()].length>Gn,[z]),le=ne||J||z.trim().length===0,ie=ne||J||w&&z.trim().length===0,oe=o!==null&&X.length>=o.state.maxPerMessage,ae=S.slots.sendButton?.textColor??S.color.brandInk,se=S.slots.sendButton?.textColor??S.color.surface;/* @__PURE__ */
144
- return N(C,{style:x.composerOuter,children:[o!==null&&O?/* @__PURE__ */U(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */U(AttachmentStrip,{attachments:X,rejected:M?lv:o.state.rejected,uploadFailed:Q,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:e=>h({uri:e.previewUri,label:e.filename}),style:v?_.tray:R.tray}):null,
145
- /* @__PURE__ */N(C,{style:v?[x.composer,_.bar,j?_.barFocused:null]:x.composer,children:[W.supported&&W.error!==null?/* @__PURE__ */N($,{children:[
146
- /* @__PURE__ */U(Text,{style:x.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:db(W.error)}),
147
- /* @__PURE__ */U(AnnounceLine,{line:db(W.error)})]}):null,
148
- /* @__PURE__ */N(C,{style:x.composerRow,children:[o!==null?/* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:oe?ob(X.length,o.state.maxPerMessage):$f.attachPhotoOrFileNative,accessibilityState:{disabled:oe,expanded:O},disabled:oe,style:[x.attachControl,v?_.add:null,oe?x.attachControlDisabled:null],hitSlop:v?Xy:void 0,onPress:()=>E(e=>!e),children:/* @__PURE__ */U(UploadGlyph,{size:v?Jy:vm,color:oe?S.color.text.muted:v?S.color.text.primary:S.color.brandInk,strokeWidth:1.75})}):null,
149
- /* @__PURE__ */U(cf,{style:v?[x.input,_.input]:x.input,onFocus:A,onBlur:D,value:z,onChangeText:ee,placeholder:B,placeholderTextColor:S.slots.composerInput?.textColor??S.color.text.placeholder,accessibilityLabel:$f.composerLabel,onSubmitEditing:Z,returnKeyType:"send",...rv,...v?nv:null,blurOnSubmit:false,multiline:true,editable:true}),W.supported?/* @__PURE__ */U(DictationButton,{active:W.active,listening:W.status==="listening",elapsedMs:W.elapsedMs,onToggle:W.toggle}):null,r?/* @__PURE__ */U(T,{onPress:te,accessibilityRole:"button",accessibilityLabel:$f.stop,style:x.sendControl,children:/* @__PURE__ */U(C,{style:v?_.disc:x.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */U(StopGlyph,{size:v?Vy:bm,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */U(T,{onPress:Z,disabled:le,accessibilityRole:"button",accessibilityLabel:$f.send,accessibilityState:{disabled:le,busy:Y},style:[x.sendControl,ie?v?_.dimmed:x.sendControlDisabled:null],children:v?/* @__PURE__ */U(C,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */U(ArrowUpGlyph,{size:Vy,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */U(C,{style:x.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */U(SendGlyph,{size:gm,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var ev=/* @__PURE__ */Object.freeze([]),tv=/* @__PURE__ */Object.freeze([]),rv=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),nv=/* @__PURE__ */Object.freeze(g.OS==="web"?{rows:1}:{}),lv=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function iv(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+Ky;return m.create({bar:{marginTop:Uy,marginHorizontal:Ny,marginBottom:$y,minHeight:By,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:Hy,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Gy,paddingLeft:8-(Gy-Hy),paddingRight:6-(Gy-Hy)},input:{fontSize:n,lineHeight:Math.round(n*Yy),minHeight:Math.round(n*Yy),...g.OS==="web"?{outlineStyle:"none"}:null},add:{width:Qy,height:Qy,borderRadius:Qy/2},disc:{width:Wy,height:Wy,borderRadius:Wy/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...rb(r)},dimmed:{opacity:qy},tray:{marginHorizontal:Ny,marginTop:Uy,paddingBottom:0}})}function ov(e){return m.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=vd(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[c,d]=l({repository:o,pets:[],loading:true,error:null}),f=c.repository===o?c:{pets:[],loading:true,error:null},h=u(0),p=s(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>$i(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function av(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var sv=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var uv=false;function cv(e,t){return t!==void 0?(Fh(t,e),"onStartInApp"):vf(e)==="presented"?"presenter":Sf(e)?"experience":(uv||(uv=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var dv=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&dv.includes(e)}var fv="/widget/v1/televet/handoffs",hv="/widget/v1/televet/availability",pv="/widget/v1/televet/chat-entry",gv=/^[a-z0-9][a-z0-9_-]{0,39}$/,bv=/^[A-Za-z0-9_-]{22}$/;var mv=32,yv=128,vv=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function kv(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function wv(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Cv(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!gv.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>vv)return{ok:false,message:`visitRef must be 1..${vv} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${dv.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Sv(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function xv(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(Pv(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>yv)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${yv} characters`}));i=e}let o=Cv(i,l);if(!o.ok){let e=kv(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:fv,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=_v(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!bv.test(d))){let e=wv("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,h=f?Sv(s.value?.visit):null;if(f&&h===null){let e=wv("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Pv(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>mv)return kv(`state must be at most ${mv} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:hv,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?wv("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:pv},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function _v(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||!zv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var Rv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),Tv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Iv=/[\s\u0000-\u001f\u007f]/;function zv(e){if(Iv.test(e))return false;let t=Tv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&Rv.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function Pv(e,t,r){if(e)try{e.track(t,r)}catch{}}var Ov=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function Ev(e,t,r){let{usState:i,chat:o,scope:a}=r,s=t&&(i!==null||o),u=`${i??""}|${o?"chat":""}`,[c,d]=l(null);if(n(()=>{if(!s)return;let t=true,r=e.current;return d(null),(async()=>{try{if(o&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&d({key:u,open:e})}),()=>{t=false}},[s,u,i,o,a,e]),!s)return null;let f=c!==null&&c.key===u;return{open:f&&c.open,pending:!f}}var jv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function Fv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=vd(),o=useCapability("televet"),c=o.enabled&&n!==null,d=t.usState??null,f=t.entry==="chat",h=t.petRef??null,p=t.prefer==="redirect",g=a(()=>{if(t.controller)return t.controller;let{services:e}=r.registry;return xv({auth:e.authFor(n),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[r,n,i,t.controller]),b=u(g);b.current=g;let m=a(()=>({runtime:r,userRef:n,scopeEpoch:i}),[r,n,i]),y=Ev(b,c,{usState:d,chat:f,scope:m}),v=c&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(Ov),S=u(null),x=u({runtime:r,userRef:n,scopeEpoch:i});x.current={runtime:r,userRef:n,scopeEpoch:i};let _=u(g);_.current=g;let R=u(v);R.current=v;let T=s((t,r)=>{if(S.current)return S.current;let n=(e,t)=>(C({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!R.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=x.current,o=_.current;C(jv);let a=(async()=>{let a,s={...k!==null?{returnTo:k}:{},...f?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},u=Object.keys(s).length===0?void 0:s,c=t===void 0?h:t;try{a=await(u===void 0?o.createHandoff(c):o.createHandoff(c,u))}catch{return e.abandon(l.value),n("unknown",null)}let d=x.current;if(d.runtime!==i.runtime||d.userRef!==i.userRef||d.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!a.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let p=await e.finish(l.value,a.value);return p!==null?n(p,null):(C(Ov),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{S.current===a&&(S.current=null)});return S.current=a,a},[e,h,k,f]),I=s((e,t)=>{if(!R.current)return C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?h:e,n={...r!==null?{petRef:r}:{},...d!==null?{usState:d}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return cv(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(Ov),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[h,d]),z=s(e=>p?T(e,null):I(e,null),[p,T,I]),P=s((e,t)=>p?T(void 0,{visitRef:e,intent:t??null}):I(void 0,{visitRef:e,intent:t??null}),[p,T,I]),O=s(e=>p?T(void 0,null):I(void 0,{consultId:e.trim()}),[p,T,I]);return{available:v,isPending:o.isPending||(y?.pending??false),status:w.status,error:w.error,errorReason:w.errorReason,open:z,openVisit:P,joinVisit:O}}var Av=e=>_.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??Av;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return Fv(n,r)}var Dv=44,Mv=.6;function VetVisitButtonCore(e){let{petRef:t,label:r,openUrl:n,onOpened:l,onError:i,style:o,labelStyle:s,controller:c,returnTo:d,usState:f,entry:h,visitRef:p,intent:g,onStartInApp:b,prefer:m}=e,y=m==="redirect",v=useVetVisit({...d!==void 0?{returnTo:d}:{},...f!==void 0?{usState:f}:{},...h!==void 0?{entry:h}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...c!==void 0?{controller:c}:{},prefer:y?"redirect":"in-app"}),k=useEverfurTheme(),w=a(()=>Lv(k),[k]),C=u(false);if(!v.available)/* @__PURE__ */
150
- return N($,{children:[null,
151
- /* @__PURE__ */U(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??sv.visitButton;/* @__PURE__ */
152
- return N($,{children:[
153
- /* @__PURE__ */U(T,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}};cv(e,b)===null&&Fh(i,"unavailable",null);return}C.current=true,(p==null?v.open():v.openVisit(p,g??null)).then(e=>{e.opened?Fh(l,e.flowId??null):e.reason!=="cancelled"&&Fh(i,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:x,accessibilityState:{busy:S,disabled:S},style:[w.button,S?w.busy:null,o],children:/* @__PURE__ */U(Text,{style:[w.label,s],children:x})}),
154
- /* @__PURE__ */U(TelevetHostOutlet,{})]})}function Lv(e){let{color:t,space:r,radius:n,type:l,slots:i}=e;return m.create({button:{minHeight:Dv,minWidth:Dv,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...rb(i.vetVisitButton)},busy:{opacity:Mv},label:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.snug,...lb(i.vetVisitButton)}})}function Bv(e){let[t,r]=l(null);return{shown:e!==null&&t!==e,onError:()=>r(e)}}function BrandImage({uri:e,label:t,decorative:r=false,style:n,resizeMode:l="contain",fallback:i=null,onError:o,testID:a}){let s=Bv(e);if(e===null||!s.shown)return i;let u=r?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...t===void 0?{}:{accessibilityLabel:t}};/* @__PURE__ */
155
- return U(E,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=Bv(e);return e===null||!i.shown?null:/* @__PURE__ */U(C,{style:r,...l===void 0?{}:{testID:l},children:/* @__PURE__ */U(E,{source:{uri:e},style:n,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:i.onError})})}var Hv=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),Uv=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function Nv(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return Uv;let n=Math.abs(e.leading-e.trailing);if(n<.5)return Uv;let l=e.row-t-e.leading-e.trailing,i=Math.min(n,Math.max(0,l-r));return i<.5?Uv:e.leading<e.trailing?{leading:e.leading+i,trailing:void 0}:{leading:void 0,trailing:e.trailing+i}}function $v(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function Wv(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function Vv(e){if(e.brightness!=="light")return false;let t=sa.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),l=new Set(Wv(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&Wv(r).every(e=>l.has(e))}function qv(e){let t=(e.brightness==="dark"?ca:sa).color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t);return{success:!n(r.success,t.success),warning:!n(r.warningStrong,t.warningStrong)||!n(r.cautionAccent,t.cautionAccent),info:!(n(r.info,r.brandInk)&&n(r.badgeBgInfo,r.brandSoft)&&n(r.infoEdge,r.structureEdge))}}function Gv(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function Kv(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function Yv(e){let t=Kv(e.ageYears),r=Gv(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var Qv=/* @__PURE__ */Object.freeze([
39
+ return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function Ai(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function Di(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,Mi)}catch(e){Mi(e)}}function Mi(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var Li=/* @__PURE__ */new WeakMap,Bi=/* @__PURE__ */new Map;function Hi(e,t){Li.set(e,t)}function Ui(e,t,r,n){let l=Li.get(e);if(l===void 0)return null;let i;if(t.mode==="personalized"&&typeof t.userRef=="string")i=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")i=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${l}|${i}|${r}|${$i(n)}`}function Ni(e,t){if(e===null)return t();let r=Bi.get(e);if(r!==void 0)return r;let n=t().finally(()=>{Bi.get(e)===n&&Bi.delete(e)});return Bi.set(e,n),n}function $i(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map($i).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${$i(t)}`).join(",")}}`}var Wi=/* @__PURE__ */new WeakMap;function Vi(e,t){let r=Wi.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,Wi.set(e,r)),r.add(t),()=>{r?.delete(t)}}function qi(e){let t=Wi.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var Gi=/* @__PURE__ */new Map;function Ki(e,t){return()=>{let r=Gi.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let l=n.finally(()=>{Gi.get(e)===l&&Gi.delete(e)});return Gi.set(e,l),l}}function parseColor(e){let t=Yi(e);return t===null?null:ro(t)}function Yi(e){if(typeof e=="number")return Xi(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Qi(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Qi(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ji(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=Qi(t);if(e!==null)return e}return/^\d+$/.test(t)?Xi(Number.parseInt(t,10)):null}function Qi(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:eo(t[0]),g:eo(t[1]),b:eo(t[2]),a:1};if(t.length===6)return{r:Zi(t,0),g:Zi(t,2),b:Zi(t,4),a:1};if(t.length===8){let e=Zi(t,0);return{r:Zi(t,2),g:Zi(t,4),b:Zi(t,6),a:e/255}}return null}function Ji(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(e=>e.trim());if(n.length<3)return null;let l=to(Number(n[0])),i=to(Number(n[1])),o=to(Number(n[2]));if(l===null||i===null||o===null)return null;let a=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;a=Math.min(1,Math.max(0,e))}return{r:l,g:i,b:o,a:a}}function Xi(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return{r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}function Zi(e,t){return Number.parseInt(e.slice(t,t+2),16)}function eo(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function to(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function ro(e){if(e.a>=1)return no(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function no(e,t,r){return`#${lo(e)}${lo(t)}${lo(r)}`.toUpperCase()}function lo(e){return e.toString(16).padStart(2,"0")}var io="#111111",oo="#FFFFFF",ao="#000000";function readableOn(e){let t=Yi(e);if(t===null)return oo;let r=co(t),n=co({r:17,g:17,b:17}),l=co({r:255,g:255,b:255});return ho(r,l)>=ho(r,n)?oo:io}function so(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(oo,e)>=contrastRatio(ao,e)?oo:ao}function uo(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(oo)>=t(ao)?oo:ao}function co(e){let t=fo(e.r/255),r=fo(e.g/255),n=fo(e.b/255);return.2126*t+.7152*r+.0722*n}function fo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function ho(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=Yi(e),n=Yi(t);if(r===null||n===null)return 1;let l=n.a>=1?n:{...n},i=r.a>=1?r:po(r,l);return ho(co(i),co(l))}function po(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function go(e,t){let r=Yi(e),n=Yi(t);if(r===null||n===null)return null;let l=r.a>=1?r:po(r,{...n});return no(l.r,l.g,l.b)}function bo(e,t){let r=Yi(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var mo=.05;function yo(e,t,r,n){let l=t[0];if(l===void 0)return r;let i=e=>t.every(t=>contrastRatio(e,t)>=n);if(Yi(e)===null)return r;if(i(e))return e;let o=go(e,l),a=o===null?null:Yi(o),s=Yi(r);if(a===null||s===null)return r;for(let e=1;e<1/mo;e+=1){let t=e*mo,r=(e,r)=>Math.round(e+(r-e)*t),n=no(r(a.r,s.r),r(a.g,s.g),r(a.b,s.b));if(i(n))return n}return r}function vo(e,t,r){let n=e/255,l=t/255,i=r/255,o=Math.max(n,l,i),a=Math.min(n,l,i),s=(o+a)/2;if(o===a)return{h:0,s:0,l:s};let u=o-a,c=u/(1-Math.abs(2*s-1)),d;return o===n?(d=(l-i)/u*60,d<0&&(d=d+360)):o===l?d=((i-n)/u+2)*60:d=((n-l)/u+4)*60,{h:d,s:c,l:s}}function ko(e){let{h:t,s:r,l:n}=e,l=(1-Math.abs(2*n-1))*r,i=t/60,o=l*(1-Math.abs(i%2-1)),a=n-l/2,s=Math.floor(i)%6,u=[[l,o,0],[o,l,0],[0,l,o],[0,o,l],[o,0,l],[l,0,o]],[c,d,f]=u[s];return{r:wo(c+a),g:wo(d+a),b:wo(f+a)}}function wo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var Co=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),So=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),xo=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return xo[e]??So}var _o=4.5,Ro=/* @__PURE__ */Object.freeze({});function To(e){return Co.includes(e)}function Io(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,l]of Object.entries(e)){if(!To(n)||l===null||typeof l!="object")continue;let e=Oo(l);if(e===null)continue;let i=zo(n,e);i!==null&&(t[n]=i,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function zo(e,t){let r=xo[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function Po(e,t,r){return e[t]!==void 0?e[t]:e[r]}function Oo(e){let t={},r=parseColor(Po(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(Po(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let l=Io(Po(e,"border_radius","borderRadius"));l!==null&&(t.borderRadius=l);let i=parseColor(Po(e,"text_color","textColor"));return i!==null&&(t.textColor=i),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??Ro:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function Eo(e){let t=Yi(e);return t!==null&&t.a>=1}var jo=3,Fo=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function Ao(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function Do(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>go(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=jo))return null;let l=[...t,...n,...r];return yo(n[0],l,uo(l),jo)}function Mo(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>go(e,t)??t)}function Lo(e,t){let r=uo(e);return e.every(e=>contrastRatio(r,e)>=t)}function Bo(e,t){let r=t[0];return r===void 0?null:go(e,r)}function Ho(e){let t=so(e[0],_o);return e.every(e=>contrastRatio(t,e)>=_o)?t:uo(e)}function Uo(e,t,r,n,l){return Fo.has(e)?false:l?true:r!==void 0&&Ao(t,r)?false:!(n!==void 0&&r!==void 0&&Eo(r))}function guardSlotContrast(e,t,r){let n=false,l={};for(let i of Co){let o=e[i];if(o===void 0)continue;let a=o.backgroundColor,s=t?.[i]??[],u=Mo(a,s),c={...o},d=false;if(a!==void 0&&u.length>1&&!Lo(u,_o)){let e=Bo(a,s);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[i],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&Eo(h)&&Do(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(a!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<_o))&&(c.textColor=Ho(u),d=true);else if(e!==void 0){let t=yo(e,u,uo(u),_o);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&Uo(i,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=yo(o.borderColor,e,uo(e),jo);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=Do(h,f,u);e!==null&&(c.borderColor=e,d=true)}l[i]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(l):e}var No=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),$o=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var Wo=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Wo(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var Vo=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),qo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),Go={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Ko={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Yo={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},Qo={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Jo={regular:"400",medium:"500",bold:"700"},Xo={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},Zo=0,ea="System",ta="monospace",ra=["content","heading","control","compact","badge"];function na(e){let t={};for(let r of ra)t[r]=e;return t}var la=[];function ia(){return{family:ea,mono:ta,fontUrl:null,families:{regular:ea,medium:ea,bold:ea,mono:ta,monoMedium:ta,monoBold:ta},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Yo,tierSizes:na(Yo),lineHeight:Qo,weight:Jo,letterSpacing:Xo,scale:1,maxScale:Zo,scaleCaps:Vo,headingFamily:null,headingWeight:null,fontSources:la,roles:$o,typeScale:1}}var oa={},aa=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(e){return`cubic-bezier(${e.join(", ")})`}var sa={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(aa.standard),emphasized:cssCubicBezier(aa.emphasized),exit:cssCubicBezier(aa.exit)},reducedMotion:false},ua={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},ca=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:ua,space:Go,radius:Ko,type:ia(),motion:sa,slots:oa}),da={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},fa=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:da,space:Go,radius:Ko,type:ia(),motion:sa,slots:oa});function ha(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function pa(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function ga(e){return pa(e).every(t=>contrastRatio(e.brand,t)>=jo)}function ba(e){return[e.chatGround,e.surface,e.surfaceCream]}function ma(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...ya(e,t)]}function ya(e,t){return[go(t,e.surface)??e.surface,go(t,e.surfaceCream)??e.surfaceCream]}function va(e){return[e.composerFill,e.chatGround]}var ka=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function wa(e,t){let r=new Set(ha(t));return ha(e).every(e=>r.has(e))}function Ca(e){let t=e.color,r=(e.brightness==="dark"?fa:ca).color,n=(e.brightness==="dark"?ca:fa).color,l=ha(t),i=uo(l)!==uo(ha(r)),o=wa(t,r),a=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,s=(e,t,r,n,l,s)=>{let u=t===r&&(e!=="errorRed"||a);return u&&o&&ka.has(e)?t:yo(u&&i?n:t,l,uo(l),s)},u=(e,l,i)=>s(`text.${e}`,t.text[e],r.text[e],n.text[e],l,i),c=(e,t,l,i)=>s(e,t,r[e],n[e],l,i),d=e=>i&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=so(f,_o),p=c("danger",t.danger,[...l,...ya(t,t.badgeBgCritical)],_o),g={...t,onPrimary:h,onAccent:so(t.accent,_o),onDanger:contrastRatio(h,p)>=_o?h:so(p,_o),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,l,_o),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,ba(t),_o),text:{...t.text,primary:u("primary",l,_o),secondary:u("secondary",l,_o),muted:u("muted",l,_o),metaCool:u("metaCool",l,_o),timestamp:u("timestamp",l,_o),placeholder:u("placeholder",pa(t),jo)},danger:p,errorRed:c("errorRed",t.errorRed,ma(t,t.badgeBgCritical),_o),warningStrong:c("warningStrong",t.warningStrong,ma(t,t.badgeBgCaution),_o),composerBorder:c("composerBorder",t.composerBorder,va(t),jo),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,pa(t),jo)},b={...g,...Pa(g,r,o)};return{...b,...Sa(t,b,r)}}function Sa(e,t,r){let n={},l=(e,t,r)=>yo(e,t,uo(t),r);if((!Ta(e.success,r.success)||!Ta(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=l(e.success,ma(t,e.badgeBgPositive),_o)),(!Ta(e.cautionAccent,r.cautionAccent)||!Ta(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=l(e.cautionAccent,ma(t,e.badgeBgCaution),_o)),xa(e,r)){n.info=l(e.info,ma(t,e.badgeBgInfo),_o);let r=[t.surface,t.chatGround,...ya(t,e.badgeBgInfo)];n.infoEdge=l(e.infoEdge,r,jo)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function xa(e,t){return!Ta(e.info,t.info)||!Ta(e.badgeBgInfo,t.badgeBgInfo)}var _a=.24,Ra=.3;function Ta(e,t){return parseColor(e)===parseColor(t)}function Ia(e,t){return Ta(e.accent,t.accent)?Ta(e.brand,t.brand)?null:e.brand:e.accent}function za(e,t,r){let n=bo(e,r);return(n===null?null:go(n,t))??t}function Pa(e,t,r){let n=Ia(e,t),l=pa(e),i=uo(l),o=uo([e.surface])===oo,a=n===null&&r,s;a?s=t.highlight:n===null?s=o?za(ca.color.highlight,e.surface,Ra):ca.color.highlight:s=za(n,e.surface,o?Ra:_a);let u=a?t.onHighlight:yo(e.text.primary,[s],uo([s]),_o),c=n===null?t.mark:yo(n,l,i,jo),d=ga(e)?e.brand:i,f=(e,t,n)=>r&&Ta(e,t)?n:yo(e,l,d,jo),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=jo)?e.primary:yo(e.primary,h,uo(h),jo);return{highlight:s,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var Oa=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function Ea(e,t){let r=(e.brightness==="dark"?fa:ca).color,n=e.color,l=t.color,i=[],o=(e,t,r,n)=>{i.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},a=(e,t)=>!Oa(e,t);a(n.text.primary,r.text.primary)&&!Oa(l.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,l.text.primary),a(n.brand,r.brand)&&(Oa(l.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,l.brandInk),Oa(l.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,l.primaryEdge),!Oa(l.controlEdge,n.brandBorder)&&!ga({...l,brand:n.brand})&&o("primary_color","control outline",n.brand,l.controlEdge)),a(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!Oa(l.linkInk,n.accent)&&o("accent_color","link text",n.accent,l.linkInk),a(n.danger,r.danger)&&!Oa(l.danger,n.danger)&&o("danger_color","error text",n.danger,l.danger),a(n.success,r.success)&&!Oa(l.success,n.success)&&o("success_color","positive status",n.success,l.success),a(n.warningStrong,r.warningStrong)&&!Oa(l.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,l.warningStrong),a(n.cautionAccent,r.cautionAccent)&&!Oa(l.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,l.cautionAccent),(a(n.info,r.info)||a(n.badgeBgInfo,r.badgeBgInfo))&&(Oa(l.info,n.info)||o("info_color","information text",n.info,l.info),Oa(l.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,l.infoEdge));for(let r of Co){let n=e.slots[r],l=t.slots[r];n===void 0||l===void 0||n===l||(l.backgroundColor!==void 0&&!Oa(l.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,l.backgroundColor),n.textColor!==void 0&&l.textColor!==void 0&&!Oa(l.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,l.textColor),l.borderColor!==void 0&&!Oa(l.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,l.borderColor))}/* @__PURE__ */
40
+ return Object.freeze(i)}var ja=/* @__PURE__ */new Set;function Fa(e){if(e.length===0)return;let t=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(ja.has(t))return;ja.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var Aa="#23272C",Da=4.5,Ma=.6,La=.9,Ba=.02,Ha="#FFFFFF",Ua="#111111";function Na(e){return contrastRatio(e,Aa)>=Da&&Math.max(contrastRatio(e,Ha),contrastRatio(e,Ua))>=Da}function deriveDarkVariant(e){let t=Yi(e);if(t===null)return null;let{h:r,s:n,l:l}=vo(t.r,t.g,t.b),i=Math.min(Math.max(l,Ma),La);for(let e=0;;e+=1){let t=i+e*Ba;if(t>La)break;let l=ko({h:r,s:n,l:t}),o=no(l.r,l.g,l.b);if(Na(o))return o}let o=ko({h:r,s:n,l:La});return no(o.r,o.g,o.b)}var $a=7,Wa=.05,Va="#000000",qa="#FFFFFF";function Ga(e,t,r,n){let l=go(e,t);if(l===null)return r;if(contrastRatio(l,t)>=n)return l;let i=Yi(l),o=Yi(r);if(i===null||o===null)return r;for(let e=1;e<1/Wa;e+=1){let r=e*Wa,l=(e,t)=>Math.round(e+(t-e)*r),a=no(l(i.r,o.r),l(i.g,o.g),l(i.b,o.b));if(contrastRatio(a,t)>=n)return a}return r}function Ka(e,t){let r=ha(e),n=r[0],l=Ya(n);for(let e of r){let r=Ya(e);(t?r>l:r<l)&&(n=e,l=r)}return n}function Ya(e){let t=Yi(e);return t===null?0:co(t)}function Qa(e,t){return go(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=uo(ha(t))===qa,n=r?qa:Va,l=Ka(t,r),i=e=>Ga(e,l,n,$a),o={...t,brandSoft:Qa(t.brandSoft,t.surface),brandSofter:Qa(t.brandSofter,t.surface),brandBorder:i(t.brandBorder),borderHairlineGreen:i(t.borderHairlineGreen),brandBorderStrong:i(t.brandBorderStrong),controlEdge:i(t.controlEdge),structureEdge:i(t.structureEdge),brandInk:i(t.brandInk),linkInk:i(t.linkInk),borderRingCream:i(t.borderRingCream),composerBorder:i(t.composerBorder),text:{primary:i(t.text.primary),secondary:i(t.text.secondary),muted:i(t.text.muted),placeholder:i(t.text.placeholder),onBrand:t.text.onBrand,metaCool:i(t.text.metaCool),timestamp:i(t.text.timestamp)},badgeBgPositive:Qa(t.badgeBgPositive,t.surface),badgeBgCaution:Qa(t.badgeBgCaution,t.surface),badgeBgCritical:Qa(t.badgeBgCritical,t.surface),badgeBgNeutral:Qa(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:Qa(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:Qa(t.checkupCardConcernBg,t.surface),info:i(t.info),infoEdge:i(t.infoEdge),badgeBgInfo:Qa(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var Ja=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),Xa=Ja.cream,Za=Ja.subtle,es=Ja.ring,ts=10;function rs(e,t,r){let n=Yi(e),l=Yi(t);if(n===null||l===null)return null;let i=(e,t)=>Math.round(e+(t-e)*r);return no(i(n.r,l.r),i(n.g,l.g),i(n.b,l.b))}function ns(e){if(e===null)return{};let t=uo([e]),r=rs(e,t,Xa),n=rs(e,t,Za),l=rs(e,t,es);return r===null||n===null||l===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:l}}function ls(e){if(e===null)return{};let t=Yi(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function is(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let l={};for(let[e,t]of Object.entries(r.type.size))l[e]=Math.max(ts,Math.round(t*n*10)/10);return l}function os(e,t,r){if(e===null)return t;let n=e/r.space.xs,l=e=>Math.round(e*n),i=r.space;return{xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),xxl:l(i.xxl)}}function as(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),l=t.radius;return{tile:n(l.tile),xs:n(l.xs),sm:n(l.sm),md:n(l.md),lg:n(l.lg),xl:n(l.xl),pill:l.pill}}var ss=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function us(e,t){let r=Yi(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function cs(e,t){if(e===null)return{};let r=us(e,t?ss.success.dark:ss.success.light),n=us(e,t?ss.successCard.dark:ss.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function ds(e,t){if(e===null)return{};let r=us(e,t?ss.warning.dark:ss.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function fs(e,t){if(e===null)return{};let r=us(e,t?ss.info.dark:ss.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function hs(e,t,r){if(e===null)return t;let n=r.type.lineHeight,l=e/n.normal;if(l===1)return n;let i=e=>Math.round(e*l*100)/100;return{tight:i(n.tight),snug:i(n.snug),normal:i(n.normal),relaxed:i(n.relaxed)}}function ps(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:ba(e),header:[e.surface,e.background,e.chatGround],banner:[go(e.badgeBgInfo,e.surface)??e.surface,go(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function gs(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function bs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ms=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),ys=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),vs=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function ks(e){return typeof e=="string"&&ms.includes(e.trim().toLowerCase())}function ws(e,t){let r=e[t];return r??void 0}var Cs=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>Cs)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var Ss=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],xs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],_s=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],Rs=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],Ts=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!bs(e))return null;let t=ks(e.theme)?ys[e.theme.trim().toLowerCase()]:{},r=bs(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let l={},i=ws(n,"colorScheme"),o=typeof i=="string"?i.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(l.color_scheme=o);let a=o==="dark"?"_dark":"";for(let[e,t]of Ss){let r=ws(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of xs){let r=ws(n,e);r!==void 0&&(l[`${t}${a}`]=r)}for(let[e,t]of Rs){let r=ws(n,e);typeof r=="string"&&r.trim().length>0&&(l[t]=r.trim())}for(let[e,t]of Ts){let r=parsePx(ws(n,e));r!==void 0&&(l[t]=r)}for(let[e,t]of _s){let r=ws(n,e);(typeof r=="number"||typeof r=="string")&&(l[t]=r)}let s=e.fonts;Array.isArray(s)&&s.length>0&&(l.font_sources=s);let u=e.rules;if(bs(u)){let e={};for(let t of Co){let r=u[t];bs(r)&&(e[t]=r)}Object.keys(e).length>0&&(l.slots=e)}return Object.keys(l).length===0?null:/* @__PURE__ */Object.freeze(l)}var Is="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function zs(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var Ps=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?zs(__EVERFUR_BRAND_CDN_ORIGIN__):Is;var Os=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),Es=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),js=Object.keys(Es),Fs="presentation",As="presentation.";function isPresentationLockName(e){if(e===Fs)return true;if(!e.startsWith(As))return false;let t=e.slice(As.length);return Object.values(Es).includes(t)}var Ds={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},Ms=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function Ls(e,t){if(t==null)return;let r=Ds[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:Ms.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of js){let n=Es[e],l=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],i=Ls(e,l);i!==void 0&&(r[e]=i)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${As}${Es[e]}`;for(let e of t)if(e===Fs||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,l=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},i=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,a={};for(let e of js){let t=l[e],r=isPresentationFieldLocked(e,o)?void 0:i[e];a[e]=r??t??Os[e]}/* @__PURE__ */
41
+ return Object.freeze(a)}var Bs=4,Hs=/* @__PURE__ */Object.freeze({min:1,max:2}),Us=100,Ns=2048,$s=["100","200","300","400","500","600","700","800","900"];function Ws(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim().length===0||e.length>16)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function Vs(e){let t=Ws(e);if(t===null)return null;let r=String(t);return $s.includes(r)?r:null}function qs(e){let t=Ws(e);return t===null?null:Math.min(Hs.max,Math.max(Hs.min,t))}function Gs(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Ns?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(t)?t:null}function Ks(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Us||/[\u0000-\u001F\u007F]/.test(t)?null:t}function Ys(e,...t){for(let r of t)if(e[r]!==void 0&&e[r]!==null)return e[r]}function Qs(e){if(!bs(e))return null;let t=Ks(e.family);if(t===null)return null;let r=Ys(e,"src"),n=Ys(e,"cssSrc","css_src");if(r===void 0==(n===void 0))return null;if(n!==void 0){let e=Gs(n);return e===null?null:/* @__PURE__ */Object.freeze({family:t,cssSrc:e})}let l=Gs(r);if(l===null)return null;let i={family:t,src:l},o=Vs(e.weight);o!==null&&(i.weight=o);let a=typeof e.style=="string"?e.style.trim().toLowerCase():null;return(a==="normal"||a==="italic")&&(i.style=a),/* @__PURE__ */Object.freeze(i)}function Js(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=Bs)break;let e=Qs(r);e!==null&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}var Xs=/* @__PURE__ */Object.freeze({size:/* @__PURE__ */Object.freeze({min:8,max:48}),letterSpacing:/* @__PURE__ */Object.freeze({min:-.1,max:.3}),typeScale:/* @__PURE__ */Object.freeze({min:.8,max:1.3})}),Zs=["content","heading","control","compact","badge"],eu=["sans","heading","mono"],tu=/* @__PURE__ */Object.freeze({min:1,max:3.1});function ru(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e.trim().replace(/px$/i,"")):Number.NaN;return Number.isFinite(t)?t:null}function nu(e,t){return Math.min(t.max,Math.max(t.min,e))}function lu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function iu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==void 0)return e[r]}function ou(e){let t=ru(e);return t===null?null:nu(t,Xs.typeScale)}function au(e){if(!lu(e))return null;let t={};for(let r of Zs){let n=ru(iu(e,r));n!==null&&(t[r]=n<=0?0:nu(n,tu))}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function su(e){if(!lu(e))return null;let t={},r=ru(iu(e,"size","fontSize","font_size"));r!==null&&(t.size=nu(r,Xs.size));let n=qs(iu(e,"lineHeight","line_height"));n!==null&&(t.lineHeight=n);let l=Vs(iu(e,"weight","fontWeight","font_weight"));l!==null&&(t.weight=l);let i=iu(e,"face");typeof i=="string"&&eu.includes(i.trim())&&(t.face=i.trim());let o=ru(iu(e,"letterSpacing","letter_spacing"));o!==null&&(t.letterSpacing=nu(o,Xs.letterSpacing));let a=iu(e,"uppercase");return typeof a=="boolean"&&(t.uppercase=a),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function uu(e){if(!lu(e))return null;let t={};for(let r of No){let n=su(iu(e,r));n!==null&&(t[r]=n)}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}var cu=e=>Math.round(e*10)/10,du=e=>Math.round(e*100)/100;function fu(e,t,r,n){if(t===null&&r===null&&n===null)return e;let l=t===null?null:t/$o.body.size,i=r===null?null:r/$o.body.lineHeight,o={};for(let t of No){let r=e[t],a=$o[t];o[t]=/* @__PURE__ */Object.freeze({...r,...l===null?{}:{size:cu(a.size*l)},...i===null?{}:{lineHeight:du(a.lineHeight*i)},...n?.[t]??{}})}/* @__PURE__ */
42
+ return Object.freeze(o)}function hu(e,t){let r=false,n={};for(let l of No){let i=e[l],o=t(i);o===1?n[l]=i:(r=true,n[l]=/* @__PURE__ */Object.freeze({...i,size:cu(i.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function pu(e,t,r){return{nano:cu(e.nano*r),small:cu(e.small*r),micro:cu(e.micro*r),tiny:cu(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:cu(e.verdict*r)}}var gu=/* @__PURE__ */Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),bu="slots.",mu=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}function isKnownBrandingSchema(e){let t=e?.schemaVersion??null;return t===null||mu.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
43
+ return new Set(["hide_powered_by",...e?.lockedFields??[]])}function yu(e){return e==="hide_powered_by"||gu.includes(e)||isPresentationLockName(e)?true:e.startsWith(bu)&&Co.includes(e.slice(bu.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=ku(t),n=expandAppearance(Su(t,"appearance")),l=n===null?r:vu(ku(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function vu(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function ku(e){return{displayName:xu(Su(e,"display_name","displayName")),logoUrl:xu(Su(e,"logo_url","logoUrl")),primaryColor:parseColor(Su(e,"primary_color","primaryColor")),accentColor:parseColor(Su(e,"accent_color","accentColor")),brightness:Pu(Su(e,"brightness","color_scheme","colorScheme")),fontFamily:xu(Su(e,"font_family","fontFamily")),fontUrl:xu(Su(e,"font_url","fontUrl")),fonts:Ru(Su(e,"fonts")),fontUrls:Ru(Su(e,"font_urls","fontUrls")),placeholder:xu(Su(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Cu(Su(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(Su(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(Su(e,"accent_color_dark","accentColorDark")),surfaceStyle:zu(Su(e,"surface_style","surfaceStyle"),Tu),radiusScale:zu(Su(e,"radius_scale","radiusScale"),Iu),logoUrlDark:xu(Su(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(Su(e,"slots")),accessibilityMaxFontScale:Fu(Su(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Mu(Su(e,"locked_fields","lockedFields")),presentation:parsePresentation(Su(e,"presentation")),schemaVersion:Au(Su(e,"schema_version","schemaVersion")),backgroundColor:parseColor(Su(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(Su(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(Su(e,"text_color","textColor")),textColorDark:parseColor(Su(e,"text_color_dark","textColorDark")),dangerColor:parseColor(Su(e,"danger_color","dangerColor")),dangerColorDark:parseColor(Su(e,"danger_color_dark","dangerColorDark")),fontSizeBase:wu(Su(e,"font_size_base","fontSizeBase"),vs.fontSizeBase),borderRadius:wu(Su(e,"border_radius","borderRadius"),vs.borderRadius),spacingUnit:wu(Su(e,"spacing_unit","spacingUnit"),vs.spacingUnit),successColor:parseColor(Su(e,"success_color","successColor")),successColorDark:parseColor(Su(e,"success_color_dark","successColorDark")),warningColor:parseColor(Su(e,"warning_color","warningColor")),warningColorDark:parseColor(Su(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(Su(e,"info_color","infoColor")),infoColorDark:parseColor(Su(e,"info_color_dark","infoColorDark")),headingFontFamily:xu(Su(e,"heading_font_family","headingFontFamily")),fontWeightBody:Vs(Su(e,"font_weight_body","fontWeightBody")),fontWeightHeading:Vs(Su(e,"font_weight_heading","fontWeightHeading")),lineHeight:qs(Su(e,"line_height","lineHeight")),fontSources:Js(Su(e,"font_sources","fontSources")),assistantAvatarUrl:xu(Su(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:au(Su(e,"text_scale_caps","textScaleCaps")),typeScale:ou(Su(e,"type_scale","typeScale")),typeRoles:uu(Su(e,"type_roles","typeRoles"))}}function wu(e,t){let r=Ou(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function Cu(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}function Su(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function xu(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var _u=["regular","medium","bold","mono","monoMedium","monoBold"];function Ru(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of _u){let n=xu(Su(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var Tu=["white","cream","subtle"],Iu=["sharp","default","round"];function zu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function Pu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Ou(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}var Eu=1,ju=3.1;function Fu(e){let t=Ou(e);return t===null?null:t<=0?0:Math.min(ju,Math.max(Eu,t))}function Au(e){if(e==null)return null;let t=Ou(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Du(e){let t=e.trim();return t.startsWith(bu)?t:t.startsWith(As)?As+t.slice(As.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Mu(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=Du(r);yu(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var Lu=/* @__PURE__ */new RegExp(`^${Ps}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&Lu.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?fa:ca:e,n=r.brightness==="dark"?fa:ca,l=r.brightness==="dark",i=l?t.primaryColorDark??$u(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??$u(t.accentColor):t.accentColor,a=i??r.color.primary,s=o??r.color.accent,u=i!==null&&qu(t,a,n,l),c=u?n.color.primary:a,d=i!==null&&!u?Yi(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?Gu(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=ns(p),b={...r.color,...g},m=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??$u(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...ls(y(t.dangerColor,t.dangerColorDark)),...cs(y(t.successColor,t.successColorDark),l),...ds(y(t.warningColor,t.warningColorDark),l),...fs(y(t.infoColor,t.infoColorDark),l),...m!==null?{text:{...h.text??r.color.text,primary:m}}:{},...Wu(t.surfaceStyle??null,b),primary:c,accent:s,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:os(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?as(t.borderRadius,n):Yu(t.radiusScale??null,r.radius,n),type:{...r.type,...Nu(r.type,t),size:is(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:hs(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:fu(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var Bu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Hu=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Uu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function Nu(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of _u){let a=Bu[e].map(e=>r[e]).find(e=>e!==void 0),s=Uu(e)?null:t.fontFamily;a!==void 0?(l[e]=a,i[e]=true):s!==null&&(l[e]=s,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:a!==void 0&&delete o[e]}for(let e of Hu)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function $u(e){return e===null?null:deriveDarkVariant(e)}function Wu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function Vu(e,t){return e==null?false:parseColor(e)===parseColor(t)}function qu(e,t,r,n){return Vu(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Vu(e.primaryColor,ca.color.primary)}function Gu(e,t){let r=e.color;return{text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}var Ku={sharp:.5,default:1,round:1.5};function Yu(e,t,r){if(e===null)return t;let n=Ku[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var Qu="Everfur",Ju=.5;function resolveTheme(e){return hc(Xu(e),e)}function themeAdjustments(e){let t=Xu(e);return Ea(t,hc(t,{...e,highContrast:false}))}function Xu(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=rc(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=lc((i==="auto"?l:i)==="dark"?fa:ca,e?.typeProfile),a=withServerBranding(o,nc(r));return withServerBranding(a,nc(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Zu(e){return e==="placeholder"?"chat_placeholder":Du(e)}var ec={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function tc(e,t){return t.has(Zu(e))?true:(ec[e]??[]).some(e=>t.has(e))}function rc(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(tc(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of Co){let n=l[r];n!==void 0&&(t.has(`${bu}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function nc(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function lc(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:qo}})}function ic(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function oc(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Ju,e)}var ac=["content","heading","control","compact","badge"];function sc(e,t){let r={};for(let n of ac){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:Vo[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return ac.every(e=>r[e]===Vo[e])?Vo:r}function uc(e,t){return t>0?Math.min(e,t):e}function cc(e,t,r,n){let l={};for(let i of ac)l[i]=n?ic(e,uc(t,r[i])):e;return l}function dc(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function fc(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return{family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces,headingFamily:e.headingFamily};let l=e.headingFamily!==null&&r!==void 0&&dc(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of _u)!(i[e]===ea||i[e]===ta)&&r!==void 0&&dc(r,i[e])===false&&(i[e]=Uu(e)?ta:ea,o[e]=false),n!==null&&Uu(e)&&i[e]===ta&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function hc(e,t){let r=e.meta.displayName.trim().length===0?Qu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of _u){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.regular??null,o=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,a=Number.isFinite(e.type.maxScale)?e.type.maxScale:Zo,s=oc(t?.textScale),u=sc(e.type.scaleCaps,a),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=hu(e.type.roles,()=>d),h=c?hu(f,e=>uc(s,u[e.tier])):f,p=t?.typeProfile==="phone"?pu(e.type.size,f,d):ic(e.type.size,d),g=cc(p,s,u,c),b=Ca(e),m={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:b,space:e.space,radius:e.radius,type:{...e.type,...fc(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:s,maxScale:a,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,ps(b),gs(b))};return t?.highContrast===true?deriveHighContrast(deepFreeze(m)):deepFreeze(m)}var pc="/widget/v1/entitlements",gc=304,bc=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",yc(t));return n.ok?vc(n.value):n.error.httpStatus===gc?bc:{kind:"failed",error:n.error}}var mc=64;function yc(e){let t={};return _c(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=mc?{method:"GET",path:pc,headers:t,query:{region:e.region}}:{method:"GET",path:pc,headers:t}}function vc(e){if(e===null||typeof e!="object"||!_c(e.revision))return xc();let t=typeof e.region=="string"?e.region:"",r=_c(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
44
+ return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Cc(e.capabilities),branding:wc(e),livemode:e.livemode!==false,...kc(e)})}function kc(e){let t=e.render_hints,r=e.sms_profile_public??(t!==null&&typeof t=="object"?t.sms_profile_public:void 0);return r!==null&&typeof r=="object"?{smsProfilePublic:r}:{}}function wc(e){let t=parseClientBranding(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let e=parseClientBranding(r.branding);return e!==null?e:parseClientBranding(r)}return null}function Cc(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Sc(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
45
+ return Object.freeze(t)}function Sc(e){return typeof e=="object"&&e!==null&&e.enabled===true}function xc(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function _c(e){return typeof e=="number"&&Number.isFinite(e)}var Rc=30;function createEntitlementPoller(e){let t=e.scheduler??Tc,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??Rc),l=e.rng??Math.random,i=()=>n+l()*n,o=false,a=false,s=null,u=null,c=n,d=0,f=()=>{s!==null&&(t.clear(s),s=null)},h=e=>{a||!o||(c=Math.max(n,e),s=t.set(()=>{s=null,b()},c*1e3))},p=null,g=async()=>{if(a)return null;let t=d;e.onFetch?.();let n=e.region?{cachedRevision:u,region:e.region}:{cachedRevision:u},l;try{l=await r(e.authFor(),n)}catch(r){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Ic(r)}),!a&&t===d&&(e.onSettled?.(),h(i())),null}if(a||t!==d)return null;switch(l.kind){case"updated":u=l.revision,l.smsProfilePublic!==void 0?e.update(l.decisions,l.branding??null,l.livemode!==false,l.smsProfilePublic):e.update(l.decisions,l.branding??null,l.livemode!==false),h(l.ttlSeconds);break;case"notModified":h(c);break;case"failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:l.error.code}),h(i());break;default:h(i())}return e.onSettled?.(),l},b=()=>{let e=g().finally(()=>{p===e&&(p=null)});return p=e,e};return{start(){o||a||(o=true,b())},prime(){return a?Promise.resolve(null):p??b()},stop(){a||(a=true,d++,f())},refresh(){a||!o||(d++,u=null,f(),b())}}}var Tc={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function Ic(e){return e instanceof Error?e.message:"poll failed"}var zc=20;function Pc(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map,n=e=>{let t=e??"",n=r.get(t);return n===void 0&&(n=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:e}),r.set(t,n)),n},l=/* @__PURE__ */new Map,i=/* @__PURE__ */new Set,o=0,a=/* @__PURE__ */new Map,s=(r,l)=>{let o=r??"",a=t.get(o)??n(r);if(!(a.hasUnread===l.hasUnread&&a.unreadCount===l.unreadCount&&a.conversationId===l.conversationId)){t.set(o,l);for(let e of[...i])e();i.size>0&&l.hasUnread!==null&&l.unreadCount!==null&&e.emit({type:"unread_changed",petRef:r,conversationId:l.conversationId,unreadCount:l.unreadCount,hasUnread:l.hasUnread})}},u=(e,t)=>{a.set(e??"",t);let r=0,n=null;for(let e of t){let t=e.unreadCount??0;r+=t,t>0&&n===null&&(n=e.id)}s(e,/* @__PURE__ */Object.freeze({hasUnread:r>0,unreadCount:r,conversationId:n??t[0]?.id??null,petRef:e}))},c=(e,t,r)=>{if(t.some(e=>e.unreadCount===null)){a.delete(e??""),s(e,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:t[0]?.id??null,petRef:e}));return}let n=t.slice(0,zc).map(e=>/* @__PURE__ */Object.freeze({id:e.id,unreadCount:e.unreadCount}));if(r||n.length===0){u(e,n);return}let l=new Set(n.map(e=>e.id)),i=(a.get(e??"")??[]).filter(e=>!l.has(e.id));u(e,[...n,...i].slice(0,zc))};return{subscribe(e){return i.add(e),()=>{i.delete(e)}},get(e){return t.get(e??"")??n(e)},refresh(t){let r=t??"",n=l.get(r);if(n!==void 0)return n;let i=e.read(t);if(i===null)return Promise.resolve();let a=o,s=i.then(e=>{a!==o||!e.ok||c(t,e.value.conversations,true)},()=>{}).finally(()=>{l.get(r)===s&&l.delete(r)});return l.set(r,s),s},reportPage(e,t){c(e,t,false)},reportHead(e,t){c(e,t===null?[]:[t],false)},reportRead(e){for(let r of[...t.values()]){let t=a.get(r.petRef??"");t===void 0||!t.some(t=>t.id===e&&(t.unreadCount??0)>0)||u(r.petRef,t.map(t=>t.id===e?/* @__PURE__ */Object.freeze({id:t.id,unreadCount:0}):t))}},reset(){if(o+=1,l.clear(),a.clear(),t.size!==0){t.clear();for(let e of[...i])e()}}}}function Oc(e,t,r){let n=An({...t===null?{}:{petRef:t},limit:zc},100);return n.ok?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${n.value}`},{maxAttempts:1}).then(e=>e.ok?Hn(e.value):err(e.error)):Promise.resolve(err(n.error))}var Ec="everfur.notifications.device";var jc="everfur.slots.v2",Fc="everfur.slots.installId.v2";var Ac=3e3,Dc=/* @__PURE__ */Object.freeze([Ec,jc,Fc]);function Mc(e){let{leaving:t,identity:r,hooks:n,telemetry:l}=e;if(t===null||r===null||n.size===0)return null;let i=/* @__PURE__ */Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),o=[...n].map(e=>{try{return Promise.resolve(e(i))}catch(e){return Promise.reject(e)}}),a=(e,t)=>{try{l.track("sdk.logout.hookFailed",{reason:e,count:t,totalCount:o.length})}catch{}},s=Promise.allSettled(o).then(e=>{let t=e.filter(e=>e.status==="rejected").length;t>0&&a("failed",t)});return new Promise(e=>{let t=false,r=()=>{t||(t=true,clearTimeout(n),e())},n=setTimeout(()=>{t||a("timeout",o.length),r()},Ac);s.then(r,r)})}function Lc(e){let{leaving:t,identity:r,transport:n,sessionId:l}=e,i=r.currentToken();i.catch(()=>{});let o={userRef:t.userRef,currentToken:()=>i,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:n,identity:o,userRef:t.userRef,sessionId:l}}async function Bc(e,t){if(Dc.length===0)return;let r=await Promise.allSettled(Dc.map(t=>e.removeItem(t))),n=r.filter(e=>e.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length})}function Hc(){/* @__PURE__ */
46
+ return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function Uc(e=Hc){let t=/* @__PURE__ */new Set,r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:null}),n=()=>{for(let e of t)e()};return{subscribe(e){return t.add(e),()=>{t.delete(e)}},getSnapshot(){return r},set(e){r=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...e.decisions]),isPending:e.isPending,branding:e.branding??null,...e.livemode===false?{livemode:false}:{},...e.smsProfilePublic!==void 0&&e.smsProfilePublic!==null?{smsProfilePublic:e.smsProfilePublic}:{}}),n()},reset(t){r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:t?.keepBranding===true?r.branding??null:null,...t?.keepBranding===true&&r.smsProfilePublic!==void 0?{smsProfilePublic:r.smsProfilePublic}:{}}),n()},setPending(e){r.isPending!==e&&(r=/* @__PURE__ */Object.freeze({...r,isPending:e}),n())}}}var Nc="everfur.branding.v1.";function $c(e){let t=[];for(let r of e){let e=r.codePointAt(0);e<128?t.push(e):e<2048?t.push(192|e>>6,128|e&63):e<65536?t.push(224|e>>12,128|e>>6&63,128|e&63):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63)}return t}function Wc(e){let t=3421674724,r=2216829733;for(let n of $c(e)){r=(r^n)>>>0;let e=r*435,l=Math.floor(e/4294967296),i=e>>>0;t=t*435+l+r*256>>>0,r=i}return t.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")}function Vc(e){return`${Nc}${Wc(e)}`}function qc(e){return e?JSON.stringify(e):null}async function Gc(e,t){try{let r=await e.getItem(Vc(t));if(r===null)return null;let n=parseClientBranding(JSON.parse(r));return n===null?null:/* @__PURE__ */Object.freeze({...n,logoUrl:hardenBrandAssetUrl(n.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(n.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(n.assistantAvatarUrl??null)})}catch{return null}}async function Kc(e,t,r){try{r===null?await e.removeItem(Vc(t)):await e.setItem(Vc(t),r)}catch{}}function Yc(e,t){let r;return{restore(r){Gc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let l=qc(n);l!==r&&(r=l,Kc(e,t,l))}}}function Qc(){let e=null,t=/* @__PURE__ */new Set;return{get:()=>e,subscribe(e){return t.add(e),()=>{t.delete(e)}},set(r){if(r!==e){e=r;for(let e of[...t])try{e()}catch{}}}}}function Jc(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:Qc(),store:null,disposed:false}}function Xc(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function Zc(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{},...e.appVersion!==void 0?{appVersion:e.appVersion}:{}};return tryResolveClientConfig(r,t===void 0?void 0:{platform:t})}function ed(e,t){/* @__PURE__ */
47
+ return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:td(r,n,t))}catch{}}})}function td(e,t,r){let n=e.indexOf("."),l=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",i=typeof t?.requestId=="string"?t.requestId:null;return{...It(r,l,i),...t}}function rd(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(l,i)=>n.call(e,l,i??It(t,r,l.requestId))}:{}}}var nd=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${At} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function ld(e,t,r=jt){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+nd[r])}function id(e){/* @__PURE__ */
48
+ return Object.freeze({request(){return Promise.resolve(err(Xc(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return async function*(){r.aborted||(yield n)}()}})}var od=/* @__PURE__ */new WeakSet;function ad(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return od.add(t),t}var sd=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new cd(e,t)}var ud=6e4,cd=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new J("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:Et,platform:t?.platform??jt,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Ot(r?.appVersion)}),this.telemetry=r.telemetry?ed(r.telemetry,this.errorContext):$e,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=id(l);else if(r.transport!==void 0)o=r.transport;else{let e=Zc(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=id(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Hi(this,this.mintScope),this.transport=o,l!==null&&(ld(l,this.telemetry,t?.platform),this.emit({type:"error",code:Xc(l).code,requestId:null,context:It(this.errorContext,"runtime",null)})),this.errorPolicy=rd(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??Ve,this.upload=r.upload??Qr,this.uploadTransport=r.uploadTransport??hl,this.imageCache=r.imageCache??sd,this.kv=r.storage??ad(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Uc():Uc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",dd(e),()=>this.buildChatController(e),fd),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${dd(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=Pc({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Oc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Yc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?Jc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=Ki(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-ud,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Di(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&qc(l)===qc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:rd(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await Bc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return Mc({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>Lc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>Ni(Ui(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(hd(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&qi(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?hd("prepare"):r===null?null:Xc(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(et(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}if(s==="ready")this.emit({type:"ready"});else if(s==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:It(this.errorContext,"runtime",e)})}/* @__PURE__ */
49
+ return Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",dd(t),()=>this.buildChatController(t),fd,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function dd(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function fd(e){e.dispose()}function hd(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function pd(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function gd(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function bd(e){return e.ok?e:err(gd(e.error))}function md(e){return{send:async(...t)=>bd(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var yd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),vd=globalThis,kd=vd[yd]??(vd[yd]=createContext(null));kd.displayName??="EverfurContext";function wd(){let e=o(kd);if(e===null)throw new J("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return wd().handle}var Cd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Sd=globalThis,xd=Sd[Cd]??(Sd[Cd]=createContext(ca));xd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(xd)}var _d=()=>()=>{},Rd=()=>null;function Td(e,t){return i(t?.subscribe??_d,t?.get??Rd,t?.get??Rd)??e}function EverfurThemeProviderCore(e){let{runtime:t}=wd(),l=t.entitlements,o=i(l.subscribe,l.getSnapshot,l.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),c=e.seams.useTextScale(),d=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,h=e.seams.typeProfile,p=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,b=e.clientTheme?Id(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=Td(o.branding??null,t.sdkConfigHost?.branding),v=a(()=>resolveTheme({branding:y,clientOverride:m,colorScheme:s,reducedMotion:u,textScale:c,scaleTypeSizes:f,highContrast:d,...h===void 0?{}:{typeProfile:h},...p===void 0?{}:{platformMonoFamily:p},...g===void 0?{}:{isFontRegistered:g}}),[y,m,s,u,c,f,h,d,p,g]);e.seams.useResolvedTheme?.(v);let k=e.seams.isDevelopment;return n(()=>{k===void 0||!zd(k)||Fa(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(xd.Provider,{value:v},e.children)}function Id(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function zd(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:l,activePet:i,theme:o,warmUp:s,children:u,seams:h}=e,p=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=c(null),b=c(null),m=c(t?.onEvent);m.current=t?.onEvent;let y=c(e=>{m.current?.(e)}),[v,k]=d(e=>e+1,0),w=c(null),C=c(void 0),S=l?.userRef??null;C.current!==S&&(C.current!==void 0&&(w.current=null),C.current=S);let x=w.current!==null?w.current.user:l??null,_=c(null),R=c(void 0),T=i??null;R.current!==T&&(R.current!==void 0&&(_.current=null),R.current=T);let I=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==p||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(b.current=g.current.runtime),g.current={key:p,runtime:createEverfurRuntime({config:Pd(h.withDefaults?h.withDefaults(t):t,y.current),user:x,activePet:I,theme:o??null},{platform:h.platform,...h.eventSourceFactory?{eventSourceFactory:h.eventSourceFactory}:{}})});let z=g.current.runtime,P=c(null);n(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||P.current!==e&&(P.current=e,k())}),n(()=>{let e=b.current;e!==null&&(b.current=null,e.dispose())});let O=x?.userRef??null;f(()=>{z.setUser(x)},[z,O]),f(()=>{z.setActivePet(I)},[z,I]);let E=c(null);n(()=>(E.current===z&&(E.current=null),()=>{E.current=z,Od(()=>{E.current===z&&(E.current=null,z.dispose())})}),[z]),n(()=>{s==="onMount"&&z.prepare(I===null?{}:{petRef:I})},[z,s,O,I]);let j=a(()=>({setUser:e=>{w.current={user:e},z.setUser(e),k()},setActivePet:e=>{_.current={pet:e},z.setActivePet(e),k()},open:e=>z.open(e),prepare:e=>z.prepare(e),registerPet:(e,t)=>z.registerPet(e,t),updatePet:(e,t)=>z.updatePet(e,t),deletePet:e=>z.deletePet(e),eraseUserData:()=>z.eraseUserData(),logout:()=>{w.current={user:null};let e=z.logout();return k(),e}}),[z,k]),F=a(()=>({runtime:z,handle:j,userRef:O,activePet:I,scopeEpoch:z.scopeEpoch,publishableKey:Ed(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:u});return r(kd.Provider,{value:F},h.wrap?h.wrap(A):A)}function Pd(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Od(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Ed(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var jd=2;function Fd(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<jd)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function Ad(){let e=N;return(t,r)=>{let n=globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]?.tap?.(t,r),l=new e(t,{method:r.method,headers:n?{...r.headers,...n.headers}:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return n?.watch(l),Object.assign(l,{getResponseHeader:e=>Fd(l,e)})}}function Dd(){let e=w();return e==="dark"?"dark":e==="light"?"light":null}function Md(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Ld(){let[e,t]=l(false);return n(()=>{let e=true,r=k?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(k);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=k?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Bd(){let e=S?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(S);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function Hd(e){let t=C?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(C,"change",e);return()=>r?.remove?.()}function Ud(){return i(Hd,Bd,Bd)}function Nd(){try{let e=m?.OS;return typeof e=="string"?e:null}catch{return null}}function $d(){return Nd()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function Wd(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=$d(),l=k?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(k);Md(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=k?.addEventListener,o=typeof i=="function"?i.call(k,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function Vd(){return Nd()==="ios"?"Menlo":ta}function qd(){return globalThis.__DEV__!==false}var Gd=/* @__PURE__ */new Set;function Kd(e){if(!qd()||Gd.has(e))return;Gd.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function Yd(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t)}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let l=n.includes(e);return l||Kd(e),l}var Qd=/* @__PURE__ */new Set;function Jd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var Xd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Zd(e){if(!qd())return;let t=Jd(e).filter(e=>!Qd.has(e));if(t.length===0)return;for(let e of t)Qd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Xd[e]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function ef(e){n(()=>{try{Zd(e)}catch{}},[e])}var tf=/* @__PURE__ */Object.freeze({useColorScheme:Dd,useReducedMotion:Ld,useTextScale:Ud,useHighContrast:Wd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:Vd,isFontRegistered:Yd,useResolvedTheme:ef,isDevelopment:qd});function rf(e){return r(H,null,e)}var nf=/* @__PURE__ */Object.freeze({platform:"react-native",...m.OS==="web"?{}:{eventSourceFactory:Ad()},wrap:rf,theme:tf});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:nf})}function useCapability(e){let{runtime:t}=wd(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function lf(e){let{runtime:t}=wd(),r=t.entitlements,n=u(e=>r===void 0?()=>{}:r.subscribe(e),[r]),l=u(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return i(n,l,l)}var of=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[of[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[of[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function af(e){return e<=450?"regular":e<=650?"medium":"bold"}var sf={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=uf.get(e);r===void 0&&(r=/* @__PURE__ */new Map,uf.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=cf(e,t);return r.set(t,l),l}var uf=/* @__PURE__ */new WeakMap;function cf(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=af(Number(n)),i=r.face==="mono"?face(e,sf[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,a=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},s=r.size,u={...a,fontSize:s,lineHeight:Math.round(s*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(s*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function df(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:t,...n}){let l=useEverfurTheme(),i=t===void 0?void 0:l.type.roles[t],o=df(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(R,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var ff=t(function(e,t){return r(y,{...e,...t===null?{}:{ref:t}})});var hf=class extends h{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:t,resetKey:n}){return r(hf,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var pf=48;function gf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:l,style:i}=e,o=useCapability(t),s=a(()=>gf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */$(HostRender,{render:l,fallback:/* @__PURE__ */$(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */$(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */$(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */$(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */$(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>bf(r),[r]);/* @__PURE__ */
50
+ return $(x,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */$(x,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>bf(r),[r]),l=e.disabled?.reason??"";/* @__PURE__ */
51
+ return $(x,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:l,children:l.length>0?/* @__PURE__ */$(Text,{style:n.offstateText,children:l}):null})}function bf(e){let{color:t,space:r,radius:n,type:l}=e;return v.create({offstate:{minHeight:pf,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:v.hairlineWidth,borderColor:t.brandBorder},offstateText:{...face(e,"regular"),fontSize:l.size.body,lineHeight:Math.round(l.size.body*l.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}var mf=createContext(null);function TelevetHostOutlet(){let e=o(mf);return e===null?null:/* @__PURE__ */$(e,{})}var yf=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function vf(){let e=globalThis,t=e[yf];if(t!==void 0)return t;let r={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return e[yf]=r,r}function kf(e){let t=vf();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function wf(e){let t=vf().presenter;if(t===null)return"absent";try{return t(e)===!1?"declined":"presented"}catch(e){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",e),"threw"}}function Cf(e){let t=vf();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function Sf(){return vf().snapshot}function xf(){return vf().hosts.length>0}function _f(e){if(!xf())return false;let t=/* @__PURE__ */Object.freeze({...e});return kf({request:t,serial:vf().snapshot.serial+1}),true}function Rf(){vf().snapshot.request!==null&&kf({request:null})}function Tf(){let e=vf(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],kf({activeHost:e.hosts[0]??null}),t}function If(e){let t=vf();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;kf(r===null?{activeHost:r,request:null}:{activeHost:r})}function zf(e){let t=null;return()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null)}),r}}function Pf(e){let[t,r]=l(null);n(()=>{let e=Tf();return r(e),()=>{If(e)}},[]);let o=i(Cf,Sf,Sf),a=t!==null&&o.activeHost===t?o.request:null,[s,u]=l(null),c=a!==null&&s===null;return n(()=>{if(!c)return;let t=true;return e().then(e=>{t&&u(()=>e)},e=>{t&&(console.warn("[everfur] The in-app vet visit could not load its screens.",e),Rf())}),()=>{t=false}},[c,e]),a===null||s===null?null:{module:s,request:a,serial:o.serial,dismiss:Rf}}var Of=zf(()=>Promise.resolve(q));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let l=Pf(Of);if(l===null)return null;let{EverfurTelevetModal:i}=l.module;/* @__PURE__ */
52
+ return $(i,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var Ef=640,jf=600,Ff=/* @__PURE__ */Object.freeze({width:0,height:0}),Af="useWindowDimensions"in b&&typeof b.useWindowDimensions=="function"?b.useWindowDimensions:()=>Ff,Df=/* @__PURE__ */Object.freeze({width:"100%",maxWidth:Ef,alignSelf:"center"});/* @__PURE__ */Object.freeze({...Df,flex:1});var Mf=/* @__PURE__ */Object.freeze({...Df,flexGrow:1,flexShrink:1});function Lf(){return Af().width>=jf}function Bf(e="flow"){let{width:t}=Af();if(t<jf)return null;if(e==="flow")return Df;let r=Math.max(0,Math.round((t-Ef)/2));return{left:r,right:r}}function Hf(e,t){return t===null?e:[e,t]}var Uf=/* @__PURE__ */Symbol.for("@everfur/sdk#InSdkColumn@v1"),Nf=globalThis,$f=Nf[Uf]??(Nf[Uf]=createContext(false));$f.displayName??="EverfurInSdkColumn";function SdkTabletColumn({children:e,style:t,testID:r}){let n=Lf(),l=o($f);return!n||l?e:/* @__PURE__ */$(x,{style:t===void 0?Mf:[Mf,t],testID:r??"everfur-tablet-column",children:/* @__PURE__ */$($f.Provider,{value:true,children:e})})}var Wf="Go to the nearest emergency vet now.";var Vf=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",sourcesHeading:"Sources",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:Wf,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",capReached:"You've used your {cap} free messages this month.",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function qf(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function Gf(e){return e?.trim()||Vf.emptyTitlePetFallback}function Kf(e,t){return qf(e,{petName:Gf(t)})}var Yf="tel:+18884264435";var Qf=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function Jf(e){let t=Qf(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var Xf=6;function Zf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function eh(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let l of e){if(n.length>=r)break;if(l===null||typeof l!="object"||Array.isArray(l))continue;let e=t(l);e!==null&&n.push(e)}/* @__PURE__ */
53
+ return Object.freeze(n)}function th(e){let t=Qf(e.title,80),r=Qf(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function rh(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=[];if(Array.isArray(t.gallery))for(let e of t.gallery){let t=Jf(e);t!==null&&r.length<Xf&&r.push(t)}let n=eh(t.doses,e=>{let t=Qf(e.label,60),r=Qf(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:Zf(e.minLb??e.min_lb),maxLb:Zf(e.maxLb??e.max_lb)})},Xf),l=eh(t.details,th,Xf),i=t.fit,o=i!==null&&typeof i=="object"&&!Array.isArray(i)?th(i):null,a=o!==null&&i.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,s=/* @__PURE__ */Object.freeze({kicker:Qf(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:l,fine:Qf(t.fine,300),fit:a});return s.kicker===null&&r.length===0&&n.length===0&&l.length===0&&s.fine===null&&a===null?void 0:s}var nh=128;var lh=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),ih=/* @__PURE__ */new Set(["y","c","g","r"]),oh=/* @__PURE__ */new Set(["done","now","next"]),ah=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,sh=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,uh=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,ch=e=>typeof e=="string"&&lh.has(e)?e:null;function dh(e){let t=sh(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var fh=e=>typeof e=="number"&&Number.isInteger(e)?String(e):sh(e,nh);function hh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function ph(e){/* @__PURE__ */
54
+ return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function gh(e,t,r=20){if(!Array.isArray(e))return null;let n=[];for(let l of e){if(n.length>=r)break;let e=t(l);e!==null&&n.push(e)}return n.length===0?null:/* @__PURE__ */Object.freeze(n)}var bh=(e,t=12,r=300)=>gh(e,e=>sh(e,r),t);function mh(e){let t=ah(e),r=sh(t?.kicker,120),n=sh(t?.title,300);if(t===null||r===null||n===null)return null;let l=ah(t.risk),i=ah(t.odds),o=ah(t.quote),a=ah(t.jump);return ph({kicker:r,title:n,sources:gh(t.sources,e=>{let t=sh(ah(e)?.label,60);return t===null?null:ph({label:t,kind:uh(ah(e)?.kind)})},6),risk:sh(l?.lead,300)===null?null:ph({lead:sh(l?.lead,300),body:sh(l?.body),kind:uh(l?.kind)}),odds:sh(i?.label,120)===null||sh(i?.from,20)===null||sh(i?.to,20)===null?null:ph({label:sh(i?.label,120),tag:sh(i?.tag,40),from:sh(i?.from,20),to:sh(i?.to,20),toLabel:sh(i?.toLabel,120)}),quote:sh(o?.text)===null?null:ph({kicker:sh(o?.kicker,120),tag:sh(o?.tag,40),text:sh(o?.text)}),jump:sh(a?.title,300)===null||sh(a?.go,60)===null?null:ph({title:sh(a?.title,300),go:sh(a?.go,60)}),report:yh(t.report)})}function yh(e){let t=ah(e),r=sh(t?.label,120),n=sh(t?.text,1200);return r===null||n===null?null:ph({label:r,text:n,actions:bh(t?.actions,5,300)})}function vh(e){let t=ah(e),r=sh(t?.title,300),n=gh(t?.steps,e=>{let t=ah(e),r=sh(t?.title,300),n=t?.tone;return r===null?null:ph({title:r,body:sh(t?.body),source:sh(t?.source,200),tone:typeof n=="string"&&ih.has(n)?n:null,icon:ch(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:ph({title:r,label:sh(t?.label,60),steps:n})}function kh(e){let t=ah(e),r=sh(t?.title,300);if(t===null||r===null)return null;let n=ah(t.rating),l=ah(t.reviews),i=ah(t.why),o=ah(i?.score),a=ah(t.dose),s=ah(t.ingredients),u=gh(l?.items,e=>{let t=ah(e),r=t?.stars,n=sh(t?.text),l=sh(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||l===null?null:ph({stars:Math.round(r),text:n,by:l})},5),c=gh(i?.rows,e=>{let t=ah(e),r=sh(t?.chip,40),n=sh(t?.title,300);return r===null||n===null?null:ph({chip:r,kind:uh(t?.kind),title:n,body:sh(t?.body)})}),d=gh(a?.stats,e=>{let t=ah(e),r=sh(t?.value,40),n=sh(t?.label,120),l=t?.kind;return r===null||n===null?null:ph({value:r,label:n,kind:l==="weight"||l==="dose"||l==="days"?l:null})},6),f=bh(s?.items,12,80);return ph({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:fh(t.productId),partnerSku:sh(t.partnerSku,200),rating:sh(n?.value,20)===null?null:ph({value:sh(n?.value,20),label:sh(n?.label,120)}),line:sh(t.line),reviews:sh(l?.label,200)===null||u===null?null:ph({label:sh(l?.label,200),items:u}),checkoutLine:sh(t.checkoutLine,300),why:sh(i?.title,200)===null||c===null?null:ph({title:sh(i?.title,200),rows:c,score:sh(o?.text,200)===null||sh(o?.value,20)===null?null:ph({text:sh(o?.text,200),value:sh(o?.value,20)})}),dose:sh(a?.title,200)===null||d===null?null:ph({title:sh(a?.title,200),stats:d,note:sh(a?.note)}),doseLabel:sh(t.doseLabel,120),ingredients:f===null?null:ph({label:sh(s?.label,200),items:f}),proof:sh(t.proof,300),trust:gh(t.trust,e=>{let t=ah(e),r=ch(t?.icon),n=sh(t?.label,120);return r===null||n===null?null:ph({icon:r,label:n})},6),more:sh(t.more,120),fine:sh(t.fine),checkin:sh(t.checkin,200),detail:rh(t.detail)??null})}function wh(e){let t=ah(e),r=sh(t?.title,200),n=gh(t?.items,e=>{let t=ah(e),r=sh(t?.title,300),n=sh(t?.body);return r===null||n===null?null:ph({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:ph({title:r,items:n})}function Ch(e){let t=ah(e),r=sh(t?.title,200),n=bh(t?.questions,12,300),l=sh(t?.add,80),i=sh(t?.added,80);return r===null||n===null||l===null||i===null?null:ph({title:r,questions:n,add:l,added:i})}function Sh(e){let t=ah(e),r=sh(t?.title,200),n=gh(t?.items,e=>{let t=ah(e),r=sh(t?.key,nh),n=sh(t?.title,300),l=sh(t?.action,80),i=fh(t?.productId),o=sh(t?.added,80)??(i!==null?l:null);return r===null||n===null||l===null||o===null?null:ph({key:r,productId:i,title:n,body:sh(t?.body),price:sh(t?.price,40),was:sh(t?.was,40),tag:sh(t?.tag,40),imageUrl:dh(t?.imageUrl),icon:ch(t?.icon),kind:uh(t?.kind),action:l,added:o,owned:t?.owned===true?true:null,detail:rh(t?.detail)??null})},6);return r===null||n===null?null:ph({title:r,items:n})}function xh(e){let t=ah(e),r=sh(t?.kicker,120),n=sh(t?.title,120);return t===null||r===null||n===null?null:ph({kicker:r,title:n,icon:ch(t.icon),track:gh(t.track,e=>{let t=ah(e),r=sh(t?.title,120),n=t?.state;return r===null?null:ph({title:r,detail:sh(t?.detail,120),state:typeof n=="string"&&oh.has(n)?n:null,tag:sh(t?.tag,40)})},6),heading:sh(t.heading,200),rows:gh(t.rows,e=>{let t=ah(e),r=ch(t?.icon),n=sh(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return ph({icon:r,label:n,text:"",fromVet:true});let l=sh(t?.text,300);return l===null?null:ph({icon:r,label:n,text:l})},6),note:sh(t.note,300),action:sh(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=ah(e),r=sh(t?.title,300),n=kh(t?.pick);if(t===null||r===null||n===null)return null;let l=ah(t.byline);return ph({eyebrow:sh(t.eyebrow,120),title:r,subtitle:sh(t.subtitle,300),subtitleNoRecords:sh(t.subtitleNoRecords,300),headImageUrl:dh(t.headImageUrl),byline:sh(l?.name,120)===null?null:ph({name:sh(l?.name,120),role:sh(l?.role,120),imageUrl:dh(l?.imageUrl),shortName:sh(l?.shortName,60)}),focus:mh(t.focus),routine:vh(t.routine),pick:n,signs:wh(t.signs),checkup:Ch(t.checkup),extras:Sh(t.extras),wait:xh(t.wait),fine:sh(t.fine),checkoutRows:gh(t.checkoutRows,e=>{let t=ah(e),r=ch(t?.icon),n=sh(t?.label,60),l=sh(t?.value,200);return r===null||n===null||l===null?null:ph({icon:r,label:n,value:l})},6)})}function healthPlanPageFromWire(e,t){let r=ah(e);if(r===null||!("page"in r))return null;let n=ah(r.pet),l=n?.sex;/* @__PURE__ */
55
+ return Object.freeze({petRef:sh(r.pet_ref,nh)??t,pet:/* @__PURE__ */Object.freeze({name:sh(n?.name,120),species:sh(n?.species,60),sex:l==="female"||l==="male"?l:null,breed:sh(n?.breed,120),weightKg:hh(n?.weight_kg),weightLb:hh(n?.weight_lb)}),checkout:r.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(r.page),vetReviewed:r.vet_reviewed===true,trackingTextsEnabled:r.tracking_texts_enabled===true})}function _h(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function Rh(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function Th(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}var Ih=e=>typeof e=="string"&&e.length>0&&e.length<=nh;function zh(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function Ph(e,t,r){if(!Ih(t))return err(_h("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${zh(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let l=healthPlanPageFromWire(n.value,t);return l===null?err(Rh("healthPlan.page.read")):ok(l)}var Oh=/* @__PURE__ */new WeakMap;function Eh(e){let t=Oh.get(e);if(t!==void 0)return t;let r=jh(e);return Oh.set(e,r),r}function jh(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(Th("getPage")));let{services:n}=e.registry,l=md(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return Ph(l,t,r)}}}function Fh(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function Ah(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Dh(e,...t){if(typeof e=="function")try{let r=e(...t);return Ah(r)&&Promise.resolve(r).then(void 0,Fh),r}catch(e){Fh(e);return}}var Mh=/* @__PURE__ */new WeakMap;function Lh(e){if(typeof e!="function")return;let t=Mh.get(e);if(t!==void 0)return t;let r=(...t)=>{Dh(e,...t)};return Mh.set(e,r),r}function Bh(e,...t){let r;try{r=e(...t)}catch(e){return Fh(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var Hh=6e4;function Uh({lifecycle:e,refreshKey:t,readyAt:r,revalidate:l,refresh:i,now:o=Date.now}){let a=c({readyAt:r,revalidate:l,refresh:i??l,now:o});a.current={readyAt:r,revalidate:l,refresh:i??l,now:o},n(()=>{if(e==null)return;let t=Dh(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=a.current;e!==null&&r()-e>=Hh&&t()}));return()=>{typeof t=="function"&&Dh(t)}},[e]);let s=c(t);n(()=>{Object.is(s.current,t)||(s.current=t,a.current.refresh())},[t])}var Nh=Hh,$h=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function Wh(){let e=globalThis,t=e[$h];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[$h]=r,r}function Vh(e,t,r,n,l){let i=Wh(),o=i.get(t);o===void 0&&(o=/* @__PURE__ */new Map,i.set(t,o));let a=o,s=`${r}\0${n}`,u=a.get(s);if(!l&&u!==void 0&&(u.at===null||Date.now()-u.at<Nh))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(a.get(s)===c&&(e.ok||pd(e.error)?c.at=Date.now():a.delete(s)),e))};return a.set(s,c),c.promise}function useHealthPlanPage(e){let{userRef:t,runtime:r}=wd(),i=a(()=>Eh(r),[r]),o=e.repository,s=o??i,d=u((e,n)=>o!==void 0||t==null?s.getPage(e):Vh(i,r,t,e,n),[o,s,i,r,t]),{petRef:f}=e,h=e.enabled!==false&&t!=null&&f!==null,[p,g]=l({phase:"idle",petRef:null,page:null,error:null}),b=c(0),m=c(0),y=u(async e=>{let t=++b.current;if(!h||f===null){g(e=>e.phase==="idle"&&e.petRef===null?e:{phase:"idle",petRef:null,page:null,error:null});return}g(e=>({phase:"loading",petRef:f,page:e.petRef===f?e.page:null,error:null}));let r=await d(f,e);t===b.current&&(r.ok?g({phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}):pd(r.error)?g({phase:"ready",petRef:f,page:null,error:null,missing:true,readyAt:Date.now()}):g({phase:"failed",petRef:f,page:null,error:r.error}))},[h,f,d]),v=u(()=>y(true),[y]),k=p.phase==="ready"&&p.petRef===f,w=u(async()=>{if(!h||f===null||!k)return;let e=b.current,t=++m.current,r=await d(f,true);e!==b.current||t!==m.current||!r.ok||g(e=>e.phase==="ready"&&e.petRef===f?{phase:"ready",petRef:f,page:r.value,error:null,readyAt:Date.now()}:e)},[h,f,k,d]);Uh({lifecycle:e.lifecycle,refreshKey:e.refreshKey,readyAt:k?p.readyAt??null:null,revalidate:()=>{w()},refresh:()=>{k?w():v()}}),n(()=>(y(false),()=>{b.current+=1}),[y]);let C=h&&p.petRef!==f;return a(()=>({phase:C?"loading":p.phase,page:C?null:p.page,error:C?null:p.error,missing:!C&&p.missing===true,refresh:v}),[C,p,v])}var qh=/* @__PURE__ */Object.freeze({branding:null}),Gh=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>qh});function Kh(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function Yh(e){let{runtime:t}=wd(),r=t?.entitlements??Gh,n=u(()=>r.getSnapshot()?.branding??null,[r]),l=Td(i(r.subscribe,n,n),t?.sdkConfigHost?.branding),o=Kh(e);return a(()=>{let t=l?.lockedFields??null;return{presentation:resolvePresentation({server:l?.presentation??null,locked:t,client:e??null}),isLocked:e=>isPresentationFieldLocked(e,t)}},[l,o])}function Qh(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function Jh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function Xh(e){let t=ft(e);return t===null?null:{reached:Vf.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function Zh(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function ep(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=Zh(r),n=t==="web",l=Xh(r);return{tone:"error",title:l!==null?l.reached:e?Vf.turnUnreachableTitle:n?Vf.turnFailedTitleWeb:Vf.turnFailedTitle,body:r.displayMessage,actionLabel:e?Vf.turnStartNewChat:n?Vf.retry:Vf.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:Vf.turnStoppedTitle,body:Vf.turnStoppedBody,actionLabel:Vf.turnRetry,action:"retry"}:null}function tp(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var rp=3,np=/* @__PURE__ */Object.freeze([]);function lp(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return np;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),l=e.replace(/\s+/g," ").toLowerCase();if(!(l.length===0||r.has(l))&&(r.add(l),n.push(e),n.length===rp))break}/* @__PURE__ */
56
+ return Object.freeze(n)}var ip=5;function op(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function ap(e,t){if(t===void 0)return lp(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return np;let n=Math.max(1,Math.min(ip,Math.floor(t.count??rp))),l=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){l=r.text;break}}let i=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(l===null?[]:[i(l)]),a=[],s=e=>{let r=e.trim(),l=i(r);a.length>=n||l.length===0||o.has(l)||op(t.exclude,r)||(o.add(l),a.push(r))};for(let t of e.suggestedPrompts)s(t);let u=[];try{u=typeof t.fill=="function"?t.fill(l):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&s(e);/* @__PURE__ */
57
+ return Object.freeze(a)}function sp(e){return e.sender?.displayName??Vf.senderVet}function up(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var cp=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function dp(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function fp(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===rp&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>cp.test(e)||dp(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var hp="pet_not_registered";function pp(e){return e!=null&&e.reasonCode===hp}var gp=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function bp(e,t,r){let{runtime:i,userRef:o,scopeEpoch:s}=wd(),d=u((e,t)=>{let r=i.registry.services.authFor(o);return Ni(Ui(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,s]),f=a(()=>t===void 0?null:$i(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=c(0),b=c(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${s}|${e}|${f}`,y=u(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=u(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?gp:h.key!==m?{status:"registering",error:null,registered:null,retry:v}:{status:h.status,error:h.error,registered:h.registered,retry:v},[m,h,v])}var mp=/* @__PURE__ */Object.freeze({});function yp(e){let[t,r]=l(mp),i=c(null),o=c([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===mp?e:mp);return}let t=i.current;if(t===null)return;let n=e.find(e=>e.role==="user"&&!t.known.has(e.id));n!==void 0&&(i.current=null,r(e=>({...e,[n.id]:t.images})))},[e]);let s=u(e=>{i.current=e.length===0?null:{images:e,known:new Set(o.current)}},[]);return a(()=>({byMessage:t,stage:s}),[t,s])}var vp=/* @__PURE__ */new WeakSet;function kp(){let e=makeEverfurError("internalError",{retryable:true});return vp.add(e),err(e)}function wp(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&vp.has(t)}var Cp=500;function Sp(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,Cp):null}function xp(e,t,r,l){let i=Sp(r),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=c(e);a.current=e;let s=c(null),u=c(null),d=c(o);d.current=o,n(()=>{if(i===null||o===null||t||s.current===o||u.current===o)return;let e=a.current;if(e===void 0)return;u.current=o;let r=e=>{u.current===o&&(u.current=null),!wp(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var _p=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),Rp=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Tp=/* @__PURE__ */Object.freeze({..._p,markRead:true}),Ip=/* @__PURE__ */Object.freeze({...Rp,markRead:true});function zp(e,t){return e?t?Tp:_p:t?Ip:Rp}function Pp(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:Dh(()=>r()!==!1)===true}function Op(e,t){let r=c({target:e,isVisible:t});r.current={target:e,isVisible:t};let l=c(e.isStreaming);n(()=>{let t=l.current;if(l.current=e.isStreaming,!t||e.isStreaming)return;let{target:n,isVisible:i}=r.current;n.status!=="complete"||n.conversationId===null||n.unreadCount===null||!i()||n.markRead()},[e.isStreaming])}var Ep=3e5;function jp(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function Fp(e,t,r){let l=c(t);l.current=t;let i=c(null),o=c(null),a=c(false),s=c(0),u=c(0),d=c(3e4),f=()=>e?.isOffline===void 0?false:Dh(()=>e.isOffline?.()===!0)===true,h=f(),p=c(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:c}=l.current,h=Yr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:c===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,jp(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,Ep),u.current=Date.now()+s.current):(s.current=0,u.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},n(()=>{if(t.isTurnInFlight||h)return;let e=o.current;e!==null&&p.current(e)},[t.isTurnInFlight,h]),n(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=Dh(()=>e(()=>{p.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)Dh(e)}},[e]);let g=r?.intervalMs??null,b=r?.isVisibleFallback;n(()=>{if(e===void 0||g===null||!Number.isFinite(g)||g<=0)return;d.current=g;let t=setInterval(()=>{Date.now()<u.current||Pp(e,b)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var Ap=/^efch_[A-Za-z0-9_-]{43}$/,Dp="efch";function Mp(e){return typeof e=="string"&&Ap.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${Dp}=`))continue;let e=r.slice(Dp.length+1);return Mp(e)?e:null}return null}var Lp=128,Bp=/[\u0000-\u001f\u007f]/;function Hp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Up(e){return typeof e!="string"||e.length===0||e.length>Lp||Bp.test(e)||e.includes("://")?null:e}function Np(e){if(e===null)return null;let t=e.conversation_id,r=Up(e.pet_ref);return typeof t!="string"||!Dn(t)||r===null?null:{conversationId:t,petRef:r}}function $p(e,t,r){return Mp(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(Np(Hp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(sn("internalError",false))):Promise.resolve(ok(null))}function Wp(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=Mp(e)?e:null,a=o===null||i===null?null:`${String(i)}|${o}`,[s,u]=l(null);return n(()=>{if(a===null||o===null||i===null||r===null)return;let e=true,t=r.registry.services;return $p(t.authFor(i),o,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||u({key:a,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[a,r,o,i]),s!==null&&s.key===a?s.target:void 0}function Vp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function qp(e,t,r){let l=Vp(t),i=t?.kind==="chat",o=t?.petRef??null,a=i&&!r.pinned&&o!==null&&r.petRef!==null&&o!==r.petRef,s=c({openCheckin:e,target:t,selectPet:r.selectPet});s.current={openCheckin:e,target:t,selectPet:r.selectPet};let u=c(null),d=c(null),f=r.petRef;n(()=>{if(l===null||u.current===l)return;let{openCheckin:e,target:t,selectPet:n}=s.current;if(a&&o!==null){if(d.current?.key!==l){d.current={key:l,from:f},n(o);return}f!==d.current.from&&(u.current=l);return}i&&!r.ready||(u.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,f,r.ready])}var Gp=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function Kp(e){let t=e?.replace(/\s+/g," ").trim();return t||Gp.untitled}function Yp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function Qp(e){let t=Yp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?Gp.newReply.replace("{date}",t):t}function Jp(e,t){return t?`${Gp.countLabel}${Gp.countSeparator}${e}`:Gp.countLabel}function Xp(e){return`${e.unreadCount!==null&&e.unreadCount>0?Gp.unreadPrefix:""}${Gp.openConversation} ${Kp(e.title)}`}function Zp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function eg(e,t){let r=Zp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=Zp(Kp(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function tg(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function rg(e){let[t,r]=l(false),[i,o]=l(""),s=e.listConversations,d=c(0),[f,h]=l(()=>tg(s)),p=f.scope===s?f:tg(s);n(()=>(d.current+=1,r(false),o(""),h(tg(s)),()=>{d.current+=1}),[s]);let g=u(async t=>{let r=++d.current,n=t!==void 0;h(e=>({...e,scope:s,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===d.current){if(!l.ok){h(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}h(e=>{let r=t&&e.scope===s?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:s,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,s]),b=()=>{r(true),o(""),g()},m=()=>{d.current+=1,r(false)},y=async t=>{let n=++d.current;h(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);n===d.current&&(h(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&r(false))},v=async()=>{let t=d.current,r=await e.loadOlderMessages();t===d.current&&!r.ok&&h(e=>({...e,error:r.error.displayMessage}))},k=()=>{e.newConversation(),d.current+=1,r(false)},w=()=>{p.cursor===null||p.loading||p.loadingMore||i.trim().length>0||g(p.cursor)},C=a(()=>eg(p.rows,i),[p.rows,i]),S=i.trim().length>0;return{...p,open:t,show:b,close:m,load:g,resume:y,earlier:v,newConversation:k,loadMore:w,query:i,setQuery:o,searching:S,filtered:C,emptyKind:p.rows.length===0?"empty":"noMatch"}}var ng="#111111",lg="#FFFFFF",ig=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:ng,pillColor:lg,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:ng,pillColor:lg,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ng,pillColor:lg,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ng,pillColor:lg,showsVetAction:false})});function og(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function ag(e){return qf(Vf.urgencyGeneralReason,{petName:e?.trim()||Vf.emptyTitlePetFallback})}function sg(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:ug(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:ag(t)}:null}return null}function ug(e){return typeof e=="string"&&e.trim().length>0?e:null}function cg(e){let t=e===null?null:og(e),[r,i]=l(null),[o,s]=l(false);n(()=>s(false),[t]);let c=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:ig[e.level],f=e!==null&&!c&&e.level!=="general",h=u(()=>{t!==null&&i(t),s(false)},[t]),p=u(()=>s(true),[]);return a(()=>({source:e,tier:d,signature:t,showBanner:c,showCompactIcon:f,showVetAction:c&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:qf(Vf.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var dg=()=>globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]??={loader:null,lazy:null};var fg=dg;function registerEverfurChatCards(e){let t=fg();t.loader=e;let r=e&&Promise.resolve().then(e).then(e=>typeof e.ServerCards=="function"?e.ServerCards:NONE3,()=>NONE3);t.lazy=r&&s(async()=>({default:await r}))}var NONE3=()=>null,hg=createContext(null);function ServerCardsSlot({message:e}){let t=o(hg),n=fg(),l=e.a2ui??n.frames?.get(e.responseId),i=n.lazy;return l===void 0||t===null||i===null?null:r(g,{fallback:null},r(i,{message:e,a2ui:l,host:t}))}var pg="everfur.com",gg=2048,bg=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function mg(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&bg.test(e)&&t.add(e)}/* @__PURE__ */
58
+ return Object.freeze([...t])}function yg(e,t){if(e===pg||e.endsWith(`.${pg}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function vg(e,t){if(typeof e!="string"||e.length===0||e.length>gg||!/^https:\/\//i.test(e))return null;let r=Se(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:yg(r.hostname,t)?r.href:null}function kg(e){try{Promise.resolve(T.openURL(e)).catch(()=>{})}catch{}}var wg=createContext(null);function Cg(){return o(wg)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:t,children:n}){let l=e===false?null:Array.isArray(e)?e.join(`\n`):"",i=a(()=>{if(l===null)return null;let e=mg(l===""?[]:l.split(`\n`));/* @__PURE__ */
59
+ return Object.freeze({hosts:e,open:t!==void 0?e=>{Dh(t,e,"message")}:kg})},[l,t]);return r(wg.Provider,{value:i},n)}var Sg={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function xg(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function _g(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l={width:e*.82,height:n,borderRadius:n,backgroundColor:t};/* @__PURE__ */
60
+ return W(x,{style:[xg(e),{gap:e*.22}],...Sg,children:[
61
+ /* @__PURE__ */$(x,{style:l}),
62
+ /* @__PURE__ */$(x,{style:l}),
63
+ /* @__PURE__ */$(x,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=_g(e,r),i=e*.78;/* @__PURE__ */
64
+ return W(x,{style:[xg(e),{transform:[{rotate:n}]}],...Sg,children:[
65
+ /* @__PURE__ */$(x,{style:{position:"absolute",width:i,height:l,borderRadius:l,backgroundColor:t}}),
66
+ /* @__PURE__ */$(x,{style:{position:"absolute",width:l,height:i,borderRadius:l,backgroundColor:t}})]})}function PlusGlyph(e){/* @__PURE__ */
67
+ return $(Cross,{...e,rotate:"0deg"})}function CloseGlyph(e){/* @__PURE__ */
68
+ return $(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r);/* @__PURE__ */
69
+ return $(x,{style:xg(e),...Sg,children:/* @__PURE__ */$(x,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}var Rg={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:e,color:t,strokeWidth:r,direction:n}){let l=_g(e,r),i=e*.46,o=Rg[n];/* @__PURE__ */
70
+ return $(x,{style:xg(e),...Sg,children:/* @__PURE__ */$(x,{style:{width:i,height:i,borderRightWidth:l,borderBottomWidth:l,borderColor:t,marginTop:i*o.marginTop,marginLeft:i*o.marginLeft,transform:[{rotate:o.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};/* @__PURE__ */
71
+ return W(x,{style:[xg(e),{flexDirection:"row",gap:1}],...Sg,children:[
72
+ /* @__PURE__ */$(x,{style:[l,{borderTopLeftRadius:e*.2}]}),
73
+ /* @__PURE__ */$(x,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l=e*.5;/* @__PURE__ */
74
+ return W(x,{style:xg(e),...Sg,children:[
75
+ /* @__PURE__ */$(x,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),
76
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l=e*.6,i={position:"absolute",width:l,height:l,borderWidth:n,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
77
+ return W(x,{style:xg(e),...Sg,children:[
78
+ /* @__PURE__ */$(x,{style:[i,{top:0,left:0}]}),
79
+ /* @__PURE__ */$(x,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=_g(e,r),o=n?t:"transparent";/* @__PURE__ */
80
+ return W(x,{style:[xg(e),{transform:[{rotate:l}]}],...Sg,children:[
81
+ /* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),
82
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),
83
+ /* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r);/* @__PURE__ */
84
+ return W(x,{style:[xg(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...Sg,children:[
85
+ /* @__PURE__ */$(x,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),
86
+ /* @__PURE__ */$(x,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l=e*.34;/* @__PURE__ */
87
+ return W(x,{style:xg(e),...Sg,children:[
88
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.06,width:l,height:l,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),
89
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),
90
+ /* @__PURE__ */$(x,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r);/* @__PURE__ */
91
+ return W(x,{style:[xg(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...Sg,children:[
92
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),
93
+ /* @__PURE__ */$(x,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r);/* @__PURE__ */
94
+ return W(x,{style:xg(e),...Sg,children:[
95
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),
96
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */$(x,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l=e/24,i=16*l+n,o=11*l-i/2,a=11+8/Math.SQRT2,s=(21-a)*Math.SQRT2*l,u=(a+21)/2*l;/* @__PURE__ */
97
+ return W(x,{style:xg(e),...Sg,children:[
98
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:o,left:o,width:i,height:i,borderRadius:i,borderWidth:n,borderColor:t}}),
99
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r);/* @__PURE__ */
100
+ return W(x,{style:xg(e),...Sg,children:[
101
+ /* @__PURE__ */$(x,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),
102
+ /* @__PURE__ */$(x,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l=e*.62;/* @__PURE__ */
103
+ return W(x,{style:xg(e),...Sg,children:[
104
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:0,width:l,height:l,borderRadius:l,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */$(x,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),
105
+ /* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.04,width:l*.5,height:l*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:e,color:t,testID:r}){let n=e*.36;/* @__PURE__ */
106
+ return $(x,{style:xg(e),testID:r,...Sg,children:/* @__PURE__ */$(x,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:r}){/* @__PURE__ */
107
+ return $(x,{style:xg(e),testID:r,...Sg,children:/* @__PURE__ */$(x,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=_g(e,r);/* @__PURE__ */
108
+ return W(x,{style:xg(e),testID:n,...Sg,children:[
109
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.08,width:e*.26,height:e*.48,borderWidth:l,borderColor:t,borderRadius:e*.13}}),
110
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.38,width:e*.56,height:e*.36,borderBottomWidth:l,borderLeftWidth:l,borderRightWidth:l,borderColor:t,borderBottomLeftRadius:e*.28,borderBottomRightRadius:e*.28}}),
111
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.74,width:l,height:e*.18,backgroundColor:t}})]})}function Ring({size:e,strokeWidth:t,color:r,children:n}){/* @__PURE__ */
112
+ return $(x,{style:[xg(e),{borderRadius:e/2,borderWidth:t??v.hairlineWidth,borderColor:r}],children:n})}function ArrowUpGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=_g(e,r),i=e*.46;/* @__PURE__ */
113
+ return W(x,{style:xg(e),testID:n,...Sg,children:[
114
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,bottom:e*.12,width:l,borderRadius:l,backgroundColor:t}}),
115
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r);/* @__PURE__ */
116
+ return W(x,{style:xg(e),...Sg,children:[
117
+ /* @__PURE__ */$(x,{style:{width:e*.8,height:e*.6,marginTop:-e*.12,borderWidth:n,borderColor:t,borderRadius:e*.14}}),
118
+ /* @__PURE__ */$(x,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=_g(e,r),l=e*.72,i=e/2;/* @__PURE__ */
119
+ return W(x,{style:xg(e),...Sg,children:[
120
+ /* @__PURE__ */$(x,{style:{width:l,height:l,borderRadius:l/2,borderWidth:n,borderColor:t,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
121
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:e*.16,left:e*.12,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}}),
122
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:i-e*.2,left:i-n/2,width:n,height:e*.2+n/2,borderRadius:n,backgroundColor:t}}),
123
+ /* @__PURE__ */$(x,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var Tg=/* @__PURE__ */Object.freeze({standard:aa.standard,emphasized:aa.emphasized,exit:aa.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var Ig=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),zg=/* @__PURE__ */Object.freeze({...Ig,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function Pg(e){return e.motion.reducedMotion?zg:Ig}function Og(e,t){return Math.max(0,t)*e.followUpStaggerMs}function Eg(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}function jg(){let e=useEverfurTheme();return Pg(e)}var Fg=8;function Ag(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function Dg(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function Mg(e){let[t,r,n,l]=e;return e=>{if(e<=0)return 0;if(e>=1)return 1;let i=e;for(let r=0;r<Fg;r+=1){let r=Dg(i,t,n);if(r===0)break;i-=(Ag(i,t,n)-e)/r}return Ag(Math.min(1,Math.max(0,i)),r,l)}}var Lg=Mg(Tg.standard),Bg=Mg(Tg.outQuad),Hg=Mg(Tg.out);function Ug(e){let t=c(null);return t.current===null&&(t.current=new M.Value(e)),t.current}function Ng(e,t={}){let r=t.risePx??0,l=t.delayMs??0,i=Ug(e>0?0:1);return n(()=>{if(e<=0){i.setValue(1);return}let t=M.timing(i,{toValue:1,duration:e,easing:Bg,useNativeDriver:true}),r=l>0?M.sequence([M.delay(l),t]):t;return r.start(),()=>r.stop()},[i,e,l]),a(()=>({opacity:i,transform:[{translateY:i.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[i,r])}function FadePresence({visible:e,inMs:t,outMs:r,style:i,children:o}){let[a,s]=l(e),u=Ug(e&&t<=0?1:0);return n(()=>{if(e){s(true);let e=M.timing(u,{toValue:1,duration:Math.max(0,t),easing:Lg,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(r<=0){s(false);return}let n=M.timing(u,{toValue:0,duration:r,easing:Lg,useNativeDriver:true});return n.start(({finished:e})=>{e&&s(false)}),()=>n.stop()},[e,a,t,r,u]),!a&&!e?null:/* @__PURE__ */$(M.View,{style:[i,{opacity:u}],children:o})}var $g=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function Wg(e,t){let[r]=l(()=>e?t.bubbleInMs:0),i=r>0,o=Ug(i?0:1);n(()=>{if(r<=0)return;let e=M.timing(o,{toValue:1,duration:r,easing:Hg,useNativeDriver:true});return e.start(),()=>e.stop()},[r,o]);let s=t.bubbleFromScale,u=t.bubbleRisePx;return a(()=>i?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[u,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:$g,[i,o,u,s])}function Vg(e){let t=c(null),r=c(null),n=e[0]?.id??null;if(t.current===null||r.current!==n){let l=t.current===null;t.current=new Map(e.map(e=>[e.id,l&&e.pending===true])),r.current=n}let l=t.current;for(let t of e)l.has(t.id)||l.set(t.id,true);return u(e=>l.get(e)===true,[l])}var qg=12;function PressScale({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:l,hitSlop:i,...o}){let a=jg(),s=Ug(1),c=u(e=>{a.pressMs<=0||a.pressScale===1||M.timing(s,{toValue:e,duration:a.pressMs,easing:Lg,useNativeDriver:true}).start()},[s,a.pressMs,a.pressScale]);/* @__PURE__ */
124
+ return $(z,{...o,hitSlop:i??qg,style:t,onPressIn:e=>{c(a.pressScale),n?.(e)},onPressOut:e=>{c(1),l?.(e)},children:/* @__PURE__ */$(M.View,{style:[e,{transform:[{scale:s}]}],children:r})})}function Gg(e,t,r){let i=t&&r.revealTickMs>0,[o,a]=l(0),s=c(e);return s.current=e,n(()=>{if(!i)return;let e=setInterval(()=>{a(e=>Eg(r,e,s.current.length))},r.revealTickMs);return()=>clearInterval(e)},[i,r]),i?e.slice(0,Math.min(o,e.length)):e}var Kg=false;function Yg(e){e.layoutMs<=0||(Kg||(Kg=true,m.OS==="android"&&typeof A.setLayoutAnimationEnabledExperimental=="function"&&A.setLayoutAnimationEnabledExperimental(true)),D.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function Qg(e,t){let r=c(e);r.current!==e&&(r.current=e,Yg(t))}var Jg=36,Xg=22,Zg=12,eb=12,tb=16,rb="#000",nb="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:r}){let n=useEverfurTheme(),l=U();return e===null?null:/* @__PURE__ */W(O,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[
125
+ /* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Vf.closePreview,style:lb.backdrop,onPress:r,children:/* @__PURE__ */$(F,{source:{uri:e},style:lb.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
126
+ /* @__PURE__ */$(x,{pointerEvents:"box-none",style:[lb.closeWrap,{top:l.top+eb}],children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Vf.closePreview,hitSlop:Zg,style:lb.closeButton,onPress:r,children:/* @__PURE__ */$(CloseGlyph,{size:Xg,color:n.color.surface,strokeWidth:2})})})]})}var lb=v.create({backdrop:{flex:1,backgroundColor:rb,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:tb},closeButton:{width:Jg,height:Jg,borderRadius:Jg/2,backgroundColor:nb,alignItems:"center",justifyContent:"center"}});var ib=()=>{};function ob(){try{return _.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let r=_.currentState==="background";t=_.addEventListener("change",t=>{t==="background"?r=!0:t==="active"&&r&&(r=!1,e())})}catch{return ib}return()=>t.remove()},isVisible:ob}}function ab(e,t){if(e===void 0)return{};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}function sb(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function ub(e){return e?.textColor===void 0?{}:{color:e.textColor}}function cb(e){switch(e.code){case"too_large":return qf(Vf.attachmentTooLarge,{max:formatBytes(bl),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return qf(Vf.attachmentTooMany,{max:ml});case"unsupported_type":return qf(Vf.attachmentUnsupported,{filename:e.filename});case"network":return Vf.attachmentNetwork;case"server":return qf(Vf.attachmentServer,{status:""});case"cancelled":return Vf.attachmentCancelled;case"rate_limited":return Vf.attachmentRateLimited;case"quota_exceeded":return Vf.attachmentQuota;case"idempotency_conflict":return Vf.attachmentConflict;case"unknown":return Vf.attachmentUnknown}}function db(e,t){return qf(e>=t?Vf.attachmentsFull:Vf.addAttachment,{used:e,total:t})}var fb=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:t,userRef:r,scopeEpoch:o}=wd(),s=e.maxPerMessage??ml,d=u(()=>{let{services:n}=t.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:n.authFor(r),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}),transport:e.transport??n.uploadTransport,maxPerMessage:s})},[t,r,o,s,e.transport]),f=a(()=>e.queue??d(),[e.queue,d]),h=c(/* @__PURE__ */new WeakSet),[p,g]=l(null),b=p!==null&&p.of===f?p.queue:f;n(()=>{if(b!==e.queue){if(h.current.has(b)){g({of:f,queue:d()});return}return()=>{b.dispose(),h.current.add(b)}}},[b,f,d,e.queue]);let m=i(b.subscribe,b.getSnapshot,()=>fb),[y,v]=l(null),k=u(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>b.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&v(r.error),t},[b,v]),w=u(e=>b.retry(e),[b]),C=u(e=>b.remove(e),[b]),S=u(()=>b.clear(),[b]),x=u(()=>v(null),[v]),_=m.attachments.some(e=>e.status==="uploading"),R=m.attachments.some(e=>e.status==="failed");return a(()=>({available:b.available,attachments:m.attachments,maxPerMessage:s,uploading:_,failed:R,blocked:_||R,s3Keys:m.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:y,add:k,retry:w,remove:C,clear:S,dismissRejected:x}),[b.available,m,s,_,R,y,k,w,C,S,x])}var hb=6e3;function pb(e,t,r){let n=t.trim();if(!n)return e;let l=e===""||/\s$/.test(e)?"":" ",i=`${e}${l}${n}`;return typeof r=="number"&&r>0?i.slice(0,r):i}function gb(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${r}:${n.toString().padStart(2,"0")}`}function bb(e){switch(e){case"permissionDenied":return Vf.micBlocked;case"noSpeech":return Vf.noSpeech;case"unavailable":return Vf.dictationUnavailable}}function mb(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var yb=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function vb(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...yb]){let e=(n??"").trim();if(!e)continue;let l=e.toLowerCase();if(!t.has(l)&&(t.add(l),r.push(e),r.length>=100))break}return r}function kb(e,t,r){let[i,o]=l({send:e,conversationId:t,text:r??"",seeded:r??null}),a=i.send===e&&(i.conversationId===null||i.conversationId===t);n(()=>{o(n=>{let l=n.send===e&&(n.conversationId===null||n.conversationId===t),i=l?n.text:"",o=l?n.seeded:null,a=r!=null&&r!==o&&i.length===0;return{send:e,conversationId:t,text:a?r:i,seeded:a?r:o}})},[e,t,r]);let s=u(r=>o(n=>({send:e,conversationId:t,text:r,seeded:n.seeded})),[e,t]);return[a?i.text:"",s]}function wb(e,t,r,i,o=false){let a=c({draft:r,setDraft:i});a.current={draft:r,setDraft:i};let s=c(null),[u,d]=l(null);n(()=>{if(e===void 0)return;let r=`${t??""}`;if(s.current===r)return;s.current=r;let n=true;return(async()=>{let l=await Bh(()=>e.read(t));if(!n)return;let i=l.ok&&typeof l.value=="string"?l.value:"";i.length>0&&a.current.draft.length===0&&a.current.setDraft(i),d(r)})(),()=>{n=false}},[e,t]),n(()=>{e===void 0||o||u!==`${t??""}`||Dh(()=>e.write(t,r))},[e,t,r,u,o])}function Cb(e){if(!(m.OS!=="ios"||e===""))try{let t=k?.announceForAccessibility;typeof t=="function"&&t.call(k,e)}catch{}}function AnnounceLine({line:e}){return n(()=>{Cb(e)},[e]),null}var Sb=12,xb=80,_b=44,Rb=22,Tb=.14,Ib=18,zb=8,Pb=/* @__PURE__ */Object.freeze({photo:Vf.attachmentPhoto,camera:Vf.attachmentCamera});function AttachmentPickerPopover({sources:e,full:t,onPick:r,onClose:n}){let l=useEverfurTheme(),i=a(()=>Ob(l),[l]);/* @__PURE__ */
127
+ return W(x,{style:i.anchor,pointerEvents:"box-none",children:[
128
+ /* @__PURE__ */$(z,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:Vf.closeAttachmentPicker,onPress:n}),
129
+ /* @__PURE__ */W(x,{style:i.bubble,children:[
130
+ /* @__PURE__ */$(x,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:Pb[e],accessibilityState:{disabled:t},disabled:t,containerStyle:i.tile,style:i.tileInner,onPress:()=>r(e),children:[
131
+ /* @__PURE__ */$(x,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */$(PhotoGlyph,{size:Rb,color:l.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */$(CameraGlyph,{size:Rb,color:l.color.brandInk,strokeWidth:1.5})}),
132
+ /* @__PURE__ */$(Text,{tier:"control",style:i.tileLabel,children:Pb[e]})]},e))}),
133
+ /* @__PURE__ */$(x,{style:i.tail}),
134
+ /* @__PURE__ */$(x,{style:i.tailFill})]})]})}function Ob(e){let t=e.color,r=e.radius;return v.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:Tb,shadowRadius:Ib,shadowOffset:{width:0,height:zb},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:xb,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:_b,height:_b,borderRadius:_b/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-Sb/2,width:Sb,height:Sb,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Sb+4,height:2,backgroundColor:t.surfaceCream}})}var Eb=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var jb=56,Fb=12,Ab=14,Db=10,Mb=.45,Lb="rgba(7,193,104,0.55)",Bb="rgba(185,28,28,0.55)",Hb=200,Ub=300,Nb=20,$b=22,Wb=12,Vb="rgba(0,0,0,0.78)",qb=220,Gb=100,Kb="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:l,onPreview:i,style:o}){let s=useEverfurTheme(),u=a(()=>Yb(s),[s]);return e.length===0&&t===null?null:/* @__PURE__ */W(x,{style:[u.strip,o],children:[e.length>0?/* @__PURE__ */$(x,{style:u.cards,children:e.map(e=>/* @__PURE__ */$(PreviewCard,{row:e,styles:u,onRetry:n,onRemove:l,onPreview:i},e.id))}):null,r?/* @__PURE__ */$(Text,{style:u.rejected,accessibilityRole:"alert",children:Vf.attachmentsFailedBlocked}):null,t!==null?/* @__PURE__ */$(Text,{style:u.rejected,accessibilityRole:"alert",children:cb(t)}):null]})}function PreviewCard({row:e,styles:t,onRetry:r,onRemove:i,onPreview:o}){let a=useEverfurTheme(),s=e.status==="uploading",u=e.status==="failed",d=e.status==="uploaded",f=c(e.status),[h,p]=l(false);return n(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */W(x,{style:t.card,children:[
135
+ /* @__PURE__ */$(z,{accessibilityRole:d?"button":"image",accessibilityLabel:d?qf(Vf.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:s,disabled:!d},disabled:!d,style:t.thumbHit,onPress:()=>o(e),children:/* @__PURE__ */W(x,{style:t.thumb,children:[
136
+ /* @__PURE__ */$(F,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */$(x,{style:t.uploadingOverlay,children:/* @__PURE__ */$(j,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */$(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),u?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:qf(Vf.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:/* @__PURE__ */$(x,{style:t.failedInner,children:/* @__PURE__ */$(CloseGlyph,{size:Nb,color:a.color.surface,strokeWidth:2})})}):null,
137
+ /* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:qf(Vf.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>i(e.id),children:/* @__PURE__ */$(CloseGlyph,{size:Wb,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:t}){let r=useEverfurTheme(),l=jg(),i=c(null);i.current===null&&(i.current=new M.Value(0));let o=i.current;return n(()=>{let e=M.sequence([M.timing(o,{toValue:1,duration:Hb,useNativeDriver:true}),M.delay(l.uploadFlashMs),M.timing(o,{toValue:0,duration:Ub,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&t()}),()=>e.stop()},[o,l.uploadFlashMs,t]),/* @__PURE__ */$(M.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:o}],children:/* @__PURE__ */$(CheckGlyph,{size:Nb,color:r.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:t}){let r=useEverfurTheme(),n=a(()=>Yb(r),[r]);if(e.length===0)return null;let l=e.length===1;/* @__PURE__ */
138
+ return $(x,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:qf(Vf.attachedImage,{filename:e.filename}),onPress:()=>t(e),children:/* @__PURE__ */$(F,{source:{uri:e.uri},style:l?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${r}`))})}function Yb(e){let t=e.color,r=e.type;return v.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:jb,height:jb,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Fb,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:v.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Eb,alignItems:"center",justifyContent:"center",backgroundColor:bo(e.color.brandInk,Mb)??e.color.brandSofter},successOverlay:{...Eb,alignItems:"center",justifyContent:"center",backgroundColor:Lb},failedOverlay:{...Eb,borderRadius:Fb,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:Bb},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:$b,height:$b,borderRadius:$b/2,backgroundColor:Vb,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:qb,height:qb,borderRadius:Ab,backgroundColor:Kb},gridImage:{width:Gb,height:Gb,borderRadius:Db,backgroundColor:Kb}})}var Qb="chat attachment upload: the file handle has no uri",Jb="chat attachment upload failed";function Xb(e){return{uri:e.uri,name:sanitizeFilename(e.name),type:e.mimeType}}function createRnChatAttachmentTransport(e={}){/* @__PURE__ */
139
+ return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Qb));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(Jb));return l?.aborted===true?o():De({url:t.upload_url,fields:t.upload_fields,file:Xb(r),signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}var Zb=300,em=3e3,tm=120,rm=44,nm=120,lm="88%",im=520,om=2,am=.5,sm=1.5,um=1.6,cm=.6,dm=56,fm=1.5,hm=5,pm=5,gm=36,bm=20,mm=14,ym=rm,vm=4,km=24,wm=22,Cm=.4,Sm=rm,xm=20,_m=.4,Rm=480,Tm=12,Im=.72,zm=48,Pm=1.5,Om=1.3,Em=1,jm=1,Fm="12%",Am=14,Dm=16,Mm=28,Lm=18,Bm="84%",Hm=10,Um=15,Nm=1.42,$m=4,Wm=3,Vm=14,qm=20;function Gm(){let e=useEverfurTheme(),t=a(()=>Km(e),[e]);return{theme:e,styles:t}}function Km(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=Math.round(l.size.body*sm),o=Math.round(l.size.body*um),a=Math.round(bm*l.size.body/mm),s=t.borderRingCream,u=e.slots;return v.create({container:{flex:1,minHeight:tm,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:tm,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:Fm,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:Rm,gap:r.lg},errorText:{...face(e,"regular"),fontSize:l.size.subtitle,lineHeight:l.size.subtitle*l.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:rm,minWidth:rm,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...ab(u.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,...ub(u.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.md,backgroundColor:t.surfaceCream,borderWidth:jm,borderColor:t.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal},turnNoticeAction:{minHeight:rm,justifyContent:"center"},turnNoticeActionLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight},setupNoticeAction:{...face(e,"medium"),color:t.brandInk,fontSize:l.size.caption},reconnectingCaption:{...face(e,"medium"),color:t.text.secondary,fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:r.xs,paddingVertical:r.md,paddingHorizontal:r.md+r.xs/2,backgroundColor:t.surfaceSubtle,borderRadius:n.md},readingDot:{width:6,height:6,borderRadius:n.pill,backgroundColor:t.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:Wm,minHeight:Vm},readingDotInline:{width:$m,height:$m,borderRadius:n.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:rm,justifyContent:"center",paddingHorizontal:r.md+r.xs/2},earlierLabel:{...face(e,"monoBold"),color:t.linkInk,fontSize:l.size.caption},listContent:{padding:r.lg,gap:r.xl},listContentCards:{paddingTop:Am,paddingHorizontal:Dm,paddingBottom:Mm,gap:Lm},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:lm,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:im,paddingVertical:r.md,paddingHorizontal:r.lg+om,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:am,borderColor:t.primaryEdge}:{},borderRadius:n.lg,borderBottomRightRadius:n.xs,...ab(u.userBubble,am)},bubbleAssistant:u.assistantBubble?.backgroundColor===void 0?{...ab(u.assistantBubble,am)}:{paddingVertical:r.md,paddingHorizontal:r.lg+om,borderRadius:n.lg,...ab(u.assistantBubble,am)},bubbleVet:{maxWidth:im,paddingVertical:r.md,paddingHorizontal:r.lg+om,backgroundColor:t.bubbleVet,borderRadius:n.lg,borderTopLeftRadius:n.xs,...ab(u.vetBubble,am)},bubbleCards:{maxWidth:Bm},bubbleUserCards:{paddingVertical:Hm,paddingHorizontal:Um},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*Nm)},bubblePending:{opacity:cm},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:l.size.body,lineHeight:i,...ub(u.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:o,...ub(u.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:l.size.body,lineHeight:i,...ub(u.vetBubble)},assistantName:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,marginBottom:r.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:r.sm,marginBottom:r.xs},assistantAvatar:{width:qm,height:qm,borderRadius:qm/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:r.sm,marginBottom:r.xs},vetSender:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.bodyTight},vetTime:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.caption},bubbleBold:face(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.md},followUpsHeading:{...face(e,"monoBold"),color:t.text.muted,fontSize:Tm,textTransform:"uppercase",letterSpacing:Im,paddingBottom:r.sm,borderBottomWidth:Em,borderBottomColor:s},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:Em,borderTopColor:s},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,minHeight:zm,paddingVertical:r.sm+om,...u.chip?.backgroundColor!==void 0||u.chip?.borderColor!==void 0?{paddingHorizontal:r.md}:{},...ab(u.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:l.size.bodyTight,...ub(u.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,marginTop:r.md},askChip:{minHeight:rm,maxWidth:"100%",justifyContent:"center",paddingVertical:r.sm,paddingHorizontal:r.lg,borderRadius:n.pill,borderWidth:Pm,borderColor:t.brandInk,backgroundColor:t.chatGround,...ab(u.chip,Pm)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*Om),...ub(u.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:r.md,marginTop:r.xs},composer:{marginHorizontal:r.md,marginTop:r.xs,minHeight:dm,justifyContent:"center",paddingLeft:r.sm,paddingRight:hm,paddingVertical:pm,backgroundColor:t.composerFill,borderWidth:fm,borderColor:t.composerBorder,borderRadius:n.pill,...ab(u.composerInput,fm)},composerRow:{flexDirection:"row",alignItems:"center",gap:r.xs,minHeight:gm},dictationError:{...face(e,"regular"),fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,color:t.danger,paddingHorizontal:r.xs},attachControl:{width:Sm,height:Sm,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:_m},input:{flex:1,minHeight:gm,maxHeight:nm,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:l.size.body,lineHeight:a,color:t.text.primary,...ub(u.composerInput)},sendControl:{minHeight:ym,minWidth:ym,alignItems:"center",justifyContent:"center"},sendDisc:{width:ym,height:ym,borderRadius:ym/2,alignItems:"center",justifyContent:"center",...ab(u.sendButton)},sendControlDisabled:{opacity:Cm},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.micro,textAlign:"center",paddingBottom:r.xs}})}var Ym=18,Qm=28,Jm=6,Xm=1200,Zm=.4,ey=.4;function DictationButton({active:e,listening:t,elapsedMs:r,disabled:l=false,onToggle:i}){let o=useEverfurTheme(),s=a(()=>ty(o),[o]);return n(()=>{if(t)try{k.announceForAccessibility(Vf.listening)}catch{}},[t]),/* @__PURE__ */W(x,{style:s.wrap,children:[t?/* @__PURE__ */$(Text,{style:s.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:gb(r)}):null,
140
+ /* @__PURE__ */$(z,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?Vf.stopDictation:Vf.dictate,accessibilityState:{selected:e,disabled:l},style:[s.button,l?s.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */W(V,{children:[
141
+ /* @__PURE__ */$(Pulse,{style:s.pulse,reduced:o.motion.reducedMotion}),
142
+ /* @__PURE__ */$(StopGlyph,{size:Qm,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */$(MicGlyph,{size:Ym,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=c(new M.Value(1)).current;return n(()=>{if(t)return;let e=M.loop(M.sequence([M.timing(r,{toValue:Zm,duration:Xm/2,useNativeDriver:true}),M.timing(r,{toValue:1,duration:Xm/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */$(M.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function ty(e){let t=e.color,r=e.type.tierSizes.compact.micro;return v.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:rm,height:rm,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:ey},pulse:{position:"absolute",top:Jm,right:Jm,bottom:Jm,left:Jm,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var ry=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function ny(){let e=globalThis,t=e[ry];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[ry]=r,r}function registerEverfurDictation(e){let t=ny();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function ly(){return ny().version??0}function iy(e){let t=ny(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function oy(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function ay(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function sy(){let e=ny();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||m.OS!=="ios"&&m.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:ay(t())}),e=>typeof e=="object"&&e!==null&&oy(e.box));return r.available&&(e.memo=r.module.box),e.memo}function uy(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function cy(){try{return Intl.DateTimeFormat().resolvedOptions().locale||fy}catch{return fy}}function dy(e){return e.replace(/_/g,"-").toLowerCase()}var fy="en-US";function hy(e=cy()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return fy;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:fy}function py(e,t){if(t.length===0)return null;let r=e=>t.find(t=>dy(t)===dy(e));return r(e)??r(fy)??t.find(e=>dy(e).startsWith("en-"))??null}async function gy(e,t){if(m.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return py(t,r??[])??t}catch{return t}}async function by(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(m.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=dy(t);return(r??[]).some(e=>dy(e)===n)?"on_device":"network"}catch{return"network"}}function my(){return m.OS!=="android"?true:Number(m.Version)>=yy}var yy=33;function vy(e,t,r){return{lang:t,interimResults:true,continuous:my(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var ky=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),wy=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Cy(e){return wy.has(e)}var Sy=600,xy=3;function _y(e,t,r){if(ky.has(r))return null;let n=Cy(r)?Sy:0;return r==="language-not-supported"&&dy(t)!==dy(fy)?{mode:"network",lang:fy,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Ry(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Ty(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Iy=55e3,zy=3e3,Py=1e3;function Oy(e){return Ey.has(e)||Cy(e)}var Ey=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),jy=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function Fy(e){return e.replace(/\s+/g," ").trim()}function Ay(e,t,r){let n=Fy(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function Dy(e){return Fy([...e.committed,e.interim].join(" "))}function My(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,a=e=>i!==null&&i.token===e?i:null;function s(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){s(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&Dy(e.transcript)===""&&e.launchedAt-o<Py}function d(e){return e.mode??"none"}function f(e,t){mb(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){mb(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(a(e.token)===null)return;u(e);let r=Dy(e.transcript),n=e.errorCode;if(n!==null&&!(r&&Oy(n))){h(e,Ry(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{a(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),mb(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(a(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=Ay(l.transcript,r,e?.isFinal===true),t.onText(Dy(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||Cy(t)))return;let r=Dy(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<xy?_y(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(a(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){b(l,e.mode);return}s(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(a(l.token)===null||l.userStopped)&&b(l,e.mode)},e.delayMs);return}p(l)}})]}function b(t,r){s(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=jy,t.errorCode=null,g(t);try{e.start(vy(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function m(t){let r=await Ty(e);if(a(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await gy(e,t.lang),a(t.token)===null)return;let n=await by(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Iy),b(t,n))}function y(r){if(!(a(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),zy);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:hy(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:jy,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),m(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,a=Dy(r.transcript);if(u(r),t.onStatus("idle"),!!l){a&&f(r,a),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function Ly({enabled:e,input:t,setInput:r,phrases:o,maxLength:s,telemetry:d}){let f=i(iy,ly,ly),h=a(()=>e?sy():null,[e,f]),p=a(()=>uy(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=c(t);w.current=t;let C=c(r);C.current=r;let S=c(d);S.current=d;let x=c(""),R=c(s);R.current=s;let T=c(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:My(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>C.current(pb(x.current,e,R.current)),onError:e=>{y(e),b("error")}},()=>S.current)});let I=h===null?null:T.current?.controller??null,z=u(()=>{I?.cancel()},[I]),P=u(()=>{if(I!==null){if(I.isActive()){I.stop();return}y(null),k(0),x.current=w.current,I.start(o)}},[I,o]);n(()=>{if(g!=="listening")return;let e=Date.now();k(0);let t=setInterval(()=>k(Date.now()-e),1e3);return()=>clearInterval(t)},[g]),n(()=>{if(g!=="error")return;let e=setTimeout(()=>{y(null),b("idle")},hb);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=_.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var By=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function Hy(){let e=globalThis,t=e[By];if(t!==void 0)return t;let r=createContext(true);return e[By]=r,r}var Uy=Hy();function Ny(){return o(Uy)}var $y=/* @__PURE__ */Object.freeze(["photo"]),Wy=52,Vy=1.5,qy=10,Gy=14,Ky=10,Yy=40,Qy=20,Jy=.3,Xy=2.5,Zy=1,ev=1.5,tv=38,rv=22,nv=3;function lv(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?Kf(Vf.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):Kf(Vf.placeholder,t):n==="urgent"?Vf.placeholderUrgentWeb:n==="followUp"?Vf.placeholderFollowUpWeb:Kf(Vf.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??ml,transport:r}),l=a(()=>({state:n,sources:e.sources??$y,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
143
+ return $(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:s,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:w=false}){let{theme:C,styles:S}=Gm(),_=a(()=>cv(C),[C]),R=a(()=>dv(C),[C]),T=jg(),[I,P]=kb(e,i,s),[O,E]=l(false),[j,F]=l(false),A=u(()=>F(true),[]),D=u(()=>F(false),[]),[M,L]=l(false);n(()=>{L(false)},[i]);let B=lv(C.meta.placeholder,p,k,b,C.meta.placeholderFillsPet===true),H=a(()=>vb({name:p,breed:g}),[p,g]),U=Ly({enabled:m,input:I,setInput:P,phrases:H,maxLength:Yn,telemetry:y}),N=U.cancel,q=U.active;wb(d,i===null?null:String(i),I,P,q);let G=c(i);n(()=>{G.current!==i&&(G.current=i,N())},[i,N]);let K=Ny();n(()=>{K||N()},[K,N]);let Y=o?.state.uploading??false,Q=o?.state.failed??false,J=Y||Q,X=o?.state.attachments??iv;Qg(X.length,T);let Z=u(()=>{let t=I.trim();if(t.length===0||J||[...t].length>Yn)return;q&&N();let r=o?.state.s3Keys??ov;o!==null&&r.length>0?(f(o.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),o.state.clear()):e(t),P(""),L(false)},[I,e,J,q,N,o,f]),ee=u(e=>{q&&N(),P(e)},[q,N,P]),te=u(()=>{t()},[t]),re=u(e=>{E(false),o!==null&&(L(false),o.state.dismissRejected(),Bh(o.pick,e).then(e=>{if(!e.ok){L(true);return}e.value!==null&&o.state.add(e.value)}))},[o]),ne=a(()=>[...I.trim()].length>Yn,[I]),le=ne||J||I.trim().length===0,ie=ne||J||w&&I.trim().length===0,oe=o!==null&&X.length>=o.state.maxPerMessage,ae=C.slots.sendButton?.textColor??C.color.brandInk,se=C.slots.sendButton?.textColor??C.color.surface;/* @__PURE__ */
144
+ return W(x,{style:S.composerOuter,children:[o!==null&&O?/* @__PURE__ */$(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */$(AttachmentStrip,{attachments:X,rejected:M?uv:o.state.rejected,uploadFailed:Q,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:e=>h({uri:e.previewUri,label:e.filename}),style:v?_.tray:R.tray}):null,
145
+ /* @__PURE__ */W(x,{style:v?[S.composer,_.bar,j?_.barFocused:null]:S.composer,children:[U.supported&&U.error!==null?/* @__PURE__ */W(V,{children:[
146
+ /* @__PURE__ */$(Text,{style:S.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:bb(U.error)}),
147
+ /* @__PURE__ */$(AnnounceLine,{line:bb(U.error)})]}):null,
148
+ /* @__PURE__ */W(x,{style:S.composerRow,children:[o!==null?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:oe?db(X.length,o.state.maxPerMessage):Vf.attachPhotoOrFileNative,accessibilityState:{disabled:oe,expanded:O},disabled:oe,style:[S.attachControl,v?_.add:null,oe?S.attachControlDisabled:null],hitSlop:v?nv:void 0,onPress:()=>E(e=>!e),children:/* @__PURE__ */$(UploadGlyph,{size:v?rv:xm,color:oe?C.color.text.muted:v?C.color.text.primary:C.color.brandInk,strokeWidth:1.75})}):null,
149
+ /* @__PURE__ */$(ff,{style:v?[S.input,_.input]:S.input,onFocus:A,onBlur:D,value:I,onChangeText:ee,placeholder:B,placeholderTextColor:C.slots.composerInput?.textColor??C.color.text.placeholder,accessibilityLabel:Vf.composerLabel,onSubmitEditing:Z,returnKeyType:"send",...av,...v?sv:null,blurOnSubmit:false,multiline:true,editable:true}),U.supported?/* @__PURE__ */$(DictationButton,{active:U.active,listening:U.status==="listening",elapsedMs:U.elapsedMs,onToggle:U.toggle}):null,r?/* @__PURE__ */$(z,{onPress:te,accessibilityRole:"button",accessibilityLabel:Vf.stop,style:S.sendControl,children:/* @__PURE__ */$(x,{style:v?_.disc:S.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */$(StopGlyph,{size:v?Qy:wm,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */$(z,{onPress:Z,disabled:le,accessibilityRole:"button",accessibilityLabel:Vf.send,accessibilityState:{disabled:le,busy:Y},style:[S.sendControl,ie?v?_.dimmed:S.sendControlDisabled:null],children:v?/* @__PURE__ */$(x,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */$(ArrowUpGlyph,{size:Qy,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */$(x,{style:S.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */$(SendGlyph,{size:km,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var iv=/* @__PURE__ */Object.freeze([]),ov=/* @__PURE__ */Object.freeze([]),av=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),sv=/* @__PURE__ */Object.freeze(m.OS==="web"?{rows:1}:{}),uv=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function cv(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+Zy;return v.create({bar:{marginTop:qy,marginHorizontal:Gy,marginBottom:Ky,minHeight:Wy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:Vy,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Xy,paddingLeft:8-(Xy-Vy),paddingRight:6-(Xy-Vy)},input:{fontSize:n,lineHeight:Math.round(n*ev),minHeight:Math.round(n*ev),...m.OS==="web"?{outlineStyle:"none"}:null},add:{width:tv,height:tv,borderRadius:tv/2},disc:{width:Yy,height:Yy,borderRadius:Yy/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...ab(r)},dimmed:{opacity:Jy},tray:{marginHorizontal:Gy,marginTop:qy,paddingBottom:0}})}function dv(e){return v.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=wd(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[s,d]=l({repository:o,pets:[],loading:true,error:null}),f=s.repository===o?s:{pets:[],loading:true,error:null},h=c(0),p=u(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>Vi(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function fv(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var hv=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var pv=false;function gv(e,t){return t!==void 0?(Dh(t,e),"onStartInApp"):wf(e)==="presented"?"presenter":_f(e)?"experience":(pv||(pv=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var bv=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&bv.includes(e)}var mv="/widget/v1/televet/handoffs",yv="/widget/v1/televet/availability",vv="/widget/v1/televet/chat-entry",kv=/^[a-z0-9][a-z0-9_-]{0,39}$/,wv=/^[A-Za-z0-9_-]{22}$/;var Cv=32,Sv=128,xv=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function _v(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Rv(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Tv(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!kv.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>xv)return{ok:false,message:`visitRef must be 1..${xv} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${bv.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Iv(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function zv(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(Av(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>Sv)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Sv} characters`}));i=e}let o=Tv(i,l);if(!o.ok){let e=_v(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:mv,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=Pv(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!wv.test(d))){let e=Rv("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,h=f?Iv(s.value?.visit):null;if(f&&h===null){let e=Rv("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Av(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Cv)return _v(`state must be at most ${Cv} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:yv,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Rv("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:vv},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function Pv(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||!Fv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var Ov=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),Ev=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,jv=/[\s\u0000-\u001f\u007f]/;function Fv(e){if(jv.test(e))return false;let t=Ev.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&Ov.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function Av(e,t,r){if(e)try{e.track(t,r)}catch{}}var Dv=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function Mv(e,t,r){let{usState:i,chat:o,scope:a}=r,s=t&&(i!==null||o),u=`${i??""}|${o?"chat":""}`,[c,d]=l(null);if(n(()=>{if(!s)return;let t=true,r=e.current;return d(null),(async()=>{try{if(o&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&d({key:u,open:e})}),()=>{t=false}},[s,u,i,o,a,e]),!s)return null;let f=c!==null&&c.key===u;return{open:f&&c.open,pending:!f}}var Lv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function Bv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=wd(),o=useCapability("televet"),s=o.enabled&&n!==null,d=t.usState??null,f=t.entry==="chat",h=t.petRef??null,p=t.prefer==="redirect",g=a(()=>{if(t.controller)return t.controller;let{services:e}=r.registry;return zv({auth:e.authFor(n),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[r,n,i,t.controller]),b=c(g);b.current=g;let m=a(()=>({runtime:r,userRef:n,scopeEpoch:i}),[r,n,i]),y=Mv(b,s,{usState:d,chat:f,scope:m}),v=s&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(Dv),S=c(null),x=c({runtime:r,userRef:n,scopeEpoch:i});x.current={runtime:r,userRef:n,scopeEpoch:i};let _=c(g);_.current=g;let R=c(v);R.current=v;let T=u((t,r)=>{if(S.current)return S.current;let n=(e,t)=>(C({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!R.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=x.current,o=_.current;C(Lv);let a=(async()=>{let a,s={...k!==null?{returnTo:k}:{},...f?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},u=Object.keys(s).length===0?void 0:s,c=t===void 0?h:t;try{a=await(u===void 0?o.createHandoff(c):o.createHandoff(c,u))}catch{return e.abandon(l.value),n("unknown",null)}let d=x.current;if(d.runtime!==i.runtime||d.userRef!==i.userRef||d.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!a.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let p=await e.finish(l.value,a.value);return p!==null?n(p,null):(C(Dv),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{S.current===a&&(S.current=null)});return S.current=a,a},[e,h,k,f]),I=u((e,t)=>{if(!R.current)return C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?h:e,n={...r!==null?{petRef:r}:{},...d!==null?{usState:d}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return gv(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(Dv),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[h,d]),z=u(e=>p?T(e,null):I(e,null),[p,T,I]),P=u((e,t)=>p?T(void 0,{visitRef:e,intent:t??null}):I(void 0,{visitRef:e,intent:t??null}),[p,T,I]),O=u(e=>p?T(void 0,null):I(void 0,{consultId:e.trim()}),[p,T,I]);return{available:v,isPending:o.isPending||(y?.pending??false),status:w.status,error:w.error,errorReason:w.errorReason,open:z,openVisit:P,joinVisit:O}}var Hv=e=>T.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??Hv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return Bv(n,r)}var Uv=44,Nv=.6;function VetVisitButtonCore(e){let{petRef:t,label:r,openUrl:n,onOpened:l,onError:i,style:o,labelStyle:s,controller:u,returnTo:d,usState:f,entry:h,visitRef:p,intent:g,onStartInApp:b,prefer:m}=e,y=m==="redirect",v=useVetVisit({...d!==void 0?{returnTo:d}:{},...f!==void 0?{usState:f}:{},...h!==void 0?{entry:h}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:y?"redirect":"in-app"}),k=useEverfurTheme(),w=a(()=>$v(k),[k]),C=c(false);if(!v.available)/* @__PURE__ */
150
+ return W(V,{children:[null,
151
+ /* @__PURE__ */$(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??hv.visitButton;/* @__PURE__ */
152
+ return W(V,{children:[
153
+ /* @__PURE__ */$(z,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}};gv(e,b)===null&&Dh(i,"unavailable",null);return}C.current=true,(p==null?v.open():v.openVisit(p,g??null)).then(e=>{e.opened?Dh(l,e.flowId??null):e.reason!=="cancelled"&&Dh(i,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:x,accessibilityState:{busy:S,disabled:S},style:[w.button,S?w.busy:null,o],children:/* @__PURE__ */$(Text,{style:[w.label,s],children:x})}),
154
+ /* @__PURE__ */$(TelevetHostOutlet,{})]})}function $v(e){let{color:t,space:r,radius:n,type:l,slots:i}=e;return v.create({button:{minHeight:Uv,minWidth:Uv,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...ab(i.vetVisitButton)},busy:{opacity:Nv},label:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.snug,...ub(i.vetVisitButton)}})}function Wv(e){let[t,r]=l(null);return{shown:e!==null&&t!==e,onError:()=>r(e)}}function BrandImage({uri:e,label:t,decorative:r=false,style:n,resizeMode:l="contain",fallback:i=null,onError:o,testID:a}){let s=Wv(e);if(e===null||!s.shown)return i;let u=r?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...t===void 0?{}:{accessibilityLabel:t}};/* @__PURE__ */
155
+ return $(F,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=Wv(e);return e===null||!i.shown?null:/* @__PURE__ */$(x,{style:r,...l===void 0?{}:{testID:l},children:/* @__PURE__ */$(F,{source:{uri:e},style:n,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:i.onError})})}var Vv=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),qv=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function Gv(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return qv;let n=Math.abs(e.leading-e.trailing);if(n<.5)return qv;let l=e.row-t-e.leading-e.trailing,i=Math.min(n,Math.max(0,l-r));return i<.5?qv:e.leading<e.trailing?{leading:e.leading+i,trailing:void 0}:{leading:void 0,trailing:e.trailing+i}}function Kv(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function Yv(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function Qv(e){if(e.brightness!=="light")return false;let t=ca.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),l=new Set(Yv(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&Yv(r).every(e=>l.has(e))}function Jv(e){let t=(e.brightness==="dark"?fa:ca).color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t);return{success:!n(r.success,t.success),warning:!n(r.warningStrong,t.warningStrong)||!n(r.cautionAccent,t.cautionAccent),info:!(n(r.info,r.brandInk)&&n(r.badgeBgInfo,r.brandSoft)&&n(r.infoEdge,r.structureEdge))}}function Xv(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function Zv(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function ek(e){let t=Zv(e.ageYears),r=Xv(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var tk=/* @__PURE__ */Object.freeze([
156
156
  /* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
157
157
  /* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
158
158
  /* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
159
159
  /* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
160
160
  /* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
161
- /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function Jv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Qv[t%Qv.length]}function Xv(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function Zv(e){return{...Jv(e.petRef),initial:Xv(e.name)}}function ek(e,t,r){let n=Zv(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function tk(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:t,ringStroke:r}){let n=useEverfurTheme(),l=a(()=>rk(n),[n]),i=t-r*2,o=e===null?null:ek(e,Vv(n),{fill:n.color.highlight,ink:n.color.onHighlight}),s=tk(i);/* @__PURE__ */
162
- return U(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */U(C,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */U(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?Xv(null):o.initial})})})}function rk(e){return m.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function nk(e,t){let{borderRadius:r,...n}=rb(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function lk(e,t){let{backgroundColor:r,borderColor:n,borderWidth:l,borderRadius:i}=rb(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:l??1},...i===void 0?{}:{borderTopRightRadius:i,borderBottomRightRadius:i}}}var ik=48,ak=2,sk=320,uk="80%",ck="rgba(17,17,17,0.45)",dk=18,fk=22,hk=12,pk=.4,gk=44;function bk(e){return e?.name?.trim()||$f.yourPet}function PetSwitcherSheet({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:l=null,onClose:i}){let o=useEverfurTheme(),s=a(()=>mk(o),[o]),u=Mf();return e?/* @__PURE__ */U(z,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"fade",onRequestClose:i,children:/* @__PURE__ */N(C,{style:s.root,children:[
163
- /* @__PURE__ */U(T,{style:Tb,onPress:i,accessibilityRole:"button",accessibilityLabel:$f.close,children:/* @__PURE__ */U(C,{style:s.backdrop})}),
164
- /* @__PURE__ */N(C,{style:Lf(s.panel,u),accessibilityViewIsModal:true,children:[
165
- /* @__PURE__ */U(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:$f.yourPets}),
166
- /* @__PURE__ */U(P,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=bk(e),i=Yv(e);/* @__PURE__ */
167
- return N(PressScale,{accessibilityRole:"button",accessibilityLabel:Wf(t?$f.petCurrentlyActive:$f.switchToPet,{name:l}),accessibilityState:{selected:t},style:[s.row,t?s.rowActive:null],onPress:()=>n(e.petRef),children:[
168
- /* @__PURE__ */U(PetDisc,{pet:e,size:ik,ringStroke:ak}),
169
- /* @__PURE__ */N(C,{style:s.copy,children:[
170
- /* @__PURE__ */U(Text,{style:s.name,numberOfLines:1,children:l}),
171
- /* @__PURE__ */U(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${$f.activePrefix}${i}`:i})]}),t?/* @__PURE__ */U(CheckGlyph,{size:dk,color:o.color.brandInk}):null]},e.petRef)})}),l!==null?/* @__PURE__ */N(PressScale,{accessibilityRole:"button",accessibilityLabel:$f.addAnotherPet,style:s.addRow,onPress:l,children:[
172
- /* @__PURE__ */U(C,{style:s.addDisc,children:/* @__PURE__ */U(Text,{tier:"control",style:s.addPlus,children:"+"})}),
173
- /* @__PURE__ */U(Text,{style:s.addLabel,children:$f.addAnotherPet})]}):null,
174
- /* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:$f.close,containerStyle:s.closeSlot,style:s.closeButton,onPress:i,children:/* @__PURE__ */U(Text,{tier:"control",style:s.closeText,children:$f.close})})]})]})}):null}function mk(e){let t=e.color,r=e.radius,n=lb(e.slots.dialog);return m.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:ck},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:fk,borderTopRightRadius:fk,gap:14,maxHeight:uk,...nk(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...n},list:{maxHeight:sk,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:gk,paddingHorizontal:8},addDisc:{width:ik,height:ik,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:ak,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...face(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...face(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary,...n},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...face(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...face(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:pk},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:hk,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:pk}})}var yk=44,vk=36,kk=22,wk=20,Ck=9,Sk=1.5,xk=6,_k=35,Rk=1.75,Tk=12.4,Ik=.5,zk=8,Pk=28,Ok=160,Ek=16,jk=8;function Fk(e,t){return av(e,t)}function ChatHeader({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onNewChat:i,onPetChange:o,onAddPet:u,vet:c,textingEntry:d=null}){let f=useEverfurTheme(),h=a(()=>Ak(f),[f]),[p,g]=l(false),b=Fk(e.pets,t),m=b!==null&&(e.pets.length>=2||u!==void 0),y=t??b?.petRef??null,v=bk(b),[k,w]=l(Hv),S=s(e=>t=>{let r=t.nativeEvent.layout.width;w(t=>$v(t,e,r))},[]),x=a(()=>S("row"),[S]),_=a(()=>S("leading"),[S]),R=a(()=>S("trailing"),[S]),T=2*Ek+2*(f.slots.header?.borderColor!==void 0?1:0)+2*jk,I=Nv(k,T,Ok),z=t=>{g(false),e.setActivePet(t),Fh(o,t)},P=u===void 0?null:()=>{g(false),Fh(u)};/* @__PURE__ */
175
- return N($,{children:[
176
- /* @__PURE__ */N(C,{style:h.row,onLayout:x,children:[
177
- /* @__PURE__ */U(C,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */N(C,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:Vp.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:i,children:/* @__PURE__ */U(EditGlyph,{size:wk,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
178
- /* @__PURE__ */N(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${$f.openHistoryNative}${$f.newReplySuffix}`:$f.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:n,children:[
179
- /* @__PURE__ */U(MenuGlyph,{size:kk,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),r?/* @__PURE__ */U(C,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
180
- /* @__PURE__ */U(C,{style:h.centre,pointerEvents:"box-none",children:/* @__PURE__ */U(BrandLogo,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,barStyle:h.logoBar,logoStyle:h.logo})}),
181
- /* @__PURE__ */U(C,{style:[h.trailing,I.trailing===void 0?null:{minWidth:I.trailing}],children:/* @__PURE__ */N(C,{style:h.trailingContent,onLayout:R,children:[y===null?null:/* @__PURE__ */U(VetVisitButtonCore,{entry:"chat",petRef:y,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:h.vetEntry,labelStyle:h.vetEntryLabel}),
182
- /* @__PURE__ */U(C,{style:h.right,children:m?/* @__PURE__ */N(PressScale,{accessibilityRole:"button",accessibilityLabel:Wf($f.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
183
- /* @__PURE__ */U(PetDisc,{pet:b,size:_k,ringStroke:Rk}),
184
- /* @__PURE__ */U(C,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */U(PlusGlyph,{size:zk,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&b===null?
185
- /* @__PURE__ */U(C,{style:h.avatarWrap,accessible:true,accessibilityLabel:$f.yourPet,children:/* @__PURE__ */U(Ring,{size:_k,strokeWidth:Rk,color:f.color.mark,children:/* @__PURE__ */U(C,{style:h.placeholderDisc})})}):/* @__PURE__ */U(C,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:b===null?$f.yourPet:v,children:/* @__PURE__ */U(PetDisc,{pet:b,size:_k,ringStroke:Rk})})})]})}),
186
- /* @__PURE__ */U(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */U(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>Ak(r),[r]);/* @__PURE__ */
187
- return U(C,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */U(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function Ak(e){let t=e.color,r=_k-Rk*2,n=e.slots.header;return m.create({vetEntry:{minHeight:yk,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:m.hairlineWidth,borderColor:t.controlEdge},vetEntryLabel:{...face(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},textingEntrySlot:{borderRadius:e.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Ek,paddingBottom:10,backgroundColor:n?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Ek,paddingTop:e.space.md,paddingBottom:e.space.xs},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:Ek,paddingVertical:10,backgroundColor:t.surface,...rb(n)},iconSlot:{borderRadius:vk/2},iconButton:{width:vk,height:vk,borderRadius:vk/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:xk,right:xk,width:Ck,height:Ck,borderRadius:Ck,backgroundColor:t.danger,borderWidth:Sk,borderColor:n?.backgroundColor??t.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:e.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:jk,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:Pk,width:Ok,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:_k/2},avatarWrap:{width:_k,height:_k,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Tk,height:Tk,borderRadius:Tk/2,borderWidth:Ik,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var Dk=/* @__PURE__ */Object.freeze([
188
- /* @__PURE__ */Object.freeze({key:"inaccurate",label:$f.feedbackReasonInaccurate,feedbackType:"wrong"}),
189
- /* @__PURE__ */Object.freeze({key:"outdated",label:$f.feedbackReasonOutdated,feedbackType:"outdated"}),
190
- /* @__PURE__ */Object.freeze({key:"unsafe",label:$f.feedbackReasonUnsafe,feedbackType:"dangerous"}),
191
- /* @__PURE__ */Object.freeze({key:"unclear",label:$f.feedbackReasonUnclear,feedbackType:"unclear"}),
192
- /* @__PURE__ */Object.freeze({key:"other",label:$f.feedbackReasonOther,feedbackType:"not_helpful"})]),Mk=/* @__PURE__ */Object.freeze([
193
- /* @__PURE__ */Object.freeze({sentiment:"up",label:$f.feedbackHelpful}),
194
- /* @__PURE__ */Object.freeze({sentiment:"down",label:$f.feedbackNotHelpful})]);function Lk(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function Bk(e,t){if(e==="down"&&t!==null){let e=Dk.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return Lk(e)}var Hk=44,Uk="rgba(17,17,17,0.55)",Nk=26,$k=36,Wk=4,Vk=20,qk=38,Gk=18,Kk=12;function FeedbackReasons({visible:e,onSubmit:t,onSkip:r}){let n=useEverfurTheme(),i=a(()=>Yk(n),[n]),o=Mf(),[s,u]=l(null),[c,d]=l(""),[f,h]=l(false),[p,b]=l(false),m=()=>{u(null),d(""),h(false),b(false)},y=()=>{f||(m(),r())},v=async()=>{if(f)return;h(true),b(false);let e=c.trim();await t(s,e.length>0?e:null)?m():(h(false),b(true))};if(!e)return null;let k=[...c].length>qn;/* @__PURE__ */
195
- return U(z,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:y,children:/* @__PURE__ */N(R,{behavior:g.OS==="ios"?"padding":void 0,style:i.root,children:[
196
- /* @__PURE__ */U(T,{style:i.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:$f.feedbackSkipA11y}),
197
- /* @__PURE__ */N(C,{style:Lf(i.sheet,o),accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
198
- /* @__PURE__ */U(C,{style:i.handle}),
199
- /* @__PURE__ */N(C,{style:i.header,children:[
200
- /* @__PURE__ */U(C,{style:i.iconBadge,children:/* @__PURE__ */U(ThumbGlyph,{size:Gk,color:n.color.brandInk,active:false,rotate:"180deg"})}),
201
- /* @__PURE__ */N(C,{style:i.headerText,children:[
202
- /* @__PURE__ */U(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:$f.feedbackTitle}),
203
- /* @__PURE__ */U(Text,{style:i.subtitle,children:$f.feedbackSubtitle})]})]}),
204
- /* @__PURE__ */U(C,{style:i.options,children:Dk.map(e=>{let t=s===e.key;/* @__PURE__ */
205
- return N(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[i.option,t?i.optionSelected:null],onPress:()=>u(t=>t===e.key?null:e.key),children:[
206
- /* @__PURE__ */U(Text,{style:[i.optionLabel,t?i.optionLabelSelected:null],children:e.label}),
207
- /* @__PURE__ */U(C,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */U(CheckGlyph,{size:Kk,color:n.color.surface,strokeWidth:2}):null})]},e.key)})}),
208
- /* @__PURE__ */N(C,{style:i.inputWrap,children:[
209
- /* @__PURE__ */U(cf,{style:i.input,placeholder:$f.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:$f.feedbackNotesPlaceholder,value:c,onChangeText:d,multiline:true,editable:!f}),c.length>0?/* @__PURE__ */U(Text,{tier:"compact",style:[i.counter,k?i.counterOver:null],children:`${[...c].length}/${qn}`}):null]}),p?/* @__PURE__ */U(Text,{style:i.failed,accessibilityRole:"alert",children:$f.feedbackFailed}):null,
210
- /* @__PURE__ */N(C,{style:i.actions,children:[
211
- /* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:$f.feedbackSubmit,accessibilityState:{busy:f,disabled:f||k},disabled:f||k,style:[i.submit,f||k?i.submitDisabled:null],onPress:()=>{v()},children:/* @__PURE__ */U(Text,{tier:"control",style:i.submitLabel,children:$f.feedbackSubmit})}),
212
- /* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:$f.feedbackSkipA11y,hitSlop:8,onPress:y,style:i.skip,children:/* @__PURE__ */U(Text,{tier:"control",style:i.skipLabel,children:$f.feedbackSkip})})]})]})]})})}function Yk(e){let t=e.color,r=e.type,n=e.radius,l=e.slots,i=lb(l.dialog);return m.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...Tb,backgroundColor:Uk},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Nk,borderTopRightRadius:Nk,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...nk(l.dialog)},handle:{alignSelf:"center",width:$k,height:Wk,borderRadius:Wk/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:qk,height:qk,borderRadius:qk/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight,...i},subtitle:{...face(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted,...i},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:m.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...rb(l.chip,m.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.primary,...lb(l.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:Vk,height:Vk,borderRadius:Vk/2,borderWidth:2,borderColor:t.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top",...rb(l.input,1),...lb(l.input)},counter:{...face(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:Hk,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...rb(l.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...lb(l.primaryButton)},skip:{minHeight:Hk,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}var Qk=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function Jk(){let e=globalThis,t=e[Qk];if(t!==void 0)return t;let r={factory:createContext(null),home:createContext(null)};return e[Qk]=r,r}var Xk=Jk().factory,Zk=Jk().home;function ew(){return o(Xk)}function tw(){return o(Zk)?.kit??null}function rw(){return o(Zk)}var nw=15,lw=8;function HistoryBar({bar:e,history:t,empty:r,unread:n,extra:l}){let i=useEverfurTheme(),o=tw(),s=a(()=>o!==null?aw(i,o):sw(i),[i,o]),u=t.cursor===null?t.rows.length:0,c=t=>{let r=e.renderIcon;if(r!==void 0)/* @__PURE__ */return U(HostRender,{render:()=>r(t),fallback:null});if(o===null)return null;let n=String(m.flatten(s.label).color??i.color.linkInk);return t==="history"?/* @__PURE__ */U(HistoryGlyph,{size:ow,color:n,strokeWidth:1.8}):/* @__PURE__ */U(EditGlyph,{size:ow,color:n,strokeWidth:1.8})};/* @__PURE__ */
213
- return N(C,{style:s.bar,testID:"everfur-history-bar",children:[
214
- /* @__PURE__ */N(T,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?iw:void 0,children:[c("history"),
215
- /* @__PURE__ */U(Text,{tier:"control",style:s.label,children:e.chats}),u>0?/* @__PURE__ */U(C,{style:s.count,children:/* @__PURE__ */U(Text,{tier:"badge",style:s.countText,children:String(u)})}):null,n?/* @__PURE__ */U(C,{style:s.dot,testID:"everfur-chat-history-bar-unread"}):null]}),e.extra??null,l??null,
216
- /* @__PURE__ */U(C,{style:s.spacer}),r?null:/* @__PURE__ */N(T,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?iw:void 0,children:[c("edit"),
217
- /* @__PURE__ */U(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var iw=4,ow=18;function aw(e,t){return{...sw(e),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:e.space.sm},control:t.view(".thread__hist"),label:t.text(".thread__hist"),count:t.view(".thread__count"),countText:t.text(".thread__count")}}function sw(e){let t=e.color,r=e.space;return m.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:Jb},label:{...face(e,"bold"),fontSize:nw,color:t.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,alignItems:"center"},countText:{...face(e,"bold"),fontSize:e.type.size.caption,color:t.text.primary},dot:{width:lw,height:lw,borderRadius:lw/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var uw=.88,cw=420,dw=58,fw="rgba(17,17,17,0.28)",hw=.15,pw=14,gw=12,bw=44,mw=16,yw=14,vw=12,kw=14,ww=8,Cw=2,Sw=.5,xw=Eg(Cg.standard);function _w(e){return Math.min(Math.round(e*uw),cw)}function HistoryDrawer({chat:e,history:t}){let[r,n]=l(t.open),i=s(()=>n(false),[]);return t.open&&!r&&n(true),r?/* @__PURE__ */U(DrawerModal,{chat:e,history:t,onHidden:i}):null}function DrawerModal({chat:e,history:t,onHidden:r}){let l=useEverfurTheme(),i=a(()=>Rw(l),[l]),o=Ig(),s=B(),{width:c}=D(),d=_w(c),f=t.open,h=u(null);h.current===null&&(h.current=new A.Value(o.drawerMs<=0&&f?1:0));let p=h.current;n(()=>{if(!f&&o.drawerMs<=0){r();return}let e=A.timing(p,{toValue:f?1:0,duration:o.drawerMs,easing:xw,useNativeDriver:true});return e.start(({finished:e})=>{e&&!f&&r()}),()=>e.stop()},[f,p,o.drawerMs,r]);let b=p.interpolate({inputRange:[0,1],outputRange:[-d,0]}),m=t.filtered,y=t.rows.length===0,v=t.cursor===null&&!t.loading&&t.error===null,k=y&&t.loading?/* @__PURE__ */N(C,{style:i.emptyCard,accessibilityLabel:Vp.loading,accessibilityState:{busy:true},children:[
218
- /* @__PURE__ */U(O,{color:i.emptyTitle.color}),
219
- /* @__PURE__ */U(Text,{style:i.emptyBody,children:Vp.loading})]}):y&&t.error!==null?/* @__PURE__ */N(C,{style:i.emptyCard,children:[
220
- /* @__PURE__ */U(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:Vp.loadFailed}),
221
- /* @__PURE__ */U(Text,{style:i.emptyBody,children:t.error}),
222
- /* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:Vp.retry,containerStyle:i.retrySlot,style:i.retryButton,onPress:()=>{t.load()},children:/* @__PURE__ */U(Text,{tier:"control",style:i.retryText,children:Vp.retry})})]}):t.emptyKind==="empty"?/* @__PURE__ */N(C,{style:i.emptyCard,children:[
223
- /* @__PURE__ */U(Text,{style:i.emptyTitle,children:Vp.empty}),
224
- /* @__PURE__ */U(Text,{style:i.emptyBody,children:Vp.emptyBody})]}):
225
- /* @__PURE__ */U(Text,{style:i.noMatch,children:Vp.noMatch}),w=!t.searching&&t.loadingMore?/* @__PURE__ */U(C,{style:i.loadMoreFooter,children:/* @__PURE__ */U(Text,{style:i.loadMoreLabel,children:Vp.loadingMore})}):null;/* @__PURE__ */
226
- return U(z,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:/* @__PURE__ */N(C,{style:i.root,children:[
227
- /* @__PURE__ */U(T,{style:Tb,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Vp.closeA11y,children:/* @__PURE__ */U(A.View,{style:[i.backdrop,{opacity:p}]})}),
228
- /* @__PURE__ */U(A.View,{style:[i.panel,{width:d,paddingTop:Math.max(dw,s.top+l.space.md),transform:[{translateX:b}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */N(R,{style:i.keyboardAvoider,behavior:g.OS==="ios"?"padding":"height",children:[
229
- /* @__PURE__ */N(C,{style:i.header,children:[
230
- /* @__PURE__ */U(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:Vp.heading}),
231
- /* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:Vp.newChat,style:i.newChat,onPress:t.newConversation,children:/* @__PURE__ */U(Text,{tier:"control",style:i.newChatLabel,children:Vp.newChat})}),
232
- /* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:Vp.close,hitSlop:0,style:i.closeButton,onPress:t.close,children:/* @__PURE__ */U(CloseGlyph,{size:mw,color:l.color.text.muted,strokeWidth:1.75})})]}),
233
- /* @__PURE__ */N(C,{style:i.searchPill,children:[
234
- /* @__PURE__ */U(SearchGlyph,{size:kw,color:l.color.text.muted,strokeWidth:1.5}),
235
- /* @__PURE__ */U(cf,{value:t.query,onChangeText:e=>t.setQuery(e.replace(/^\s+/,"")),style:i.searchInput,placeholder:Vp.searchPlaceholder,placeholderTextColor:l.color.text.placeholder,accessibilityLabel:Vp.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
236
- /* @__PURE__ */U(Text,{tier:"compact",style:i.countLabel,children:Yp(t.rows.length,v)}),t.error!==null&&!y?/* @__PURE__ */U(C,{style:i.errorCard,children:/* @__PURE__ */U(Text,{style:i.errorText,accessibilityRole:"alert",children:t.error})}):null,
237
- /* @__PURE__ */U(M,{data:m,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */U(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:m.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:w,onEndReached:t.loadMore,onEndReachedThreshold:Sw})]})})]})})}function Row({row:e,active:t,disabled:r,styles:n,onPress:l}){let i=e.unreadCount!==null&&e.unreadCount>0,o=Kp(e);/* @__PURE__ */
238
- return N(PressScale,{accessibilityRole:"button",accessibilityLabel:Qp(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:l,children:[
239
- /* @__PURE__ */N(C,{style:n.itemRow,children:[
240
- /* @__PURE__ */U(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:qp(e.title)}),i?/* @__PURE__ */U(C,{style:n.unreadDot}):null]}),o!==null?/* @__PURE__ */U(Text,{tier:"compact",style:n.itemMeta,numberOfLines:1,children:o}):null]})}function Rw(e){let t=e.color,r=e.space,n=e.type,l=e.slots,i=t.text.primary,o=lb(l.card);return m.create({root:{flex:1},backdrop:{flex:1,backgroundColor:fw},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:r.lg,borderRightWidth:m.hairlineWidth,borderRightColor:t.borderRingCream,gap:r.md,...lk(l.dialog,m.hairlineWidth)},keyboardAvoider:{flex:1,gap:r.md},header:{flexDirection:"row",alignItems:"center",gap:r.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:n.size.subtitle,color:i,...lb(l.dialog)},newChat:{minHeight:bw,justifyContent:"center",paddingHorizontal:r.xs},newChatLabel:{...face(e,"bold"),fontSize:pw,color:t.brandInk},closeButton:{width:bw,height:bw,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:r.md+Cw,paddingVertical:r.sm+Cw,borderWidth:1,borderColor:t.borderRingCream,...rb(l.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:n.size.bodyTight,color:t.text.primary,padding:0,...lb(l.input)},countLabel:{...face(e,"mono"),fontSize:gw,color:t.text.muted},list:{gap:r.xs,paddingBottom:r.xl},listEmpty:{flexGrow:1},item:{paddingVertical:r.sm+Cw,paddingHorizontal:r.sm,borderRadius:e.radius.md,gap:Cw},itemActive:{backgroundColor:po(t.highlight,hw)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:r.sm},itemTitle:{...face(e,"bold"),flex:1,fontSize:n.size.bodyTight,color:i},itemMeta:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted},unreadDot:{width:ww,height:ww,borderRadius:ww/2,backgroundColor:t.danger},errorCard:{borderRadius:vw,borderWidth:m.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:r.md},errorText:{...face(e,"regular"),fontSize:n.size.caption,color:t.danger},emptyCard:{borderRadius:yw,padding:r.md+Cw,gap:r.xs+Cw,backgroundColor:t.surfaceSubtle,borderWidth:m.hairlineWidth,borderColor:t.borderRingCream,...rb(l.card,m.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:n.size.bodyTight,color:i,...o},emptyBody:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.secondary,...o},noMatch:{...face(e,"regular"),fontSize:n.size.bodyTight,color:t.text.muted,paddingVertical:r.sm},retrySlot:{marginTop:r.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:r.md+Cw,paddingVertical:r.sm,borderWidth:1,borderColor:t.brandInk,...rb(l.primaryButton)},retryText:{...face(e,"bold"),fontSize:n.size.caption,color:t.brandInk,...lb(l.primaryButton)},loadMoreFooter:{paddingVertical:r.md+Cw,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted}})}function Tw(e,t=/* @__PURE__ */new Date,r){let n=new Date(e);if(Number.isNaN(n.getTime()))return null;let l=new Date(t);l.setHours(0,0,0,0);let i=new Date(n);i.setHours(0,0,0,0);let o=Math.round((l.getTime()-i.getTime())/864e5);if(o===0||o===1)try{let e=new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day");return e.charAt(0).toLocaleUpperCase(r)+e.slice(1)}catch{}return n.toLocaleDateString(r,{month:"short",day:"numeric"})}function Iw(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function zw(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=Tw(n.updatedAt,t)??"",l=r[r.length-1];l!==void 0&&l.day===e?l.rows.push(n):r.push({day:e,rows:[n]})}return r}var Pw="rgba(38,37,35,0.38)",Ow=28,Ew=40,jw=5,Fw=11,Aw=10.5,Dw=36,Mw=11,Lw=14,Bw=15,Hw=13.5,Uw=48,Nw=2,$w=1.3,Ww=.12,Vw=16,qw=8,Gw="80%";function Kw(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */U(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:t,sheet:r}){let n=useEverfurTheme(),l=a(()=>Yw(n),[n]),i=B(),o=a(()=>zw(t.rows),[t.rows]),s=Mf();if(!t.open)return null;let u=n.color,c=r?.title?.trim(),d=c!==void 0&&c!==""?c:Vp.heading;/* @__PURE__ */
241
- return U(z,{visible:true,transparent:true,animationType:"slide",onRequestClose:t.close,children:/* @__PURE__ */N(C,{style:l.root,children:[
242
- /* @__PURE__ */U(T,{style:[Tb,l.scrim],onPress:t.close,accessibilityRole:"button",accessibilityLabel:Vp.closeA11y}),
243
- /* @__PURE__ */N(C,{style:Lf([l.sheet,{paddingBottom:Math.max(40,i.bottom+n.space.lg)}],s),accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
244
- /* @__PURE__ */U(C,{style:l.grab}),
245
- /* @__PURE__ */N(C,{style:l.top,children:[
246
- /* @__PURE__ */U(Text,{tier:"compact",style:l.kicker,accessibilityRole:"header",children:d}),
247
- /* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:Vp.closeA11y,onPress:t.close,style:l.close,children:Kw(r,"close",/* @__PURE__ */U(CloseGlyph,{size:22,color:u.text.primary,strokeWidth:2}))})]}),
248
- /* @__PURE__ */N(P,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */N(C,{style:l.state,accessibilityLabel:Vp.loading,accessibilityState:{busy:true},children:[
249
- /* @__PURE__ */U(O,{color:u.brandInk}),
250
- /* @__PURE__ */U(Text,{tier:"compact",style:l.mono,children:Vp.loading})]}):null,t.error!==null?/* @__PURE__ */N(C,{style:l.state,children:[
251
- /* @__PURE__ */U(Text,{style:l.stateText,accessibilityRole:"alert",children:Vp.loadFailed}),
252
- /* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:Vp.retry,onPress:()=>{t.load()},style:l.link,children:/* @__PURE__ */U(Text,{tier:"control",style:l.linkText,children:Vp.retry})})]}):null,!t.loading&&t.error===null&&t.rows.length===0?/* @__PURE__ */U(Text,{style:[l.stateText,l.state],children:Vp.empty}):null,o.map((n,i)=>/* @__PURE__ */N(h,{children:[n.day?/* @__PURE__ */U(Text,{tier:"compact",style:[l.mono,l.day,i===0?l.dayFirst:null],children:n.day}):null,n.rows.map(n=>{let i=n.id===e.conversationId,o=n.unreadCount!==null&&n.unreadCount>0,a=Iw(n.updatedAt);/* @__PURE__ */
253
- return N(T,{accessibilityRole:"button",accessibilityLabel:Qp(n),accessibilityState:{selected:i},onPress:()=>{t.resume(n.id)},style:[l.row,i?l.rowCurrent:null],children:[
254
- /* @__PURE__ */U(C,{style:l.icon,children:Kw(r,"chat",/* @__PURE__ */U(ChatBubbleGlyph,{size:19,color:u.linkInk,strokeWidth:1.75}))}),
255
- /* @__PURE__ */N(C,{style:l.rowWords,children:[
256
- /* @__PURE__ */U(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:qp(n.title)}),n.preview!==void 0?/* @__PURE__ */U(Text,{tier:"compact",style:l.preview,numberOfLines:1,children:n.preview}):null]}),
257
- /* @__PURE__ */N(C,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */U(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */U(C,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:Vp.more,onPress:t.loadMore,style:l.link,children:/* @__PURE__ */U(Text,{tier:"control",style:l.linkText,children:Vp.more})}):null]}),
258
- /* @__PURE__ */N(T,{accessibilityRole:"button",accessibilityLabel:Vp.newChat,onPress:t.newConversation,style:l.newChat,children:[Kw(r,"edit",/* @__PURE__ */U(EditGlyph,{size:18,color:n.slots.primaryButton?.textColor??u.onPrimary,strokeWidth:1.75})),
259
- /* @__PURE__ */U(Text,{tier:"control",style:l.newChatText,children:Vp.newChat})]})]})]})})}function Yw(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:Aw,letterSpacing:Aw*.06,textTransform:"uppercase",color:t.text.muted};return m.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:Pw},sheet:{maxHeight:Gw,backgroundColor:t.surface,borderTopLeftRadius:Ow,borderTopRightRadius:Ow,paddingTop:10,paddingHorizontal:20},grab:{width:Ew,height:jw,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...n,fontSize:Fw,letterSpacing:Fw*.08,flexShrink:1},close:{width:Jb,height:Jb,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:Jb/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:r.xs},mono:n,day:{marginTop:r.lg,marginBottom:r.xs},dayFirst:{marginTop:Nw},state:{marginVertical:r.md,gap:r.sm,alignItems:"flex-start"},stateText:{...face(e,"regular"),fontSize:e.type.size.body,color:t.text.primary},link:{minHeight:Jb,justifyContent:"center"},linkText:{...face(e,"bold"),fontSize:e.type.size.body,color:t.brandInk},row:{flexDirection:"row",alignItems:"center",gap:r.md,paddingVertical:10,paddingHorizontal:r.sm,borderRadius:Lw,minHeight:Jb},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:Dw,height:Dw,borderRadius:Mw,backgroundColor:po(t.linkInk,Ww)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:Bw,lineHeight:Bw*$w,color:t.text.primary},preview:{...face(e,"regular"),fontSize:Hw,color:t.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:Aw*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:qw,height:qw,borderRadius:qw/2,backgroundColor:t.danger},newChat:{marginTop:r.lg,minHeight:Uw,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...rb(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:Vw,color:t.onPrimary,...lb(e.slots.primaryButton)}})}var Qw="Close",Jw=/* @__PURE__ */Object.freeze({action:e=>e.possessive===null?null:`See ${e.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(e,t)=>e.risk?.lead?`${e.risk.lead} ${t}`:`${e.title}: ${t}`,close:e=>e.possessive===null?null:`Close ${e.possessive} focus`,resultsKicker:e=>e.possessive===null?null:`${Xw(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function Xw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function healthPlanPossessive(e){let t=typeof e.sex=="string"?e.sex.trim().toLowerCase():null;if(t==="female")return"her";if(t==="male")return"his";let r=typeof e.name=="string"?e.name.trim():"";return r!==""?`${r}'s`:null}function healthPlanTopCard(e,t={}){let r=e?.page?.focus;if(e===null||r===void 0||r.title.trim()===""||r.kicker.trim()==="")return;let n={...Jw,...t.copy},l={pet:e.pet,possessive:healthPlanPossessive(e.pet)},i=r.sources?.find(e=>e.label.trim()!=="")?.label,o=t.onOpenPlan,a=o===void 0?null:n.action(l),s=n.close(l),u=n.ask.trim(),c=t.results!==void 0&&r.report!==void 0?t.results:void 0;if(c!==void 0){let e=n.resultsKicker(l)?.trim()||r.kicker,s=n.resultsClose(l),d=c.onTopRisk??o,f={key:"top-risk",label:n.resultsTopRisk,title:r.title,...r.risk?.lead?{line:r.risk.lead}:{},tone:"risk",...d===void 0?{}:{onPress:d}};return{kicker:e,...i===void 0?{}:{badge:i},title:r.title,results:[f,...c.rows??[]],...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?Qw:s,pill:e,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}return{kicker:r.kicker,...i===void 0?{}:{badge:i},title:r.title,...r.risk?.lead?{lead:r.risk.lead}:{},...r.risk?.body?{body:r.risk.body}:{},...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?Qw:s,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function Zw(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function eC(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var tC=20,rC=14,nC=16,lC=18,iC=22,oC=15,aC=12,sC=24,uC=15,cC=14.5,dC=21,fC=14.5,hC=18,pC=9,gC=36,bC=14,mC=15,yC=8,vC=40;function TopCard({card:e,open:t,onOpenChange:r,ask:n}){let l=useEverfurTheme(),i=tw(),o=a(()=>i!==null?wC(i):CC(l),[l,i]),s=a(()=>rb(l.slots.card),[l.slots.card]);if(!t)return null;let u=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:$f.close,c=e.action,d=e.ask,f=/* @__PURE__ */U(CloseGlyph,{size:i!==null?HOME_CLOSE_GLYPH(i):hC,color:i!==null?String(i.text(".ask-focus__x").color):l.color.text.primary,strokeWidth:2});/* @__PURE__ */
260
- return N(C,{style:[o.card,s],testID:"everfur-top-card",children:[
261
- /* @__PURE__ */N(C,{style:o.kickerRow,children:[
262
- /* @__PURE__ */U(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */U(C,{style:o.badge,children:/* @__PURE__ */U(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */U(T,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?kC:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */U(HostRender,{render:()=>e.renderIcon?.("close"),fallback:f}):f}):null]}),
263
- /* @__PURE__ */U(Text,{tier:"heading",style:o.title,accessibilityRole:"header",children:e.title}),e.lead!==void 0||e.body!==void 0?/* @__PURE__ */N(C,{style:o.finding,children:[
264
- /* @__PURE__ */U(C,{style:o.dot}),
265
- /* @__PURE__ */N(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */U(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */N(C,{style:o.actions,children:[c!==void 0?/* @__PURE__ */U(T,{onPress:()=>{Fh(c.onPress)},accessibilityRole:"button",accessibilityLabel:c.label,style:o.action,hitSlop:i!==null?kC:void 0,children:/* @__PURE__ */U(Text,{tier:"control",style:o.actionText,children:c.label})}):null,d!==void 0?/* @__PURE__ */U(T,{onPress:()=>n(d.prompt),accessibilityRole:"button",accessibilityLabel:d.label,style:o.ask,hitSlop:i!==null?kC:void 0,children:/* @__PURE__ */U(Text,{tier:"control",style:o.askText,children:d.label})}):null]}):null]})}function TopCardPill({card:e,open:t,onOpenChange:r}){let n=useEverfurTheme(),l=tw(),i=a(()=>l!==null?wC(l):CC(n),[n,l]);if(t||e.closeLabel===void 0)return null;let o=e.pill??e.kicker;/* @__PURE__ */
266
- return N(T,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?kC:void 0,testID:"everfur-top-card-pill",children:[
267
- /* @__PURE__ */U(C,{style:i.pillDot}),
268
- /* @__PURE__ */U(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var kC=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:hC};function wC(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),l=typeof n.height=="number"?n.height:pC;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-l)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function CC(e){let t=e.color,r=e.space;return m.create({card:{paddingTop:rC,paddingHorizontal:nC,paddingBottom:nC,borderRadius:tC,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Jb-8},kicker:{...eC(e),fontSize:oC,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:sC,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:aC,color:t.text.secondary},close:{width:Jb,height:Jb,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:Jb/2},title:{...eC(e),fontSize:lC,lineHeight:iC,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:pC,height:pC,borderRadius:pC/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:cC,lineHeight:dC,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(vC,Jb),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:uC,color:t.onPrimary},ask:{minHeight:Jb,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:fC,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(gC,Jb),paddingHorizontal:bC,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:yC,height:yC,borderRadius:yC/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:mC,color:t.danger,flexShrink:1}})}var SC=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),xC=/* @__PURE__ */new WeakMap;function _C(e){let t=xC.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...SC},i=(e,t)=>bo(e,t,ao(t),RC),o=(e,t)=>contrastRatio(e,t)>=RC?e:oo(t,RC),a=[l.card,l.paper].map(e=>ho(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return xC.set(e,u),u}var RC=4.5;function TC(e,t){for(let r of t)if(contrastRatio(r,e)>=RC)return r;return oo(e,RC)}function IC(e,t,r){let n=po(e,t);return(n===null?null:ho(n,r))??r}function zC(e){let t=_C(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:TC(t.accent,[t.ink,t.onAccent]),accent2:IC(t.accent,.75,n),accent4:IC(t.accent,.17,n),accentChip:IC(t.accent,.47,n),link:t.link,linkChip:IC(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var PC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),OC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),EC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],jC=17,FC=1.5,AC=400,DC=700;function MC(e){return e<=450?"regular":e<=650?"medium":"bold"}function LC(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function BC(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:LC(r)}}let n=t==="$serif"?headingFace(e,MC(r)):face(e,MC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:LC(r)}}function HC(e,t,r={}){let n=zC(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},a=/* @__PURE__ */new Map,s=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),s=a.get(l);if(s!==void 0)return s;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return a.set(l,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=s(e),l={};for(let[e,t]of Object.entries(n))PC.has(e)||OC.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of EC){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let a=n.shadow;if(Array.isArray(a)){let[e,t,r,n]=a;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=s(r),a=typeof o.fontSize=="number"?o.fontSize:jC,u=typeof o.lh=="number"?o.lh:FC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...BC(e,f,c),fontSize:a,lineHeight:Math.round(a*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*a*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(AC,e),strong:(...e)=>f(DC,e),icon:(...e)=>{let t=s(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=s([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=s(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>s(t)[e]}}var UC={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},NC=16;var $C=4e3,WC=.5;function VC(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function qC(e,t,r){if(e.length===0)return r;let n=VC(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=WC*e.length+1;for(let o of l)if(VC(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=m.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=u({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[c,d]=l(null),f=c!==null&&c.key===o?c.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=qC(t,l,(e.ch+WC)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
269
- return N(C,{style:GC.wrap,children:[
270
- /* @__PURE__ */U(Text,{tier:"heading",style:f===null?t:[t,{maxWidth:f}],accessibilityRole:"header",children:e}),
271
- /* @__PURE__ */U(C,{style:GC.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */N(C,{style:GC.probeRow,children:[
272
- /* @__PURE__ */U(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.ch=t}),children:"0"}),
273
- /* @__PURE__ */U(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */U(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var GC=m.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:$C,flexDirection:"row",alignItems:"flex-start"}});function KC(e){return{kit:HC(e,UC),Title:BalancedTitle,titleCh:NC}}var YC=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function QC(){let e=globalThis,t=e[YC];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[YC]=r,r}var JC=e=>{let t=QC();return t.listeners.add(e),()=>t.listeners.delete(e)},XC=()=>QC().count>0;function useHostPoweredBy(){return i(JC,XC,XC)}var ZC=/* @__PURE__ */Object.freeze({}),eS=100,tS=20;function rS(e,t,r,n){return![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}function nS(e,t){let r=typeof e=="number"&&Number.isFinite(e),i=u(null),[o,c]=l(null),d=u(null),f=u(null),h=u(true),p=s(()=>{f.current!==null&&clearTimeout(f.current),f.current=null},[]);n(()=>(h.current=true,()=>{h.current=false,p()}),[p]);let g=s(function e(t){i.current?.measureInWindow((r,n)=>{let l=d.current;if(!h.current||l===null)return;let i=rS(n,l.y,l.height,k.get("window").height);if(i!==null){c(e=>e!==null&&e.chatTop===i.chatTop&&e.parentTop===i.parentTop?e:i);return}t>=tS||(f.current=setTimeout(()=>{f.current=null,e(t+1)},eS))})},[]),b=s(e=>{let{y:t,height:r}=e.nativeEvent.layout;d.current={y:t,height:r},p(),g(0)},[g,p]);return a(()=>{if(!t)return{avoidingProps:r?{keyboardVerticalOffset:e}:ZC,probeRef:null,topInWindow:null};let n=o?.parentTop??0;return{avoidingProps:r?{keyboardVerticalOffset:e,onLayout:b}:n>0?{keyboardVerticalOffset:n,onLayout:b}:{onLayout:b},probeRef:i,topInWindow:o?.chatTop??null}},[t,r,e,o,b])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */U(C,{ref:e,collapsable:false,pointerEvents:"none",style:lS})}var lS=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function iS(){let[e,t]=l(false);return n(()=>{let e=I;if(typeof e?.addListener!="function")return;let r=g.OS==="ios",n=e.addListener(r?"keyboardWillShow":"keyboardDidShow",()=>t(true)),l=e.addListener(r?"keyboardWillHide":"keyboardDidHide",()=>t(false));return()=>{n.remove(),l.remove()}},[]),e}function oS(e,t,r){return bo(e,t,ao(t),r)}function aS(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=qv(t),l=r?n.warning:n.info,i=Vv(t)&&!l?e:sS(e,t,r);return uS(i,t.slots.banner)}function sS(e,t,r){let n=t.color,l=ho(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,i=r?n.cautionAccent:n.infoEdge,o=oS(ho(i,n.surface)??i,[n.surface,n.chatGround],Oo),a=oS(r?n.warningStrong:n.info,[l,n.surface],So);/* @__PURE__ */
274
- return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:oS(n.text.primary,[l],So),pillColor:n.surface})}function uS(e,t){if(t===void 0)return e;let r={...e};return t.backgroundColor!==void 0&&(r.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(r.borderColor=t.borderColor),t.textColor!==void 0&&(r.textColor=t.textColor,r.reasonColor=t.textColor),/* @__PURE__ */Object.freeze(r)}function cS(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}var dS=.75,fS=1.5,hS=.4,pS=4,gS=1.5,bS=22,mS=14,yS=8,vS=20,kS=10,wS=13,CS=12,SS=15,xS=44,_S=14,RS=1.25,TS=14,IS=6,zS=2;function PS(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:po(r.danger,hS)??r.danger,borderWidth:fS},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}};let n=e.slots.banner?.borderRadius;return{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:dS,...n===void 0?{}:{borderRadius:n}},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}function UrgencyBanner({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,compact:i=false}){let o=useEverfurTheme(),s=a(()=>OS(o),[o]),u=Ig(),c=e.tier===null?null:aS(e.tier,o),d=e.source;/* @__PURE__ */
275
- return N($,{children:[
276
- /* @__PURE__ */U(FadePresence,{visible:e.showBanner&&c!==null,inMs:u.bannerInMs,outMs:u.bannerOutMs,style:s.pinned,children:c!==null&&d!==null?/* @__PURE__ */U(BannerCard,{tier:c,reason:d.reason,surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,styles:s,compact:i}):null}),
277
- /* @__PURE__ */U(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:$f.showLatestVetAlert,hitSlop:kS,onPress:e.expand,children:/* @__PURE__ */U(InfoGlyph,{size:vS,color:o.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:e,reason:t,surface:r,petRef:n,renderVetAction:l,onFindVet:i,vet:o,styles:a,compact:s}){let u=useEverfurTheme(),c=PS(u,e),d=/* @__PURE__ */U(VetAction,{tier:e,paint:c,petRef:n,onFindVet:i,vet:o,styles:a}),f=r.showVetAction?l!==void 0?/* @__PURE__ */U(HostRender,{render:()=>l(e.level),fallback:d,resetKey:e.level}):d:null,h=c.action!==null?/* @__PURE__ */U(PoisonControl,{paint:c.action,styles:a}):null,p=e.level==="emergency"&&i===void 0,g=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
278
- return N(C,{...g?{accessibilityRole:"alert"}:{accessibilityLiveRegion:"polite"},style:[a.card,c.card,s?a.cardCompact:null],testID:s?"chat-urgency-compact":void 0,children:[
279
- /* @__PURE__ */U(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */U(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?zS:void 0,accessibilityLabel:s?t:void 0,children:t}):null,p?/* @__PURE__ */U(Text,{style:[a.reason,a.erLine,{color:c.reason}],children:$f.goToNearestEmergencyVet}):null,f!==null||h!==null?/* @__PURE__ */N(C,{style:a.actions,children:[f,h]}):null,r.dismissLabel!==null?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:r.dismissLabel,hitSlop:yS,containerStyle:a.closeSlot,style:a.closeButton,onPress:r.dismiss,children:/* @__PURE__ */U(CloseGlyph,{size:mS,color:c.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let r=()=>{try{_.openURL(Gf).catch(()=>{})}catch{}};/* @__PURE__ */
280
- return U(PressScale,{accessibilityRole:"button",accessibilityLabel:$f.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:r,children:/* @__PURE__ */U(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:$f.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:l,styles:i}){let o=useEverfurTheme(),a=useVetVisit(cS(r,l)),s=a.status==="opening",u=!a.available&&n!==void 0,c=a.available?()=>{a.open()}:n!==void 0?()=>{Fh(n,e.level)}:null;if(c===null)return null;let d=t.action;if(d!==null){let e=u?$f.nearestEmergencyVet:$f.findVet,t=nb(o.slots.vetVisitButton)?.textColor??d.ink;/* @__PURE__ */
281
- return N(PressScale,{accessibilityRole:"button",accessibilityLabel:u?$f.nearestEmergencyVet:$f.findVetA11y,accessibilityState:{busy:s},hitSlop:0,style:[i.action,{backgroundColor:d.fill,borderColor:d.edge},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
282
- /* @__PURE__ */U(MapPinGlyph,{size:wS,color:t,strokeWidth:1.5}),
283
- /* @__PURE__ */U(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=nb(o.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
284
- return N(PressScale,{accessibilityRole:"button",accessibilityLabel:$f.findVetA11y,accessibilityState:{busy:s},style:[i.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
285
- /* @__PURE__ */U(MapPinGlyph,{size:wS,color:f,strokeWidth:1.5}),
286
- /* @__PURE__ */U(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:$f.findVet})]})}function OS(e){let t=nb(e.slots.vetVisitButton),r=e.space,n=e.type;return m.create({pinned:{marginTop:0,marginBottom:r.xs,paddingHorizontal:r.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:r.lg+pS,paddingVertical:r.lg,gap:r.sm},cardCompact:{paddingVertical:r.md,gap:r.xs},label:{...face(e,"bold"),fontSize:n.size.body,paddingRight:bS},reason:{...face(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*gS),paddingRight:bS},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm},action:{flexDirection:"row",alignItems:"center",gap:IS,minHeight:xS,paddingHorizontal:_S,borderRadius:e.radius.pill,borderWidth:RS},actionLabel:{...face(e,"bold"),fontSize:TS},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...rb(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:CS,lineHeight:SS},closeSlot:{position:"absolute",top:r.md,right:r.md},closeButton:{width:bS,height:bS,borderRadius:bS/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:r.lg,paddingTop:2,paddingBottom:r.xs}})}function ES(e,t,r,i){let[o,a]=l({pet:r,user:t}),s=o.pet!==r||o.user===null&&t!==null;s&&a({pet:r,user:t});let u=s?{user:t}:o,c=r!==null&&u.user!==null&&u.user!==t;return n(()=>{if(!c||t===null||r===null)return;let n=true,l=createPetsRepository(e.registry.services.authFor(t)),i=async()=>{let e=await l.list();n&&e.ok&&e.value.some(e=>e.petRef===r)&&a({pet:r,user:t})};i();let o=$i(e,()=>{i()});return()=>{n=false,o()}},[c,e,t,r,i]),c}var jS=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(e){let{runtime:t,userRef:r,activePet:o,scopeEpoch:c}=vd(),d=e?.petRef??o??null,f=e?.conversationId??null,h=ES(t,r,d,c),p=a(()=>({runtime:t,userRef:r,petRef:d,conversationId:f,scopeEpoch:c,held:h}),[t,r,d,f,c,h]),[g,b]=l(null),m=h?null:g?.scope===p?g.controller:t.registry.peekChat({userRef:r,petRef:d,conversationId:f}),y=u(null);n(()=>{if(h)return;let e=t.registry.acquireChat({userRef:r,petRef:d,conversationId:f});return y.current=e,b({scope:p,controller:e}),()=>{y.current=null,b(t=>t?.controller===e?null:t),t.registry.releaseChat(e)}},[t,r,d,f,c,h,p]);let v=s(e=>m?m.subscribe(e):NOOP_UNSUBSCRIBE,[m]),k=s(()=>m?m.getSnapshot():jS,[m]),w=i(v,k,k),C=s((e,t)=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?AS(m,m.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>y.current===m):Promise.resolve(MS()),[m]),S=s(e=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?AS(m,m.askEverfur(e),()=>y.current===m):Promise.resolve(MS()),[m]),x=s(()=>m&&y.current===m?AS(m,m.retryLast(),()=>y.current===m):Promise.resolve(MS()),[m]),_=s(()=>{m&&y.current===m&&m.stop()},[m]),R=s(()=>{m&&y.current===m&&m.newConversation()},[m]),[T,I]=l({controller:null,byMessage:{}}),z=T.controller===m?T.byMessage:FS,P=s(async(e,t,r,n)=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let l=String(e),i=T.controller===m?T.byMessage[l]:void 0;if(i===t&&r==null)return I(e=>{let t={...e.controller===m?e.byMessage:{}};return delete t[l],{controller:m,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));I(e=>({controller:m,byMessage:{...e.controller===m?e.byMessage:{},[l]:t}}));let o=await m.submitFeedback(e,Bk(t,r??null),n??null);return y.current!==m?err(makeEverfurError("accessDenied")):(o.ok||I(e=>{let t={...e.controller===m?e.byMessage:{}};return i===void 0?delete t[l]:t[l]=i,{controller:m,byMessage:t}}),o)},[m,T]),O=a(()=>{let e=async e=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let t=await e(m);return y.current===m?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...d?{petRef:d}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[m,d]);return a(()=>({status:w.status,messages:w.messages,conversationId:w.conversationId,petRef:d,error:w.error,isStreaming:w.isStreaming,isBootstrapping:w.isBootstrapping,historyCursor:w.historyCursor??null,isLoadingHistory:w.isLoadingHistory??false,stopped:w.stopped??false,reconnecting:w.reconnecting??false,...O,suggestedPrompts:w.suggestedPrompts,unreadCount:w.unreadCount,hasUnreadThreads:w.hasUnreadThreads??false,pendingCheckin:w.pendingCheckin??null,newConversation:R,sentimentByMessage:z,feedback:P,send:C,askEverfur:S,retryLast:x,stop:_}),[w,d,C,S,x,_,O,R,z,P])}var NOOP_UNSUBSCRIBE=()=>{},FS=/* @__PURE__ */Object.freeze({});async function AS(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(DS(n.messages))}function DS(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}function MS(){return yp()}function LS(){let e=useEverfurPets(),{handle:t}=vd(),r=s(e=>t.setActivePet(e),[t]);return a(()=>({...e,setActivePet:r}),[e,r])}function BS(){try{let e=y?.announceForAccessibility;typeof e=="function"&&e.call(y,$f.answered)}catch{}}function HS(e){let t=u(false),r=u({send:e.send,id:e.conversationId});n(()=>{let n=r.current;if((n.send!==e.send||n.id!==null&&n.id!==e.conversationId)&&(t.current=false),r.current={send:e.send,id:e.conversationId},t.current&&!e.isStreaming){let t=e.messages[e.messages.length-1];t!==void 0&&t.role==="assistant"&&BS()}t.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var US=/* @__PURE__ */Object.freeze({kind:"live"}),NS=/* @__PURE__ */Object.freeze({kind:"folded"});function $S(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=On(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function WS(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=$S(t);if(e===null)continue;let n=r.get(e.caseId);(n===void 0||e.dueDay>=n.dueDay)&&r.set(e.caseId,{messageId:t.id,dueDay:e.dueDay})}if(r.size===0)return t;let n=null;for(let l of e){let e=$S(l);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===l.id){t.set(l.id,US),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(l.id,NS);continue}let i=[e.dueDay];n={id:l.id,caseId:e.caseId,days:i},t.set(l.id,{kind:"past",runDueDays:i})}return t}function VS(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var qS=864e5,GS=365;function KS(e,t){if(typeof e!="string"||typeof t!="string")return null;let r=Date.parse(e),n=Date.parse(t);if(Number.isNaN(r)||Number.isNaN(n))return null;let l=Math.floor(n/qS)-Math.floor(r/qS);return l<1||l>GS?null:l}function YS(e){return $S(e)?.dueDay||null}function QS(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:e,named:t,styles:r}){let n=Bv(e);return n.shown?/* @__PURE__ */N(C,{style:r.assistantSender,testID:"everfur-assistant-sender",children:[
287
- /* @__PURE__ */U(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */U(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:$f.assistantName}):null]}):t?/* @__PURE__ */U(Text,{tier:"control",style:r.assistantName,children:$f.assistantName}):null}var JS=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),XS="#C8BEB4";function ZS(e){return e?JS[e.toUpperCase()]??XS:XS}function ex(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function tx(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function rx(e){let t=tx(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function nx(e,t){let r=tx(e.source_name)??tx(e.sourceName),n=tx(e.section),l=tx(e.authority_tier)??tx(e.authorityTier),i=ex(l),o=r??tx(e.title)??`Source ${t+1}`,a=tx(e.monograph_chunk_id)??tx(e.chunkId),s=[n,i].filter(e=>e!==null).join(" · ");/* @__PURE__ */
288
- return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:rx(e.url),excerpt:tx(e.excerpt),tierColor:ZS(l),key:`${o}-${a??"none"}-${t}`})}function lx(e){return e===void 0||e.length===0?ix:/* @__PURE__ */Object.freeze(e.map((e,t)=>nx(e,t)))}var ix=/* @__PURE__ */Object.freeze([]);function ox(e){return e===1?`1 ${$f.sourceSingular}`:`${e} ${$f.sourcePlural}`}function ax(e,t){return`${t?$f.hideSources:$f.showSources} ${ox(e)}`}function sx(e){return[e.url!==null?`${$f.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function ux(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var cx=/^\s*[-*]\s+(\S.*)$/,dx=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function fx(e){let t=[],r=[],n=null,l=()=>{r.length>0&&t.push({kind:"text",text:r.join(`\n`)}),r=[]},i=()=>{n!==null&&t.push(n.ordered?{kind:"list",ordered:true,start:n.start,items:n.items}:{kind:"list",ordered:false,items:n.items}),n=null};for(let t of e.split(`\n`)){let e=cx.exec(t),o=e===null?dx.exec(t):null,a=e?.[1]??o?.[2];if(a===void 0){i(),r.push(t);continue}let s=o!==null;l(),n!==null&&n.ordered!==s&&i(),n===null&&(n={ordered:s,start:o===null?1:Number(o[1]),items:[]}),n.items.push(a.trim())}return l(),i(),t}function hx(e,t){let r=e.findIndex(e=>e.id===t);for(let t=r-1;t>=0;t-=1){let r=e[t];if(r!==void 0&&r.role==="user")return r.text}return null}function px(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function gx(e){return hardenHttpsUrl(e.trim())}function bx(e,t){if(t?.followUpActions===void 0||e.isStreaming||e.status==="error")return[];let r=e.messages[e.messages.length-1];return r===void 0||r.role!=="assistant"||r.pending===true?[]:px(t.followUpActions,{answer:r.text,question:hx(e.messages,r.id),messageId:r.id})}var mx=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,yx=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${cg}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${cg}})`,"gi"),vx=/https:\/\//i,kx=`.,;:!?'"`;function wx(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&vx.test(e)}function Cx(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):_x(r,e,t)},l=0;mx.lastIndex=0;for(let t=mx.exec(e);t!==null;t=mx.exec(e)){t.index>l&&n(e.slice(l,t.index));let i=t[1],o=t[2],a=t[3];i!==void 0?r.push({kind:"bold",text:i}):o!==void 0?r.push({kind:"italic",text:o}):a!==void 0&&r.push({kind:"code",text:a}),l=t.index+t[0].length}return l<e.length&&n(e.slice(l)),r}function Sx(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(kx.includes(r))t-=1;else if(r===")"&&xx(e,"(",t)<xx(e,")",t))t-=1;else break}return e.slice(0,t)}function xx(e,t,r){let n=0;for(let l=0;l<r;l+=1)e[l]===t&&(n+=1);return n}function _x(e,t,r){if(!vx.test(t)){e.push({kind:"text",text:t});return}let n=0;yx.lastIndex=0;for(let l=yx.exec(t);l!==null;l=yx.exec(t)){let i=l[1],o=l[2],a=l[3],s,u,c;if(i!==void 0&&o!==void 0)s=i.trim(),u=s.length>0?pg(o,r):null,c=l[0].length;else if(a!==void 0)s=Sx(a),u=pg(s,r),c=s.length;else continue;u!==null&&(l.index>n&&e.push({kind:"text",text:t.slice(n,l.index)}),e.push({kind:"link",text:s,href:u}),n=l.index+c,yx.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var Rx=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function Tx(e,t){return t===void 0||!wx(e,t.hosts)?false:Cx(e,t.hosts).some(e=>e.kind==="link")}function Ix(e,t,r){let n=r?.hosts;return wx(e,n)?Cx(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
289
- return U(Text,{style:t.bold,children:e.text},n);case"italic":return t.italic?/* @__PURE__ */U(Text,{style:t.italic,children:e.text},n):e.text;case"code":return t.code?/* @__PURE__ */U(Text,{style:t.code,children:e.text},n):e.text;case"link":{if(r===void 0)return e.text;let{href:t}=e;/* @__PURE__ */
290
- return U(Text,{style:Rx,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var zx=10.5,Px=16,Ox=12,Ex=38,jx=11,Fx=15,Ax=22,Dx=32,Mx=13.5,Lx=14,Bx=15,Hx=16,Ux=13,Nx=13,$x=26,Wx=21,Vx=42,qx=1,Gx=.06,Kx=.07,Yx=.12,Qx="45%";function Jx(){let e=useEverfurTheme(),t=a(()=>Xx(e),[e]);return{theme:e,styles:t}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */U(ChevronGlyph,{size:Hx,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */U(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:r,styles:n}=Jx();if(e.render!==void 0){let r=e.render;/* @__PURE__ */
291
- return U(C,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */U(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?gx(e.tile.imageUrl):null,c=/* @__PURE__ */N($,{children:[l?null:/* @__PURE__ */U(C,{style:[n.tile,a!==void 0?i?.tileTone?.[a]:null],children:u!==null?/* @__PURE__ */U(E,{source:{uri:u},style:n.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
292
- /* @__PURE__ */N(C,{style:n.cardWords,children:[
293
- /* @__PURE__ */U(Text,{tier:"control",style:n.cardTitle,children:e.title}),e.meta!==void 0?/* @__PURE__ */U(Text,{tier:"compact",style:n.cardMeta,children:e.meta}):null]}),l?/* @__PURE__ */N(Text,{tier:"control",style:n.stat,children:[e.value?.amount,e.value?.unit!==void 0?/* @__PURE__ */U(Text,{style:n.statUnit,children:e.value.unit}):null]}):/* @__PURE__ */N($,{children:[e.pill!==void 0?/* @__PURE__ */U(C,{style:[n.pill,s!==void 0?i?.pillTone?.[s]:null],children:/* @__PURE__ */U(Text,{tier:"badge",style:[n.pillText,s!==void 0?i?.pillToneText?.[s]:null],numberOfLines:1,ellipsizeMode:"tail",children:e.pill.label})}):null,e.onPress!==void 0?/* @__PURE__ */U(Chevron,{options:t,color:r.color.text.muted}):null]})]});if(e.onPress!==void 0){let t=e.onPress;/* @__PURE__ */
294
- return U(T,{onPress:()=>{Fh(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:o,children:c})}/* @__PURE__ */
295
- return U(C,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=Jx(),f=a(()=>({answer:e.text,question:hx(n,e.id),messageId:e.id}),[e.text,e.id,n]),h=!r&&e.pending!==true,p=h?px(l?.cards,f):[],g=a(()=>h?lx(e.citations):[],[h,e.citations]),b=l?.byline,m=l?.feedback!==void 0&&e.responseId!==void 0&&o!==void 0?l.feedback:null,y={bold:d.bold,italic:d.italic,code:d.code},v=mg(),k=h?v:void 0;/* @__PURE__ */
296
- return N(C,{style:d.answer,testID:"everfur-answer-cards",children:[b!==void 0?/* @__PURE__ */N(C,{style:d.byline,children:[b.icon??null,
297
- /* @__PURE__ */U(Text,{tier:"compact",style:d.bylineText,children:b.label})]}):s,
298
- /* @__PURE__ */U(C,{style:d.body,children:ux(t).flatMap((e,t)=>fx(e).map((e,r)=>{let n=`${t}-${r}`;return e.kind==="text"?/* @__PURE__ */U(Text,{style:d.paragraph,children:Ix(e.text,y,k)},n):/* @__PURE__ */U(C,{style:d.list,children:e.items.map((t,r)=>/* @__PURE__ */N(C,{style:d.listItem,children:[
299
- /* @__PURE__ */U(Text,{style:d.paragraph,children:e.ordered?`${e.start+r}.`:"•"}),
300
- /* @__PURE__ */U(Text,{style:[d.paragraph,d.listText],children:Ix(t,y,k)})]},r))},n)}))}),p.length>0?/* @__PURE__ */U(C,{style:d.cards,children:p.map(e=>/* @__PURE__ */U(AnswerCard,{card:e,options:l},e.key))}):null,g.length>0?/* @__PURE__ */N(C,{style:d.cards,accessibilityLabel:ox(g.length),children:[
301
- /* @__PURE__ */U(Text,{tier:"compact",style:d.label,children:$f.sourcesHeading}),g.map(e=>{let t=e.url;/* @__PURE__ */
302
- return U(AnswerCard,{card:{key:e.key,title:e.title,...e.meta!==null?{meta:e.meta}:{},tile:{icon:/* @__PURE__ */U(SourceTileGlyph,{})},...c!==void 0&&t!==null?{onPress:()=>c(t)}:{}},options:l},e.key)})]}):null,h&&m!==null&&o!==void 0?/* @__PURE__ */N(C,{style:[d.feedback,l?.styles?.feedback],children:[
303
- /* @__PURE__ */U(FeedbackChip,{label:m.helpful,on:i==="up",onPress:()=>o("up"),styles:d,host:l?.styles}),
304
- /* @__PURE__ */U(FeedbackChip,{label:m.notHelpful,on:i==="down",onPress:()=>o("down"),styles:d,host:l?.styles})]}):null,h?u(m===null):null]})}function SourceTileGlyph(){let e=useEverfurTheme();/* @__PURE__ */
305
- return U(BookGlyph,{size:Wx,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:r,styles:n,host:l}){/* @__PURE__ */
306
- return U(T,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(Jb-Dx)/2,children:/* @__PURE__ */U(Text,{tier:"control",style:[n.chipText,l?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:t,label:r,actions:n,options:l}){let{theme:i,styles:o}=Jx();if(e.length===0&&n.length===0)return null;let a=l?.styles,s=r??$f.followUpsHeadingNative;/* @__PURE__ */
307
- return N(C,{style:[o.followUps,a?.followUps],accessibilityLabel:s,testID:"everfur-cards-follow-ups",children:[
308
- /* @__PURE__ */U(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */N(T,{onPress:()=>{Fh(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:qx,style:[o.row,o.rowAction,a?.followUp,a?.followUpAction],children:[e.icon??null,
309
- /* @__PURE__ */U(Text,{tier:"control",style:[o.rowText,o.rowTextAction,a?.followUpText,a?.followUpActionText],children:e.label}),
310
- /* @__PURE__ */U(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */N(T,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:qx,style:[o.row,a?.followUp],children:[
311
- /* @__PURE__ */U(Text,{tier:"control",style:[o.rowText,a?.followUpText],children:e}),
312
- /* @__PURE__ */U(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=Jx();/* @__PURE__ */
313
- return U(C,{style:t.byline,children:/* @__PURE__ */U(Text,{tier:"compact",style:t.bylineText,children:e})})}function Xx(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:zx,textTransform:"uppercase",color:t.text.muted},l={borderWidth:1,borderColor:t.borderRingCream},i={borderWidth:1,borderColor:po(t.text.primary,Gx)??t.borderRingCream},o={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:Kx,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=lb(e.slots.chip);return m.create({answer:{gap:r.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...n,letterSpacing:zx*.06,flexShrink:1},body:{gap:10},paragraph:{...face(e,"regular"),fontSize:a.fontSize,lineHeight:Math.round(a.lineHeight),color:t.text.primary},list:{gap:4},listItem:{flexDirection:"row",gap:r.sm,paddingLeft:r.xs},listText:{flex:1},bold:face(e,"bold"),italic:{fontStyle:"italic"},code:face(e,"mono"),cards:{gap:r.sm},card:{flexDirection:"row",alignItems:"center",gap:r.md,padding:Ox,borderRadius:Px,backgroundColor:t.surface,...i,...o,minHeight:Jb,...rb(e.slots.card)},tile:{width:Ex,height:Ex,borderRadius:jx,backgroundColor:po(t.linkInk,Yx)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:Ex,height:Ex},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:Fx,lineHeight:Math.round(Fx*1.25),color:t.text.primary,...lb(e.slots.card)},cardMeta:{...n,letterSpacing:zx*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:Ax,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:zx+2,color:t.text.muted},pill:{minHeight:$x,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:Qx},pillText:{...face(e,"bold"),fontSize:Nx,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,alignItems:"center"},chip:{minHeight:Dx,paddingHorizontal:12,borderRadius:e.radius.pill,...l,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...Zw(e),fontSize:Mx,color:t.text.primary,...chipInk},followUps:{gap:r.sm,alignSelf:"stretch",marginTop:r.xs},label:{...face(e,"bold"),fontSize:Ux,lineHeight:Math.round(Ux*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:Vx,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:Lx,backgroundColor:t.surface,...i},rowAction:{},rowText:{...Zw(e),flex:1,fontSize:Bx,lineHeight:Math.round(Bx*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var Zx=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),e_=/* @__PURE__ */Object.freeze(Mr.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:Zx.answers[e]})));function t_(e,t){let[r,n]=l(null),[i,o]=l(null),[a,u]=l(null),c=s(r=>{t!==null&&(n(r),o(null),t(e.caseId,r).then(e=>{n(null),e.ok?u(r):o(e.error)}))},[t,e.caseId]),d=a??e.answer;return{answer:d,answerable:!isCheckinSettled(e),escalated:d==="worse",pending:r,error:i,choose:c}}var r_=44,n_=.6,l_=/* @__PURE__ */Object.freeze({caseId:"",answer:null,resolutionText:null,status:null});function CheckinCard({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:l,vet:i,onLayout:o,onOpen:s}){let u=useEverfurTheme(),c=a(()=>i_(u),[u]),d=t_(t??l_,t===null?null:r),f=d.answer!==null||d.pending!==null,h=t!==null&&r!==null&&d.answerable,p=t===null?null:KS(t.openedAt,YS(e));/* @__PURE__ */
314
- return N(C,{style:c.card,accessibilityLabel:Zx.eyebrow,onLayout:o,children:[
315
- /* @__PURE__ */N(C,{style:c.head,children:[
316
- /* @__PURE__ */U(Text,{tier:"compact",style:c.eyebrow,children:Zx.eyebrow}),p!==null?/* @__PURE__ */U(Text,{tier:"compact",style:c.headDay,children:Wf(Zx.day,{day:p})}):null]}),s?/* @__PURE__ */U(T,{onPress:s,accessibilityRole:"button",accessibilityLabel:e.text,style:c.open,children:/* @__PURE__ */U(Text,{style:[c.question,c.openText],children:e.text})}):/* @__PURE__ */U(Text,{style:c.question,accessibilityRole:"text",children:e.text}),h?/* @__PURE__ */U(C,{style:[c.row,d.pending?c.rowPending:null],children:e_.map(({answer:e,label:t})=>{let r=(d.pending??d.answer)===e;/* @__PURE__ */
317
- return U(T,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */U(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */U(Text,{style:c.logged,children:Zx.logged}):null,d.escalated?/* @__PURE__ */U(CheckinFindVet,{petRef:n??null,onFindVet:l,vet:i,styles:c}):null,t?.resolutionText?/* @__PURE__ */U(Text,{style:c.resolution,children:t.resolutionText}):null,d.error?/* @__PURE__ */U(Text,{style:c.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:r,styles:n}){return useVetVisit(cS(e,r)).available&&e!==null?/* @__PURE__ */U(VetVisitButtonCore,{entry:"chat",petRef:e,label:Zx.findVet,...r?.returnTo!==void 0?{returnTo:r.returnTo}:{},...r?.usState!==void 0?{usState:r.usState}:{},...r?.prefer!==void 0?{prefer:r.prefer}:{},style:n.findVet,labelStyle:n.findVetLabel}):t===void 0?null:/* @__PURE__ */U(T,{onPress:t,accessibilityRole:"button",accessibilityLabel:Zx.findVet,style:n.findVet,children:/* @__PURE__ */U(Text,{tier:"control",style:n.findVetLabel,children:Zx.findVet})})}function i_(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=nb(e.slots.card),o=lb(i);return m.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:m.hairlineWidth,borderColor:t.brandBorder,...rb(i,m.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},question:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},open:{minHeight:r_,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:n_},pill:{flex:1,minHeight:r_,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.controlEdge,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,...o},resolution:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},error:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption},findVet:{alignSelf:"stretch",minHeight:r_,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.controlEdge,backgroundColor:t.surface},findVetLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.body}})}var o_=244,a_=8,s_=13,u_=14,c_=.3,d_=-.24,f_=22,h_=10,p_=15;function CitationCards({citations:e,onOpenUrl:t}){let r=useEverfurTheme(),n=a(()=>g_(r),[r]),i=a(()=>lx(e),[e]),[o,s]=l(false);if(i.length===0)return null;let u=i.length;/* @__PURE__ */
318
- return N(C,{style:n.block,children:[
319
- /* @__PURE__ */N(PressScale,{accessibilityRole:"button",accessibilityLabel:ax(u,o),accessibilityState:{expanded:o},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>s(e=>!e),children:[
320
- /* @__PURE__ */U(BookGlyph,{size:s_,color:r.color.brandInk,strokeWidth:1.5}),
321
- /* @__PURE__ */U(Text,{tier:"compact",style:n.toggleLabel,children:ox(u)}),
322
- /* @__PURE__ */U(ChevronGlyph,{size:s_,color:r.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?/* @__PURE__ */U(Deck,{cards:i,styles:n,open:t}):null]})}function Deck({cards:e,styles:t,open:r}){let n=Ig(),l=Mg(n.citationsInMs,{risePx:n.citationsRisePx});/* @__PURE__ */
323
- return U(A.View,{style:l,children:/* @__PURE__ */U(P,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */U(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=sx(l?e:{...e,url:null}),o=/* @__PURE__ */N($,{children:[
324
- /* @__PURE__ */N(C,{style:t.cardHeader,children:[
325
- /* @__PURE__ */U(C,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),
326
- /* @__PURE__ */U(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */U(ArrowUpRightGlyph,{size:u_,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */U(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */U(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let n=e.url;/* @__PURE__ */
327
- return U(PressScale,{accessibilityRole:"link",accessibilityLabel:i,style:t.card,onPress:()=>r(n),children:o})}/* @__PURE__ */
328
- return U(C,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function g_(e){let t=e.color,r=e.space,n=e.radius,l=e.type.size,i=lb(e.slots.card);return m.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:l.micro,lineHeight:l.micro,letterSpacing:c_,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:o_,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2,...rb(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:a_,height:a_,borderRadius:n.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:l.bodyTight,lineHeight:f_,color:t.text.primary,letterSpacing:d_,...i},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:l.nano,lineHeight:h_,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...i},cardExcerpt:{...face(e,"regular"),fontSize:l.tiny,lineHeight:p_,color:t.text.muted,...i}})}var b_=15,m_=44,y_=16,v_=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:e,onCopy:t,sentiment:r=null,onSentiment:i,note:o=null}){let s=useEverfurTheme(),c=a(()=>k_(s),[s]),d=Ig(),f=e.role==="user",h=a(()=>QS(e.createdAt),[e.createdAt]),p=t!==void 0&&e.role!=="vet"&&e.text.length>0,g=e.role==="assistant"&&i!==void 0&&e.responseId!==void 0,[b,m]=l(false),y=u(null);n(()=>()=>{y.current&&clearTimeout(y.current)},[]);let v=()=>{t!==void 0&&(Mh(t,e.text),m(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null},d.copiedMs))};return h===null&&!p&&!g?null:/* @__PURE__ */N(C,{style:c.wrap,children:[
329
- /* @__PURE__ */N(C,{style:[c.row,f?c.rowUser:c.rowAssistant],children:[h!==null?/* @__PURE__ */U(Text,{tier:"compact",style:c.timestamp,children:h}):null,p?/* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:b?$f.copied:f?$f.copyUserMessage:$f.copyAssistantMessage,onPress:v,style:c.iconHit,children:b?/* @__PURE__ */U(CheckGlyph,{size:b_,color:s.color.success,strokeWidth:2}):/* @__PURE__ */U(CopyGlyph,{size:b_,color:s.color.text.timestamp,strokeWidth:1.5})}):null,g?Mk.map(({sentiment:e,label:t})=>/* @__PURE__ */U(T,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r===e},onPress:()=>i?.(e),style:c.iconHit,children:/* @__PURE__ */U(ThumbGlyph,{size:b_,color:r===e?s.color.sentiment[e]:s.color.text.timestamp,active:r===e,rotate:v_[e],strokeWidth:1.5})},e)):null]}),o==="thanks"?/* @__PURE__ */U(Text,{style:c.thanks,accessibilityLiveRegion:"polite",children:$f.feedbackThanks}):null,o==="failed"?/* @__PURE__ */N($,{children:[
330
- /* @__PURE__ */U(Text,{style:c.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:$f.feedbackFailed}),
331
- /* @__PURE__ */U(AnnounceLine,{line:$f.feedbackFailed})]}):null]})}function k_(e){let t=e.type;return m.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:y_,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:m_,height:m_,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary},failed:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.danger}})}var w_=16,C_=10,S_=12,x_=10,__=2,R_=.06,T_=34,I_=9,z_=10.5,P_=.06,O_=15,E_=19.5,j_=14,F_=19.6;function OpeningCard({card:e,onLayout:t}){let r=useEverfurTheme(),n=a(()=>A_(r),[r]),l=e.styles;/* @__PURE__ */
332
- return N(C,{testID:"everfur-opening-card",onLayout:t,accessible:true,accessibilityLabel:[e.kicker,e.title,e.body].filter(e=>e!==void 0).join(", "),style:[n.card,l?.card],children:[e.icon!==void 0?/* @__PURE__ */U(C,{style:[n.icon,l?.icon],children:e.icon}):null,
333
- /* @__PURE__ */N(C,{style:n.words,children:[
334
- /* @__PURE__ */U(Text,{tier:"compact",style:[n.kicker,l?.kicker],children:e.kicker}),
335
- /* @__PURE__ */U(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */U(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function A_(e){let t=e.color;return m.create({card:{flexDirection:"row",alignItems:"flex-start",gap:x_,paddingVertical:C_,paddingHorizontal:S_,alignSelf:"stretch",borderRadius:w_,backgroundColor:t.surface,borderWidth:1,borderColor:po(t.text.primary,R_)??t.borderRingCream},icon:{flexShrink:0,width:T_,height:T_,borderRadius:I_,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:__},kicker:{...face(e,"mono"),fontSize:z_,letterSpacing:z_*P_,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:O_,lineHeight:E_,color:t.text.primary},body:{...face(e,"regular"),fontSize:j_,lineHeight:F_,color:t.text.secondary}})}var D_="#10462E",M_="Book a video visit",L_="#000000",B_="#83E0B4",H_=/* @__PURE__ */Object.freeze([
161
+ /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function rk(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return tk[t%tk.length]}function nk(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function lk(e){return{...rk(e.petRef),initial:nk(e.name)}}function ik(e,t,r){let n=lk(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function ak(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:t,ringStroke:r}){let n=useEverfurTheme(),l=a(()=>sk(n),[n]),i=t-r*2,o=e===null?null:ik(e,Qv(n),{fill:n.color.highlight,ink:n.color.onHighlight}),s=ak(i);/* @__PURE__ */
162
+ return $(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */$(x,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */$(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?nk(null):o.initial})})})}function sk(e){return v.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function uk(e,t){let{borderRadius:r,...n}=ab(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function ck(e,t){let{backgroundColor:r,borderColor:n,borderWidth:l,borderRadius:i}=ab(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:l??1},...i===void 0?{}:{borderTopRightRadius:i,borderBottomRightRadius:i}}}var dk=48,fk=2,hk=320,pk="80%",gk="rgba(17,17,17,0.45)",bk=18,mk=22,yk=12,vk=.4,kk=44;function wk(e){return e?.name?.trim()||Vf.yourPet}function PetSwitcherSheet({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:l=null,onClose:i}){let o=useEverfurTheme(),s=a(()=>Ck(o),[o]),u=Bf();return e?/* @__PURE__ */$(O,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"fade",onRequestClose:i,children:/* @__PURE__ */W(x,{style:s.root,children:[
163
+ /* @__PURE__ */$(z,{style:Eb,onPress:i,accessibilityRole:"button",accessibilityLabel:Vf.close,children:/* @__PURE__ */$(x,{style:s.backdrop})}),
164
+ /* @__PURE__ */W(x,{style:Hf(s.panel,u),accessibilityViewIsModal:true,children:[
165
+ /* @__PURE__ */$(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:Vf.yourPets}),
166
+ /* @__PURE__ */$(E,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=wk(e),i=ek(e);/* @__PURE__ */
167
+ return W(PressScale,{accessibilityRole:"button",accessibilityLabel:qf(t?Vf.petCurrentlyActive:Vf.switchToPet,{name:l}),accessibilityState:{selected:t},style:[s.row,t?s.rowActive:null],onPress:()=>n(e.petRef),children:[
168
+ /* @__PURE__ */$(PetDisc,{pet:e,size:dk,ringStroke:fk}),
169
+ /* @__PURE__ */W(x,{style:s.copy,children:[
170
+ /* @__PURE__ */$(Text,{style:s.name,numberOfLines:1,children:l}),
171
+ /* @__PURE__ */$(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${Vf.activePrefix}${i}`:i})]}),t?/* @__PURE__ */$(CheckGlyph,{size:bk,color:o.color.brandInk}):null]},e.petRef)})}),l!==null?/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:Vf.addAnotherPet,style:s.addRow,onPress:l,children:[
172
+ /* @__PURE__ */$(x,{style:s.addDisc,children:/* @__PURE__ */$(Text,{tier:"control",style:s.addPlus,children:"+"})}),
173
+ /* @__PURE__ */$(Text,{style:s.addLabel,children:Vf.addAnotherPet})]}):null,
174
+ /* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Vf.close,containerStyle:s.closeSlot,style:s.closeButton,onPress:i,children:/* @__PURE__ */$(Text,{tier:"control",style:s.closeText,children:Vf.close})})]})]})}):null}function Ck(e){let t=e.color,r=e.radius,n=ub(e.slots.dialog);return v.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:gk},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:mk,borderTopRightRadius:mk,gap:14,maxHeight:pk,...uk(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...n},list:{maxHeight:hk,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:kk,paddingHorizontal:8},addDisc:{width:dk,height:dk,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:fk,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...face(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...face(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary,...n},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...face(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...face(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:vk},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:yk,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:vk}})}var Sk=44,xk=36,_k=22,Rk=20,Tk=9,Ik=1.5,zk=6,Pk=35,Ok=1.75,Ek=12.4,jk=.5,Fk=8,Ak=28,Dk=160,Mk=16,Lk=8;function Bk(e,t){return fv(e,t)}function ChatHeader({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onNewChat:i,onPetChange:o,onAddPet:s,vet:c,textingEntry:d=null}){let f=useEverfurTheme(),h=a(()=>Hk(f),[f]),[p,g]=l(false),b=Bk(e.pets,t),m=b!==null&&(e.pets.length>=2||s!==void 0),y=t??b?.petRef??null,v=wk(b),[k,w]=l(Vv),C=u(e=>t=>{let r=t.nativeEvent.layout.width;w(t=>Kv(t,e,r))},[]),S=a(()=>C("row"),[C]),_=a(()=>C("leading"),[C]),R=a(()=>C("trailing"),[C]),T=2*Mk+2*(f.slots.header?.borderColor!==void 0?1:0)+2*Lk,I=Gv(k,T,Dk),z=t=>{g(false),e.setActivePet(t),Dh(o,t)},P=s===void 0?null:()=>{g(false),Dh(s)};/* @__PURE__ */
175
+ return W(V,{children:[
176
+ /* @__PURE__ */W(x,{style:h.row,onLayout:S,children:[
177
+ /* @__PURE__ */$(x,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */W(x,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Gp.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:i,children:/* @__PURE__ */$(EditGlyph,{size:Rk,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
178
+ /* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${Vf.openHistoryNative}${Vf.newReplySuffix}`:Vf.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:n,children:[
179
+ /* @__PURE__ */$(MenuGlyph,{size:_k,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),r?/* @__PURE__ */$(x,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
180
+ /* @__PURE__ */$(x,{style:h.centre,pointerEvents:"box-none",children:/* @__PURE__ */$(BrandLogo,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,barStyle:h.logoBar,logoStyle:h.logo})}),
181
+ /* @__PURE__ */$(x,{style:[h.trailing,I.trailing===void 0?null:{minWidth:I.trailing}],children:/* @__PURE__ */W(x,{style:h.trailingContent,onLayout:R,children:[y===null?null:/* @__PURE__ */$(VetVisitButtonCore,{entry:"chat",petRef:y,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:h.vetEntry,labelStyle:h.vetEntryLabel}),
182
+ /* @__PURE__ */$(x,{style:h.right,children:m?/* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:qf(Vf.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
183
+ /* @__PURE__ */$(PetDisc,{pet:b,size:Pk,ringStroke:Ok}),
184
+ /* @__PURE__ */$(x,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */$(PlusGlyph,{size:Fk,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&b===null?
185
+ /* @__PURE__ */$(x,{style:h.avatarWrap,accessible:true,accessibilityLabel:Vf.yourPet,children:/* @__PURE__ */$(Ring,{size:Pk,strokeWidth:Ok,color:f.color.mark,children:/* @__PURE__ */$(x,{style:h.placeholderDisc})})}):/* @__PURE__ */$(x,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:b===null?Vf.yourPet:v,children:/* @__PURE__ */$(PetDisc,{pet:b,size:Pk,ringStroke:Ok})})})]})}),
186
+ /* @__PURE__ */$(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */$(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>Hk(r),[r]);/* @__PURE__ */
187
+ return $(x,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */$(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function Hk(e){let t=e.color,r=Pk-Ok*2,n=e.slots.header;return v.create({vetEntry:{minHeight:Sk,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:v.hairlineWidth,borderColor:t.controlEdge},vetEntryLabel:{...face(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},textingEntrySlot:{borderRadius:e.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Mk,paddingBottom:10,backgroundColor:n?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:Mk,paddingTop:e.space.md,paddingBottom:e.space.xs},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:Mk,paddingVertical:10,backgroundColor:t.surface,...ab(n)},iconSlot:{borderRadius:xk/2},iconButton:{width:xk,height:xk,borderRadius:xk/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:zk,right:zk,width:Tk,height:Tk,borderRadius:Tk,backgroundColor:t.danger,borderWidth:Ik,borderColor:n?.backgroundColor??t.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:e.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:Lk,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:Ak,width:Dk,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:Pk/2},avatarWrap:{width:Pk,height:Pk,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:Ek,height:Ek,borderRadius:Ek/2,borderWidth:jk,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var Uk=/* @__PURE__ */Object.freeze([
188
+ /* @__PURE__ */Object.freeze({key:"inaccurate",label:Vf.feedbackReasonInaccurate,feedbackType:"wrong"}),
189
+ /* @__PURE__ */Object.freeze({key:"outdated",label:Vf.feedbackReasonOutdated,feedbackType:"outdated"}),
190
+ /* @__PURE__ */Object.freeze({key:"unsafe",label:Vf.feedbackReasonUnsafe,feedbackType:"dangerous"}),
191
+ /* @__PURE__ */Object.freeze({key:"unclear",label:Vf.feedbackReasonUnclear,feedbackType:"unclear"}),
192
+ /* @__PURE__ */Object.freeze({key:"other",label:Vf.feedbackReasonOther,feedbackType:"not_helpful"})]),Nk=/* @__PURE__ */Object.freeze([
193
+ /* @__PURE__ */Object.freeze({sentiment:"up",label:Vf.feedbackHelpful}),
194
+ /* @__PURE__ */Object.freeze({sentiment:"down",label:Vf.feedbackNotHelpful})]);function $k(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function Wk(e,t){if(e==="down"&&t!==null){let e=Uk.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return $k(e)}var Vk=44,qk="rgba(17,17,17,0.55)",Gk=26,Kk=36,Yk=4,Qk=20,Jk=38,Xk=18,Zk=12;function FeedbackReasons({visible:e,onSubmit:t,onSkip:r}){let n=useEverfurTheme(),i=a(()=>ew(n),[n]),o=Bf(),[s,u]=l(null),[c,d]=l(""),[f,h]=l(false),[p,g]=l(false),b=()=>{u(null),d(""),h(false),g(false)},y=()=>{f||(b(),r())},v=async()=>{if(f)return;h(true),g(false);let e=c.trim();await t(s,e.length>0?e:null)?b():(h(false),g(true))};if(!e)return null;let k=[...c].length>Kn;/* @__PURE__ */
195
+ return $(O,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:y,children:/* @__PURE__ */W(I,{behavior:m.OS==="ios"?"padding":void 0,style:i.root,children:[
196
+ /* @__PURE__ */$(z,{style:i.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:Vf.feedbackSkipA11y}),
197
+ /* @__PURE__ */W(x,{style:Hf(i.sheet,o),accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
198
+ /* @__PURE__ */$(x,{style:i.handle}),
199
+ /* @__PURE__ */W(x,{style:i.header,children:[
200
+ /* @__PURE__ */$(x,{style:i.iconBadge,children:/* @__PURE__ */$(ThumbGlyph,{size:Xk,color:n.color.brandInk,active:false,rotate:"180deg"})}),
201
+ /* @__PURE__ */W(x,{style:i.headerText,children:[
202
+ /* @__PURE__ */$(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:Vf.feedbackTitle}),
203
+ /* @__PURE__ */$(Text,{style:i.subtitle,children:Vf.feedbackSubtitle})]})]}),
204
+ /* @__PURE__ */$(x,{style:i.options,children:Uk.map(e=>{let t=s===e.key;/* @__PURE__ */
205
+ return W(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[i.option,t?i.optionSelected:null],onPress:()=>u(t=>t===e.key?null:e.key),children:[
206
+ /* @__PURE__ */$(Text,{style:[i.optionLabel,t?i.optionLabelSelected:null],children:e.label}),
207
+ /* @__PURE__ */$(x,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */$(CheckGlyph,{size:Zk,color:n.color.surface,strokeWidth:2}):null})]},e.key)})}),
208
+ /* @__PURE__ */W(x,{style:i.inputWrap,children:[
209
+ /* @__PURE__ */$(ff,{style:i.input,placeholder:Vf.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:Vf.feedbackNotesPlaceholder,value:c,onChangeText:d,multiline:true,editable:!f}),c.length>0?/* @__PURE__ */$(Text,{tier:"compact",style:[i.counter,k?i.counterOver:null],children:`${[...c].length}/${Kn}`}):null]}),p?/* @__PURE__ */$(Text,{style:i.failed,accessibilityRole:"alert",children:Vf.feedbackFailed}):null,
210
+ /* @__PURE__ */W(x,{style:i.actions,children:[
211
+ /* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Vf.feedbackSubmit,accessibilityState:{busy:f,disabled:f||k},disabled:f||k,style:[i.submit,f||k?i.submitDisabled:null],onPress:()=>{v()},children:/* @__PURE__ */$(Text,{tier:"control",style:i.submitLabel,children:Vf.feedbackSubmit})}),
212
+ /* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Vf.feedbackSkipA11y,hitSlop:8,onPress:y,style:i.skip,children:/* @__PURE__ */$(Text,{tier:"control",style:i.skipLabel,children:Vf.feedbackSkip})})]})]})]})})}function ew(e){let t=e.color,r=e.type,n=e.radius,l=e.slots,i=ub(l.dialog);return v.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...Eb,backgroundColor:qk},sheet:{backgroundColor:t.surface,borderTopLeftRadius:Gk,borderTopRightRadius:Gk,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...uk(l.dialog)},handle:{alignSelf:"center",width:Kk,height:Yk,borderRadius:Yk/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:Jk,height:Jk,borderRadius:Jk/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight,...i},subtitle:{...face(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted,...i},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:v.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...ab(l.chip,v.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.primary,...ub(l.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:Qk,height:Qk,borderRadius:Qk/2,borderWidth:2,borderColor:t.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top",...ab(l.input,1),...ub(l.input)},counter:{...face(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...face(e,"regular"),fontSize:r.size.caption,lineHeight:r.size.caption*r.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:Vk,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...ab(l.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...ub(l.primaryButton)},skip:{minHeight:Vk,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}var tw=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function rw(){let e=globalThis,t=e[tw];if(t!==void 0)return t;let r={factory:createContext(null),home:createContext(null)};return e[tw]=r,r}var nw=rw().factory,lw=rw().home;function iw(){return o(nw)}function ow(){return o(lw)?.kit??null}function aw(){return o(lw)}var sw=15,uw=8;function HistoryBar({bar:e,history:t,empty:r,unread:n,extra:l}){let i=useEverfurTheme(),o=ow(),s=a(()=>o!==null?fw(i,o):hw(i),[i,o]),u=t.cursor===null?t.rows.length:0,c=t=>{let r=e.renderIcon;if(r!==void 0)/* @__PURE__ */return $(HostRender,{render:()=>r(t),fallback:null});if(o===null)return null;let n=String(v.flatten(s.label).color??i.color.linkInk);return t==="history"?/* @__PURE__ */$(HistoryGlyph,{size:dw,color:n,strokeWidth:1.8}):/* @__PURE__ */$(EditGlyph,{size:dw,color:n,strokeWidth:1.8})};/* @__PURE__ */
213
+ return W(x,{style:s.bar,testID:"everfur-history-bar",children:[
214
+ /* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?cw:void 0,children:[c("history"),
215
+ /* @__PURE__ */$(Text,{tier:"control",style:s.label,children:e.chats}),u>0?/* @__PURE__ */$(x,{style:s.count,children:/* @__PURE__ */$(Text,{tier:"badge",style:s.countText,children:String(u)})}):null,n?/* @__PURE__ */$(x,{style:s.dot,testID:"everfur-chat-history-bar-unread"}):null]}),e.extra??null,l??null,
216
+ /* @__PURE__ */$(x,{style:s.spacer}),r?null:/* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?cw:void 0,children:[c("edit"),
217
+ /* @__PURE__ */$(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var cw=4,dw=18;function fw(e,t){return{...hw(e),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:e.space.sm},control:t.view(".thread__hist"),label:t.text(".thread__hist"),count:t.view(".thread__count"),countText:t.text(".thread__count")}}function hw(e){let t=e.color,r=e.space;return v.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:rm},label:{...face(e,"bold"),fontSize:sw,color:t.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,alignItems:"center"},countText:{...face(e,"bold"),fontSize:e.type.size.caption,color:t.text.primary},dot:{width:uw,height:uw,borderRadius:uw/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var pw=.88,gw=420,bw=58,mw="rgba(17,17,17,0.28)",yw=.15,vw=14,kw=12,ww=44,Cw=16,Sw=14,xw=12,_w=14,Rw=8,Tw=2,Iw=.5,zw=Mg(Tg.standard);function Pw(e){return Math.min(Math.round(e*pw),gw)}function HistoryDrawer({chat:e,history:t}){let[r,n]=l(t.open),i=u(()=>n(false),[]);return t.open&&!r&&n(true),r?/* @__PURE__ */$(DrawerModal,{chat:e,history:t,onHidden:i}):null}function DrawerModal({chat:e,history:t,onHidden:r}){let l=useEverfurTheme(),i=a(()=>Ow(l),[l]),o=jg(),s=U(),{width:u}=L(),d=Pw(u),f=t.open,h=c(null);h.current===null&&(h.current=new M.Value(o.drawerMs<=0&&f?1:0));let p=h.current;n(()=>{if(!f&&o.drawerMs<=0){r();return}let e=M.timing(p,{toValue:f?1:0,duration:o.drawerMs,easing:zw,useNativeDriver:true});return e.start(({finished:e})=>{e&&!f&&r()}),()=>e.stop()},[f,p,o.drawerMs,r]);let g=p.interpolate({inputRange:[0,1],outputRange:[-d,0]}),b=t.filtered,y=t.rows.length===0,v=t.cursor===null&&!t.loading&&t.error===null,k=y&&t.loading?/* @__PURE__ */W(x,{style:i.emptyCard,accessibilityLabel:Gp.loading,accessibilityState:{busy:true},children:[
218
+ /* @__PURE__ */$(j,{color:i.emptyTitle.color}),
219
+ /* @__PURE__ */$(Text,{style:i.emptyBody,children:Gp.loading})]}):y&&t.error!==null?/* @__PURE__ */W(x,{style:i.emptyCard,children:[
220
+ /* @__PURE__ */$(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:Gp.loadFailed}),
221
+ /* @__PURE__ */$(Text,{style:i.emptyBody,children:t.error}),
222
+ /* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Gp.retry,containerStyle:i.retrySlot,style:i.retryButton,onPress:()=>{t.load()},children:/* @__PURE__ */$(Text,{tier:"control",style:i.retryText,children:Gp.retry})})]}):t.emptyKind==="empty"?/* @__PURE__ */W(x,{style:i.emptyCard,children:[
223
+ /* @__PURE__ */$(Text,{style:i.emptyTitle,children:Gp.empty}),
224
+ /* @__PURE__ */$(Text,{style:i.emptyBody,children:Gp.emptyBody})]}):
225
+ /* @__PURE__ */$(Text,{style:i.noMatch,children:Gp.noMatch}),w=!t.searching&&t.loadingMore?/* @__PURE__ */$(x,{style:i.loadMoreFooter,children:/* @__PURE__ */$(Text,{style:i.loadMoreLabel,children:Gp.loadingMore})}):null;/* @__PURE__ */
226
+ return $(O,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:/* @__PURE__ */W(x,{style:i.root,children:[
227
+ /* @__PURE__ */$(z,{style:Eb,onPress:t.close,accessibilityRole:"button",accessibilityLabel:Gp.closeA11y,children:/* @__PURE__ */$(M.View,{style:[i.backdrop,{opacity:p}]})}),
228
+ /* @__PURE__ */$(M.View,{style:[i.panel,{width:d,paddingTop:Math.max(bw,s.top+l.space.md),transform:[{translateX:g}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */W(I,{style:i.keyboardAvoider,behavior:m.OS==="ios"?"padding":"height",children:[
229
+ /* @__PURE__ */W(x,{style:i.header,children:[
230
+ /* @__PURE__ */$(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:Gp.heading}),
231
+ /* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Gp.newChat,style:i.newChat,onPress:t.newConversation,children:/* @__PURE__ */$(Text,{tier:"control",style:i.newChatLabel,children:Gp.newChat})}),
232
+ /* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Gp.close,hitSlop:0,style:i.closeButton,onPress:t.close,children:/* @__PURE__ */$(CloseGlyph,{size:Cw,color:l.color.text.muted,strokeWidth:1.75})})]}),
233
+ /* @__PURE__ */W(x,{style:i.searchPill,children:[
234
+ /* @__PURE__ */$(SearchGlyph,{size:_w,color:l.color.text.muted,strokeWidth:1.5}),
235
+ /* @__PURE__ */$(ff,{value:t.query,onChangeText:e=>t.setQuery(e.replace(/^\s+/,"")),style:i.searchInput,placeholder:Gp.searchPlaceholder,placeholderTextColor:l.color.text.placeholder,accessibilityLabel:Gp.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
236
+ /* @__PURE__ */$(Text,{tier:"compact",style:i.countLabel,children:Jp(t.rows.length,v)}),t.error!==null&&!y?/* @__PURE__ */$(x,{style:i.errorCard,children:/* @__PURE__ */$(Text,{style:i.errorText,accessibilityRole:"alert",children:t.error})}):null,
237
+ /* @__PURE__ */$(B,{data:b,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */$(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:b.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:w,onEndReached:t.loadMore,onEndReachedThreshold:Iw})]})})]})})}function Row({row:e,active:t,disabled:r,styles:n,onPress:l}){let i=e.unreadCount!==null&&e.unreadCount>0,o=Qp(e);/* @__PURE__ */
238
+ return W(PressScale,{accessibilityRole:"button",accessibilityLabel:Xp(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:l,children:[
239
+ /* @__PURE__ */W(x,{style:n.itemRow,children:[
240
+ /* @__PURE__ */$(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:Kp(e.title)}),i?/* @__PURE__ */$(x,{style:n.unreadDot}):null]}),o!==null?/* @__PURE__ */$(Text,{tier:"compact",style:n.itemMeta,numberOfLines:1,children:o}):null]})}function Ow(e){let t=e.color,r=e.space,n=e.type,l=e.slots,i=t.text.primary,o=ub(l.card);return v.create({root:{flex:1},backdrop:{flex:1,backgroundColor:mw},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:r.lg,borderRightWidth:v.hairlineWidth,borderRightColor:t.borderRingCream,gap:r.md,...ck(l.dialog,v.hairlineWidth)},keyboardAvoider:{flex:1,gap:r.md},header:{flexDirection:"row",alignItems:"center",gap:r.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:n.size.subtitle,color:i,...ub(l.dialog)},newChat:{minHeight:ww,justifyContent:"center",paddingHorizontal:r.xs},newChatLabel:{...face(e,"bold"),fontSize:vw,color:t.brandInk},closeButton:{width:ww,height:ww,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:r.md+Tw,paddingVertical:r.sm+Tw,borderWidth:1,borderColor:t.borderRingCream,...ab(l.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:n.size.bodyTight,color:t.text.primary,padding:0,...ub(l.input)},countLabel:{...face(e,"mono"),fontSize:kw,color:t.text.muted},list:{gap:r.xs,paddingBottom:r.xl},listEmpty:{flexGrow:1},item:{paddingVertical:r.sm+Tw,paddingHorizontal:r.sm,borderRadius:e.radius.md,gap:Tw},itemActive:{backgroundColor:bo(t.highlight,yw)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:r.sm},itemTitle:{...face(e,"bold"),flex:1,fontSize:n.size.bodyTight,color:i},itemMeta:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted},unreadDot:{width:Rw,height:Rw,borderRadius:Rw/2,backgroundColor:t.danger},errorCard:{borderRadius:xw,borderWidth:v.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:r.md},errorText:{...face(e,"regular"),fontSize:n.size.caption,color:t.danger},emptyCard:{borderRadius:Sw,padding:r.md+Tw,gap:r.xs+Tw,backgroundColor:t.surfaceSubtle,borderWidth:v.hairlineWidth,borderColor:t.borderRingCream,...ab(l.card,v.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:n.size.bodyTight,color:i,...o},emptyBody:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.secondary,...o},noMatch:{...face(e,"regular"),fontSize:n.size.bodyTight,color:t.text.muted,paddingVertical:r.sm},retrySlot:{marginTop:r.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:r.md+Tw,paddingVertical:r.sm,borderWidth:1,borderColor:t.brandInk,...ab(l.primaryButton)},retryText:{...face(e,"bold"),fontSize:n.size.caption,color:t.brandInk,...ub(l.primaryButton)},loadMoreFooter:{paddingVertical:r.md+Tw,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted}})}function Ew(e,t=/* @__PURE__ */new Date,r){let n=new Date(e);if(Number.isNaN(n.getTime()))return null;let l=new Date(t);l.setHours(0,0,0,0);let i=new Date(n);i.setHours(0,0,0,0);let o=Math.round((l.getTime()-i.getTime())/864e5);if(o===0||o===1)try{let e=new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day");return e.charAt(0).toLocaleUpperCase(r)+e.slice(1)}catch{}return n.toLocaleDateString(r,{month:"short",day:"numeric"})}function jw(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function Fw(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=Ew(n.updatedAt,t)??"",l=r[r.length-1];l!==void 0&&l.day===e?l.rows.push(n):r.push({day:e,rows:[n]})}return r}var Aw="rgba(38,37,35,0.38)",Dw=28,Mw=40,Lw=5,Bw=11,Hw=10.5,Uw=36,Nw=11,$w=14,Ww=15,Vw=13.5,qw=48,Gw=2,Kw=1.3,Yw=.12,Qw=16,Jw=8,Xw="80%";function Zw(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */$(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:t,sheet:r}){let n=useEverfurTheme(),l=a(()=>eC(n),[n]),i=U(),o=a(()=>Fw(t.rows),[t.rows]),s=Bf();if(!t.open)return null;let u=n.color,c=r?.title?.trim(),d=c!==void 0&&c!==""?c:Gp.heading;/* @__PURE__ */
241
+ return $(O,{visible:true,transparent:true,animationType:"slide",onRequestClose:t.close,children:/* @__PURE__ */W(x,{style:l.root,children:[
242
+ /* @__PURE__ */$(z,{style:[Eb,l.scrim],onPress:t.close,accessibilityRole:"button",accessibilityLabel:Gp.closeA11y}),
243
+ /* @__PURE__ */W(x,{style:Hf([l.sheet,{paddingBottom:Math.max(40,i.bottom+n.space.lg)}],s),accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
244
+ /* @__PURE__ */$(x,{style:l.grab}),
245
+ /* @__PURE__ */W(x,{style:l.top,children:[
246
+ /* @__PURE__ */$(Text,{tier:"compact",style:l.kicker,accessibilityRole:"header",children:d}),
247
+ /* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Gp.closeA11y,onPress:t.close,style:l.close,children:Zw(r,"close",/* @__PURE__ */$(CloseGlyph,{size:22,color:u.text.primary,strokeWidth:2}))})]}),
248
+ /* @__PURE__ */W(E,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */W(x,{style:l.state,accessibilityLabel:Gp.loading,accessibilityState:{busy:true},children:[
249
+ /* @__PURE__ */$(j,{color:u.brandInk}),
250
+ /* @__PURE__ */$(Text,{tier:"compact",style:l.mono,children:Gp.loading})]}):null,t.error!==null?/* @__PURE__ */W(x,{style:l.state,children:[
251
+ /* @__PURE__ */$(Text,{style:l.stateText,accessibilityRole:"alert",children:Gp.loadFailed}),
252
+ /* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Gp.retry,onPress:()=>{t.load()},style:l.link,children:/* @__PURE__ */$(Text,{tier:"control",style:l.linkText,children:Gp.retry})})]}):null,!t.loading&&t.error===null&&t.rows.length===0?/* @__PURE__ */$(Text,{style:[l.stateText,l.state],children:Gp.empty}):null,o.map((n,i)=>/* @__PURE__ */W(p,{children:[n.day?/* @__PURE__ */$(Text,{tier:"compact",style:[l.mono,l.day,i===0?l.dayFirst:null],children:n.day}):null,n.rows.map(n=>{let i=n.id===e.conversationId,o=n.unreadCount!==null&&n.unreadCount>0,a=jw(n.updatedAt);/* @__PURE__ */
253
+ return W(z,{accessibilityRole:"button",accessibilityLabel:Xp(n),accessibilityState:{selected:i},onPress:()=>{t.resume(n.id)},style:[l.row,i?l.rowCurrent:null],children:[
254
+ /* @__PURE__ */$(x,{style:l.icon,children:Zw(r,"chat",/* @__PURE__ */$(ChatBubbleGlyph,{size:19,color:u.linkInk,strokeWidth:1.75}))}),
255
+ /* @__PURE__ */W(x,{style:l.rowWords,children:[
256
+ /* @__PURE__ */$(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:Kp(n.title)}),n.preview!==void 0?/* @__PURE__ */$(Text,{tier:"compact",style:l.preview,numberOfLines:1,children:n.preview}):null]}),
257
+ /* @__PURE__ */W(x,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */$(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */$(x,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:Gp.more,onPress:t.loadMore,style:l.link,children:/* @__PURE__ */$(Text,{tier:"control",style:l.linkText,children:Gp.more})}):null]}),
258
+ /* @__PURE__ */W(z,{accessibilityRole:"button",accessibilityLabel:Gp.newChat,onPress:t.newConversation,style:l.newChat,children:[Zw(r,"edit",/* @__PURE__ */$(EditGlyph,{size:18,color:n.slots.primaryButton?.textColor??u.onPrimary,strokeWidth:1.75})),
259
+ /* @__PURE__ */$(Text,{tier:"control",style:l.newChatText,children:Gp.newChat})]})]})]})})}function eC(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:Hw,letterSpacing:Hw*.06,textTransform:"uppercase",color:t.text.muted};return v.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:Aw},sheet:{maxHeight:Xw,backgroundColor:t.surface,borderTopLeftRadius:Dw,borderTopRightRadius:Dw,paddingTop:10,paddingHorizontal:20},grab:{width:Mw,height:Lw,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...n,fontSize:Bw,letterSpacing:Bw*.08,flexShrink:1},close:{width:rm,height:rm,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:rm/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:r.xs},mono:n,day:{marginTop:r.lg,marginBottom:r.xs},dayFirst:{marginTop:Gw},state:{marginVertical:r.md,gap:r.sm,alignItems:"flex-start"},stateText:{...face(e,"regular"),fontSize:e.type.size.body,color:t.text.primary},link:{minHeight:rm,justifyContent:"center"},linkText:{...face(e,"bold"),fontSize:e.type.size.body,color:t.brandInk},row:{flexDirection:"row",alignItems:"center",gap:r.md,paddingVertical:10,paddingHorizontal:r.sm,borderRadius:$w,minHeight:rm},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:Uw,height:Uw,borderRadius:Nw,backgroundColor:bo(t.linkInk,Yw)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:Ww,lineHeight:Ww*Kw,color:t.text.primary},preview:{...face(e,"regular"),fontSize:Vw,color:t.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:Hw*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:Jw,height:Jw,borderRadius:Jw/2,backgroundColor:t.danger},newChat:{marginTop:r.lg,minHeight:qw,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...ab(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:Qw,color:t.onPrimary,...ub(e.slots.primaryButton)}})}var tC="Close",rC=/* @__PURE__ */Object.freeze({action:e=>e.possessive===null?null:`See ${e.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(e,t)=>e.risk?.lead?`${e.risk.lead} ${t}`:`${e.title}: ${t}`,close:e=>e.possessive===null?null:`Close ${e.possessive} focus`,resultsKicker:e=>e.possessive===null?null:`${nC(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function nC(e){return e.charAt(0).toUpperCase()+e.slice(1)}function healthPlanPossessive(e){let t=typeof e.sex=="string"?e.sex.trim().toLowerCase():null;if(t==="female")return"her";if(t==="male")return"his";let r=typeof e.name=="string"?e.name.trim():"";return r!==""?`${r}'s`:null}function healthPlanTopCard(e,t={}){let r=e?.page?.focus;if(e===null||r===void 0||r.title.trim()===""||r.kicker.trim()==="")return;let n={...rC,...t.copy},l={pet:e.pet,possessive:healthPlanPossessive(e.pet)},i=r.sources?.find(e=>e.label.trim()!=="")?.label,o=t.onOpenPlan,a=o===void 0?null:n.action(l),s=n.close(l),u=n.ask.trim(),c=t.results!==void 0&&r.report!==void 0?t.results:void 0;if(c!==void 0){let e=n.resultsKicker(l)?.trim()||r.kicker,s=n.resultsClose(l),d=c.onTopRisk??o,f={key:"top-risk",label:n.resultsTopRisk,title:r.title,...r.risk?.lead?{line:r.risk.lead}:{},tone:"risk",...d===void 0?{}:{onPress:d}};return{kicker:e,...i===void 0?{}:{badge:i},title:r.title,results:[f,...c.rows??[]],...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?tC:s,pill:e,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}return{kicker:r.kicker,...i===void 0?{}:{badge:i},title:r.title,...r.risk?.lead?{lead:r.risk.lead}:{},...r.risk?.body?{body:r.risk.body}:{},...a===null||a.trim()===""||o===void 0?{}:{action:{label:a,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:s===null||s.trim()===""?tC:s,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function lC(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function iC(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var oC=20,aC=14,sC=16,uC=18,cC=22,dC=15,fC=12,hC=24,pC=15,gC=14.5,bC=21,mC=14.5,yC=18,vC=9,kC=36,wC=14,CC=15,SC=8,xC=40;function TopCard({card:e,open:t,onOpenChange:r,ask:n}){let l=useEverfurTheme(),i=ow(),o=a(()=>i!==null?RC(i):TC(l),[l,i]),s=a(()=>ab(l.slots.card),[l.slots.card]);if(!t)return null;let u=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:Vf.close,c=e.action,d=e.ask,f=/* @__PURE__ */$(CloseGlyph,{size:i!==null?HOME_CLOSE_GLYPH(i):yC,color:i!==null?String(i.text(".ask-focus__x").color):l.color.text.primary,strokeWidth:2});/* @__PURE__ */
260
+ return W(x,{style:[o.card,s],testID:"everfur-top-card",children:[
261
+ /* @__PURE__ */W(x,{style:o.kickerRow,children:[
262
+ /* @__PURE__ */$(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */$(x,{style:o.badge,children:/* @__PURE__ */$(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */$(z,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?_C:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */$(HostRender,{render:()=>e.renderIcon?.("close"),fallback:f}):f}):null]}),
263
+ /* @__PURE__ */$(Text,{tier:"heading",style:o.title,accessibilityRole:"header",children:e.title}),e.lead!==void 0||e.body!==void 0?/* @__PURE__ */W(x,{style:o.finding,children:[
264
+ /* @__PURE__ */$(x,{style:o.dot}),
265
+ /* @__PURE__ */W(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */$(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */W(x,{style:o.actions,children:[c!==void 0?/* @__PURE__ */$(z,{onPress:()=>{Dh(c.onPress)},accessibilityRole:"button",accessibilityLabel:c.label,style:o.action,hitSlop:i!==null?_C:void 0,children:/* @__PURE__ */$(Text,{tier:"control",style:o.actionText,children:c.label})}):null,d!==void 0?/* @__PURE__ */$(z,{onPress:()=>n(d.prompt),accessibilityRole:"button",accessibilityLabel:d.label,style:o.ask,hitSlop:i!==null?_C:void 0,children:/* @__PURE__ */$(Text,{tier:"control",style:o.askText,children:d.label})}):null]}):null]})}function TopCardPill({card:e,open:t,onOpenChange:r}){let n=useEverfurTheme(),l=ow(),i=a(()=>l!==null?RC(l):TC(n),[n,l]);if(t||e.closeLabel===void 0)return null;let o=e.pill??e.kicker;/* @__PURE__ */
266
+ return W(z,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?_C:void 0,testID:"everfur-top-card-pill",children:[
267
+ /* @__PURE__ */$(x,{style:i.pillDot}),
268
+ /* @__PURE__ */$(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var _C=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:yC};function RC(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),l=typeof n.height=="number"?n.height:vC;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-l)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function TC(e){let t=e.color,r=e.space;return v.create({card:{paddingTop:aC,paddingHorizontal:sC,paddingBottom:sC,borderRadius:oC,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:rm-8},kicker:{...iC(e),fontSize:dC,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:hC,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:fC,color:t.text.secondary},close:{width:rm,height:rm,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:rm/2},title:{...iC(e),fontSize:uC,lineHeight:cC,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:vC,height:vC,borderRadius:vC/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:gC,lineHeight:bC,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(xC,rm),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:pC,color:t.onPrimary},ask:{minHeight:rm,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:mC,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(kC,rm),paddingHorizontal:wC,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:SC,height:SC,borderRadius:SC/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:CC,color:t.danger,flexShrink:1}})}var IC=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),zC=/* @__PURE__ */new WeakMap;function PC(e){let t=zC.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...IC},i=(e,t)=>yo(e,t,uo(t),OC),o=(e,t)=>contrastRatio(e,t)>=OC?e:so(t,OC),a=[l.card,l.paper].map(e=>go(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return zC.set(e,u),u}var OC=4.5;function EC(e,t){for(let r of t)if(contrastRatio(r,e)>=OC)return r;return so(e,OC)}function jC(e,t,r){let n=bo(e,t);return(n===null?null:go(n,r))??r}function FC(e){let t=PC(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:EC(t.accent,[t.ink,t.onAccent]),accent2:jC(t.accent,.75,n),accent4:jC(t.accent,.17,n),accentChip:jC(t.accent,.47,n),link:t.link,linkChip:jC(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var AC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),DC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),MC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],LC=17,BC=1.5,HC=400,UC=700;function NC(e){return e<=450?"regular":e<=650?"medium":"bold"}function $C(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function WC(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:$C(r)}}let n=t==="$serif"?headingFace(e,NC(r)):face(e,NC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:$C(r)}}function VC(e,t,r={}){let n=FC(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},a=/* @__PURE__ */new Map,s=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),s=a.get(l);if(s!==void 0)return s;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return a.set(l,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=s(e),l={};for(let[e,t]of Object.entries(n))AC.has(e)||DC.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of MC){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let a=n.shadow;if(Array.isArray(a)){let[e,t,r,n]=a;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=s(r),a=typeof o.fontSize=="number"?o.fontSize:LC,u=typeof o.lh=="number"?o.lh:BC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...WC(e,f,c),fontSize:a,lineHeight:Math.round(a*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*a*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(HC,e),strong:(...e)=>f(UC,e),icon:(...e)=>{let t=s(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=s([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=s(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>s(t)[e]}}var qC={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},GC=16;var KC=4e3,YC=.5;function QC(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function JC(e,t,r){if(e.length===0)return r;let n=QC(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=YC*e.length+1;for(let o of l)if(QC(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=v.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=c({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[u,d]=l(null),f=u!==null&&u.key===o?u.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=JC(t,l,(e.ch+YC)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
269
+ return W(x,{style:XC.wrap,children:[
270
+ /* @__PURE__ */$(Text,{tier:"heading",style:f===null?t:[t,{maxWidth:f}],accessibilityRole:"header",children:e}),
271
+ /* @__PURE__ */$(x,{style:XC.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */W(x,{style:XC.probeRow,children:[
272
+ /* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.ch=t}),children:"0"}),
273
+ /* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */$(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var XC=v.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:KC,flexDirection:"row",alignItems:"flex-start"}});function ZC(e){return{kit:VC(e,qC),Title:BalancedTitle,titleCh:GC}}var eS=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function tS(){let e=globalThis,t=e[eS];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[eS]=r,r}var rS=e=>{let t=tS();return t.listeners.add(e),()=>t.listeners.delete(e)},nS=()=>tS().count>0;function useHostPoweredBy(){return i(rS,nS,nS)}var lS=/* @__PURE__ */Object.freeze({}),iS=100,oS=20;function aS(e,t,r,n){return![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}function sS(e,t){let r=typeof e=="number"&&Number.isFinite(e),i=c(null),[o,s]=l(null),d=c(null),f=c(null),h=c(true),p=u(()=>{f.current!==null&&clearTimeout(f.current),f.current=null},[]);n(()=>(h.current=true,()=>{h.current=false,p()}),[p]);let g=u(function e(t){i.current?.measureInWindow((r,n)=>{let l=d.current;if(!h.current||l===null)return;let i=aS(n,l.y,l.height,C.get("window").height);if(i!==null){s(e=>e!==null&&e.chatTop===i.chatTop&&e.parentTop===i.parentTop?e:i);return}t>=oS||(f.current=setTimeout(()=>{f.current=null,e(t+1)},iS))})},[]),b=u(e=>{let{y:t,height:r}=e.nativeEvent.layout;d.current={y:t,height:r},p(),g(0)},[g,p]);return a(()=>{if(!t)return{avoidingProps:r?{keyboardVerticalOffset:e}:lS,probeRef:null,topInWindow:null};let n=o?.parentTop??0;return{avoidingProps:r?{keyboardVerticalOffset:e,onLayout:b}:n>0?{keyboardVerticalOffset:n,onLayout:b}:{onLayout:b},probeRef:i,topInWindow:o?.chatTop??null}},[t,r,e,o,b])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */$(x,{ref:e,collapsable:false,pointerEvents:"none",style:uS})}var uS=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function cS(){let[e,t]=l(false);return n(()=>{let e=P;if(typeof e?.addListener!="function")return;let r=m.OS==="ios",n=e.addListener(r?"keyboardWillShow":"keyboardDidShow",()=>t(true)),l=e.addListener(r?"keyboardWillHide":"keyboardDidHide",()=>t(false));return()=>{n.remove(),l.remove()}},[]),e}function dS(e,t,r){return yo(e,t,uo(t),r)}function fS(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=Jv(t),l=r?n.warning:n.info,i=Qv(t)&&!l?e:hS(e,t,r);return pS(i,t.slots.banner)}function hS(e,t,r){let n=t.color,l=go(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,i=r?n.cautionAccent:n.infoEdge,o=dS(go(i,n.surface)??i,[n.surface,n.chatGround],jo),a=dS(r?n.warningStrong:n.info,[l,n.surface],_o);/* @__PURE__ */
274
+ return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:dS(n.text.primary,[l],_o),pillColor:n.surface})}function pS(e,t){if(t===void 0)return e;let r={...e};return t.backgroundColor!==void 0&&(r.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(r.borderColor=t.borderColor),t.textColor!==void 0&&(r.textColor=t.textColor,r.reasonColor=t.textColor),/* @__PURE__ */Object.freeze(r)}function gS(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}var bS=.75,mS=1.5,yS=.4,vS=4,kS=1.5,wS=22,CS=14,SS=8,xS=20,_S=10,RS=13,TS=12,IS=15,zS=44,PS=14,OS=1.25,ES=14,jS=6,FS=2;function AS(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:bo(r.danger,yS)??r.danger,borderWidth:mS},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}};let n=e.slots.banner?.borderRadius;return{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:bS,...n===void 0?{}:{borderRadius:n}},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}function UrgencyBanner({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,compact:i=false}){let o=useEverfurTheme(),s=a(()=>DS(o),[o]),u=jg(),c=e.tier===null?null:fS(e.tier,o),d=e.source;/* @__PURE__ */
275
+ return W(V,{children:[
276
+ /* @__PURE__ */$(FadePresence,{visible:e.showBanner&&c!==null,inMs:u.bannerInMs,outMs:u.bannerOutMs,style:s.pinned,children:c!==null&&d!==null?/* @__PURE__ */$(BannerCard,{tier:c,reason:d.reason,surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,styles:s,compact:i}):null}),
277
+ /* @__PURE__ */$(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:Vf.showLatestVetAlert,hitSlop:_S,onPress:e.expand,children:/* @__PURE__ */$(InfoGlyph,{size:xS,color:o.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:e,reason:t,surface:r,petRef:n,renderVetAction:l,onFindVet:i,vet:o,styles:a,compact:s}){let u=useEverfurTheme(),c=AS(u,e),d=/* @__PURE__ */$(VetAction,{tier:e,paint:c,petRef:n,onFindVet:i,vet:o,styles:a}),f=r.showVetAction?l!==void 0?/* @__PURE__ */$(HostRender,{render:()=>l(e.level),fallback:d,resetKey:e.level}):d:null,h=c.action!==null?/* @__PURE__ */$(PoisonControl,{paint:c.action,styles:a}):null,p=e.level==="emergency"&&i===void 0,g=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
278
+ return W(x,{...g?{accessibilityRole:"alert"}:{accessibilityLiveRegion:"polite"},style:[a.card,c.card,s?a.cardCompact:null],testID:s?"chat-urgency-compact":void 0,children:[
279
+ /* @__PURE__ */$(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */$(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?FS:void 0,accessibilityLabel:s?t:void 0,children:t}):null,p?/* @__PURE__ */$(Text,{style:[a.reason,a.erLine,{color:c.reason}],children:Vf.goToNearestEmergencyVet}):null,f!==null||h!==null?/* @__PURE__ */W(x,{style:a.actions,children:[f,h]}):null,r.dismissLabel!==null?/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:r.dismissLabel,hitSlop:SS,containerStyle:a.closeSlot,style:a.closeButton,onPress:r.dismiss,children:/* @__PURE__ */$(CloseGlyph,{size:CS,color:c.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let r=()=>{try{T.openURL(Yf).catch(()=>{})}catch{}};/* @__PURE__ */
280
+ return $(PressScale,{accessibilityRole:"button",accessibilityLabel:Vf.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:r,children:/* @__PURE__ */$(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:Vf.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:l,styles:i}){let o=useEverfurTheme(),a=useVetVisit(gS(r,l)),s=a.status==="opening",u=!a.available&&n!==void 0,c=a.available?()=>{a.open()}:n!==void 0?()=>{Dh(n,e.level)}:null;if(c===null)return null;let d=t.action;if(d!==null){let e=u?Vf.nearestEmergencyVet:Vf.findVet,t=sb(o.slots.vetVisitButton)?.textColor??d.ink;/* @__PURE__ */
281
+ return W(PressScale,{accessibilityRole:"button",accessibilityLabel:u?Vf.nearestEmergencyVet:Vf.findVetA11y,accessibilityState:{busy:s},hitSlop:0,style:[i.action,{backgroundColor:d.fill,borderColor:d.edge},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
282
+ /* @__PURE__ */$(MapPinGlyph,{size:RS,color:t,strokeWidth:1.5}),
283
+ /* @__PURE__ */$(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=sb(o.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
284
+ return W(PressScale,{accessibilityRole:"button",accessibilityLabel:Vf.findVetA11y,accessibilityState:{busy:s},style:[i.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
285
+ /* @__PURE__ */$(MapPinGlyph,{size:RS,color:f,strokeWidth:1.5}),
286
+ /* @__PURE__ */$(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:Vf.findVet})]})}function DS(e){let t=sb(e.slots.vetVisitButton),r=e.space,n=e.type;return v.create({pinned:{marginTop:0,marginBottom:r.xs,paddingHorizontal:r.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:r.lg+vS,paddingVertical:r.lg,gap:r.sm},cardCompact:{paddingVertical:r.md,gap:r.xs},label:{...face(e,"bold"),fontSize:n.size.body,paddingRight:wS},reason:{...face(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*kS),paddingRight:wS},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm},action:{flexDirection:"row",alignItems:"center",gap:jS,minHeight:zS,paddingHorizontal:PS,borderRadius:e.radius.pill,borderWidth:OS},actionLabel:{...face(e,"bold"),fontSize:ES},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...ab(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:TS,lineHeight:IS},closeSlot:{position:"absolute",top:r.md,right:r.md},closeButton:{width:wS,height:wS,borderRadius:wS/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:r.lg,paddingTop:2,paddingBottom:r.xs}})}function MS(e,t,r,i){let[o,a]=l({pet:r,user:t}),s=o.pet!==r||o.user===null&&t!==null;s&&a({pet:r,user:t});let u=s?{user:t}:o,c=r!==null&&u.user!==null&&u.user!==t;return n(()=>{if(!c||t===null||r===null)return;let n=true,l=createPetsRepository(e.registry.services.authFor(t)),i=async()=>{let e=await l.list();n&&e.ok&&e.value.some(e=>e.petRef===r)&&a({pet:r,user:t})};i();let o=Vi(e,()=>{i()});return()=>{n=false,o()}},[c,e,t,r,i]),c}var LS=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(e){let{runtime:t,userRef:r,activePet:o,scopeEpoch:s}=wd(),d=e?.petRef??o??null,f=e?.conversationId??null,h=MS(t,r,d,s),p=a(()=>({runtime:t,userRef:r,petRef:d,conversationId:f,scopeEpoch:s,held:h}),[t,r,d,f,s,h]),[g,b]=l(null),m=h?null:g?.scope===p?g.controller:t.registry.peekChat({userRef:r,petRef:d,conversationId:f}),y=c(null);n(()=>{if(h)return;let e=t.registry.acquireChat({userRef:r,petRef:d,conversationId:f});return y.current=e,b({scope:p,controller:e}),()=>{y.current=null,b(t=>t?.controller===e?null:t),t.registry.releaseChat(e)}},[t,r,d,f,s,h,p]);let v=u(e=>m?m.subscribe(e):NOOP_UNSUBSCRIBE,[m]),k=u(()=>m?m.getSnapshot():LS,[m]),w=i(v,k,k),C=u((e,t)=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?HS(m,m.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>y.current===m):Promise.resolve(NS()),[m]),S=u(e=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?HS(m,m.askEverfur(e),()=>y.current===m):Promise.resolve(NS()),[m]),x=u(()=>m&&y.current===m?HS(m,m.retryLast(),()=>y.current===m):Promise.resolve(NS()),[m]),_=u(()=>{m&&y.current===m&&m.stop()},[m]),R=u(()=>{m&&y.current===m&&m.newConversation()},[m]),[T,I]=l({controller:null,byMessage:{}}),z=T.controller===m?T.byMessage:BS,P=u(async(e,t,r,n)=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let l=String(e),i=T.controller===m?T.byMessage[l]:void 0;if(i===t&&r==null)return I(e=>{let t={...e.controller===m?e.byMessage:{}};return delete t[l],{controller:m,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));I(e=>({controller:m,byMessage:{...e.controller===m?e.byMessage:{},[l]:t}}));let o=await m.submitFeedback(e,Wk(t,r??null),n??null);return y.current!==m?err(makeEverfurError("accessDenied")):(o.ok||I(e=>{let t={...e.controller===m?e.byMessage:{}};return i===void 0?delete t[l]:t[l]=i,{controller:m,byMessage:t}}),o)},[m,T]),O=a(()=>{let e=async e=>{if(!m||y.current!==m)return err(makeEverfurError("accessDenied"));let t=await e(m);return y.current===m?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...d?{petRef:d}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[m,d]);return a(()=>({status:w.status,messages:w.messages,conversationId:w.conversationId,petRef:d,error:w.error,isStreaming:w.isStreaming,isBootstrapping:w.isBootstrapping,historyCursor:w.historyCursor??null,isLoadingHistory:w.isLoadingHistory??false,stopped:w.stopped??false,reconnecting:w.reconnecting??false,...O,suggestedPrompts:w.suggestedPrompts,unreadCount:w.unreadCount,hasUnreadThreads:w.hasUnreadThreads??false,pendingCheckin:w.pendingCheckin??null,newConversation:R,sentimentByMessage:z,feedback:P,send:C,askEverfur:S,retryLast:x,stop:_}),[w,d,C,S,x,_,O,R,z,P])}var NOOP_UNSUBSCRIBE=()=>{},BS=/* @__PURE__ */Object.freeze({});async function HS(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(US(n.messages))}function US(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}function NS(){return kp()}function $S(){let e=useEverfurPets(),{handle:t}=wd(),r=u(e=>t.setActivePet(e),[t]);return a(()=>({...e,setActivePet:r}),[e,r])}function WS(){try{let e=k?.announceForAccessibility;typeof e=="function"&&e.call(k,Vf.answered)}catch{}}function VS(e){let t=c(false),r=c({send:e.send,id:e.conversationId});n(()=>{let n=r.current;if((n.send!==e.send||n.id!==null&&n.id!==e.conversationId)&&(t.current=false),r.current={send:e.send,id:e.conversationId},t.current&&!e.isStreaming){let t=e.messages[e.messages.length-1];t!==void 0&&t.role==="assistant"&&WS()}t.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var qS=/* @__PURE__ */Object.freeze({kind:"live"}),GS=/* @__PURE__ */Object.freeze({kind:"folded"});function KS(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=jn(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function YS(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=KS(t);if(e===null)continue;let n=r.get(e.caseId);(n===void 0||e.dueDay>=n.dueDay)&&r.set(e.caseId,{messageId:t.id,dueDay:e.dueDay})}if(r.size===0)return t;let n=null;for(let l of e){let e=KS(l);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===l.id){t.set(l.id,qS),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(l.id,GS);continue}let i=[e.dueDay];n={id:l.id,caseId:e.caseId,days:i},t.set(l.id,{kind:"past",runDueDays:i})}return t}function QS(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var JS=864e5,XS=365;function ZS(e,t){if(typeof e!="string"||typeof t!="string")return null;let r=Date.parse(e),n=Date.parse(t);if(Number.isNaN(r)||Number.isNaN(n))return null;let l=Math.floor(n/JS)-Math.floor(r/JS);return l<1||l>XS?null:l}function ex(e){return KS(e)?.dueDay||null}function tx(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:e,named:t,styles:r}){let n=Wv(e);return n.shown?/* @__PURE__ */W(x,{style:r.assistantSender,testID:"everfur-assistant-sender",children:[
287
+ /* @__PURE__ */$(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */$(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:Vf.assistantName}):null]}):t?/* @__PURE__ */$(Text,{tier:"control",style:r.assistantName,children:Vf.assistantName}):null}var rx=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),nx="#C8BEB4";function lx(e){return e?rx[e.toUpperCase()]??nx:nx}function ix(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function ox(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function ax(e){let t=ox(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function sx(e,t){let r=ox(e.source_name)??ox(e.sourceName),n=ox(e.section),l=ox(e.authority_tier)??ox(e.authorityTier),i=ix(l),o=r??ox(e.title)??`Source ${t+1}`,a=ox(e.monograph_chunk_id)??ox(e.chunkId),s=[n,i].filter(e=>e!==null).join(" · ");/* @__PURE__ */
288
+ return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:ax(e.url),excerpt:ox(e.excerpt),tierColor:lx(l),key:`${o}-${a??"none"}-${t}`})}function ux(e){return e===void 0||e.length===0?cx:/* @__PURE__ */Object.freeze(e.map((e,t)=>sx(e,t)))}var cx=/* @__PURE__ */Object.freeze([]);function dx(e){return e===1?`1 ${Vf.sourceSingular}`:`${e} ${Vf.sourcePlural}`}function fx(e,t){return`${t?Vf.hideSources:Vf.showSources} ${dx(e)}`}function hx(e){return[e.url!==null?`${Vf.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function px(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var gx=/^\s*[-*]\s+(\S.*)$/,bx=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function mx(e){let t=[],r=[],n=null,l=()=>{r.length>0&&t.push({kind:"text",text:r.join(`\n`)}),r=[]},i=()=>{n!==null&&t.push(n.ordered?{kind:"list",ordered:true,start:n.start,items:n.items}:{kind:"list",ordered:false,items:n.items}),n=null};for(let t of e.split(`\n`)){let e=gx.exec(t),o=e===null?bx.exec(t):null,a=e?.[1]??o?.[2];if(a===void 0){i(),r.push(t);continue}let s=o!==null;l(),n!==null&&n.ordered!==s&&i(),n===null&&(n={ordered:s,start:o===null?1:Number(o[1]),items:[]}),n.items.push(a.trim())}return l(),i(),t}function yx(e,t){let r=e.findIndex(e=>e.id===t);for(let t=r-1;t>=0;t-=1){let r=e[t];if(r!==void 0&&r.role==="user")return r.text}return null}function vx(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function kx(e){return hardenHttpsUrl(e.trim())}function wx(e,t){if(t?.followUpActions===void 0||e.isStreaming||e.status==="error")return[];let r=e.messages[e.messages.length-1];return r===void 0||r.role!=="assistant"||r.pending===true?[]:vx(t.followUpActions,{answer:r.text,question:yx(e.messages,r.id),messageId:r.id})}var Cx=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,Sx=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${gg}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${gg}})`,"gi"),xx=/https:\/\//i,_x=`.,;:!?'"`;function Rx(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&xx.test(e)}function Tx(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):Px(r,e,t)},l=0;Cx.lastIndex=0;for(let t=Cx.exec(e);t!==null;t=Cx.exec(e)){t.index>l&&n(e.slice(l,t.index));let i=t[1],o=t[2],a=t[3];i!==void 0?r.push({kind:"bold",text:i}):o!==void 0?r.push({kind:"italic",text:o}):a!==void 0&&r.push({kind:"code",text:a}),l=t.index+t[0].length}return l<e.length&&n(e.slice(l)),r}function Ix(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(_x.includes(r))t-=1;else if(r===")"&&zx(e,"(",t)<zx(e,")",t))t-=1;else break}return e.slice(0,t)}function zx(e,t,r){let n=0;for(let l=0;l<r;l+=1)e[l]===t&&(n+=1);return n}function Px(e,t,r){if(!xx.test(t)){e.push({kind:"text",text:t});return}let n=0;Sx.lastIndex=0;for(let l=Sx.exec(t);l!==null;l=Sx.exec(t)){let i=l[1],o=l[2],a=l[3],s,u,c;if(i!==void 0&&o!==void 0)s=i.trim(),u=s.length>0?vg(o,r):null,c=l[0].length;else if(a!==void 0)s=Ix(a),u=vg(s,r),c=s.length;else continue;u!==null&&(l.index>n&&e.push({kind:"text",text:t.slice(n,l.index)}),e.push({kind:"link",text:s,href:u}),n=l.index+c,Sx.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var Ox=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function Ex(e,t){return t===void 0||!Rx(e,t.hosts)?false:Tx(e,t.hosts).some(e=>e.kind==="link")}function jx(e,t,r){let n=r?.hosts;return Rx(e,n)?Tx(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
289
+ return $(Text,{style:t.bold,children:e.text},n);case"italic":return t.italic?/* @__PURE__ */$(Text,{style:t.italic,children:e.text},n):e.text;case"code":return t.code?/* @__PURE__ */$(Text,{style:t.code,children:e.text},n):e.text;case"link":{if(r===void 0)return e.text;let{href:t}=e;/* @__PURE__ */
290
+ return $(Text,{style:Ox,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var Fx=10.5,Ax=16,Dx=12,Mx=38,Lx=11,Bx=15,Hx=22,Ux=32,Nx=13.5,$x=14,Wx=15,Vx=16,qx=13,Gx=13,Kx=26,Yx=21,Qx=42,Jx=1,Xx=.06,Zx=.07,e_=.12,t_="45%";function r_(){let e=useEverfurTheme(),t=a(()=>n_(e),[e]);return{theme:e,styles:t}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */$(ChevronGlyph,{size:Vx,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */$(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:r,styles:n}=r_();if(e.render!==void 0){let r=e.render;/* @__PURE__ */
291
+ return $(x,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */$(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?kx(e.tile.imageUrl):null,c=/* @__PURE__ */W(V,{children:[l?null:/* @__PURE__ */$(x,{style:[n.tile,a!==void 0?i?.tileTone?.[a]:null],children:u!==null?/* @__PURE__ */$(F,{source:{uri:u},style:n.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
292
+ /* @__PURE__ */W(x,{style:n.cardWords,children:[
293
+ /* @__PURE__ */$(Text,{tier:"control",style:n.cardTitle,children:e.title}),e.meta!==void 0?/* @__PURE__ */$(Text,{tier:"compact",style:n.cardMeta,children:e.meta}):null]}),l?/* @__PURE__ */W(Text,{tier:"control",style:n.stat,children:[e.value?.amount,e.value?.unit!==void 0?/* @__PURE__ */$(Text,{style:n.statUnit,children:e.value.unit}):null]}):/* @__PURE__ */W(V,{children:[e.pill!==void 0?/* @__PURE__ */$(x,{style:[n.pill,s!==void 0?i?.pillTone?.[s]:null],children:/* @__PURE__ */$(Text,{tier:"badge",style:[n.pillText,s!==void 0?i?.pillToneText?.[s]:null],numberOfLines:1,ellipsizeMode:"tail",children:e.pill.label})}):null,e.onPress!==void 0?/* @__PURE__ */$(Chevron,{options:t,color:r.color.text.muted}):null]})]});if(e.onPress!==void 0){let t=e.onPress;/* @__PURE__ */
294
+ return $(z,{onPress:()=>{Dh(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:o,children:c})}/* @__PURE__ */
295
+ return $(x,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=r_(),f=a(()=>({answer:e.text,question:yx(n,e.id),messageId:e.id}),[e.text,e.id,n]),h=!r&&e.pending!==true,p=h?vx(l?.cards,f):[],g=a(()=>h?ux(e.citations):[],[h,e.citations]),b=l?.byline,m=l?.feedback!==void 0&&e.responseId!==void 0&&o!==void 0?l.feedback:null,y={bold:d.bold,italic:d.italic,code:d.code},v=Cg(),k=h?v:void 0;/* @__PURE__ */
296
+ return W(x,{style:d.answer,testID:"everfur-answer-cards",children:[b!==void 0?/* @__PURE__ */W(x,{style:d.byline,children:[b.icon??null,
297
+ /* @__PURE__ */$(Text,{tier:"compact",style:d.bylineText,children:b.label})]}):s,
298
+ /* @__PURE__ */$(x,{style:d.body,children:px(t).flatMap((e,t)=>mx(e).map((e,r)=>{let n=`${t}-${r}`;return e.kind==="text"?/* @__PURE__ */$(Text,{style:d.paragraph,children:jx(e.text,y,k)},n):/* @__PURE__ */$(x,{style:d.list,children:e.items.map((t,r)=>/* @__PURE__ */W(x,{style:d.listItem,children:[
299
+ /* @__PURE__ */$(Text,{style:d.paragraph,children:e.ordered?`${e.start+r}.`:"•"}),
300
+ /* @__PURE__ */$(Text,{style:[d.paragraph,d.listText],children:jx(t,y,k)})]},r))},n)}))}),p.length>0?/* @__PURE__ */$(x,{style:d.cards,children:p.map(e=>/* @__PURE__ */$(AnswerCard,{card:e,options:l},e.key))}):null,h?/* @__PURE__ */$(ServerCardsSlot,{message:e}):null,g.length>0?/* @__PURE__ */W(x,{style:d.cards,accessibilityLabel:dx(g.length),children:[
301
+ /* @__PURE__ */$(Text,{tier:"compact",style:d.label,children:Vf.sourcesHeading}),g.map(e=>{let t=e.url;/* @__PURE__ */
302
+ return $(AnswerCard,{card:{key:e.key,title:e.title,...e.meta!==null?{meta:e.meta}:{},tile:{icon:/* @__PURE__ */$(SourceTileGlyph,{})},...c!==void 0&&t!==null?{onPress:()=>c(t)}:{}},options:l},e.key)})]}):null,h&&m!==null&&o!==void 0?/* @__PURE__ */W(x,{style:[d.feedback,l?.styles?.feedback],children:[
303
+ /* @__PURE__ */$(FeedbackChip,{label:m.helpful,on:i==="up",onPress:()=>o("up"),styles:d,host:l?.styles}),
304
+ /* @__PURE__ */$(FeedbackChip,{label:m.notHelpful,on:i==="down",onPress:()=>o("down"),styles:d,host:l?.styles})]}):null,h?u(m===null):null]})}function SourceTileGlyph(){let e=useEverfurTheme();/* @__PURE__ */
305
+ return $(BookGlyph,{size:Yx,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:r,styles:n,host:l}){/* @__PURE__ */
306
+ return $(z,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(rm-Ux)/2,children:/* @__PURE__ */$(Text,{tier:"control",style:[n.chipText,l?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:t,label:r,actions:n,options:l}){let{theme:i,styles:o}=r_();if(e.length===0&&n.length===0)return null;let a=l?.styles,s=r??Vf.followUpsHeadingNative;/* @__PURE__ */
307
+ return W(x,{style:[o.followUps,a?.followUps],accessibilityLabel:s,testID:"everfur-cards-follow-ups",children:[
308
+ /* @__PURE__ */$(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */W(z,{onPress:()=>{Dh(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:Jx,style:[o.row,o.rowAction,a?.followUp,a?.followUpAction],children:[e.icon??null,
309
+ /* @__PURE__ */$(Text,{tier:"control",style:[o.rowText,o.rowTextAction,a?.followUpText,a?.followUpActionText],children:e.label}),
310
+ /* @__PURE__ */$(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */W(z,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:Jx,style:[o.row,a?.followUp],children:[
311
+ /* @__PURE__ */$(Text,{tier:"control",style:[o.rowText,a?.followUpText],children:e}),
312
+ /* @__PURE__ */$(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=r_();/* @__PURE__ */
313
+ return $(x,{style:t.byline,children:/* @__PURE__ */$(Text,{tier:"compact",style:t.bylineText,children:e})})}function n_(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:Fx,textTransform:"uppercase",color:t.text.muted},l={borderWidth:1,borderColor:t.borderRingCream},i={borderWidth:1,borderColor:bo(t.text.primary,Xx)??t.borderRingCream},o={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:Zx,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=ub(e.slots.chip);return v.create({answer:{gap:r.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...n,letterSpacing:Fx*.06,flexShrink:1},body:{gap:10},paragraph:{...face(e,"regular"),fontSize:a.fontSize,lineHeight:Math.round(a.lineHeight),color:t.text.primary},list:{gap:4},listItem:{flexDirection:"row",gap:r.sm,paddingLeft:r.xs},listText:{flex:1},bold:face(e,"bold"),italic:{fontStyle:"italic"},code:face(e,"mono"),cards:{gap:r.sm},card:{flexDirection:"row",alignItems:"center",gap:r.md,padding:Dx,borderRadius:Ax,backgroundColor:t.surface,...i,...o,minHeight:rm,...ab(e.slots.card)},tile:{width:Mx,height:Mx,borderRadius:Lx,backgroundColor:bo(t.linkInk,e_)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:Mx,height:Mx},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:Bx,lineHeight:Math.round(Bx*1.25),color:t.text.primary,...ub(e.slots.card)},cardMeta:{...n,letterSpacing:Fx*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:Hx,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:Fx+2,color:t.text.muted},pill:{minHeight:Kx,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:t_},pillText:{...face(e,"bold"),fontSize:Gx,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,alignItems:"center"},chip:{minHeight:Ux,paddingHorizontal:12,borderRadius:e.radius.pill,...l,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...lC(e),fontSize:Nx,color:t.text.primary,...chipInk},followUps:{gap:r.sm,alignSelf:"stretch",marginTop:r.xs},label:{...face(e,"bold"),fontSize:qx,lineHeight:Math.round(qx*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:Qx,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:$x,backgroundColor:t.surface,...i},rowAction:{},rowText:{...lC(e),flex:1,fontSize:Wx,lineHeight:Math.round(Wx*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var l_=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),i_=/* @__PURE__ */Object.freeze(Br.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:l_.answers[e]})));function o_(e,t){let[r,n]=l(null),[i,o]=l(null),[a,s]=l(null),c=u(r=>{t!==null&&(n(r),o(null),t(e.caseId,r).then(e=>{n(null),e.ok?s(r):o(e.error)}))},[t,e.caseId]),d=a??e.answer;return{answer:d,answerable:!isCheckinSettled(e),escalated:d==="worse",pending:r,error:i,choose:c}}var a_=44,s_=.6,u_=/* @__PURE__ */Object.freeze({caseId:"",answer:null,resolutionText:null,status:null});function CheckinCard({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:l,vet:i,onLayout:o,onOpen:s}){let u=useEverfurTheme(),c=a(()=>c_(u),[u]),d=o_(t??u_,t===null?null:r),f=d.answer!==null||d.pending!==null,h=t!==null&&r!==null&&d.answerable,p=t===null?null:ZS(t.openedAt,ex(e));/* @__PURE__ */
314
+ return W(x,{style:c.card,accessibilityLabel:l_.eyebrow,onLayout:o,children:[
315
+ /* @__PURE__ */W(x,{style:c.head,children:[
316
+ /* @__PURE__ */$(Text,{tier:"compact",style:c.eyebrow,children:l_.eyebrow}),p!==null?/* @__PURE__ */$(Text,{tier:"compact",style:c.headDay,children:qf(l_.day,{day:p})}):null]}),s?/* @__PURE__ */$(z,{onPress:s,accessibilityRole:"button",accessibilityLabel:e.text,style:c.open,children:/* @__PURE__ */$(Text,{style:[c.question,c.openText],children:e.text})}):/* @__PURE__ */$(Text,{style:c.question,accessibilityRole:"text",children:e.text}),h?/* @__PURE__ */$(x,{style:[c.row,d.pending?c.rowPending:null],children:i_.map(({answer:e,label:t})=>{let r=(d.pending??d.answer)===e;/* @__PURE__ */
317
+ return $(z,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */$(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */$(Text,{style:c.logged,children:l_.logged}):null,d.escalated?/* @__PURE__ */$(CheckinFindVet,{petRef:n??null,onFindVet:l,vet:i,styles:c}):null,t?.resolutionText?/* @__PURE__ */$(Text,{style:c.resolution,children:t.resolutionText}):null,d.error?/* @__PURE__ */$(Text,{style:c.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:r,styles:n}){return useVetVisit(gS(e,r)).available&&e!==null?/* @__PURE__ */$(VetVisitButtonCore,{entry:"chat",petRef:e,label:l_.findVet,...r?.returnTo!==void 0?{returnTo:r.returnTo}:{},...r?.usState!==void 0?{usState:r.usState}:{},...r?.prefer!==void 0?{prefer:r.prefer}:{},style:n.findVet,labelStyle:n.findVetLabel}):t===void 0?null:/* @__PURE__ */$(z,{onPress:t,accessibilityRole:"button",accessibilityLabel:l_.findVet,style:n.findVet,children:/* @__PURE__ */$(Text,{tier:"control",style:n.findVetLabel,children:l_.findVet})})}function c_(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=sb(e.slots.card),o=ub(i);return v.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:v.hairlineWidth,borderColor:t.brandBorder,...ab(i,v.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},question:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},open:{minHeight:a_,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:s_},pill:{flex:1,minHeight:a_,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.controlEdge,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,...o},resolution:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},error:{...face(e,"regular"),color:t.danger,fontSize:l.size.caption},findVet:{alignSelf:"stretch",minHeight:a_,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.controlEdge,backgroundColor:t.surface},findVetLabel:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.body}})}var d_=244,f_=8,h_=13,p_=14,g_=.3,b_=-.24,m_=22,y_=10,v_=15;function CitationCards({citations:e,onOpenUrl:t}){let r=useEverfurTheme(),n=a(()=>k_(r),[r]),i=a(()=>ux(e),[e]),[o,s]=l(false);if(i.length===0)return null;let u=i.length;/* @__PURE__ */
318
+ return W(x,{style:n.block,children:[
319
+ /* @__PURE__ */W(PressScale,{accessibilityRole:"button",accessibilityLabel:fx(u,o),accessibilityState:{expanded:o},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>s(e=>!e),children:[
320
+ /* @__PURE__ */$(BookGlyph,{size:h_,color:r.color.brandInk,strokeWidth:1.5}),
321
+ /* @__PURE__ */$(Text,{tier:"compact",style:n.toggleLabel,children:dx(u)}),
322
+ /* @__PURE__ */$(ChevronGlyph,{size:h_,color:r.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?/* @__PURE__ */$(Deck,{cards:i,styles:n,open:t}):null]})}function Deck({cards:e,styles:t,open:r}){let n=jg(),l=Ng(n.citationsInMs,{risePx:n.citationsRisePx});/* @__PURE__ */
323
+ return $(M.View,{style:l,children:/* @__PURE__ */$(E,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */$(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=hx(l?e:{...e,url:null}),o=/* @__PURE__ */W(V,{children:[
324
+ /* @__PURE__ */W(x,{style:t.cardHeader,children:[
325
+ /* @__PURE__ */$(x,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),
326
+ /* @__PURE__ */$(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */$(ArrowUpRightGlyph,{size:p_,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */$(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */$(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let n=e.url;/* @__PURE__ */
327
+ return $(PressScale,{accessibilityRole:"link",accessibilityLabel:i,style:t.card,onPress:()=>r(n),children:o})}/* @__PURE__ */
328
+ return $(x,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function k_(e){let t=e.color,r=e.space,n=e.radius,l=e.type.size,i=ub(e.slots.card);return v.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:l.micro,lineHeight:l.micro,letterSpacing:g_,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:d_,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2,...ab(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:f_,height:f_,borderRadius:n.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:l.bodyTight,lineHeight:m_,color:t.text.primary,letterSpacing:b_,...i},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:l.nano,lineHeight:y_,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...i},cardExcerpt:{...face(e,"regular"),fontSize:l.tiny,lineHeight:v_,color:t.text.muted,...i}})}var w_=15,C_=44,S_=16,x_=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:e,onCopy:t,sentiment:r=null,onSentiment:i,note:o=null}){let s=useEverfurTheme(),u=a(()=>__(s),[s]),d=jg(),f=e.role==="user",h=a(()=>tx(e.createdAt),[e.createdAt]),p=t!==void 0&&e.role!=="vet"&&e.text.length>0,g=e.role==="assistant"&&i!==void 0&&e.responseId!==void 0,[b,m]=l(false),y=c(null);n(()=>()=>{y.current&&clearTimeout(y.current)},[]);let v=()=>{t!==void 0&&(Bh(t,e.text),m(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null},d.copiedMs))};return h===null&&!p&&!g?null:/* @__PURE__ */W(x,{style:u.wrap,children:[
329
+ /* @__PURE__ */W(x,{style:[u.row,f?u.rowUser:u.rowAssistant],children:[h!==null?/* @__PURE__ */$(Text,{tier:"compact",style:u.timestamp,children:h}):null,p?/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:b?Vf.copied:f?Vf.copyUserMessage:Vf.copyAssistantMessage,onPress:v,style:u.iconHit,children:b?/* @__PURE__ */$(CheckGlyph,{size:w_,color:s.color.success,strokeWidth:2}):/* @__PURE__ */$(CopyGlyph,{size:w_,color:s.color.text.timestamp,strokeWidth:1.5})}):null,g?Nk.map(({sentiment:e,label:t})=>/* @__PURE__ */$(z,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r===e},onPress:()=>i?.(e),style:u.iconHit,children:/* @__PURE__ */$(ThumbGlyph,{size:w_,color:r===e?s.color.sentiment[e]:s.color.text.timestamp,active:r===e,rotate:x_[e],strokeWidth:1.5})},e)):null]}),o==="thanks"?/* @__PURE__ */$(Text,{style:u.thanks,accessibilityLiveRegion:"polite",children:Vf.feedbackThanks}):null,o==="failed"?/* @__PURE__ */W(V,{children:[
330
+ /* @__PURE__ */$(Text,{style:u.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:Vf.feedbackFailed}),
331
+ /* @__PURE__ */$(AnnounceLine,{line:Vf.feedbackFailed})]}):null]})}function __(e){let t=e.type;return v.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:S_,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:C_,height:C_,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary},failed:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.danger}})}var R_=16,T_=10,I_=12,z_=10,P_=2,O_=.06,E_=34,j_=9,F_=10.5,A_=.06,D_=15,M_=19.5,L_=14,B_=19.6;function OpeningCard({card:e,onLayout:t}){let r=useEverfurTheme(),n=a(()=>H_(r),[r]),l=e.styles;/* @__PURE__ */
332
+ return W(x,{testID:"everfur-opening-card",onLayout:t,accessible:true,accessibilityLabel:[e.kicker,e.title,e.body].filter(e=>e!==void 0).join(", "),style:[n.card,l?.card],children:[e.icon!==void 0?/* @__PURE__ */$(x,{style:[n.icon,l?.icon],children:e.icon}):null,
333
+ /* @__PURE__ */W(x,{style:n.words,children:[
334
+ /* @__PURE__ */$(Text,{tier:"compact",style:[n.kicker,l?.kicker],children:e.kicker}),
335
+ /* @__PURE__ */$(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */$(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function H_(e){let t=e.color;return v.create({card:{flexDirection:"row",alignItems:"flex-start",gap:z_,paddingVertical:T_,paddingHorizontal:I_,alignSelf:"stretch",borderRadius:R_,backgroundColor:t.surface,borderWidth:1,borderColor:bo(t.text.primary,O_)??t.borderRingCream},icon:{flexShrink:0,width:E_,height:E_,borderRadius:j_,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:P_},kicker:{...face(e,"mono"),fontSize:F_,letterSpacing:F_*A_,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:D_,lineHeight:M_,color:t.text.primary},body:{...face(e,"regular"),fontSize:L_,lineHeight:B_,color:t.text.secondary}})}var U_="#10462E",N_="Book a video visit",$_="#000000",W_="#83E0B4",V_=/* @__PURE__ */Object.freeze([
336
336
  /* @__PURE__ */Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
337
- /* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:B_,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
338
- /* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:D_,brandEdge:true,borderWidth:1}),
339
- /* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function U_(e,t){return e?null:{fill:t.fill,ink:t.ink}}var N_=8;function $_(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function W_(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=N_)break;if(r===null||typeof r!="object"||typeof r.label!="string")continue;let e=r.label.trim();if(e.length===0)continue;let n=typeof r.prompt=="string"&&r.prompt.trim().length>0?r.prompt.trim():e,l=$_(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:l,ink:l===null?null:$_(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var V_=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function q_(e){return e==null?e:e.replace(V_,"").trim()}var G_=/* @__PURE__ */new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function K_(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return G_.has(t)}function Y_(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function Q_(e,t){let r=e?.trim();if(r===void 0||r==="")return J_(t);let n=t?.name?.trim()||$f.emptyTitlePetFallback,l=n.charAt(0).toUpperCase()+n.slice(1);return r.replace(/\{(pet|petName)\}/g,(e,t,r)=>r===0?l:n)}function J_(e){let t=e?.name?.trim()||$f.emptyTitlePetFallback;return Wf($f.emptyTitle,{petName:t})}function X_(e){let t=e.toLowerCase();return t===Y_("dog").toLowerCase()||t===Y_("cat").toLowerCase()}function Z_(e){let t=q_(e);if(K_(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return X_(r)?null:r}function eR(e,t=D_,r){let n=canonicalPetSpecies(e?.species),l=e?.name?.trim()||null,i=Z_(e?.breed),o=Kv(e?.ageYears),a=o===null?null:String(o),s=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
340
- return Object.freeze(H_.flatMap(e=>{let r=e.intent==="vet_report"&&s!==null?s:e.label,o=r.includes("{breed}"),u=r.includes("{ageYears}"),c=e.fallbackLabel!==void 0&&(o&&!i||u&&!a)&&e.fallbackLabel?e.fallbackLabel:r;if(c.includes("{breed}")&&i===null||c.includes("{ageYears}")&&a===null||n===null&&(c.includes("{species}")||c.includes("{petName}")&&l===null))return[];let d=Wf(c,{petName:l??(n==="cat"?"my cat":"my dog"),breed:i??"",species:n??"",ageYears:a??""}),f=!l&&c.startsWith("{petName}")?d.charAt(0).toUpperCase()+d.slice(1):d;return[/* @__PURE__ */Object.freeze({id:e.id,intent:e.intent,label:f,background:e.background,borderColor:e.brandEdge===true?t:e.borderColor,borderWidth:e.borderWidth})]}))}var tR=44,rR=0,nR={top:3,bottom:3},lR=1,iR=.28,oR=2,aR=2,sR=1.3,uR=-.015,cR=/* @__PURE__ */Object.freeze([
337
+ /* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:W_,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
338
+ /* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:U_,brandEdge:true,borderWidth:1}),
339
+ /* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function q_(e,t){return e?null:{fill:t.fill,ink:t.ink}}var G_=8;function K_(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function Y_(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=G_)break;if(r===null||typeof r!="object"||typeof r.label!="string")continue;let e=r.label.trim();if(e.length===0)continue;let n=typeof r.prompt=="string"&&r.prompt.trim().length>0?r.prompt.trim():e,l=K_(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:l,ink:l===null?null:K_(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var Q_=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function J_(e){return e==null?e:e.replace(Q_,"").trim()}var X_=/* @__PURE__ */new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function Z_(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return X_.has(t)}function eR(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function tR(e,t){let r=e?.trim();if(r===void 0||r==="")return rR(t);let n=t?.name?.trim()||Vf.emptyTitlePetFallback,l=n.charAt(0).toUpperCase()+n.slice(1);return r.replace(/\{(pet|petName)\}/g,(e,t,r)=>r===0?l:n)}function rR(e){let t=e?.name?.trim()||Vf.emptyTitlePetFallback;return qf(Vf.emptyTitle,{petName:t})}function nR(e){let t=e.toLowerCase();return t===eR("dog").toLowerCase()||t===eR("cat").toLowerCase()}function lR(e){let t=J_(e);if(Z_(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return nR(r)?null:r}function iR(e,t=U_,r){let n=canonicalPetSpecies(e?.species),l=e?.name?.trim()||null,i=lR(e?.breed),o=Zv(e?.ageYears),a=o===null?null:String(o),s=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
340
+ return Object.freeze(V_.flatMap(e=>{let r=e.intent==="vet_report"&&s!==null?s:e.label,o=r.includes("{breed}"),u=r.includes("{ageYears}"),c=e.fallbackLabel!==void 0&&(o&&!i||u&&!a)&&e.fallbackLabel?e.fallbackLabel:r;if(c.includes("{breed}")&&i===null||c.includes("{ageYears}")&&a===null||n===null&&(c.includes("{species}")||c.includes("{petName}")&&l===null))return[];let d=qf(c,{petName:l??(n==="cat"?"my cat":"my dog"),breed:i??"",species:n??"",ageYears:a??""}),f=!l&&c.startsWith("{petName}")?d.charAt(0).toUpperCase()+d.slice(1):d;return[/* @__PURE__ */Object.freeze({id:e.id,intent:e.intent,label:f,background:e.background,borderColor:e.brandEdge===true?t:e.borderColor,borderWidth:e.borderWidth})]}))}var oR=44,aR=0,sR={top:3,bottom:3},uR=1,cR=.28,dR=2,fR=2,hR=1.3,pR=-.015,gR=/* @__PURE__ */Object.freeze([
341
341
  /* @__PURE__ */Object.freeze({tint:"#FFE7A1",ink:"#262523"}),
342
342
  /* @__PURE__ */Object.freeze({tint:"#C8F4F8",ink:"#262523"}),
343
343
  /* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
344
- /* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()=>dR(u),[u]),d=a(()=>W_(i),[i]),f=a(()=>d!==null?d.map(e=>({prompt:{id:e.id,intent:"send",label:e.label,background:e.tint??u.color.highlight,borderColor:"transparent",borderWidth:1},send:e.prompt,paint:e.tint===null?null:{fill:e.tint,ink:e.ink??u.color.text.primary}})):eR(e,u.color.brandInk,{vetPrepLabel:M_}).map(e=>({prompt:e,send:e.label,paint:null})),[d,e,u.color.brandInk,u.color.highlight,u.color.text.primary]),h=o?.chipTints!==void 0,p=a(()=>(o?.chipTints??(u.brightness==="light"?cR:[])).filter(e=>typeof e.tint=="string"&&e.tint.trim()!==""),[o?.chipTints,u.brightness]),g=a(()=>p.length===0?f:f.map((e,t)=>{if(e.paint!==null)return e;let r=p[t%p.length];return{...e,paint:{fill:r.tint,ink:r.ink??u.color.text.primary},...h?{}:{cycleDefault:true}}}),[f,p,h,u.color.text.primary]),b=a(()=>U_(Vv(u),{fill:u.color.highlight,ink:u.color.onHighlight}),[u]),m=a(()=>({fill:u.color.highlight,ink:u.color.onHighlight}),[u.color.highlight,u.color.onHighlight]),y=Q_(o?.title,e),v=tw(),k=rw(),w=v!==null&&k!==null?/* @__PURE__ */U(k.Title,{text:y,style:[c.title,v.text(".serif",".ask-empty h2"),c.centerText],measureCh:k.titleCh}):/* @__PURE__ */U(Text,{tier:"heading",style:s?[c.title,c.centerText]:c.title,accessibilityRole:"header",children:y});/* @__PURE__ */
345
- return N(C,{style:v!==null?c.homeBlock:c.block,children:[w,
346
- /* @__PURE__ */U(C,{style:v!==null?[c.list,c.listCentered,v.view(".ask-chips",".ask-empty .ask-chips")]:s?[c.list,c.listCentered]:c.list,accessibilityLabel:$f.suggestions,children:g.map(({prompt:i,send:o,paint:a,cycleDefault:u},f)=>/* @__PURE__ */U(Chip,{prompt:i,send:o,themed:a??(d!==null?m:b),index:f,petRef:t,onSend:r,onVetPrep:n,vet:l,pet:e,styles:c,tinted:a!==null&&u!==true,soft:a!==null,centered:s},i.id))})]})}function Chip({prompt:e,send:t,themed:r,index:n,pet:l,petRef:i,onSend:o,onVetPrep:a,vet:s,styles:u,tinted:c,soft:d,centered:f}){let h=Ig(),p=Mg(h.followUpInMs,{delayMs:Rg(h,n),risePx:h.promptRisePx}),g=tw(),b=g!==null?[u.chipHome,g.view(".chip")]:f&&d?u.chipNoEdge:u.chipEdge,m={backgroundColor:r?.fill??e.background},y=u.chipSlot===null?m:c?{...u.chipSlot,...m}:{...m,...u.chipSlot},v=g!==null?[u.chipLabel,g.text(".chip")]:f?[u.chipLabel,u.centerText]:[u.chipLabel],k=g!==null?nR:rR,w=r===null?u.chipSlotLabel===null?v:[...v,u.chipSlotLabel]:c?[...v,...u.chipSlotLabel===null?[]:[u.chipSlotLabel],{color:r.ink}]:[...v,{color:r.ink},...u.chipSlotLabel===null?[]:[u.chipSlotLabel]];return e.intent==="vet_report"?a!==void 0?/* @__PURE__ */U(A.View,{style:p,children:/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>{Fh(a,l)},children:/* @__PURE__ */U(Text,{tier:"compact",style:w,children:e.label})})}):i===null?null:/* @__PURE__ */U(A.View,{style:p,children:/* @__PURE__ */U(VetVisitButtonCore,{entry:"chat",petRef:i,label:e.label,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:[u.chip,b,y],labelStyle:w})}):/* @__PURE__ */U(A.View,{style:p,children:/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>o(t),children:/* @__PURE__ */U(Text,{tier:"compact",style:w,children:e.label})})})}function dR(e){let t=nb(e.slots.chip),r=lb(t);return{chipSlot:t===void 0?null:rb(t,lR),chipSlotLabel:r.color===void 0?null:r,...fR(e)}}function fR(e){let t=e.color,r=e.space,n=e.type;return m.create({block:{gap:r.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:n.size.heading,lineHeight:Math.round(n.size.heading*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.size.heading*uR,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:r.sm+oR},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:lR,borderColor:"transparent"},chip:{borderRadius:e.radius.pill,paddingHorizontal:r.lg+aR,paddingVertical:r.sm,minHeight:tR,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:lR,borderColor:po(t.brandInk,iR)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*sR),color:L_,textAlign:"left"}})}var hR=1e3,pR=150,gR=.25,bR=.5,mR=3;function TypingIndicator({petName:e=null,inline:t=false}){let{theme:r,styles:l}=Nm(),i=r.motion.reducedMotion,o=qf($f.reading,e),a=u(Array.from({length:mR},()=>new A.Value(0))).current;return n(()=>{if(i)return;let e=a.map((e,t)=>A.loop(A.sequence([A.delay(t*pR),A.timing(e,{toValue:1,duration:hR*.4,useNativeDriver:true}),A.timing(e,{toValue:0,duration:hR*.6,useNativeDriver:true}),A.delay((mR-t-1)*pR)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[i,a]),/* @__PURE__ */U(C,{style:t?l.readingInline:l.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:o,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:a.map((e,r)=>/* @__PURE__ */U(A.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[t?l.readingDotInline:l.readingDot,i?{opacity:bR}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[gR,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},r))})}function yR(e,t,r){let n=e-r,l=t!=null?Math.min(n,t):n;return Math.max(0,l)}function vR(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return{assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}function kR(e,t,r){let n=Math.max(0,r),l=e===null?n:Math.min(Math.max(0,e),n);return l>t+1?l:null}var wR=16;function CR(e,t,r=null){let l=u(null),i=u(true),o=u(t),a=u(0),c=u(0),d=u(0),f=u(/* @__PURE__ */new Map),h=u(null),p=u(false),g=e[0]?.id??null,b=u(g),m=u(null);n(()=>{let t=b.current;if(b.current=g,t===null||t===g||(m.current=null,i.current||!e.some(e=>e.id===t)))return;let r=f.current.get(t);r!==void 0&&(m.current={id:t,top:r,offset:a.current})},[g,e]);let y=vR(e),v=y===null?null:e[y.assistantIndex]?.id??null,k=y===null||y.userIndex===null?null:e[y.userIndex]?.id??null,w=s(()=>{let e=l.current;if(e===null||!i.current||c.current===0)return;let t=null;if(v!==null){let e=f.current.get(v);if(e===void 0)return;let r=k===null?null:f.current.get(k)??null;t=yR(e,r,96)}let r=kR(t,a.current,d.current-c.current);if(r!==null&&(a.current=r,e.scrollTo({y:r,animated:false})),!p.current||h.current===null)return;let n=kR(h.current+wR-c.current,a.current,d.current-c.current);n!==null&&(a.current=n,e.scrollTo({y:n,animated:false}))},[v,k]);n(()=>{p.current=r!==null,r===null&&(h.current=null),w()},[r,w]),n(()=>{t&&!o.current&&(i.current=true,p.current=false),o.current=t,w()},[e,t,w]);let C=s(e=>{c.current=e.nativeEvent.layout.height,w()},[w]),S=s((e,t)=>{d.current=t,c.current>0&&(a.current=Math.min(a.current,Math.max(0,t-c.current))),w()},[w]),x=s(e=>{a.current=e.nativeEvent.contentOffset.y},[]),_=s(()=>{i.current=false,p.current=false},[]),R=s(e=>{let{contentOffset:t,contentSize:r,layoutMeasurement:n}=e.nativeEvent;a.current=t.y,i.current=r.height-t.y-n.height<=24},[]),T=s(e=>t=>{let r=t.nativeEvent.layout.y;f.current.set(e,r);let n=m.current;if(n!==null&&n.id===e&&r!==n.top){m.current=null;let e=Math.max(0,n.offset+r-n.top);a.current=e,l.current?.scrollTo({y:e,animated:false})}(e===v||e===k)&&w()},[v,k,w]),I=s(e=>{let{y:t,height:r}=e.nativeEvent.layout;h.current=t+r,w()},[w]);return{ref:l,onLayout:C,onContentSizeChange:S,onScroll:x,onScrollBeginDrag:_,onScrollEnd:R,rowLayout:T,asideLayout:I}}function SR(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */U(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */U(LoadingState,{})}):/* @__PURE__ */U(LoadingState,{});case"empty":/* @__PURE__ */
347
- return U(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,renderEmptyHeader:r.renderEmptyHeader});case"error":/* @__PURE__ */
348
- return U(ErrorState,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case"populated":/* @__PURE__ */
349
- return U(PopulatedState,{messages:t.messages,prompts:ip(t,r.followUpPolicy),actions:r.answerCards?bx(t,r.answerCards):_R,answerCards:r.answerCards??null,threadTop:r.threadTop,pendingCheckin:r.pendingCheckin??null,threadAside:r.threadAside,threadAsideKey:r.threadAsideKey??null,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,feedbackNote:r.feedbackNote,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl,petName:r.shownPet?.name??null,followUpLabel:r.followUpPolicy?.label,openingCard:r.openingCard,earlier:t.historyCursor?{loading:t.isLoadingHistory,load:t.loadOlderMessages}:null});default:return assertNever(e)}}function LoadingState(){let{theme:e,styles:t}=Nm(),[r,i]=l(false);return n(()=>{let e=setTimeout(()=>i(true),Kb);return()=>clearTimeout(e)},[]),/* @__PURE__ */U(C,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:$f.loading,children:r?/* @__PURE__ */U(O,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:l,top:i,topCard:o,pendingCheckin:a,starterPrompts:s,emptyState:u,centered:c,renderEmptyHeader:d}){let{styles:f}=Nm(),h=tw(),p=d===void 0?null:/* @__PURE__ */U(C,{testID:"everfur-empty-header",children:/* @__PURE__ */U(HostRender,{render:()=>d({ask:r}),fallback:null})});if(h!==null){let{minHeight:c,...d}=h.view(".ask-empty");/* @__PURE__ */
350
- return N(P,{contentContainerStyle:[d,f.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:TR,nestedScrollEnabled:true,accessibilityLabel:$f.empty,children:[i!=null?/* @__PURE__ */U(C,{style:h.view(".ask-top"),children:i}):null,a,o??null,p,
351
- /* @__PURE__ */U(C,{style:h.view(".ask-start"),children:/* @__PURE__ */U(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:true})})]})}
344
+ /* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()=>bR(u),[u]),d=a(()=>Y_(i),[i]),f=a(()=>d!==null?d.map(e=>({prompt:{id:e.id,intent:"send",label:e.label,background:e.tint??u.color.highlight,borderColor:"transparent",borderWidth:1},send:e.prompt,paint:e.tint===null?null:{fill:e.tint,ink:e.ink??u.color.text.primary}})):iR(e,u.color.brandInk,{vetPrepLabel:N_}).map(e=>({prompt:e,send:e.label,paint:null})),[d,e,u.color.brandInk,u.color.highlight,u.color.text.primary]),h=o?.chipTints!==void 0,p=a(()=>(o?.chipTints??(u.brightness==="light"?gR:[])).filter(e=>typeof e.tint=="string"&&e.tint.trim()!==""),[o?.chipTints,u.brightness]),g=a(()=>p.length===0?f:f.map((e,t)=>{if(e.paint!==null)return e;let r=p[t%p.length];return{...e,paint:{fill:r.tint,ink:r.ink??u.color.text.primary},...h?{}:{cycleDefault:true}}}),[f,p,h,u.color.text.primary]),b=a(()=>q_(Qv(u),{fill:u.color.highlight,ink:u.color.onHighlight}),[u]),m=a(()=>({fill:u.color.highlight,ink:u.color.onHighlight}),[u.color.highlight,u.color.onHighlight]),y=tR(o?.title,e),v=ow(),k=aw(),w=v!==null&&k!==null?/* @__PURE__ */$(k.Title,{text:y,style:[c.title,v.text(".serif",".ask-empty h2"),c.centerText],measureCh:k.titleCh}):/* @__PURE__ */$(Text,{tier:"heading",style:s?[c.title,c.centerText]:c.title,accessibilityRole:"header",children:y});/* @__PURE__ */
345
+ return W(x,{style:v!==null?c.homeBlock:c.block,children:[w,
346
+ /* @__PURE__ */$(x,{style:v!==null?[c.list,c.listCentered,v.view(".ask-chips",".ask-empty .ask-chips")]:s?[c.list,c.listCentered]:c.list,accessibilityLabel:Vf.suggestions,children:g.map(({prompt:i,send:o,paint:a,cycleDefault:u},f)=>/* @__PURE__ */$(Chip,{prompt:i,send:o,themed:a??(d!==null?m:b),index:f,petRef:t,onSend:r,onVetPrep:n,vet:l,pet:e,styles:c,tinted:a!==null&&u!==true,soft:a!==null,centered:s},i.id))})]})}function Chip({prompt:e,send:t,themed:r,index:n,pet:l,petRef:i,onSend:o,onVetPrep:a,vet:s,styles:u,tinted:c,soft:d,centered:f}){let h=jg(),p=Ng(h.followUpInMs,{delayMs:Og(h,n),risePx:h.promptRisePx}),g=ow(),b=g!==null?[u.chipHome,g.view(".chip")]:f&&d?u.chipNoEdge:u.chipEdge,m={backgroundColor:r?.fill??e.background},y=u.chipSlot===null?m:c?{...u.chipSlot,...m}:{...m,...u.chipSlot},v=g!==null?[u.chipLabel,g.text(".chip")]:f?[u.chipLabel,u.centerText]:[u.chipLabel],k=g!==null?sR:aR,w=r===null?u.chipSlotLabel===null?v:[...v,u.chipSlotLabel]:c?[...v,...u.chipSlotLabel===null?[]:[u.chipSlotLabel],{color:r.ink}]:[...v,{color:r.ink},...u.chipSlotLabel===null?[]:[u.chipSlotLabel]];return e.intent==="vet_report"?a!==void 0?/* @__PURE__ */$(M.View,{style:p,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>{Dh(a,l)},children:/* @__PURE__ */$(Text,{tier:"compact",style:w,children:e.label})})}):i===null?null:/* @__PURE__ */$(M.View,{style:p,children:/* @__PURE__ */$(VetVisitButtonCore,{entry:"chat",petRef:i,label:e.label,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:[u.chip,b,y],labelStyle:w})}):/* @__PURE__ */$(M.View,{style:p,children:/* @__PURE__ */$(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>o(t),children:/* @__PURE__ */$(Text,{tier:"compact",style:w,children:e.label})})})}function bR(e){let t=sb(e.slots.chip),r=ub(t);return{chipSlot:t===void 0?null:ab(t,uR),chipSlotLabel:r.color===void 0?null:r,...mR(e)}}function mR(e){let t=e.color,r=e.space,n=e.type;return v.create({block:{gap:r.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:n.size.heading,lineHeight:Math.round(n.size.heading*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.size.heading*pR,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:r.sm+dR},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:uR,borderColor:"transparent"},chip:{borderRadius:e.radius.pill,paddingHorizontal:r.lg+fR,paddingVertical:r.sm,minHeight:oR,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:uR,borderColor:bo(t.brandInk,cR)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*hR),color:$_,textAlign:"left"}})}var yR=1e3,vR=150,kR=.25,wR=.5,CR=3;function TypingIndicator({petName:e=null,inline:t=false}){let{theme:r,styles:l}=Gm(),i=r.motion.reducedMotion,o=Kf(Vf.reading,e),a=c(Array.from({length:CR},()=>new M.Value(0))).current;return n(()=>{if(i)return;let e=a.map((e,t)=>M.loop(M.sequence([M.delay(t*vR),M.timing(e,{toValue:1,duration:yR*.4,useNativeDriver:true}),M.timing(e,{toValue:0,duration:yR*.6,useNativeDriver:true}),M.delay((CR-t-1)*vR)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[i,a]),/* @__PURE__ */$(x,{style:t?l.readingInline:l.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:o,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:a.map((e,r)=>/* @__PURE__ */$(M.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[t?l.readingDotInline:l.readingDot,i?{opacity:wR}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[kR,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},r))})}function SR(e,t,r){let n=e-r,l=t!=null?Math.min(n,t):n;return Math.max(0,l)}function xR(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return{assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}function _R(e,t,r){let n=Math.max(0,r),l=e===null?n:Math.min(Math.max(0,e),n);return l>t+1?l:null}var RR=16;function TR(e,t,r=null){let l=c(null),i=c(true),o=c(t),a=c(0),s=c(0),d=c(0),f=c(/* @__PURE__ */new Map),h=c(null),p=c(false),g=e[0]?.id??null,b=c(g),m=c(null);n(()=>{let t=b.current;if(b.current=g,t===null||t===g||(m.current=null,i.current||!e.some(e=>e.id===t)))return;let r=f.current.get(t);r!==void 0&&(m.current={id:t,top:r,offset:a.current})},[g,e]);let y=xR(e),v=y===null?null:e[y.assistantIndex]?.id??null,k=y===null||y.userIndex===null?null:e[y.userIndex]?.id??null,w=u(()=>{let e=l.current;if(e===null||!i.current||s.current===0)return;let t=null;if(v!==null){let e=f.current.get(v);if(e===void 0)return;let r=k===null?null:f.current.get(k)??null;t=SR(e,r,96)}let r=_R(t,a.current,d.current-s.current);if(r!==null&&(a.current=r,e.scrollTo({y:r,animated:false})),!p.current||h.current===null)return;let n=_R(h.current+RR-s.current,a.current,d.current-s.current);n!==null&&(a.current=n,e.scrollTo({y:n,animated:false}))},[v,k]);n(()=>{p.current=r!==null,r===null&&(h.current=null),w()},[r,w]),n(()=>{t&&!o.current&&(i.current=true,p.current=false),o.current=t,w()},[e,t,w]);let C=u(e=>{s.current=e.nativeEvent.layout.height,w()},[w]),S=u((e,t)=>{d.current=t,s.current>0&&(a.current=Math.min(a.current,Math.max(0,t-s.current))),w()},[w]),x=u(e=>{a.current=e.nativeEvent.contentOffset.y},[]),_=u(()=>{i.current=false,p.current=false},[]),R=u(e=>{let{contentOffset:t,contentSize:r,layoutMeasurement:n}=e.nativeEvent;a.current=t.y,i.current=r.height-t.y-n.height<=24},[]),T=u(e=>t=>{let r=t.nativeEvent.layout.y;f.current.set(e,r);let n=m.current;if(n!==null&&n.id===e&&r!==n.top){m.current=null;let e=Math.max(0,n.offset+r-n.top);a.current=e,l.current?.scrollTo({y:e,animated:false})}(e===v||e===k)&&w()},[v,k,w]),I=u(e=>{let{y:t,height:r}=e.nativeEvent.layout;h.current=t+r,w()},[w]);return{ref:l,onLayout:C,onContentSizeChange:S,onScroll:x,onScrollBeginDrag:_,onScrollEnd:R,rowLayout:T,asideLayout:I}}function IR(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */$(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */$(LoadingState,{})}):/* @__PURE__ */$(LoadingState,{});case"empty":/* @__PURE__ */
347
+ return $(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,renderEmptyHeader:r.renderEmptyHeader});case"error":/* @__PURE__ */
348
+ return $(ErrorState,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case"populated":/* @__PURE__ */
349
+ return $(PopulatedState,{messages:t.messages,prompts:ap(t,r.followUpPolicy),actions:r.answerCards?wx(t,r.answerCards):PR,answerCards:r.answerCards??null,threadTop:r.threadTop,pendingCheckin:r.pendingCheckin??null,threadAside:r.threadAside,threadAsideKey:r.threadAsideKey??null,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,feedbackNote:r.feedbackNote,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl,petName:r.shownPet?.name??null,followUpLabel:r.followUpPolicy?.label,openingCard:r.openingCard,earlier:t.historyCursor?{loading:t.isLoadingHistory,load:t.loadOlderMessages}:null});default:return assertNever(e)}}function LoadingState(){let{theme:e,styles:t}=Gm(),[r,i]=l(false);return n(()=>{let e=setTimeout(()=>i(true),Zb);return()=>clearTimeout(e)},[]),/* @__PURE__ */$(x,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:Vf.loading,children:r?/* @__PURE__ */$(j,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:l,top:i,topCard:o,pendingCheckin:a,starterPrompts:s,emptyState:u,centered:c,renderEmptyHeader:d}){let{styles:f}=Gm(),h=ow(),p=d===void 0?null:/* @__PURE__ */$(x,{testID:"everfur-empty-header",children:/* @__PURE__ */$(HostRender,{render:()=>d({ask:r}),fallback:null})});if(h!==null){let{minHeight:c,...d}=h.view(".ask-empty");/* @__PURE__ */
350
+ return W(E,{contentContainerStyle:[d,f.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:ER,nestedScrollEnabled:true,accessibilityLabel:Vf.empty,children:[i!=null?/* @__PURE__ */$(x,{style:h.view(".ask-top"),children:i}):null,a,o??null,p,
351
+ /* @__PURE__ */$(x,{style:h.view(".ask-start"),children:/* @__PURE__ */$(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:true})})]})}
352
352
  /* @__PURE__ */
353
- return N(P,{contentContainerStyle:f.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:TR,nestedScrollEnabled:true,accessibilityLabel:$f.empty,children:[i??null,a,o??null,p,
354
- /* @__PURE__ */U(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:r}){let{styles:n}=Nm();return e.length===0?null:/* @__PURE__ */N(C,{style:n.followUps,children:[
355
- /* @__PURE__ */U(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??$f.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */U(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:l}=Nm(),i=Ig(),o=Mg(i.followUpInMs,{delayMs:Rg(i,t)});/* @__PURE__ */
356
- return U(A.View,{style:o,children:/* @__PURE__ */N(PressScale,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[l.followUpSlot,t>0?l.followUpSlotRuled:null],style:l.followUpRow,children:[
357
- /* @__PURE__ */U(Text,{tier:"control",style:l.followUpText,children:e}),
358
- /* @__PURE__ */U(PlusGlyph,{size:IR,color:n.slots.chip?.textColor??n.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Nm(),l=fp(e)?Dh(r):void 0,i=Qh(e);/* @__PURE__ */
359
- return N(C,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[i!==null?/* @__PURE__ */U(Text,{style:n.errorText,testID:"everfur-chat-cap-reached",children:i.reached}):null,
360
- /* @__PURE__ */U(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */U(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */U(T,{onPress:l,accessibilityRole:"button",accessibilityLabel:$f.addPet,style:n.retryButton,children:/* @__PURE__ */U(Text,{tier:"control",style:n.retryLabel,children:$f.addPet})}):null,e.retryable?/* @__PURE__ */U(T,{onPress:t,accessibilityRole:"button",accessibilityLabel:$f.retry,style:n.retryButton,children:/* @__PURE__ */U(Text,{tier:"control",style:n.retryLabel,children:$f.retry})}):null]})}function PopulatedState({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:l,onCopy:i,sentimentByMessage:o,onSentiment:s,feedbackNote:u,imagesByMessage:c,onPreview:d,notice:f,reconnecting:h,onRetry:p,onStartNew:g,petRef:b,onFindVet:m,vet:y,onOpenUrl:v,petName:k,actions:w,answerCards:S,threadTop:x,pendingCheckin:_,threadAside:R,threadAsideKey:I,followUpLabel:z,openingCard:O,earlier:E}){let{styles:j}=Nm(),F=Ig();Vg(e.length,F);let A=a(()=>VS(WS(e)),[e]),D=Zh(e,n),M=e[e.length-1],L=R??null,B=CR(e,n,L===null?null:I??"shown"),H=Hg(e),$=e[0],W=O!==void 0&&$!==void 0&&$.role==="user"&&$.text.trim()===O.prompt?$.id:null;/* @__PURE__ */
361
- return N(P,{ref:B.ref,style:j.list,contentContainerStyle:S!==null?j.listContentCards:j.listContent,accessibilityLabel:$f.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:TR,nestedScrollEnabled:true,onLayout:B.onLayout,onContentSizeChange:B.onContentSizeChange,onScroll:B.onScroll,scrollEventThrottle:RR,onScrollBeginDrag:B.onScrollBeginDrag,onScrollEndDrag:B.onScrollEnd,onMomentumScrollEnd:B.onScrollEnd,children:[x??null,_,E!==null?/* @__PURE__ */U(T,{onPress:()=>{E.load()},disabled:E.loading,accessibilityRole:"button",accessibilityLabel:E.loading?Vp.loadingEarlier:Vp.earlier,accessibilityState:{disabled:E.loading,busy:E.loading},hitSlop:pm,style:j.earlierButton,children:/* @__PURE__ */U(Text,{tier:"compact",style:j.earlierLabel,children:E.loading?Vp.loadingEarlier:Vp.earlier})}):null,e.map(t=>t.id===W&&O!==void 0?/* @__PURE__ */U(OpeningCard,{card:O.card,onLayout:B.rowLayout(t.id)},t.id):t.checkin&&A.has(t.id)?/* @__PURE__ */U(CheckinCard,{message:t,checkin:t.checkin,onAnswer:l,petRef:b,onFindVet:m,vet:y,onLayout:B.rowLayout(t.id)},t.id):/* @__PURE__ */U(MessageRow,{onLayout:B.rowLayout(t.id),message:t,revealing:n&&t===M&&t.role==="assistant",onCopy:i,sentiment:t.responseId===void 0?null:o[String(t.responseId)]??null,onSentiment:s,note:t.responseId!==void 0&&u?.responseId===String(t.responseId)?u.kind:null,images:c[t.id]??xR,onPreview:d,onOpenUrl:v,entering:H(t.id),answerCards:S,messages:e},t.id)),h?/* @__PURE__ */U(Text,{tier:"compact",style:j.reconnectingCaption,accessibilityRole:"text",children:$f.reconnecting}):null,D?/* @__PURE__ */U(TypingIndicator,{petName:k,inline:S!==null}):null,f!==null?/* @__PURE__ */U(TurnNoticeCard,{notice:f,onRetry:p,onStartNew:g}):null,S!==null?/* @__PURE__ */U(CardsFollowUps,{prompts:t,onSelectPrompt:r,label:z,actions:w,options:S}):/* @__PURE__ */U(FollowUps,{prompts:t,onSelectPrompt:r,label:z}),L!==null?/* @__PURE__ */U(C,{onLayout:B.asideLayout,children:L}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Nm(),l=e.tone==="error";/* @__PURE__ */
362
- return N(C,{style:[n.turnNotice,l?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
363
- /* @__PURE__ */U(Text,{tier:"control",style:[n.turnNoticeTitle,l?n.turnNoticeTitleError:null],children:e.title}),
364
- /* @__PURE__ */U(Text,{tier:"compact",style:n.turnNoticeBody,children:e.body}),e.guidance!==void 0?/* @__PURE__ */U(Text,{tier:"compact",style:n.turnNoticeBody,testID:"everfur-chat-cap-guidance",children:e.guidance}):null,
365
- /* @__PURE__ */U(T,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:pm,style:n.turnNoticeAction,children:/* @__PURE__ */U(Text,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}var xR=/* @__PURE__ */Object.freeze([]),_R=/* @__PURE__ */Object.freeze([]),RR=16,TR=g.OS==="ios"?"interactive":"on-drag",IR=18;function MessageRow({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:l,note:i,images:o,onPreview:a,onOpenUrl:u,onLayout:c,entering:d,answerCards:f,messages:h}){let{theme:p,styles:g}=Nm(),b=Ig(),m=Bg(d,b),y=Ng(e.text,t,b),v=e.role==="user",k=e.role==="vet",w=e.role==="assistant",S=mg(),x=w&&!t?S:void 0,_=x!==void 0&&Tx(e.text,x),R=w&&!p.meta.hidePoweredBy,T=v?$f.senderUser:k?op(e):R?$f.assistantName:$f.senderAssistant,I=k?QS(e.createdAt):null,z=s(t=>l(e,t),[l,e]),P=e.pending!==true,O=w&&p.meta.assistantAvatarUrl!==null?/* @__PURE__ */U(AssistantSender,{avatarUrl:p.meta.assistantAvatarUrl,named:R,styles:g}):R?f!==null?/* @__PURE__ */U(CardsByline,{label:$f.assistantName}):/* @__PURE__ */U(Text,{tier:"control",style:g.assistantName,children:$f.assistantName}):null,E=f!==null;return w&&f!==null?/* @__PURE__ */U(A.View,{style:[g.rowBlock,m],onLayout:c,accessibilityLabel:`${T}: ${e.text}`,children:/* @__PURE__ */U(CardsAnswer,{message:e,text:y,streaming:t,messages:h,options:f,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,sender:O,onOpenUrl:u,footer:t=>/* @__PURE__ */U(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:t&&e.responseId!==void 0?z:void 0,note:i})})}):/* @__PURE__ */N(C,{style:[g.rowBlock,v?g.rowBlockUser:g.rowBlockAssistant],onLayout:c,children:[
366
- /* @__PURE__ */U(C,{style:[g.row,v?g.rowUser:g.rowAssistant],accessible:!_,accessibilityRole:_?void 0:"text",accessibilityLabel:_?void 0:`${T}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:/* @__PURE__ */N(A.View,{style:[g.bubble,E?g.bubbleCards:null,v?g.bubbleSideUser:null,m],children:[O,k?/* @__PURE__ */N(C,{style:g.vetHeader,children:[
367
- /* @__PURE__ */U(Text,{tier:"control",style:g.vetSender,children:T}),I!==null?/* @__PURE__ */U(Text,{tier:"compact",style:g.vetTime,children:I}):null]}):null,
368
- /* @__PURE__ */N(C,{style:[v?g.bubbleUser:k?g.bubbleVet:g.bubbleAssistant,v&&E?g.bubbleUserCards:null,e.pending?g.bubblePending:null],children:[v&&o.length>0?/* @__PURE__ */U(SentImages,{images:o,onPreview:e=>a({uri:e.uri,label:e.filename})}):null,
369
- /* @__PURE__ */U(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:w?Ix(y,{bold:g.bubbleBold,italic:g.bubbleItalic,code:g.bubbleCode},x):e.text})]})]})}),w&&!t?/* @__PURE__ */U(CitationCards,{citations:e.citations,onOpenUrl:u}):null,P&&!(v&&f!==null)?/* @__PURE__ */U(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,note:i}):null]})}var zR=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(e){if(e.isBootstrapping===true||e.isLoadingHistory===true||e.isStreaming===true||e.status==="error"||e.stopped===true)return false;let t=e.messages[e.messages.length-1];return t===void 0||t.role!=="assistant"||t.pending===true||t.checkin!==void 0||t.text.trim().length===0?false:!(typeof t.urgencyLevel=="string"&&zR.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function PR(){let{runtime:e}=vd(),t=e.entitlements??null,r=s(e=>t===null?()=>{}:t.subscribe(e),[t]),n=t===null?NO_SNAPSHOT2:t.getSnapshot,l=i(r,n,n);return a(()=>l!==null&&decideCapability("texting",l.decisions,{isPending:l.isPending}).enabled,[l])}var OR=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function ER(e,t,r=false){let[n,i]=l(null);if(!e)return OR;let o=/* @__PURE__ */U(AskRunner,{ready:textingAskThreadReady(t),onAsk:i,entry:r}),a=r&&n!==null&&n.canOpen?{label:V.textingAskLines(n).accept,onOpen:n.open}:null;if(n===null||n.stage==="hidden"||n.stage==="dismissed")return{runner:o,line:null,entry:null,stage:null,headerEntry:a};let s=V.textingAskLines(n),u=/* @__PURE__ */U(AskLine,{stage:n.stage,text:n.stage==="verified"?s.verified:s.line,accept:s.accept,dismiss:s.dismiss,onAccept:n.accept,onDismiss:n.dismiss}),c=n.stage==="enrolling"?/* @__PURE__ */U(V.ChatTextingAskComposer,{ask:n}):null;return{runner:o,line:u,entry:c,stage:n.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:t,entry:r}){let{userRef:l}=vd(),i=PR(),o=l!==null&&i;return n(()=>{o||t(null)},[o,t]),o?/* @__PURE__ */U(V.ChatTextingAskController,{enabled:true,ready:e,onAsk:t,entry:r}):null}function AskLine({stage:e,text:t,accept:r,dismiss:n,onAccept:l,onDismiss:i}){let{theme:o,styles:a}=Nm(),s=!o.meta.hidePoweredBy,u=s?$f.assistantName:$f.senderAssistant,c=o.meta.assistantAvatarUrl!==null?/* @__PURE__ */U(AssistantSender,{avatarUrl:o.meta.assistantAvatarUrl,named:s,styles:a}):s?/* @__PURE__ */U(Text,{tier:"control",style:a.assistantName,children:$f.assistantName}):null;/* @__PURE__ */
370
- return N(C,{style:[a.rowBlock,a.rowBlockAssistant],testID:`everfur-texting-ask-${e}`,children:[
371
- /* @__PURE__ */U(C,{style:[a.row,a.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${u}: ${t}`,children:/* @__PURE__ */N(C,{style:a.bubble,children:[c,
372
- /* @__PURE__ */U(C,{style:a.bubbleAssistant,children:/* @__PURE__ */U(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */U(C,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */U(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */U(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function jR(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),t=globalThis;return t[e]??(t[e]=createContext(null))}var FR=/* @__PURE__ */jR();function AR(e){return typeof e=="object"&&e!==null&&e.ok===true}function DR(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:ct(t.error)}function MR(e){let t=o(FR),r=t?.onMessageSent,n=t?.onFreeCapReached,l=s((...t)=>{let l=e(...t);return Promise.resolve(l).then(e=>{try{if(AR(e)){r?.();return}let t=n===void 0?null:DR(e);t!==null&&n?.(t)}catch{}},()=>{}),l},[e,r,n]);return r===void 0&&n===void 0?e:l}function EverfurChatCore(e){let{style:t,renderPending:r}=e;/* @__PURE__ */
373
- return U(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */U(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */U(ChatBody,{...e})})})}function LR(){try{return vd()}catch{return null}}function BR(e){return Kh({...e.presentation,chatComposerMic:e.presentation?.chatComposerMic??(e.dictation===void 0?void 0:e.dictation!==false),chatComposerUpload:e.presentation?.chatComposerUpload??(e.attachments===void 0?void 0:true)})}function ChatBody(e){let t=LR();return t===null?/* @__PURE__ */U(ChatBodyAlone,{...e}):/* @__PURE__ */U(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let t=BR(e),r=JSON.stringify(t),n=e.petRef??null,l=a(()=>({presentation:resolvePresentation({server:null,locked:null,client:t}),isLocked:()=>false,planPage:null,planPetRef:n,inProvider:false,telemetry:null}),[r,n]);/* @__PURE__ */
374
- return U(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=Gh(BR(r)),l=rf("healthPlan"),i=n.chatTopCard==="focus"&&r.topCard===void 0&&l,o=r.petRef??e??null,s=useHealthPlanPage({petRef:o,enabled:i}),u=i&&s.phase==="ready"?s.page:null,c=a(()=>({presentation:n,isLocked:isLocked,planPage:u,planPetRef:o,inProvider:true,telemetry:t}),[n,isLocked,u,o,t]);/* @__PURE__ */
375
- return U(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:c,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:p,attachments:b,pet:m,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:w,initialAskKey:S,composerSeed:x,lifecycle:_,refreshIntervalMs:T,refreshesBlankThread:I,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:L,historySheet:H,historyBar:W,starterPrompts:V,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:J}){let{presentation:X,isLocked:isLocked,planPage:Z,planPetRef:ee}=e,{theme:te,styles:re}=Nm(),ne=ew()??(X.chatAnswerStyle==="cards"?KC:null),le=a(()=>ne===null?null:ne(te),[ne,te]),ie=useHostPoweredBy(),oe=Ig(),ae=a(()=>ap(t,r),[t,r]),se=useEverfurChat(ae),ue=MR(se.send),ce=a(()=>ue===se.send?se:{...se,send:ue},[se,ue]),de=Yh(ce),fe=LS(),he=eg(ce),pe=B(),ge=Xh(ce,"web"),be=a(()=>h===void 0?void 0:()=>{Fh(h,"emergency")},[h]),me=a(()=>O===void 0&&E===void 0&&j===void 0?void 0:{returnTo:O,usState:E,prefer:j},[O,E,j]),ye=Fk(fe.pets,ce.petRef),ve=a(()=>og(ce.messages,ye?.name??null),[ce.messages,ye?.name]),ke=sg(ve);HS(ce),Vg(ke.showBanner,oe);let we=LR(),Ce=Np(k,we);Wp(ce.openCheckin,v??Ce,{petRef:ce.petRef,pinned:t!==void 0,ready:!ce.isBootstrapping,selectPet:e=>{fe.setActivePet(e),Fh(d,e)}}),Cp(ce.askEverfur,ce.isBootstrapping,w,S);let Se=a(()=>wp(x),[x]),xe=a(()=>wp(w),[w]),_e=a(()=>J!==void 0&&xe!==null?{card:J,prompt:xe}:void 0,[J,xe]),Re=a(()=>_===void 0?createAppStateLifecycle():_??void 0,[_]);Ep(Re,{conversationId:ce.conversationId===null?null:String(ce.conversationId),isTurnInFlight:ce.isStreaming,refreshesBlankThread:I===true||z===true,refresh:ce.refreshActiveThread===void 0?void 0:()=>ce.refreshActiveThread?.(Tp(z===true,Ip(Re,tb)))??Promise.resolve()},{intervalMs:T===void 0?3e4:T,isVisibleFallback:tb}),zp({isStreaming:ce.isStreaming,status:ce.status,conversationId:ce.conversationId===null?null:String(ce.conversationId),unreadCount:ce.unreadCount,markRead:ce.markRead},()=>Ip(Re,tb));let Te=ce.pendingCheckin??null,Ie=Te===null?null:/* @__PURE__ */U(C,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */U(CheckinCard,{message:Te.message,checkin:Te.checkin,onAnswer:ce.petRef?ce.answerCheckin:null,petRef:ce.petRef,onFindVet:be,vet:me,onOpen:()=>{ce.resumeConversation(Te.conversationId)}})}),ze=(ce.hasUnreadThreads??false)||he.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(ce.unreadCount??0)>0,Pe=bp(ce.messages),[Oe,Ee]=l(null),je=s(()=>Ee(null),[]),[Fe,Ae]=l(null),[De,Me]=l(null),Le=u(null);n(()=>()=>{Le.current&&clearTimeout(Le.current)},[]);let Be=s((e,t)=>{Me({responseId:String(e),kind:t}),Le.current&&clearTimeout(Le.current),Le.current=t==="thanks"?setTimeout(()=>{Me(null),Le.current=null},Yb):null},[]),He=s((e,t)=>{let r=e.responseId;if(r===void 0)return;let n=ce.sentimentByMessage[String(r)];Me(e=>e?.responseId===String(r)?null:e),ce.feedback(r,t).then(e=>{e.ok||Be(r,"failed")}),t==="down"&&n!=="down"&&Ae(r)},[ce,Be]),Ue=s(async(e,t)=>Fe===null||!(e==null&&t===null?{ok:true}:await ce.feedback(Fe,"down",e??"other",t)).ok?false:(Ae(null),Be(Fe,"thanks"),true),[ce,Fe,Be]),Ne=s(()=>Ae(null),[]),$e=s(e=>{ce.send(e)},[ce.send]),We=a(()=>F===void 0?void 0:e=>{Fh(F,e,"citation")},[F]),Ve=g.OS==="ios"?"padding":void 0,qe=nS(A,Ve!==void 0),Ge=qe.topInWindow===null?pe.top:Math.max(0,pe.top-qe.topInWindow),Ke=iS(),Ye=a(()=>M===void 0?void 0:()=>{Fh(M,ee)},[M,ee]),Qe=a(()=>D===void 0?healthPlanTopCard(Z,{onOpenPlan:Ye}):void 0,[D,Z,Ye]),Je=X.chatTopCard==="focus"?D??Qe:void 0,[Xe,Ze]=l(true),et=s(e=>{ce.send(e)},[ce.send]),tt=a(()=>cp(Q,X,isLocked("chatFollowUpCount")),[Q,X,isLocked]),rt=X.chatAnswerStyle==="cards",nt=a(()=>rt&&ce.messages.length===0?NR(ce.suggestedPrompts):void 0,[rt,ce.messages.length,ce.suggestedPrompts]),lt=X.chatHistoryStyle==="sheet",it=ce.messages.length===0,ot=Je!==void 0?/* @__PURE__ */U(TopCardPill,{card:Je,open:Xe,onOpenChange:Ze}):null,at=W??(G?void 0:$R),st=at!==void 0?/* @__PURE__ */U(HistoryBar,{bar:at,history:he,empty:it,unread:ze,extra:ot}):null,ut=X.chatHistoryBar==="scroll"&&(de==="empty"||de==="populated"),ct=Je===void 0?null:/* @__PURE__ */N($,{children:[
376
- /* @__PURE__ */U(TopCard,{card:Je,open:Xe,onOpenChange:Ze,ask:et}),at===void 0?ot:null]}),dt=at!==void 0,ft=he.load,ht=he.open;n(()=>{dt&&!ht&&ft()},[dt,ht,ce.conversationId,ft]);let pt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:Se,draftStore:P,onStage:Pe.stage,onPreview:Ee,petName:ye?.name??null,petBreed:ye?.breed??null,compact:X.chatComposerStyle==="compact",petPlaceholder:X.chatComposerPlaceholder==="pet_name",dimEmptySend:X.chatSendButton==="dim_when_empty",mood:WR(de,ke.source?.level??null),dictation:X.chatComposerMic,telemetry:e.telemetry},gt=ER(X.chatTextingAsk&&e.inProvider,ce,K),bt=b!==void 0&&X.chatComposerUpload,mt=!X.chatGeneralBanner&&ke.source?.level==="general";
353
+ return W(E,{contentContainerStyle:f.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:ER,nestedScrollEnabled:true,accessibilityLabel:Vf.empty,children:[i??null,a,o??null,p,
354
+ /* @__PURE__ */$(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:r}){let{styles:n}=Gm();return e.length===0?null:/* @__PURE__ */W(x,{style:n.followUps,children:[
355
+ /* @__PURE__ */$(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??Vf.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */$(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:l}=Gm(),i=jg(),o=Ng(i.followUpInMs,{delayMs:Og(i,t)});/* @__PURE__ */
356
+ return $(M.View,{style:o,children:/* @__PURE__ */W(PressScale,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[l.followUpSlot,t>0?l.followUpSlotRuled:null],style:l.followUpRow,children:[
357
+ /* @__PURE__ */$(Text,{tier:"control",style:l.followUpText,children:e}),
358
+ /* @__PURE__ */$(PlusGlyph,{size:jR,color:n.slots.chip?.textColor??n.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:r}){let{styles:n}=Gm(),l=pp(e)?Lh(r):void 0,i=Xh(e);/* @__PURE__ */
359
+ return W(x,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[i!==null?/* @__PURE__ */$(Text,{style:n.errorText,testID:"everfur-chat-cap-reached",children:i.reached}):null,
360
+ /* @__PURE__ */$(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */$(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */$(z,{onPress:l,accessibilityRole:"button",accessibilityLabel:Vf.addPet,style:n.retryButton,children:/* @__PURE__ */$(Text,{tier:"control",style:n.retryLabel,children:Vf.addPet})}):null,e.retryable?/* @__PURE__ */$(z,{onPress:t,accessibilityRole:"button",accessibilityLabel:Vf.retry,style:n.retryButton,children:/* @__PURE__ */$(Text,{tier:"control",style:n.retryLabel,children:Vf.retry})}):null]})}function PopulatedState({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:l,onCopy:i,sentimentByMessage:o,onSentiment:s,feedbackNote:u,imagesByMessage:c,onPreview:d,notice:f,reconnecting:h,onRetry:p,onStartNew:g,petRef:b,onFindVet:m,vet:y,onOpenUrl:v,petName:k,actions:w,answerCards:C,threadTop:S,pendingCheckin:_,threadAside:R,threadAsideKey:T,followUpLabel:I,openingCard:P,earlier:O}){let{styles:j}=Gm(),F=jg();Qg(e.length,F);let A=a(()=>QS(YS(e)),[e]),D=tp(e,n),M=e[e.length-1],L=R??null,B=TR(e,n,L===null?null:T??"shown"),H=Vg(e),U=e[0],N=P!==void 0&&U!==void 0&&U.role==="user"&&U.text.trim()===P.prompt?U.id:null;/* @__PURE__ */
361
+ return W(E,{ref:B.ref,style:j.list,contentContainerStyle:C!==null?j.listContentCards:j.listContent,accessibilityLabel:Vf.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:ER,nestedScrollEnabled:true,onLayout:B.onLayout,onContentSizeChange:B.onContentSizeChange,onScroll:B.onScroll,scrollEventThrottle:OR,onScrollBeginDrag:B.onScrollBeginDrag,onScrollEndDrag:B.onScrollEnd,onMomentumScrollEnd:B.onScrollEnd,children:[S??null,_,O!==null?/* @__PURE__ */$(z,{onPress:()=>{O.load()},disabled:O.loading,accessibilityRole:"button",accessibilityLabel:O.loading?Gp.loadingEarlier:Gp.earlier,accessibilityState:{disabled:O.loading,busy:O.loading},hitSlop:vm,style:j.earlierButton,children:/* @__PURE__ */$(Text,{tier:"compact",style:j.earlierLabel,children:O.loading?Gp.loadingEarlier:Gp.earlier})}):null,e.map(t=>t.id===N&&P!==void 0?/* @__PURE__ */$(OpeningCard,{card:P.card,onLayout:B.rowLayout(t.id)},t.id):t.checkin&&A.has(t.id)?/* @__PURE__ */$(CheckinCard,{message:t,checkin:t.checkin,onAnswer:l,petRef:b,onFindVet:m,vet:y,onLayout:B.rowLayout(t.id)},t.id):/* @__PURE__ */$(MessageRow,{onLayout:B.rowLayout(t.id),message:t,revealing:n&&t===M&&t.role==="assistant",onCopy:i,sentiment:t.responseId===void 0?null:o[String(t.responseId)]??null,onSentiment:s,note:t.responseId!==void 0&&u?.responseId===String(t.responseId)?u.kind:null,images:c[t.id]??zR,onPreview:d,onOpenUrl:v,entering:H(t.id),answerCards:C,messages:e},t.id)),h?/* @__PURE__ */$(Text,{tier:"compact",style:j.reconnectingCaption,accessibilityRole:"text",children:Vf.reconnecting}):null,D?/* @__PURE__ */$(TypingIndicator,{petName:k,inline:C!==null}):null,f!==null?/* @__PURE__ */$(TurnNoticeCard,{notice:f,onRetry:p,onStartNew:g}):null,C!==null?/* @__PURE__ */$(CardsFollowUps,{prompts:t,onSelectPrompt:r,label:I,actions:w,options:C}):/* @__PURE__ */$(FollowUps,{prompts:t,onSelectPrompt:r,label:I}),L!==null?/* @__PURE__ */$(x,{onLayout:B.asideLayout,children:L}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=Gm(),l=e.tone==="error";/* @__PURE__ */
362
+ return W(x,{style:[n.turnNotice,l?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
363
+ /* @__PURE__ */$(Text,{tier:"control",style:[n.turnNoticeTitle,l?n.turnNoticeTitleError:null],children:e.title}),
364
+ /* @__PURE__ */$(Text,{tier:"compact",style:n.turnNoticeBody,children:e.body}),e.guidance!==void 0?/* @__PURE__ */$(Text,{tier:"compact",style:n.turnNoticeBody,testID:"everfur-chat-cap-guidance",children:e.guidance}):null,
365
+ /* @__PURE__ */$(z,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:vm,style:n.turnNoticeAction,children:/* @__PURE__ */$(Text,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}var zR=/* @__PURE__ */Object.freeze([]),PR=/* @__PURE__ */Object.freeze([]),OR=16,ER=m.OS==="ios"?"interactive":"on-drag",jR=18;function MessageRow({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:l,note:i,images:o,onPreview:a,onOpenUrl:s,onLayout:c,entering:d,answerCards:f,messages:h}){let{theme:p,styles:g}=Gm(),b=jg(),m=Wg(d,b),y=Gg(e.text,t,b),v=e.role==="user",k=e.role==="vet",w=e.role==="assistant",C=Cg(),S=w&&!t?C:void 0,_=S!==void 0&&Ex(e.text,S),R=w&&!p.meta.hidePoweredBy,T=v?Vf.senderUser:k?sp(e):R?Vf.assistantName:Vf.senderAssistant,I=k?tx(e.createdAt):null,z=u(t=>l(e,t),[l,e]),P=e.pending!==true,O=w&&p.meta.assistantAvatarUrl!==null?/* @__PURE__ */$(AssistantSender,{avatarUrl:p.meta.assistantAvatarUrl,named:R,styles:g}):R?f!==null?/* @__PURE__ */$(CardsByline,{label:Vf.assistantName}):/* @__PURE__ */$(Text,{tier:"control",style:g.assistantName,children:Vf.assistantName}):null,E=f!==null;return w&&f!==null?/* @__PURE__ */$(M.View,{style:[g.rowBlock,m],onLayout:c,accessibilityLabel:`${T}: ${e.text}`,children:/* @__PURE__ */$(CardsAnswer,{message:e,text:y,streaming:t,messages:h,options:f,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,sender:O,onOpenUrl:s,footer:t=>/* @__PURE__ */$(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:t&&e.responseId!==void 0?z:void 0,note:i})})}):/* @__PURE__ */W(x,{style:[g.rowBlock,v?g.rowBlockUser:g.rowBlockAssistant],onLayout:c,children:[
366
+ /* @__PURE__ */$(x,{style:[g.row,v?g.rowUser:g.rowAssistant],accessible:!_,accessibilityRole:_?void 0:"text",accessibilityLabel:_?void 0:`${T}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:/* @__PURE__ */W(M.View,{style:[g.bubble,E?g.bubbleCards:null,v?g.bubbleSideUser:null,m],children:[O,k?/* @__PURE__ */W(x,{style:g.vetHeader,children:[
367
+ /* @__PURE__ */$(Text,{tier:"control",style:g.vetSender,children:T}),I!==null?/* @__PURE__ */$(Text,{tier:"compact",style:g.vetTime,children:I}):null]}):null,
368
+ /* @__PURE__ */W(x,{style:[v?g.bubbleUser:k?g.bubbleVet:g.bubbleAssistant,v&&E?g.bubbleUserCards:null,e.pending?g.bubblePending:null],children:[v&&o.length>0?/* @__PURE__ */$(SentImages,{images:o,onPreview:e=>a({uri:e.uri,label:e.filename})}):null,
369
+ /* @__PURE__ */$(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:w?jx(y,{bold:g.bubbleBold,italic:g.bubbleItalic,code:g.bubbleCode},S):e.text})]})]})}),w&&!t?/* @__PURE__ */$(ServerCardsSlot,{message:e}):null,w&&!t?/* @__PURE__ */$(CitationCards,{citations:e.citations,onOpenUrl:s}):null,P&&!(v&&f!==null)?/* @__PURE__ */$(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,note:i}):null]})}var FR=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(e){if(e.isBootstrapping===true||e.isLoadingHistory===true||e.isStreaming===true||e.status==="error"||e.stopped===true)return false;let t=e.messages[e.messages.length-1];return t===void 0||t.role!=="assistant"||t.pending===true||t.checkin!==void 0||t.text.trim().length===0?false:!(typeof t.urgencyLevel=="string"&&FR.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function AR(){let{runtime:e}=wd(),t=e.entitlements??null,r=u(e=>t===null?()=>{}:t.subscribe(e),[t]),n=t===null?NO_SNAPSHOT2:t.getSnapshot,l=i(r,n,n);return a(()=>l!==null&&decideCapability("texting",l.decisions,{isPending:l.isPending}).enabled,[l])}var DR=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function MR(e,t,r=false){let[n,i]=l(null);if(!e)return DR;let o=/* @__PURE__ */$(AskRunner,{ready:textingAskThreadReady(t),onAsk:i,entry:r}),a=r&&n!==null&&n.canOpen?{label:G.textingAskLines(n).accept,onOpen:n.open}:null;if(n===null||n.stage==="hidden"||n.stage==="dismissed")return{runner:o,line:null,entry:null,stage:null,headerEntry:a};let s=G.textingAskLines(n),u=/* @__PURE__ */$(AskLine,{stage:n.stage,text:n.stage==="verified"?s.verified:s.line,accept:s.accept,dismiss:s.dismiss,onAccept:n.accept,onDismiss:n.dismiss}),c=n.stage==="enrolling"?/* @__PURE__ */$(G.ChatTextingAskComposer,{ask:n}):null;return{runner:o,line:u,entry:c,stage:n.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:t,entry:r}){let{userRef:l}=wd(),i=AR(),o=l!==null&&i;return n(()=>{o||t(null)},[o,t]),o?/* @__PURE__ */$(G.ChatTextingAskController,{enabled:true,ready:e,onAsk:t,entry:r}):null}function AskLine({stage:e,text:t,accept:r,dismiss:n,onAccept:l,onDismiss:i}){let{theme:o,styles:a}=Gm(),s=!o.meta.hidePoweredBy,u=s?Vf.assistantName:Vf.senderAssistant,c=o.meta.assistantAvatarUrl!==null?/* @__PURE__ */$(AssistantSender,{avatarUrl:o.meta.assistantAvatarUrl,named:s,styles:a}):s?/* @__PURE__ */$(Text,{tier:"control",style:a.assistantName,children:Vf.assistantName}):null;/* @__PURE__ */
370
+ return W(x,{style:[a.rowBlock,a.rowBlockAssistant],testID:`everfur-texting-ask-${e}`,children:[
371
+ /* @__PURE__ */$(x,{style:[a.row,a.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${u}: ${t}`,children:/* @__PURE__ */W(x,{style:a.bubble,children:[c,
372
+ /* @__PURE__ */$(x,{style:a.bubbleAssistant,children:/* @__PURE__ */$(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */$(x,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */$(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */$(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function LR(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),t=globalThis;return t[e]??(t[e]=createContext(null))}var BR=/* @__PURE__ */LR();function HR(e){return typeof e=="object"&&e!==null&&e.ok===true}function UR(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:ft(t.error)}function NR(e){let t=o(BR),r=t?.onMessageSent,n=t?.onFreeCapReached,l=u((...t)=>{let l=e(...t);return Promise.resolve(l).then(e=>{try{if(HR(e)){r?.();return}let t=n===void 0?null:UR(e);t!==null&&n?.(t)}catch{}},()=>{}),l},[e,r,n]);return r===void 0&&n===void 0?e:l}function EverfurChatCore(e){let{style:t,renderPending:r}=e;/* @__PURE__ */
373
+ return $(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */$(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */$(ChatBody,{...e})})})}function $R(){try{return wd()}catch{return null}}function WR(e){return Qh({...e.presentation,chatComposerMic:e.presentation?.chatComposerMic??(e.dictation===void 0?void 0:e.dictation!==false),chatComposerUpload:e.presentation?.chatComposerUpload??(e.attachments===void 0?void 0:true)})}function ChatBody(e){let t=$R();return t===null?/* @__PURE__ */$(ChatBodyAlone,{...e}):/* @__PURE__ */$(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let t=WR(e),r=JSON.stringify(t),n=e.petRef??null,l=a(()=>({presentation:resolvePresentation({server:null,locked:null,client:t}),isLocked:()=>false,planPage:null,planPetRef:n,inProvider:false,telemetry:null}),[r,n]);/* @__PURE__ */
374
+ return $(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=Yh(WR(r)),l=lf("healthPlan"),i=n.chatTopCard==="focus"&&r.topCard===void 0&&l,o=r.petRef??e??null,s=useHealthPlanPage({petRef:o,enabled:i}),u=i&&s.phase==="ready"?s.page:null,c=a(()=>({presentation:n,isLocked:isLocked,planPage:u,planPetRef:o,inProvider:true,telemetry:t}),[n,isLocked,u,o,t]);/* @__PURE__ */
375
+ return $(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:s,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:p,attachments:g,pet:b,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:w,initialAskKey:C,composerSeed:S,lifecycle:_,refreshIntervalMs:R,refreshesBlankThread:T,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:L,historySheet:B,historyBar:H,starterPrompts:N,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:J}){let{presentation:X,isLocked:isLocked,planPage:Z,planPetRef:ee}=e,{theme:te,styles:re}=Gm(),ne=iw()??(X.chatAnswerStyle==="cards"?ZC:null),le=a(()=>ne===null?null:ne(te),[ne,te]),ie=useHostPoweredBy(),oe=jg(),ae=a(()=>up(t,r),[t,r]),se=useEverfurChat(ae),ue=NR(se.send),ce=a(()=>ue===se.send?se:{...se,send:ue},[se,ue]),de=Jh(ce),fe=$S(),he=rg(ce),pe=U(),ge=ep(ce,"web"),be=a(()=>h===void 0?void 0:()=>{Dh(h,"emergency")},[h]),me=a(()=>O===void 0&&E===void 0&&j===void 0?void 0:{returnTo:O,usState:E,prefer:j},[O,E,j]),ye=Bk(fe.pets,ce.petRef),[ve,ke]=l(null),we=a(()=>{let e=sg(ce.messages,ye?.name??null);return e?.level==="schedule_soon"&&e.messageId===ve?null:e},[ce.messages,ye?.name,ve]),Ce=cg(we);VS(ce),Qg(Ce.showBanner,oe);let Se=$R(),xe=Wp(k,Se);qp(ce.openCheckin,v??xe,{petRef:ce.petRef,pinned:t!==void 0,ready:!ce.isBootstrapping,selectPet:e=>{fe.setActivePet(e),Dh(d,e)}}),xp(ce.askEverfur,ce.isBootstrapping,w,C);let _e=a(()=>Sp(S),[S]),Re=a(()=>Sp(w),[w]),Te=a(()=>J!==void 0&&Re!==null?{card:J,prompt:Re}:void 0,[J,Re]),Ie=a(()=>_===void 0?createAppStateLifecycle():_??void 0,[_]);Fp(Ie,{conversationId:ce.conversationId===null?null:String(ce.conversationId),isTurnInFlight:ce.isStreaming,refreshesBlankThread:T===true||z===true,refresh:ce.refreshActiveThread===void 0?void 0:()=>ce.refreshActiveThread?.(zp(z===true,Pp(Ie,ob)))??Promise.resolve()},{intervalMs:R===void 0?3e4:R,isVisibleFallback:ob}),Op({isStreaming:ce.isStreaming,status:ce.status,conversationId:ce.conversationId===null?null:String(ce.conversationId),unreadCount:ce.unreadCount,markRead:ce.markRead},()=>Pp(Ie,ob));let ze=ce.pendingCheckin??null,Pe=ze===null?null:/* @__PURE__ */$(x,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */$(CheckinCard,{message:ze.message,checkin:ze.checkin,onAnswer:ce.petRef?ce.answerCheckin:null,petRef:ce.petRef,onFindVet:be,vet:me,onOpen:()=>{ce.resumeConversation(ze.conversationId)}})}),Oe=(ce.hasUnreadThreads??false)||he.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(ce.unreadCount??0)>0,Ee=yp(ce.messages),[je,Fe]=l(null),Ae=u(()=>Fe(null),[]),[De,Me]=l(null),[Le,Be]=l(null),He=c(null);n(()=>()=>{He.current&&clearTimeout(He.current)},[]);let Ue=u((e,t)=>{Be({responseId:String(e),kind:t}),He.current&&clearTimeout(He.current),He.current=t==="thanks"?setTimeout(()=>{Be(null),He.current=null},em):null},[]),Ne=u((e,t)=>{let r=e.responseId;if(r===void 0)return;let n=ce.sentimentByMessage[String(r)];Be(e=>e?.responseId===String(r)?null:e),ce.feedback(r,t).then(e=>{e.ok||Ue(r,"failed")}),t==="down"&&n!=="down"&&Me(r)},[ce,Ue]),$e=u(async(e,t)=>De===null||!(e==null&&t===null?{ok:true}:await ce.feedback(De,"down",e??"other",t)).ok?false:(Me(null),Ue(De,"thanks"),true),[ce,De,Ue]),We=u(()=>Me(null),[]),Ve=u(e=>{ce.send(e)},[ce.send]),qe=a(()=>F===void 0?void 0:e=>{Dh(F,e,"citation")},[F]),Ge=m.OS==="ios"?"padding":void 0,Ke=sS(A,Ge!==void 0),Ye=Ke.topInWindow===null?pe.top:Math.max(0,pe.top-Ke.topInWindow),Qe=cS(),Je=a(()=>M===void 0?void 0:()=>{Dh(M,ee)},[M,ee]),Xe=a(()=>({petRef:ce.petRef,vet:me,cover:ke}),[ce.petRef,me]),Ze=a(()=>D===void 0?healthPlanTopCard(Z,{onOpenPlan:Je}):void 0,[D,Z,Je]),et=X.chatTopCard==="focus"?D??Ze:void 0,[tt,rt]=l(true),nt=u(e=>{ce.send(e)},[ce.send]),lt=a(()=>fp(Q,X,isLocked("chatFollowUpCount")),[Q,X,isLocked]),it=X.chatAnswerStyle==="cards",ot=a(()=>it&&ce.messages.length===0?GR(ce.suggestedPrompts):void 0,[it,ce.messages.length,ce.suggestedPrompts]),at=X.chatHistoryStyle==="sheet",st=ce.messages.length===0,ut=et!==void 0?/* @__PURE__ */$(TopCardPill,{card:et,open:tt,onOpenChange:rt}):null,ct=H??(G?void 0:KR),dt=ct!==void 0?/* @__PURE__ */$(HistoryBar,{bar:ct,history:he,empty:st,unread:Oe,extra:ut}):null,ft=X.chatHistoryBar==="scroll"&&(de==="empty"||de==="populated"),ht=et===void 0?null:/* @__PURE__ */W(V,{children:[
376
+ /* @__PURE__ */$(TopCard,{card:et,open:tt,onOpenChange:rt,ask:nt}),ct===void 0?ut:null]}),pt=ct!==void 0,gt=he.load,bt=he.open;n(()=>{pt&&!bt&&gt()},[pt,bt,ce.conversationId,gt]);let mt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:_e,draftStore:P,onStage:Ee.stage,onPreview:Fe,petName:ye?.name??null,petBreed:ye?.breed??null,compact:X.chatComposerStyle==="compact",petPlaceholder:X.chatComposerPlaceholder==="pet_name",dimEmptySend:X.chatSendButton==="dim_when_empty",mood:YR(de,Ce.source?.level??null),dictation:X.chatComposerMic,telemetry:e.telemetry},yt=MR(X.chatTextingAsk&&e.inProvider,ce,K),vt=g!==void 0&&X.chatComposerUpload,kt=!X.chatGeneralBanner&&Ce.source?.level==="general";
377
377
  /* @__PURE__ */
378
- return U(Zk.Provider,{value:le,children:/* @__PURE__ */N(R,{style:[re.container,{paddingTop:Ge},i],behavior:Ve,...qe.avoidingProps,children:[
379
- /* @__PURE__ */U(KeyboardOffsetProbe,{probeRef:qe.probeRef}),
380
- /* @__PURE__ */N(SdkTabletColumn,{children:[G?/* @__PURE__ */U(ChatHeader,{pets:fe,petRef:ce.petRef,historyUnread:ze,onOpenHistory:he.show,onNewChat:he.newConversation,onPetChange:d,onAddPet:y,vet:me,textingEntry:gt.headerEntry}):null,m!==void 0?/* @__PURE__ */U(PetSetupNotice,{petRef:t??null,pet:m,onRegistered:fe.refresh}):null,!G&&gt.headerEntry!==null?/* @__PURE__ */U(TextingEntryRow,{entry:gt.headerEntry,place:"thread"}):null,ut?null:st,mt?null:/* @__PURE__ */U(UrgencyBanner,{surface:ke,petRef:ce.petRef,renderVetAction:p,onFindVet:h,vet:me,compact:Ke}),
381
- /* @__PURE__ */U(C,{style:re.body,children:SR(de,ce,{notice:ge,vet:me,onCheckinFindVet:be,onSelectPrompt:$e,renderPending:o,shownPet:ye,onVetPrep:f,onCopy:c,onSentiment:He,feedbackNote:De,imagesByMessage:Pe.byMessage,onPreview:Ee,onAddPet:y,onOpenUrl:We,threadTop:ut?st:null,pendingCheckin:Ie,topCard:ct,starterPrompts:V??nt,emptyState:q,emptyCentered:X.chatAnswerStyle==="cards",followUpPolicy:tt,answerCards:X.chatAnswerStyle==="cards"?L??HR:null,threadAside:gt.line,threadAsideKey:gt.stage,renderEmptyHeader:Y,openingCard:_e})}),gt.runner,gt.entry!==null?/* @__PURE__ */U(C,{style:re.composerOuter,children:/* @__PURE__ */U(C,{style:re.askEntry,children:gt.entry})}):bt&&b!==void 0?/* @__PURE__ */U(ComposerWithAttachments,{...pt,attachments:b}):/* @__PURE__ */U(Composer,{...pt,attachments:null}),te.meta.hidePoweredBy||ie?null:/* @__PURE__ */U(Text,{tier:"compact",style:re.poweredBy,accessibilityRole:"text",accessibilityLabel:$f.poweredBy,children:$f.poweredBy})]}),lt?/* @__PURE__ */U(HistorySheet,{chat:ce,history:he,sheet:H}):/* @__PURE__ */U(HistoryDrawer,{chat:ce,history:he}),
382
- /* @__PURE__ */U(FeedbackReasons,{visible:Fe!==null,onSubmit:Ue,onSkip:Ne}),
383
- /* @__PURE__ */U(AttachmentImageLightbox,{uri:Oe?.uri??null,label:Oe?.label??"",onClose:je}),
384
- /* @__PURE__ */U(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Nm(),l=pp(e,t,r);return l.status!=="failed"||l.error===null?null:/* @__PURE__ */N(C,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[
385
- /* @__PURE__ */U(Text,{tier:"compact",style:n.setupNoticeText,children:l.error.displayMessage}),
386
- /* @__PURE__ */U(T,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:$f.retry,hitSlop:pm,children:/* @__PURE__ */U(Text,{tier:"control",style:n.setupNoticeAction,children:$f.retry})})]})}var HR=/* @__PURE__ */Object.freeze({}),UR=3;function NR(e){let t=[];for(let r of e){let e=r.trim();if(e.length>0&&!t.some(t=>t.label===e)&&t.push(/* @__PURE__ */Object.freeze({label:e})),t.length===UR)break}return t.length>0?/* @__PURE__ */Object.freeze(t):void 0}var $R=/* @__PURE__ */Object.freeze({chats:Vp.heading,newChat:Vp.newChat});function WR(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
387
- return U(gf.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */U(EverfurChatCore,{...e})})}var VR=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function qR(e,t){let{runtime:r,userRef:l,activePet:o,scopeEpoch:u}=vd(),c=r.unread??null,d=e===void 0?o:e,f=s(e=>c===null?NO_SUBSCRIPTION():c.subscribe(e),[c]),h=s(()=>c===null||l===null?VR:c.get(d),[c,l,d]),p=i(f,h,h),g=s(()=>c===null||l===null?Promise.resolve():c.refresh(d),[c,l,d]);return n(()=>{g()},[g,u]),Ep(t,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:g}),a(()=>({...p,refresh:g}),[p,g])}function useEverfurUnread(e={}){let{lifecycle:t}=e,r=a(()=>t===void 0?createAppStateLifecycle():t??void 0,[t]);return qR(e.petRef,r)}function useEverfurPetProfile(e){let{runtime:t,userRef:r,scopeEpoch:i}=vd(),o=a(()=>createPetsRepository(t.registry.services.authFor(r)),[t,r,i]),c=a(()=>({repository:o,petRef:e}),[o,e]),[d,f]=l({key:c,profile:null,loading:e!==null,error:null}),h=d.key===c?d:{profile:null,loading:e!==null,error:null},p=u(0),g=s(async()=>{let e=++p.current;if(c.petRef===null){f({key:c,profile:null,loading:false,error:null});return}f(e=>({key:c,profile:e.key===c?e.profile:null,loading:true,error:null}));let t=await c.repository.getPetProfile(c.petRef);e===p.current&&f(t.ok?{key:c,profile:t.value,loading:false,error:null}:{key:c,profile:null,loading:false,error:t.error})},[c]);return n(()=>(g(),()=>{p.current+=1}),[g]),a(()=>({profile:h.profile,loading:h.loading,error:h.error,refresh:g}),[h.profile,h.loading,h.error,g])}function EverfurThemeProvider(e){return r(EverfurThemeProviderCore,{clientTheme:e.clientTheme??null,seams:Zd,children:e.children})}export{bs as APPEARANCE_PRESETS,gs as APPEARANCE_PRESET_NAMES,ms as APPEARANCE_SIZE_RANGES,CapabilityGate,EverfurChat,Y as EverfurConfigError,EverfurProvider,EverfurThemeProvider,K as EverfurThrownError,Wo as PHONE_TEXT_SCALE_CAPS,wo as THEME_SLOT_KEYS,Co as THEME_SLOT_KEYS_BY_SLOT,ko as THEME_SLOT_NAMES,Uo as TYPE_ROLE_DEFAULTS,Ho as TYPE_ROLE_NAMES,canonicalPetSpecies,categoryFor,chatHandoffTokenFromUrl,conversationId,createAppStateLifecycle,createRnRecordsUploadTransport,expandAppearance,face,headingFace,isErr,isOk,isRetryableCode,petRef,previewTheme,registerEverfurDictation,textRole,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurTheme,useEverfurUnread,userFacingError,userRef};
378
+ return $(lw.Provider,{value:le,children:/* @__PURE__ */W(I,{style:[re.container,{paddingTop:Ye},i],behavior:Ge,...Ke.avoidingProps,children:[
379
+ /* @__PURE__ */$(KeyboardOffsetProbe,{probeRef:Ke.probeRef}),
380
+ /* @__PURE__ */W(SdkTabletColumn,{children:[G?/* @__PURE__ */$(ChatHeader,{pets:fe,petRef:ce.petRef,historyUnread:Oe,onOpenHistory:he.show,onNewChat:he.newConversation,onPetChange:d,onAddPet:y,vet:me,textingEntry:yt.headerEntry}):null,b!==void 0?/* @__PURE__ */$(PetSetupNotice,{petRef:t??null,pet:b,onRegistered:fe.refresh}):null,!G&&yt.headerEntry!==null?/* @__PURE__ */$(TextingEntryRow,{entry:yt.headerEntry,place:"thread"}):null,ft?null:dt,kt?null:/* @__PURE__ */$(UrgencyBanner,{surface:Ce,petRef:ce.petRef,renderVetAction:p,onFindVet:h,vet:me,compact:Qe}),
381
+ /* @__PURE__ */$(x,{style:re.body,children:/* @__PURE__ */$(hg.Provider,{value:Xe,children:IR(de,ce,{notice:ge,vet:me,onCheckinFindVet:be,onSelectPrompt:Ve,renderPending:o,shownPet:ye,onVetPrep:f,onCopy:s,onSentiment:Ne,feedbackNote:Le,imagesByMessage:Ee.byMessage,onPreview:Fe,onAddPet:y,onOpenUrl:qe,threadTop:ft?dt:null,pendingCheckin:Pe,topCard:ht,starterPrompts:N??ot,emptyState:q,emptyCentered:X.chatAnswerStyle==="cards",followUpPolicy:lt,answerCards:X.chatAnswerStyle==="cards"?L??VR:null,threadAside:yt.line,threadAsideKey:yt.stage,renderEmptyHeader:Y,openingCard:Te})})}),yt.runner,yt.entry!==null?/* @__PURE__ */$(x,{style:re.composerOuter,children:/* @__PURE__ */$(x,{style:re.askEntry,children:yt.entry})}):vt&&g!==void 0?/* @__PURE__ */$(ComposerWithAttachments,{...mt,attachments:g}):/* @__PURE__ */$(Composer,{...mt,attachments:null}),te.meta.hidePoweredBy||ie?null:/* @__PURE__ */$(Text,{tier:"compact",style:re.poweredBy,accessibilityRole:"text",accessibilityLabel:Vf.poweredBy,children:Vf.poweredBy})]}),at?/* @__PURE__ */$(HistorySheet,{chat:ce,history:he,sheet:B}):/* @__PURE__ */$(HistoryDrawer,{chat:ce,history:he}),
382
+ /* @__PURE__ */$(FeedbackReasons,{visible:De!==null,onSubmit:$e,onSkip:We}),
383
+ /* @__PURE__ */$(AttachmentImageLightbox,{uri:je?.uri??null,label:je?.label??"",onClose:Ae}),
384
+ /* @__PURE__ */$(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=Gm(),l=bp(e,t,r);return l.status!=="failed"||l.error===null?null:/* @__PURE__ */W(x,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[
385
+ /* @__PURE__ */$(Text,{tier:"compact",style:n.setupNoticeText,children:l.error.displayMessage}),
386
+ /* @__PURE__ */$(z,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:Vf.retry,hitSlop:vm,children:/* @__PURE__ */$(Text,{tier:"control",style:n.setupNoticeAction,children:Vf.retry})})]})}var VR=/* @__PURE__ */Object.freeze({}),qR=3;function GR(e){let t=[];for(let r of e){let e=r.trim();if(e.length>0&&!t.some(t=>t.label===e)&&t.push(/* @__PURE__ */Object.freeze({label:e})),t.length===qR)break}return t.length>0?/* @__PURE__ */Object.freeze(t):void 0}var KR=/* @__PURE__ */Object.freeze({chats:Gp.heading,newChat:Gp.newChat});function YR(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
387
+ return $(mf.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */$(EverfurChatCore,{...e})})}var QR=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function JR(e,t){let{runtime:r,userRef:l,activePet:o,scopeEpoch:s}=wd(),c=r.unread??null,d=e===void 0?o:e,f=u(e=>c===null?NO_SUBSCRIPTION():c.subscribe(e),[c]),h=u(()=>c===null||l===null?QR:c.get(d),[c,l,d]),p=i(f,h,h),g=u(()=>c===null||l===null?Promise.resolve():c.refresh(d),[c,l,d]);return n(()=>{g()},[g,s]),Fp(t,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:g}),a(()=>({...p,refresh:g}),[p,g])}function useEverfurUnread(e={}){let{lifecycle:t}=e,r=a(()=>t===void 0?createAppStateLifecycle():t??void 0,[t]);return JR(e.petRef,r)}function useEverfurPetProfile(e){let{runtime:t,userRef:r,scopeEpoch:i}=wd(),o=a(()=>createPetsRepository(t.registry.services.authFor(r)),[t,r,i]),s=a(()=>({repository:o,petRef:e}),[o,e]),[d,f]=l({key:s,profile:null,loading:e!==null,error:null}),h=d.key===s?d:{profile:null,loading:e!==null,error:null},p=c(0),g=u(async()=>{let e=++p.current;if(s.petRef===null){f({key:s,profile:null,loading:false,error:null});return}f(e=>({key:s,profile:e.key===s?e.profile:null,loading:true,error:null}));let t=await s.repository.getPetProfile(s.petRef);e===p.current&&f(t.ok?{key:s,profile:t.value,loading:false,error:null}:{key:s,profile:null,loading:false,error:t.error})},[s]);return n(()=>(g(),()=>{p.current+=1}),[g]),a(()=>({profile:h.profile,loading:h.loading,error:h.error,refresh:g}),[h.profile,h.loading,h.error,g])}function EverfurThemeProvider(e){return r(EverfurThemeProviderCore,{clientTheme:e.clientTheme??null,seams:tf,children:e.children})}export{ys as APPEARANCE_PRESETS,ms as APPEARANCE_PRESET_NAMES,vs as APPEARANCE_SIZE_RANGES,CapabilityGate,EverfurChat,J as EverfurConfigError,EverfurProvider,EverfurThemeProvider,Q as EverfurThrownError,qo as PHONE_TEXT_SCALE_CAPS,So as THEME_SLOT_KEYS,xo as THEME_SLOT_KEYS_BY_SLOT,Co as THEME_SLOT_NAMES,$o as TYPE_ROLE_DEFAULTS,No as TYPE_ROLE_NAMES,canonicalPetSpecies,categoryFor,chatHandoffTokenFromUrl,conversationId,createAppStateLifecycle,createRnRecordsUploadTransport,expandAppearance,face,headingFace,isErr,isOk,isRetryableCode,petRef,previewTheme,registerEverfurChatCards,registerEverfurDictation,textRole,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurTheme,useEverfurUnread,userFacingError,userRef};