@everfur/sdk 1.4.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Chat.d-D9n8tSDD.d.cts → Chat.d-Bl-_TsvQ.d.cts} +1 -1
- package/dist/{Chat.d-BXuEjJsg.d.ts → Chat.d-qQVN6VLp.d.ts} +1 -1
- package/dist/animations/index.cjs +1 -1
- package/dist/animations/index.js +1 -1
- package/dist/{attachments.d-Bsg6duaq.d.cts → attachments.d-DBlHzWYy.d.cts} +1 -1
- package/dist/{attachments.d-DjWUR-h9.d.ts → attachments.d-DOmkQ_8O.d.ts} +1 -1
- package/dist/{branding.d-Bzs4HJoN.d.cts → branding.d-CqDLKj1U.d.cts} +1 -1
- package/dist/{branding.d-CiC6xfGT.d.ts → branding.d-XrZYClN4.d.ts} +1 -1
- package/dist/chat/index.cjs +194 -194
- package/dist/chat/index.d.cts +7 -7
- package/dist/chat/index.d.ts +7 -7
- package/dist/chat/index.js +202 -202
- package/dist/chat/lite/index.cjs +205 -205
- package/dist/chat/lite/index.d.cts +7 -7
- package/dist/chat/lite/index.d.ts +7 -7
- package/dist/chat/lite/index.js +205 -205
- package/dist/{chatHandoffToken.d-sbumx0He.d.cts → chatHandoffToken.d-B4-iQ35P.d.cts} +3 -3
- package/dist/{chatHandoffToken.d-YJY6TZbj.d.ts → chatHandoffToken.d-Br3Gw3w-.d.ts} +3 -3
- package/dist/{checkin.d-DxpoRutq.d.cts → checkin.d-CAKQydg8.d.cts} +14 -2
- package/dist/{checkin.d-C6vh9KVr.d.ts → checkin.d-qvYXugN3.d.ts} +14 -2
- package/dist/{chunk-AJEELSFO.js → chunk-5OK2AF63.js} +14 -14
- package/dist/{chunk-II4QDD6F.js → chunk-6I4REU4U.js} +1 -1
- package/dist/{chunk-ZPIOCHKW.js → chunk-7MMJ7CYN.js} +1 -1
- package/dist/{chunk-FZ6DAQFH.js → chunk-PJHMKQ5C.js} +19 -19
- package/dist/client/index.cjs +2 -2
- package/dist/client/index.d.cts +7 -7
- package/dist/client/index.d.ts +7 -7
- package/dist/client/index.js +2 -2
- package/dist/consent/index.cjs +1 -1
- package/dist/consent/index.js +2 -2
- package/dist/{context.d-Cq2C4vdh.d.cts → context.d-DZfxKxNi.d.cts} +3 -3
- package/dist/{context.d-D1l56nFr.d.ts → context.d-FjU7dQP7.d.ts} +3 -3
- package/dist/core/index.cjs +21 -21
- package/dist/core/index.d.cts +10 -10
- package/dist/core/index.d.ts +10 -10
- package/dist/core/index.js +21 -21
- package/dist/{entitlementRepository.d-x2YFdgYD.d.ts → entitlementRepository.d-BltqS1W8.d.ts} +1 -1
- package/dist/{entitlementRepository.d-CEDU1gZE.d.cts → entitlementRepository.d-wfqpUIKN.d.cts} +1 -1
- package/dist/health-plan/index.cjs +1 -1
- package/dist/health-plan/index.d.cts +4 -4
- package/dist/health-plan/index.d.ts +4 -4
- package/dist/health-plan/index.js +1 -1
- package/dist/index.cjs +221 -221
- package/dist/index.d.cts +13 -13
- package/dist/index.d.ts +13 -13
- package/dist/index.js +221 -221
- package/dist/notifications/inbox/index.cjs +9 -9
- package/dist/notifications/inbox/index.js +9 -9
- package/dist/notifications/index.cjs +3 -3
- package/dist/notifications/index.d.cts +3 -3
- package/dist/notifications/index.d.ts +3 -3
- package/dist/notifications/index.js +6 -6
- package/dist/photo/index.cjs +1 -1
- package/dist/photo/index.js +23 -23
- package/dist/{presentation.d-CWGjwq8Z.d.cts → presentation.d-BkIvMtIl.d.cts} +3 -3
- package/dist/{presentation.d-CWGjwq8Z.d.ts → presentation.d-BkIvMtIl.d.ts} +3 -3
- package/dist/records/depth/index.cjs +1 -1
- package/dist/records/depth/index.js +1 -1
- package/dist/records/index.cjs +2 -2
- package/dist/records/index.d.cts +2 -2
- package/dist/records/index.d.ts +2 -2
- package/dist/records/index.js +71 -71
- package/dist/{route.d-IP_gkOWL.d.ts → route.d-B395-hNX.d.ts} +1 -1
- package/dist/{route.d-9wclfD-y.d.cts → route.d-DSSSpSB-.d.cts} +1 -1
- package/dist/{runtimeTypes.d-BdUe3tYs.d.ts → runtimeTypes.d-DAz0Tgw5.d.ts} +5 -5
- package/dist/{runtimeTypes.d-_UZ6rMUY.d.cts → runtimeTypes.d-DPh1Wh15.d.cts} +5 -5
- package/dist/server/events/index.cjs +3 -3
- package/dist/server/events/index.js +3 -3
- package/dist/server/index.cjs +8 -8
- package/dist/server/index.d.cts +15 -1
- package/dist/server/index.d.ts +15 -1
- package/dist/server/index.js +8 -8
- package/dist/slots/index.cjs +1 -1
- package/dist/slots/index.js +1 -1
- package/dist/tabs/index.cjs +2 -2
- package/dist/tabs/index.js +24 -24
- package/dist/televet/booking/index.cjs +51 -51
- package/dist/televet/booking/index.js +1 -1
- package/dist/televet/index.cjs +1 -1
- package/dist/televet/index.js +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/rn/index.cjs +8 -8
- package/dist/testing/rn/index.d.cts +5 -5
- package/dist/testing/rn/index.d.ts +5 -5
- package/dist/testing/rn/index.js +9 -9
- package/dist/testing/web/index.cjs +3 -3
- package/dist/testing/web/index.d.cts +5 -5
- package/dist/testing/web/index.d.ts +5 -5
- package/dist/testing/web/index.js +1 -1
- package/dist/texting/index.cjs +1 -1
- package/dist/texting/index.js +26 -26
- package/dist/{threadOptions.d-BW0rePcs.d.cts → threadOptions.d-DUQxxHyM.d.cts} +3 -3
- package/dist/{threadOptions.d-CrAb71J2.d.ts → threadOptions.d-DnM9UcMx.d.ts} +3 -3
- package/dist/{typeStyle.d-rzVzCfLz.d.ts → typeStyle.d-8mcLhtbH.d.ts} +1 -1
- package/dist/{typeStyle.d-B-YgiWcS.d.cts → typeStyle.d-CLrQZW-r.d.cts} +1 -1
- package/dist/{unreadStore.d-gCsleb6l.d.ts → unreadStore.d-CLnChKca.d.ts} +17 -9
- package/dist/{unreadStore.d-w5x6lEpR.d.cts → unreadStore.d-Donv4bcF.d.cts} +17 -9
- package/dist/{usePresentation.d-w5_oWKmh.d.ts → usePresentation.d-Buxz2Jkt.d.ts} +1 -1
- package/dist/{usePresentation.d-DefUwatV.d.cts → usePresentation.d-DUYzYXgA.d.cts} +1 -1
- package/dist/{useUnread.d-DeRDFtTb.d.cts → useUnread.d-7-cuCooM.d.cts} +3 -3
- package/dist/{useUnread.d-xDOpYyqx.d.ts → useUnread.d-B6Ehu0ao.d.ts} +3 -3
- package/dist/video/index.cjs +1 -1
- package/dist/video/index.js +1 -1
- package/dist/web/consent/index.cjs +3 -3
- package/dist/web/consent/index.js +5 -5
- package/dist/web/health-plan/index.cjs +2 -2
- package/dist/web/health-plan/index.d.cts +5 -5
- package/dist/web/health-plan/index.d.ts +5 -5
- package/dist/web/health-plan/index.js +1 -1
- package/dist/web/inbox/index.cjs +5 -5
- package/dist/web/inbox/index.js +5 -5
- package/dist/web/index.cjs +176 -176
- package/dist/web/index.d.cts +18 -18
- package/dist/web/index.d.ts +18 -18
- package/dist/web/index.js +181 -181
- package/dist/web/intro/index.cjs +10 -10
- package/dist/web/intro/index.js +6 -6
- package/dist/web/notifications/index.cjs +5 -5
- package/dist/web/notifications/index.d.cts +2 -2
- package/dist/web/notifications/index.d.ts +2 -2
- package/dist/web/notifications/index.js +1 -1
- package/dist/web/records/depth/index.cjs +1 -1
- package/dist/web/records/depth/index.js +1 -1
- package/dist/web/records/index.cjs +1 -1
- package/dist/web/records/index.js +1 -1
- package/dist/web/records-sheet/index.cjs +2 -2
- package/dist/web/records-sheet/index.js +2 -2
- package/dist/web/shop/index.cjs +1 -1
- package/dist/web/shop/index.js +15 -15
- package/dist/web/televet/booking/index.cjs +2 -2
- package/dist/web/televet/booking/index.js +64 -64
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +6 -6
- package/dist/web/televet/index.js +1 -1
- package/dist/web/texting/index.cjs +1 -1
- package/dist/web/texting/index.js +1 -1
- package/dist/web/ui/index.cjs +1 -1
- package/dist/web/ui/index.js +33 -33
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
2
|
import{z as e}from"zod";import{createContext,forwardRef as t,createElement as r,useEffect as n,useState as l,useSyncExternalStore as i,useContext as o,useMemo as a,useCallback as s,useRef as u,useReducer as c,useLayoutEffect as d,Component as f,Fragment as h}from"react";import{Platform as p,TextInput as g,StyleSheet as b,AccessibilityInfo as m,useColorScheme as y,Dimensions as v,PixelRatio as k,View as w,AppState as C,Text as S,Linking as x,KeyboardAvoidingView as _,Pressable as R,Keyboard as T,Modal as I,ScrollView as z,ActivityIndicator as P,Image as O,UIManager as E,LayoutAnimation as j,Animated as F,useWindowDimensions as A,FlatList as D}from"react-native";import{SafeAreaProvider as M,useSafeAreaInsets as L}from"react-native-safe-area-context";import B from"react-native-sse";import{jsx as H,jsxs as U,Fragment as N}from"react/jsx-runtime";import*as $ from"@everfur/sdk/televet/booking";import*as W from"@everfur/sdk/texting";function V(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))return true;t+=1}else if(r>=56320&&r<=57343)return true}return false}function q(e){return[...e].length}function ok(e,t){/* @__PURE__ */
|
|
3
3
|
return Object.freeze({ok:true,value:e})}function err(e){/* @__PURE__ */
|
|
4
|
-
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var G=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new G(e.error)}var K=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var Y=128,Q=128,J=/[\u0000-\u001F\u007F]/,X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=q(t);if(r===0||r>Q)throw new K("invalid-argument",`petRef must be 1..${Q} characters`);if(J.test(t))throw new K("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=q(t);if(r===0||r>Y)throw new K("invalid-argument",`userRef must be 1..${Y} characters`);if(t.includes("@"))throw new K("invalid-argument","userRef must not contain '@'");if(J.test(t))throw new K("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!X.test(e))throw new K("invalid-argument","conversationId must be a UUID");return e}var Z=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],ee=/* @__PURE__ */Object.freeze(Z.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(ee.map(e=>e.wireCode));var te=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound"}),re=/* @__PURE__ */Object.freeze(ee.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:te[e.wireCode]}))),ne=new Map(re.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),le=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(re.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...le]){let t=ne.get(e+r);if(t)return t}}var ie=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return ie[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var oe=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return oe.has(e)}var ae=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||ae.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var se=500,ue=8e3,ce=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(se*2**r,ue);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var de="This feature isn't available on your account right now.",fe="Something in that request was not right. Check the details and try again.",he=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:de,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:fe,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:de,runtimeDisposed:fe,unknown:"Something went wrong. Please try again."}),pe="This session has ended. Please sign in again.",ge="linked_account_read_only";function be(e,t,r){return e==="conflict"&&r===ge?de:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?pe:userFacingError(e)}function userFacingError(e){return he[e]}function me(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var ye=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===ge,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:be(e,t?.wireCode,n?ge:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&ye.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&me(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&me(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var ve=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function ke(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return xe(e)}var we=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,Ce=/[\s\u0000-\u001f\u007f\\]/,Se={"http:":"80","https:":"443"};function xe(e,t){let r=e.trim();let n=Ce.test(r)?null:we.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===Se[f]?"":String(h),g=Se[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var _e="application/pdf",Re=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Te=e=>Re.includes(e);function Ie(e,t){return e===_e||t!==void 0&&Te(e)&&t.includes(e)}var ze=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function Pe(e){return Ie(e,Re)?ze[e]:ze["application/pdf"]}var Oe="file",Ee="multipart upload failed";function je(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Oe,e.file)}catch{return Promise.reject(new Error(Ee))}return e.fetch!==void 0?De(e.fetch,e.url,t,e.signal):Ae(e.url,t,e.signal)}function Fe(e){return e>=200&&e<300}function Ae(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(Ee));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(Ee))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Fe(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function De(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var Me="records upload: the file handle has no uri",Le="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
4
|
+
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var G=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new G(e.error)}var K=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var Y=128,Q=128,J=/[\u0000-\u001F\u007F]/,X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=q(t);if(r===0||r>Q)throw new K("invalid-argument",`petRef must be 1..${Q} characters`);if(J.test(t))throw new K("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=q(t);if(r===0||r>Y)throw new K("invalid-argument",`userRef must be 1..${Y} characters`);if(t.includes("@"))throw new K("invalid-argument","userRef must not contain '@'");if(J.test(t))throw new K("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!X.test(e))throw new K("invalid-argument","conversationId must be a UUID");return e}var Z=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],ee=/* @__PURE__ */Object.freeze(Z.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(ee.map(e=>e.wireCode));var te=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),re=/* @__PURE__ */Object.freeze(ee.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:te[e.wireCode]}))),ne=new Map(re.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),le=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(re.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...le]){let t=ne.get(e+r);if(t)return t}}var ie=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return ie[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var oe=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return oe.has(e)}var ae=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||ae.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var se=500,ue=8e3,ce=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(se*2**r,ue);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var de="This feature isn't available on your account right now.",fe="Something in that request was not right. Check the details and try again.",he=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:de,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:fe,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:de,runtimeDisposed:fe,unknown:"Something went wrong. Please try again."}),pe="This session has ended. Please sign in again.",ge="linked_account_read_only";function be(e,t,r){return e==="conflict"&&r===ge?de:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?pe:userFacingError(e)}function userFacingError(e){return he[e]}function me(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var ye=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===ge,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:be(e,t?.wireCode,n?ge:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&ye.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&me(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&me(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var ve=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function ke(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return xe(e)}var we=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,Ce=/[\s\u0000-\u001f\u007f\\]/,Se={"http:":"80","https:":"443"};function xe(e,t){let r=e.trim();let n=Ce.test(r)?null:we.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(s);if(h>65535)return null;let p=s===""||String(h)===Se[f]?"":String(h),g=Se[f]!==void 0,b=a.toLowerCase()+(p&&`:${p}`),m=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${b}${m}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:p,origin:g?`${f}//${b}`:"null",pathname:m,search:c==="?"?"":c,hash:d==="#"?"":d}}var _e="application/pdf",Re=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Te=e=>Re.includes(e);function Ie(e,t){return e===_e||t!==void 0&&Te(e)&&t.includes(e)}var ze=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function Pe(e){return Ie(e,Re)?ze[e]:ze["application/pdf"]}var Oe="file",Ee="multipart upload failed";function je(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(Oe,e.file)}catch{return Promise.reject(new Error(Ee))}return e.fetch!==void 0?De(e.fetch,e.url,t,e.signal):Ae(e.url,t,e.signal)}function Fe(e){return e>=200&&e<300}function Ae(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(Ee));return}let o=null,a=()=>{o!==null&&r?.removeEventListener("abort",o)},s=()=>{a(),l(new Error(Ee))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{a(),n(Fe(l.status))},l.onerror=s,l.ontimeout=s,l.onabort=s,r!==void 0&&(o=()=>{try{l.abort()}finally{s()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{s()}})}function De(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var Me="records upload: the file handle has no uri",Le="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
5
5
|
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Me));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(Le));return l?.aborted===true?o():je({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:Pe(r.mimeType),type:Be(r.mimeType)},signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}function Be(e){return Ie(e,Re)?e:"application/pdf"}var He=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var Ue=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<ce},maxAttempts(){return ce}});var Ne=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(e,t,r){let n;try{n=t()}catch(t){return We(`optional peer '${e}' is not installed: ${Ve(t)}`)}let l=$e(n);return l==null?We(`optional peer '${e}' resolved to no module`):r&&!r(l)?We(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:l})}function $e(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function We(e){/* @__PURE__ */
|
|
6
6
|
return Object.freeze({available:false,module:null,reason:e})}function Ve(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function acceptedFrame(e,t,r=null){/* @__PURE__ */
|
|
7
7
|
return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}function heartbeatFrame(e,t=null){/* @__PURE__ */
|
|
@@ -12,7 +12,7 @@ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryab
|
|
|
12
12
|
return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
|
|
13
13
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
|
|
14
14
|
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var qe="/widget/v1/anon-identity",Ge="x-everfur-anon-token",Ke="anonTokenInvalid";function Ye(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let l=null,i=null,o=null,a=null,s=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs-2592e5),d=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,a={method:"POST",path:qe,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},s=await e.request(a),u=s.ok?s.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(l={token:c,mintedAtMs:n(),ttlMs:Ye(u?.expires_at,i)},o=null,c)}catch{return o=n(),d()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(a,3e4)?Promise.resolve(l?.token??null):(a=n(),l=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function Qe(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function Je(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let l=null,i=false,o=null,a=false,s=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new K("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:Xe(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(a)throw new K("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:s()},hasToken(){return!a&&l!==null},clear(){a=true,l=null},reportRejected(){a||i||(i=true,n?.())}}}function Xe(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[Ge]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...Ze(e.headers),...authHeaders(t)}}}function Ze(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===Ge||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await Qe(t),n=await t.transport.request(withAuthHeaders(e,et(t,r)));if(n.ok||rt(n.error.raw)!==Ke||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,et(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(Je(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(Je(e,{wireCode:rt(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(tt(i.error))):i}function et(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function tt(e){let t=e.raw,r=rt(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function rt(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var nt="DAILY_QUOTA_EXCEEDED",lt=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function it(e,t){if(!lt.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?nt:e}var ot="free_cap_reached";function at(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function st(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==ot&&n.code!==ot)return null;let l=at(n.limit),i=at(n.used);if(l===null||i===null)return null;let o=n.resets_at,a=n.emergency_guidance;/* @__PURE__ */
|
|
15
|
-
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ut(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:st(t)}function ct(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function dt(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ct()}var ft=`\n\n`,ht=1048576,pt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),gt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=dt(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(ft,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+ft.length),o=0;let r=bt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>ht){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=bt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function bt(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=pt.safeParse(l);return i.success?mt(i.data,r,t):null}function mt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:yt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:yt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:st(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:yt(e.conversation_id)??"",messageId:yt(e.message_id),title:yt(e.title),followUpQuestions:Ct(e.follow_up_questions),citations:xt(e.citations),citationStatus:yt(e.citation_status),urgencyLevel:kt(e.urgency_level),urgencyReason:yt(e.urgency_reason),urgencyProvided:wt(e),resultId:yt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(yt(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=yt(e.delta)??yt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(yt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:yt(e.result_id),analysisType:yt(e.analysis_type),modelVersion:yt(e.model_version),confidence:vt(e.confidence),detections:xt(e.detections),interpretation:yt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function yt(e){return typeof e=="string"?e:null}function vt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function kt(e){return typeof e=="string"&>.includes(e)?e:null}function wt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||kt(t)!==null}function Ct(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e){return Array.isArray(e)?e.filter(St):[]}var _t="1.4.
|
|
15
|
+
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function ut(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:st(t)}function ct(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function dt(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ct()}var ft=`\n\n`,ht=1048576,pt=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),gt=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=dt(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(ft,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+ft.length),o=0;let r=bt(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>ht){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=bt(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function bt(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=pt.safeParse(l);return i.success?mt(i.data,r,t):null}function mt(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:yt(e.code)??"unknown",retryable:e.retryable===true,wireMessage:yt(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:st(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:yt(e.conversation_id)??"",messageId:yt(e.message_id),title:yt(e.title),followUpQuestions:Ct(e.follow_up_questions),citations:xt(e.citations),citationStatus:yt(e.citation_status),urgencyLevel:kt(e.urgency_level),urgencyReason:yt(e.urgency_reason),urgencyProvided:wt(e),resultId:yt(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(yt(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=yt(e.delta)??yt(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(yt(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:yt(e.result_id),analysisType:yt(e.analysis_type),modelVersion:yt(e.model_version),confidence:vt(e.confidence),detections:xt(e.detections),interpretation:yt(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function yt(e){return typeof e=="string"?e:null}function vt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function kt(e){return typeof e=="string"&>.includes(e)?e:null}function wt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||kt(t)!==null}function Ct(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e){return Array.isArray(e)?e.filter(St):[]}var _t="1.4.1";var Rt="react-native",Tt="2026-09-19",It="EVERFUR_API_BASE_URL";function zt(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
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()||Tt;/* @__PURE__ */
|
|
18
18
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:_t,platform:t?.platform??Rt,debug:e.debug===true})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:Dt(It);return r?Ft(r):zt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${It}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){return{"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}function Pt(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function Ot(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function Et(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Ot(t)}function jt(e,t){return`${e}://${t}`}function Ft(e){let t=e.trim(),r=ve.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return zt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=Pt(r[2]);if(l.length===0)return zt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=Et(t,l)?`: ${jt(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&At(l)))return n==="http"?zt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):zt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
@@ -27,8 +27,8 @@ return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...
|
|
|
27
27
|
return Object.freeze(r)}function on(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 an(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sn(e){return typeof e=="string"?e:null}function un(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(an(r)){let e=sn(r.text)??sn(r.prompt)??sn(r.title);e!==null&&t.push(e)}return t}function cn(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function dn(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var fn={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*hn(e,t,r,n){let l=e[Symbol.asyncIterator](),i=bn(t.overallMs,n),o=bn(t.idleMs,n),a=mn(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 gn();return}if(n.tag==="idle"||n.tag==="overall"){yield pn();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 pn(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function gn(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function bn(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 mn(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var yn="checkin",vn=/^\d{4}-\d{2}-\d{2}$/,kn="watching";function wn(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 Cn(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=xn(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
28
|
return Object.freeze({conversationId:r,message:c,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==kn}function Sn(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 xn(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==yn||n===void 0||l===void 0||!jr.test(n)||!vn.test(l)?null:{caseId:n,dueDay:l}}function _n(e){return xn(e)?.caseId??null}function Rn(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||V(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function Tn(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 In(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function zn(e){return e==null||typeof e=="string"&&e.length>0&&!V(e)}function Pn(){return err(makeEverfurError("internalError",{retryable:false}))}function On(e){let t=In(e);if(!t||!Array.isArray(t.conversations)||!zn(t.next_cursor))return Pn();let r=[];for(let e of t.conversations){let t=In(e);if(!t||typeof t.conversation_id!="string"||!Tn(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return Pn();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return Pn();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 En(e){let t=In(e);if(!t||!Array.isArray(t.messages)||!zn(t.next_cursor))return Pn();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=In(e);if(!t||typeof t.message_id!="string"||!Tn(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return Pn();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(jn(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"?_n(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:An(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Dn(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 jn(e,t,r,n){let l=In(e.sender),i=Fn(l?.display_name)??Fn(e.sender_display_name),o=Fn(l?.specialty);/* @__PURE__ */
|
|
29
29
|
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function Fn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!V(t)?t:null}function An(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function Dn(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=In(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function Mn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Ln=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Bn=4e3;var Hn=4e3;function Un(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:en("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:en("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Nn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:en("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Hn?{reason:"too_long",error:en("validationFailed",false,`message is ${r} characters; the server accepts at most ${Hn}`)}:null}function $n(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Wn(e){yield e}async function*Vn(){}var qn=6e4,Gn=18e4,Kn=24,Yn=512,Qn=false;function createChatController(e){return new el(e)}function Jn(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Xn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function Zn(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var el=class extends Gr{constructor(e){super(Zr({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Hr(this.funnel),this.telemetry=e.telemetry??He,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??Ue,this.timers=e.timers??fn,this.rng=e.rng??Math.random,this.newId=e.newId??cn(),this.makeIdempotencyKey=e.makeIdempotencyKey??dn(),this.budget={idleMs:e.budget?.idleMs??qn,overallMs:e.budget?.overallMs??Gn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=en(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Wn(rn(e))}let l=Nn(e)??Un(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Wn(rn(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Wn(rn(en("accessDenied",false)));let r=Nn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Wn(rn(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):Vn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Kr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?Qr(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(on(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=Rn(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(en("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(en("accessDenied",false));if(!l.ok)return l;let i=On(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return i}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Cn(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Xn(n.error)?n.error:null;if(n.error.category==="notFound"&&Zn(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=wn(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}Jn(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(en("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(en("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(en("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(en("accessDenied",false));if(typeof e!="string"||e.trim().length===0||V(e))return err(en("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Ln.includes(t))return err(en("validationFailed",false,`feedback_type must be one of ${Ln.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>Bn)return err(en("validationFailed",false,`notes is over ${Bn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(en("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(en("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(en("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(en("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!Tn(e))return err(en("validationFailed",false));let r=Rn(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(en("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(en("accessDenied",false)):l.ok?En(l.value):l}async resumeConversation(e){if(this.disposed)return err(en("accessDenied",false));if(!Tn(e))return err(en("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===kn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||Sn({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
-
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?kn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(en("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(!i.ok)return err(i.error);let o=Mn(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.reportLoadFailures===true&&!n.ok&&Xn(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(en("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield rn(t.error))}async primeConversation(e){if(this.disposed)return err(en("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(en("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(en("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(en("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(en("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(en("accessDenied",false));let r=e?.petRef??null;if(r!==null&&V(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(en("accessDenied",false)):l.ok?ok(ln(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=qr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Kr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,rn(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=en("internalError",!0);yield*this.emitTerminal(e,t,rn(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=qr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,rn(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Ge]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of hn(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=en("streamIncomplete",!0);yield*this.emitTerminal(e,t,rn(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===Ke||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,tn(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(Qn&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,tn(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Qr(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,Yr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Yn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Kn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Jr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?Xr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Qr(e):e),Xr(Yr(r,"",this.stamp()),e)]}let l=on([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=$n(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?Qr(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?en("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,rl(e)?(a=true,u=e):(nl(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){rl(e)?(a=true,u===null&&(u=e)):nl(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
30
|
+
return Object.freeze(e.flatMap(e=>{let r=In(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function Mn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var Ln=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Bn=4e3;var Hn=4e3;function Un(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:en("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:en("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Nn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:en("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Hn?{reason:"too_long",error:en("validationFailed",false,`message is ${r} characters; the server accepts at most ${Hn}`)}:null}function $n(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Wn(e){yield e}async function*Vn(){}var qn=6e4,Gn=18e4,Kn=24,Yn=512,Qn=false;function createChatController(e){return new el(e)}function Jn(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Xn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function Zn(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var el=class extends Gr{constructor(e){super(Zr({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Hr(this.funnel),this.telemetry=e.telemetry??He,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??Ue,this.timers=e.timers??fn,this.rng=e.rng??Math.random,this.newId=e.newId??cn(),this.makeIdempotencyKey=e.makeIdempotencyKey??dn(),this.budget={idleMs:e.budget?.idleMs??qn,overallMs:e.budget?.overallMs??Gn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=en(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Wn(rn(e))}let l=Nn(e)??Un(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):Wn(rn(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return Wn(rn(en("accessDenied",false)));let r=Nn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Wn(rn(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):Vn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Kr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?Qr(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(on(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=Rn(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(en("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(en("accessDenied",false));if(!l.ok)return l;let i=On(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.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=Cn(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Xn(n.error)?n.error:null;if(n.error.category==="notFound"&&Zn(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=wn(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}Jn(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(en("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(en("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(en("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(en("accessDenied",false));if(typeof e!="string"||e.trim().length===0||V(e))return err(en("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Ln.includes(t))return err(en("validationFailed",false,`feedback_type must be one of ${Ln.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>Bn)return err(en("validationFailed",false,`notes is over ${Bn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(en("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(en("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(en("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(en("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!Tn(e))return err(en("validationFailed",false));let r=Rn(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(en("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(en("accessDenied",false)):l.ok?En(l.value):l}async resumeConversation(e){if(this.disposed)return err(en("accessDenied",false));if(!Tn(e))return err(en("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===kn).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||Sn({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
+
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?kn:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(en("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(!i.ok)return err(i.error);let o=Mn(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&Xn(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(en("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(en("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield rn(t.error))}async primeConversation(e){if(this.disposed)return err(en("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(en("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(en("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(en("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(en("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(en("accessDenied",false));let r=e?.petRef??null;if(r!==null&&V(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(en("accessDenied",false)):l.ok?ok(ln(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=qr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Kr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,rn(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=en("internalError",!0);yield*this.emitTerminal(e,t,rn(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=qr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,rn(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[Ge]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of hn(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=en("streamIncomplete",!0);yield*this.emitTerminal(e,t,rn(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===Ke||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,tn(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(Qn&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,tn(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Qr(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,Yr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Yn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Kn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Jr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?Xr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Qr(e):e),Xr(Yr(r,"",this.stamp()),e)]}let l=on([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=$n(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?Qr(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?en("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,rl(e)?(a=true,u=e):(nl(e)&&(o=true),s=true)}let b=[];p.ok?b=p.value:m(p.error);function m(e){rl(e)?(a=true,u===null&&(u=e)):nl(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
32
32
|
return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:b,error:y,warning:y===null&&g===null&&s?tl:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...i]),sawForbidden:o,sawUnauthorized:a,sawConversationInitFailure:s})})}var tl="Chat is ready. Your first message will start the conversation.";function rl(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function nl(e){return e.httpStatus===403||e.code==="accessDenied"}var ll=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function il(e){return e!==ll}var ol=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var al=10*1024*1024,sl=5,ul=120,cl="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&ol.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<=ul)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,ul);let n=t.slice(r);return n.length>=ul?t.slice(0,ul):`${t.slice(0,r).slice(0,ul-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 dl=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),fl=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function hl(e,t,r,n){/* @__PURE__ */
|
|
33
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 fl(hl("unsupported_type",false,t));let n=attachmentSize(e);return n===null?fl(hl("unknown",false,t)):n>al?fl(hl("too_large",false,t,{sizeBytes:n})):dl(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function pl(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
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)??al,s3_key:o,purpose:r(t.purpose)})}function gl(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return hl("quota_exceeded",false,t,{cause:e});case"rateLimited":return hl("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return hl("idempotency_conflict",true,t,{cause:e});case"validationFailed":return hl("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return hl("network",true,t,{cause:e});default:return r===429?hl("rate_limited",true,t,{cause:e}):r===503?hl("network",true,t,{cause:e}):r===void 0?hl("network",true,t,{cause:e}):hl("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:cl,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return fl(gl(n.error,t.filename));let l=pl(n.value);return l===null?fl(hl("server",false,t.filename)):dl(l)}async function uploadAttachmentBytes(e,t,r,n){let l=()=>n?.signal?.aborted===true;if(l())return fl(hl("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),dl(void 0)}catch{return l()?fl(hl("cancelled",true,r.filename)):fl(hl("server",true,r.filename))}}var bl=2,ml=3,yl=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),vl=0;function kl(){return vl+=1,`attachment-${vl}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??bl),r=Math.max(1,e.maxAttempts??ml),n=e.backoffMs??yl,l=Math.max(1,e.maxPerMessage??sl),i=e.timers??Wr,o=e.newId??kl,a=il(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=fl(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:wl(e)})}});if(p||o.aborted)return;s=r.ok?dl(a.value.s3_key):fl(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 Vr(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 fl(hl("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),dl(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 wl(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var Cl=/* @__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(Cl,t)?Cl[t]:null}var Sl=50,xl=128,_l=120,Rl=120,Tl=2e3,Il=120,zl=80,Pl=/* @__PURE__ */new Set(["male","female","unknown"]),Ol=/* @__PURE__ */new Set(["day","month","year"]),El=/* @__PURE__ */new Set(["low","medium","high","athletic"]),jl=/* @__PURE__ */new Set(["indoor","outdoor","both"]),Fl=/* @__PURE__ */new Set(["mild","moderate","severe"]),Al=/^(\d{4})-(\d{2})-(\d{2})$/,Dl=[["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"]],Ml=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...Dl,...Ml].map(([e])=>e));function Ll(e){let t=Al.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 Bl=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,Hl=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,Ul=(e,t)=>typeof t=="string"&&Ll(t)?null:`${e} must be a real date written YYYY-MM-DD`,Nl=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(V(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let l=t.trimmed?n.trim():n;if(t.required&&l.length===0)return`${r} is required and must not be blank`;let i=q(l);return i<=e?null:`${r} is ${i} characters; the server accepts at most ${e}`},$l={sex:Bl(Pl),spayedNeutered:Hl,birthDate:Ul,birthDatePrecision:Bl(Ol),activityLevel:Bl(El),indoorOutdoor:Bl(jl),foodBrand:Nl(Il),foodType:Nl(Il),microchipId:Nl(zl)},Wl=["ref","ref",false,Nl(xl,{required:true,trimmed:true})],Vl=["notes","notes",false,Nl(Tl,{trimmed:true})],ql=[Wl,["name","name",true,Nl(_l,{required:true,trimmed:true})],["dose","dose",false,Nl(Rl,{trimmed:true})],["frequency","frequency",false,Nl(Rl,{trimmed:true})],["startDate","start_date",false,Ul],["endDate","end_date",false,Ul],Vl],Gl={allergies:[Wl,["allergen","allergen",true,Nl(_l,{required:true,trimmed:true})],["severity","severity",false,Bl(Fl)],Vl],medications:ql,supplements:ql,conditions:[Wl,["conditionName","condition_name",true,Nl(_l,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ul],Vl]};function Kl(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 Gl[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 Yl(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>Sl)return{error:`${e} has ${t.length} items; the server accepts at most ${Sl}`};let r=[],n=/* @__PURE__ */new Set;for(let l=0;l<t.length;l+=1){let i=Kl(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 Ql(e,t){let r=e,n={};for(let[e,t]of Dl){let l=r[e];if(l!==void 0){if(l!==null){let t=$l[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 Ml){let l=r[e];if(l===void 0)continue;let i=Yl(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 Jl=e=>typeof e=="string"?e:null,Xl=(e,t)=>typeof t=="string"&&e.has(t)?t:null,Zl=e=>typeof e=="boolean"?e:null;function ei(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 ti(e){let t=Jl(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:Jl(e.ref),name:t,dose:Jl(e.dose),frequency:Jl(e.frequency),startDate:Jl(e.start_date),endDate:Jl(e.end_date),notes:Jl(e.notes)})}function ri(e){let t=e.profile_version;/* @__PURE__ */
|
|
@@ -42,344 +42,344 @@ return Object.freeze(a)}var Ps=4,Os=/* @__PURE__ */Object.freeze({min:1,max:2}),
|
|
|
42
42
|
return Object.freeze(o)}function lu(e,t){let r=false,n={};for(let l of jo){let i=e[l],o=t(i);o===1?n[l]=i:(r=true,n[l]=/* @__PURE__ */Object.freeze({...i,size:tu(i.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function iu(e,t,r){return{nano:tu(e.nano*r),small:tu(e.small*r),micro:tu(e.micro*r),tiny:tu(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:tu(e.verdict*r)}}var ou=/* @__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"]),au="slots.",su=/* @__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||su.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
|
|
43
43
|
return new Set(["hide_powered_by",...e?.lockedFields??[]])}function uu(e){return e==="hide_powered_by"||ou.includes(e)||isPresentationLockName(e)?true:e.startsWith(au)&&ho.includes(e.slice(au.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=du(t),n=expandAppearance(pu(t,"appearance")),l=n===null?r:cu(du(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function cu(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function du(e){return{displayName:gu(pu(e,"display_name","displayName")),logoUrl:gu(pu(e,"logo_url","logoUrl")),primaryColor:parseColor(pu(e,"primary_color","primaryColor")),accentColor:parseColor(pu(e,"accent_color","accentColor")),brightness:wu(pu(e,"brightness","color_scheme","colorScheme")),fontFamily:gu(pu(e,"font_family","fontFamily")),fontUrl:gu(pu(e,"font_url","fontUrl")),fonts:mu(pu(e,"fonts")),fontUrls:mu(pu(e,"font_urls","fontUrls")),placeholder:gu(pu(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:hu(pu(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pu(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pu(e,"accent_color_dark","accentColorDark")),surfaceStyle:ku(pu(e,"surface_style","surfaceStyle"),yu),radiusScale:ku(pu(e,"radius_scale","radiusScale"),vu),logoUrlDark:gu(pu(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pu(e,"slots")),accessibilityMaxFontScale:_u(pu(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Iu(pu(e,"locked_fields","lockedFields")),presentation:parsePresentation(pu(e,"presentation")),schemaVersion:Ru(pu(e,"schema_version","schemaVersion")),backgroundColor:parseColor(pu(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(pu(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(pu(e,"text_color","textColor")),textColorDark:parseColor(pu(e,"text_color_dark","textColorDark")),dangerColor:parseColor(pu(e,"danger_color","dangerColor")),dangerColorDark:parseColor(pu(e,"danger_color_dark","dangerColorDark")),fontSizeBase:fu(pu(e,"font_size_base","fontSizeBase"),cs.fontSizeBase),borderRadius:fu(pu(e,"border_radius","borderRadius"),cs.borderRadius),spacingUnit:fu(pu(e,"spacing_unit","spacingUnit"),cs.spacingUnit),successColor:parseColor(pu(e,"success_color","successColor")),successColorDark:parseColor(pu(e,"success_color_dark","successColorDark")),warningColor:parseColor(pu(e,"warning_color","warningColor")),warningColorDark:parseColor(pu(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(pu(e,"info_color","infoColor")),infoColorDark:parseColor(pu(e,"info_color_dark","infoColorDark")),headingFontFamily:gu(pu(e,"heading_font_family","headingFontFamily")),fontWeightBody:Ds(pu(e,"font_weight_body","fontWeightBody")),fontWeightHeading:Ds(pu(e,"font_weight_heading","fontWeightHeading")),lineHeight:Ms(pu(e,"line_height","lineHeight")),fontSources:Ns(pu(e,"font_sources","fontSources")),assistantAvatarUrl:gu(pu(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:Xs(pu(e,"text_scale_caps","textScaleCaps")),typeScale:Js(pu(e,"type_scale","typeScale")),typeRoles:eu(pu(e,"type_roles","typeRoles"))}}function fu(e,t){let r=Cu(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function hu(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}function pu(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function gu(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var bu=["regular","medium","bold","mono","monoMedium","monoBold"];function mu(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of bu){let n=gu(pu(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var yu=["white","cream","subtle"],vu=["sharp","default","round"];function ku(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function wu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function Cu(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}var Su=1,xu=3.1;function _u(e){let t=Cu(e);return t===null?null:t<=0?0:Math.min(xu,Math.max(Su,t))}function Ru(e){if(e==null)return null;let t=Cu(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function Tu(e){let t=e.trim();return t.startsWith(au)?t:t.startsWith(Rs)?Rs+t.slice(Rs.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Iu(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=Tu(r);uu(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var zu=/* @__PURE__ */new RegExp(`^${ws}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&zu.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?na:ta:e,n=r.brightness==="dark"?na:ta,l=r.brightness==="dark",i=l?t.primaryColorDark??Fu(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??Fu(t.accentColor):t.accentColor,a=i??r.color.primary,s=o??r.color.accent,u=i!==null&&Mu(t,a,n,l),c=u?n.color.primary:a,d=i!==null&&!u?Hi(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?Lu(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=Ka(p),b={...r.color,...g},m=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??Fu(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...Ya(y(t.dangerColor,t.dangerColorDark)),...ts(y(t.successColor,t.successColorDark),l),...rs(y(t.warningColor,t.warningColorDark),l),...ns(y(t.infoColor,t.infoColorDark),l),...m!==null?{text:{...h.text??r.color.text,primary:m}}:{},...Au(t.surfaceStyle??null,b),primary:c,accent:s,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:Ja(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Xa(t.borderRadius,n):Hu(t.radiusScale??null,r.radius,n),type:{...r.type,...ju(r.type,t),size:Qa(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:ls(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:nu(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var Pu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Ou=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Eu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function ju(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of bu){let a=Pu[e].map(e=>r[e]).find(e=>e!==void 0),s=Eu(e)?null:t.fontFamily;a!==void 0?(l[e]=a,i[e]=true):s!==null&&(l[e]=s,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:a!==void 0&&delete o[e]}for(let e of Ou)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function Fu(e){return e===null?null:deriveDarkVariant(e)}function Au(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function Du(e,t){return e==null?false:parseColor(e)===parseColor(t)}function Mu(e,t,r,n){return Du(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Du(e.primaryColor,ta.color.primary)}function Lu(e,t){let r=e.color;return{text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}var Bu={sharp:.5,default:1,round:1.5};function Hu(e,t,r){if(e===null)return t;let n=Bu[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var Uu="Everfur",Nu=.5;function resolveTheme(e){return lc($u(e),e)}function themeAdjustments(e){let t=$u(e);return Sa(t,lc(t,{...e,highContrast:false}))}function $u(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=Gu(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=Yu((i==="auto"?l:i)==="dark"?na:ta,e?.typeProfile),a=withServerBranding(o,Ku(r));return withServerBranding(a,Ku(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Wu(e){return e==="placeholder"?"chat_placeholder":Tu(e)}var Vu={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function qu(e,t){return t.has(Wu(e))?true:(Vu[e]??[]).some(e=>t.has(e))}function Gu(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(qu(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of ho){let n=l[r];n!==void 0&&(t.has(`${au}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function Ku(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function Yu(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:Mo}})}function Qu(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function Ju(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Nu,e)}var Xu=["content","heading","control","compact","badge"];function Zu(e,t){let r={};for(let n of Xu){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:Do[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return Xu.every(e=>r[e]===Do[e])?Do:r}function ec(e,t){return t>0?Math.min(e,t):e}function tc(e,t,r,n){let l={};for(let i of Xu)l[i]=n?Qu(e,ec(t,r[i])):e;return l}function rc(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function nc(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return{family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces,headingFamily:e.headingFamily};let l=e.headingFamily!==null&&r!==void 0&&rc(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of bu)!(i[e]===Vo||i[e]===qo)&&r!==void 0&&rc(r,i[e])===false&&(i[e]=Eu(e)?qo:Vo,o[e]=false),n!==null&&Eu(e)&&i[e]===qo&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function lc(e,t){let r=e.meta.displayName.trim().length===0?Uu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of bu){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.regular??null,o=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,a=Number.isFinite(e.type.maxScale)?e.type.maxScale:Wo,s=Ju(t?.textScale),u=Zu(e.type.scaleCaps,a),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=lu(e.type.roles,()=>d),h=c?lu(f,e=>ec(s,u[e.tier])):f,p=t?.typeProfile==="phone"?iu(e.type.size,f,d):Qu(e.type.size,d),g=tc(p,s,u,c),b=ha(e),m={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:b,space:e.space,radius:e.radius,type:{...e.type,...nc(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:s,maxScale:a,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,is(b),os(b))};return t?.highContrast===true?deriveHighContrast(deepFreeze(m)):deepFreeze(m)}var ic="/widget/v1/entitlements",oc=304,ac=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",uc(t));return n.ok?cc(n.value):n.error.httpStatus===oc?ac:{kind:"failed",error:n.error}}var sc=64;function uc(e){let t={};return bc(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=sc?{method:"GET",path:ic,headers:t,query:{region:e.region}}:{method:"GET",path:ic,headers:t}}function cc(e){if(e===null||typeof e!="object"||!bc(e.revision))return gc();let t=typeof e.region=="string"?e.region:"",r=bc(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
|
|
44
44
|
return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:hc(e.capabilities),branding:fc(e),livemode:e.livemode!==false,...dc(e)})}function dc(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 fc(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 hc(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))pc(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
|
|
45
|
-
return Object.freeze(t)}function pc(e){return typeof e=="object"&&e!==null&&e.enabled===true}function gc(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function bc(e){return typeof e=="number"&&Number.isFinite(e)}var mc=30;function createEntitlementPoller(e){let t=e.scheduler??yc,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??mc),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:vc(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 yc={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function vc(e){return e instanceof Error?e.message:"poll failed"}function
|
|
46
|
-
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function
|
|
47
|
-
return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r)}catch{}}})}var
|
|
48
|
-
return Object.freeze({request(){return Promise.resolve(err(Nc(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){r.aborted||(yield n)}}}})}var Kc=/* @__PURE__ */new WeakSet;function Yc(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return Kc.add(t),t}var Qc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new Xc(e,t)}var Jc=6e4,Xc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new K("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=r.telemetry?Wc(r.telemetry):He,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=Gc(l);else if(r.transport!==void 0)o=r.transport;else{let e=$c(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=Gc(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Oi(this,this.mintScope),this.transport=o,l!==null&&(qc(l,this.telemetry,t?.platform),this.emit({type:"error",code:Nc(l).code,requestId:null})),this.errorPolicy=r.errorPolicy,this.camera=r.camera??Ne,this.upload=r.upload??$r,this.uploadTransport=r.uploadTransport??ll,this.imageCache=r.imageCache??Qc,this.kv=r.storage??Yc(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Oc():Oc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",Zc(e),()=>this.buildChatController(e),ed),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${Zc(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=kc({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:wc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Bc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?Uc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=Bi(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-Jc,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Ti(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&Dc(l)===Dc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await zc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return Tc({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>Ic({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>ji(Ei(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(td(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&Mi(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?td("prepare"):r===null?null:Nc(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(Je(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}return s==="ready"?this.emit({type:"ready"}):s==="failed"&&!i.ok&&r===null&&!this.disposed&&this.emit({type:"error",code:i.error.code,requestId:i.error.requestId??null}),/* @__PURE__ */Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",Zc(t),()=>this.buildChatController(t),ed,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function Zc(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function ed(e){e.dispose()}function td(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function rd(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function nd(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function ld(e){return e.ok?e:err(nd(e.error))}function id(e){return{send:async(...t)=>ld(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var od=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),ad=globalThis,sd=ad[od]??(ad[od]=createContext(null));sd.displayName??="EverfurContext";function ud(){let e=o(sd);if(e===null)throw new K("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return ud().handle}var cd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),dd=globalThis,fd=dd[cd]??(dd[cd]=createContext(ta));fd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(fd)}var hd=()=>()=>{},pd=()=>null;function gd(e,t){return i(t?.subscribe??hd,t?.get??pd,t?.get??pd)??e}function EverfurThemeProviderCore(e){let{runtime:t}=ud(),l=t.entitlements,o=i(l.subscribe,l.getSnapshot,l.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),c=e.seams.useTextScale(),d=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,h=e.seams.typeProfile,p=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,b=e.clientTheme?bd(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=gd(o.branding??null,t.sdkConfigHost?.branding),v=a(()=>resolveTheme({branding:y,clientOverride:m,colorScheme:s,reducedMotion:u,textScale:c,scaleTypeSizes:f,highContrast:d,...h===void 0?{}:{typeProfile:h},...p===void 0?{}:{platformMonoFamily:p},...g===void 0?{}:{isFontRegistered:g}}),[y,m,s,u,c,f,h,d,p,g]);e.seams.useResolvedTheme?.(v);let k=e.seams.isDevelopment;return n(()=>{k===void 0||!md(k)||_a(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(fd.Provider,{value:v},e.children)}function bd(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function md(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:l,activePet:i,theme:o,warmUp:s,children:f,seams:h}=e,p=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=u(null),b=u(null),m=u(t?.onEvent);m.current=t?.onEvent;let y=u(e=>{m.current?.(e)}),[v,k]=c(e=>e+1,0),w=u(null),C=u(void 0),S=l?.userRef??null;C.current!==S&&(C.current!==void 0&&(w.current=null),C.current=S);let x=w.current!==null?w.current.user:l??null,_=u(null),R=u(void 0),T=i??null;R.current!==T&&(R.current!==void 0&&(_.current=null),R.current=T);let I=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==p||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(b.current=g.current.runtime),g.current={key:p,runtime:createEverfurRuntime({config:yd(h.withDefaults?h.withDefaults(t):t,y.current),user:x,activePet:I,theme:o??null},{platform:h.platform,...h.eventSourceFactory?{eventSourceFactory:h.eventSourceFactory}:{}})});let z=g.current.runtime,P=u(null);n(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||P.current!==e&&(P.current=e,k())}),n(()=>{let e=b.current;e!==null&&(b.current=null,e.dispose())});let O=x?.userRef??null;d(()=>{z.setUser(x)},[z,O]),d(()=>{z.setActivePet(I)},[z,I]);let E=u(null);n(()=>(E.current===z&&(E.current=null),()=>{E.current=z,vd(()=>{E.current===z&&(E.current=null,z.dispose())})}),[z]),n(()=>{s==="onMount"&&z.prepare(I===null?{}:{petRef:I})},[z,s,O,I]);let j=a(()=>({setUser:e=>{w.current={user:e},z.setUser(e),k()},setActivePet:e=>{_.current={pet:e},z.setActivePet(e),k()},open:e=>z.open(e),prepare:e=>z.prepare(e),registerPet:(e,t)=>z.registerPet(e,t),updatePet:(e,t)=>z.updatePet(e,t),deletePet:e=>z.deletePet(e),eraseUserData:()=>z.eraseUserData(),logout:()=>{w.current={user:null};let e=z.logout();return k(),e}}),[z,k]),F=a(()=>({runtime:z,handle:j,userRef:O,activePet:I,scopeEpoch:z.scopeEpoch,publishableKey:kd(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:f});return r(sd.Provider,{value:F},h.wrap?h.wrap(A):A)}function yd(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function vd(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function kd(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var wd=2;function Cd(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<wd)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function Sd(){let e=B;return(t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:e=>Cd(n,e)})}}function xd(){let e=y();return e==="dark"?"dark":e==="light"?"light":null}function _d(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Rd(){let[e,t]=l(false);return n(()=>{let e=true,r=m?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(m);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=m?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Td(){let e=k?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(k);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function Id(e){let t=v?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(v,"change",e);return()=>r?.remove?.()}function zd(){return i(Id,Td,Td)}function Pd(){try{let e=p?.OS;return typeof e=="string"?e:null}catch{return null}}function Od(){return Pd()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function Ed(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=Od(),l=m?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(m);_d(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=m?.addEventListener,o=typeof i=="function"?i.call(m,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function jd(){return Pd()==="ios"?"Menlo":qo}function Fd(){return globalThis.__DEV__!==false}var Ad=/* @__PURE__ */new Set;function Dd(e){if(!Fd()||Ad.has(e))return;Ad.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function Md(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t)}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let l=n.includes(e);return l||Dd(e),l}var Ld=/* @__PURE__ */new Set;function Bd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var Hd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Ud(e){if(!Fd())return;let t=Bd(e).filter(e=>!Ld.has(e));if(t.length===0)return;for(let e of t)Ld.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Hd[e]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function Nd(e){n(()=>{try{Ud(e)}catch{}},[e])}var $d=/* @__PURE__ */Object.freeze({useColorScheme:xd,useReducedMotion:Rd,useTextScale:zd,useHighContrast:Ed,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:jd,isFontRegistered:Md,useResolvedTheme:Nd,isDevelopment:Fd});function Wd(e){return r(M,null,e)}var Vd=/* @__PURE__ */Object.freeze({platform:"react-native",...p.OS==="web"?{}:{eventSourceFactory:Sd()},wrap:Wd,theme:$d});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:Vd})}function useCapability(e){let{runtime:t}=ud(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function qd(e){let{runtime:t}=ud(),r=t.entitlements,n=s(e=>r===void 0?()=>{}:r.subscribe(e),[r]),l=s(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return i(n,l,l)}var Gd=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Gd[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[Gd[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function Kd(e){return e<=450?"regular":e<=650?"medium":"bold"}var Yd={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=Qd.get(e);r===void 0&&(r=/* @__PURE__ */new Map,Qd.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=Jd(e,t);return r.set(t,l),l}var Qd=/* @__PURE__ */new WeakMap;function Jd(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=Kd(Number(n)),i=r.face==="mono"?face(e,Yd[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,a=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},s=r.size,u={...a,fontSize:s,lineHeight:Math.round(s*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(s*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function Xd(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:t,...n}){let l=useEverfurTheme(),i=t===void 0?void 0:l.type.roles[t],o=Xd(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(S,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var Zd=t(function(e,t){return r(g,{...e,...t===null?{}:{ref:t}})});var ef=class extends f{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:t,resetKey:n}){return r(ef,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var tf=48;function rf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:l,style:i}=e,o=useCapability(t),s=a(()=>rf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */H(HostRender,{render:l,fallback:/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */H(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */H(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */H(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>nf(r),[r]);/* @__PURE__ */
|
|
49
|
-
return H(w,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */H(w,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>
|
|
50
|
-
return H(w,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:l,children:l.length>0?/* @__PURE__ */H(Text,{style:n.offstateText,children:l}):null})}function
|
|
51
|
-
return H(i,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var
|
|
52
|
-
return Object.freeze(n)}function
|
|
53
|
-
return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function
|
|
54
|
-
return Object.freeze({petRef:
|
|
55
|
-
return Object.freeze(n)}var
|
|
56
|
-
return Object.freeze(a)}function Lh(e){return e.sender?.displayName??wf.senderVet}function Bh(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var Hh=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function Uh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Nh(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===Eh&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>Hh.test(e)||Uh(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var $h="pet_not_registered";function Wh(e){return e!=null&&e.reasonCode===$h}var Vh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function qh(e,t,r){let{runtime:i,userRef:o,scopeEpoch:c}=ud(),d=s((e,t)=>{let r=i.registry.services.authFor(o);return ji(Ei(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,c]),f=a(()=>t===void 0?null:Fi(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=u(0),b=u(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${c}|${e}|${f}`,y=s(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=s(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?Vh:h.key!==m?{status:"registering",error:null,registered:null,retry:v}:{status:h.status,error:h.error,registered:h.registered,retry:v},[m,h,v])}var Gh=/* @__PURE__ */Object.freeze({});function Kh(e){let[t,r]=l(Gh),i=u(null),o=u([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===Gh?e:Gh);return}let t=i.current;if(t===null)return;let n=e.find(e=>e.role==="user"&&!t.known.has(e.id));n!==void 0&&(i.current=null,r(e=>({...e,[n.id]:t.images})))},[e]);let c=s(e=>{i.current=e.length===0?null:{images:e,known:new Set(o.current)}},[]);return a(()=>({byMessage:t,stage:c}),[t,c])}var Yh=/* @__PURE__ */new WeakSet;function Qh(){let e=makeEverfurError("internalError",{retryable:true});return Yh.add(e),err(e)}function Jh(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&Yh.has(t)}var Xh=500;function Zh(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,Xh):null}function ep(e,t,r,l){let i=Zh(r),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=u(e);a.current=e;let s=u(null),c=u(null),d=u(o);d.current=o,n(()=>{if(i===null||o===null||t||s.current===o||c.current===o)return;let e=a.current;if(e===void 0)return;c.current=o;let r=e=>{c.current===o&&(c.current=null),!Jh(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var tp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),rp=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),np=3e5;function lp(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function ip(e,t,r){let l=u(t);l.current=t;let i=u(null),o=u(null),a=u(false),s=u(0),c=u(0),d=u(3e4),f=()=>e?.isOffline===void 0?false:fh(()=>e.isOffline?.()===!0)===true,h=f(),p=u(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:u}=l.current,h=Nr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:u===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,lp(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,np),c.current=Date.now()+s.current):(s.current=0,c.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},n(()=>{if(t.isTurnInFlight||h)return;let e=o.current;e!==null&&p.current(e)},[t.isTurnInFlight,h]),n(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=fh(()=>e(()=>{p.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)fh(e)}},[e]);let g=r?.intervalMs??null,b=r?.isVisibleFallback;n(()=>{if(e===void 0||g===null||!Number.isFinite(g)||g<=0)return;d.current=g;let t=setInterval(()=>{if(Date.now()<c.current)return;let t=e.isVisible===void 0?b:e.isVisible.bind(e);(t===void 0||fh(()=>t()!==!1)===true)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var op=/^efch_[A-Za-z0-9_-]{43}$/,ap="efch";function sp(e){return typeof e=="string"&&op.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${ap}=`))continue;let e=r.slice(ap.length+1);return sp(e)?e:null}return null}var up=128,cp=/[\u0000-\u001f\u007f]/;function dp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function fp(e){return typeof e!="string"||e.length===0||e.length>up||cp.test(e)||e.includes("://")?null:e}function hp(e){if(e===null)return null;let t=e.conversation_id,r=fp(e.pet_ref);return typeof t!="string"||!Tn(t)||r===null?null:{conversationId:t,petRef:r}}function pp(e,t,r){return sp(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(hp(dp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(en("internalError",false))):Promise.resolve(ok(null))}function gp(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=sp(e)?e:null,a=o===null||i===null?null:`${String(i)}|${o}`,[s,u]=l(null);return n(()=>{if(a===null||o===null||i===null||r===null)return;let e=true,t=r.registry.services;return pp(t.authFor(i),o,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||u({key:a,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[a,r,o,i]),s!==null&&s.key===a?s.target:void 0}function bp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function mp(e,t,r){let l=bp(t),i=t?.kind==="chat",o=t?.petRef??null,a=i&&!r.pinned&&o!==null&&r.petRef!==null&&o!==r.petRef,s=u({openCheckin:e,target:t,selectPet:r.selectPet});s.current={openCheckin:e,target:t,selectPet:r.selectPet};let c=u(null),d=u(null),f=r.petRef;n(()=>{if(l===null||c.current===l)return;let{openCheckin:e,target:t,selectPet:n}=s.current;if(a&&o!==null){if(d.current?.key!==l){d.current={key:l,from:f},n(o);return}f!==d.current.from&&(c.current=l);return}i&&!r.ready||(c.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,f,r.ready])}var yp=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function vp(e){let t=e?.replace(/\s+/g," ").trim();return t||yp.untitled}function kp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function wp(e){let t=kp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?yp.newReply.replace("{date}",t):t}function Cp(e,t){return t?`${yp.countLabel}${yp.countSeparator}${e}`:yp.countLabel}function Sp(e){return`${e.unreadCount!==null&&e.unreadCount>0?yp.unreadPrefix:""}${yp.openConversation} ${vp(e.title)}`}function xp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function _p(e,t){let r=xp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=xp(vp(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function Rp(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function Tp(e){let[t,r]=l(false),[i,o]=l(""),c=e.listConversations,d=u(0),[f,h]=l(()=>Rp(c)),p=f.scope===c?f:Rp(c);n(()=>(d.current+=1,r(false),o(""),h(Rp(c)),()=>{d.current+=1}),[c]);let g=s(async t=>{let r=++d.current,n=t!==void 0;h(e=>({...e,scope:c,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===d.current){if(!l.ok){h(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}h(e=>{let r=t&&e.scope===c?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:c,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,c]),b=()=>{r(true),o(""),g()},m=()=>{d.current+=1,r(false)},y=async t=>{let n=++d.current;h(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);n===d.current&&(h(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&r(false))},v=async()=>{let t=d.current,r=await e.loadOlderMessages();t===d.current&&!r.ok&&h(e=>({...e,error:r.error.displayMessage}))},k=()=>{e.newConversation(),d.current+=1,r(false)},w=()=>{p.cursor===null||p.loading||p.loadingMore||i.trim().length>0||g(p.cursor)},C=a(()=>_p(p.rows,i),[p.rows,i]),S=i.trim().length>0;return{...p,open:t,show:b,close:m,load:g,resume:y,earlier:v,newConversation:k,loadMore:w,query:i,setQuery:o,searching:S,filtered:C,emptyKind:p.rows.length===0?"empty":"noMatch"}}var Ip="#111111",zp="#FFFFFF",Pp=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Ip,pillColor:zp,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Ip,pillColor:zp,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Ip,pillColor:zp,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Ip,pillColor:zp,showsVetAction:false})});function Op(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function Ep(e){return Cf(wf.urgencyGeneralReason,{petName:e?.trim()||wf.emptyTitlePetFallback})}function jp(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:Fp(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Ep(t)}:null}return null}function Fp(e){return typeof e=="string"&&e.trim().length>0?e:null}function Ap(e){let t=e===null?null:Op(e),[r,i]=l(null),[o,u]=l(false);n(()=>u(false),[t]);let c=e!==null&&(o||!(r!==null&&r===t)),d=e===null?null:Pp[e.level],f=e!==null&&!c&&e.level!=="general",h=s(()=>{t!==null&&i(t),u(false)},[t]),p=s(()=>u(true),[]);return a(()=>({source:e,tier:d,signature:t,showBanner:c,showCompactIcon:f,showVetAction:c&&d!==null&&d.showsVetAction,dismissLabel:d===null?null:Cf(wf.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var Dp="everfur.com",Mp=2048,Lp=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Bp(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&Lp.test(e)&&t.add(e)}/* @__PURE__ */
|
|
57
|
-
return Object.freeze([...t])}function
|
|
58
|
-
return Object.freeze({hosts:e,open:t!==void 0?e=>{
|
|
59
|
-
return U(w,{style:[
|
|
45
|
+
return Object.freeze(t)}function pc(e){return typeof e=="object"&&e!==null&&e.enabled===true}function gc(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function bc(e){return typeof e=="number"&&Number.isFinite(e)}var mc=30;function createEntitlementPoller(e){let t=e.scheduler??yc,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??mc),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:vc(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 yc={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function vc(e){return e instanceof Error?e.message:"poll failed"}var kc=20;function wc(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,kc).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,kc))};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 Cc(e,t,r){let n=Rn({...t===null?{}:{petRef:t},limit:kc},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?On(e.value):err(e.error)):Promise.resolve(err(n.error))}var Sc="everfur.notifications.device";var xc="everfur.slots.v2",_c="everfur.slots.installId.v2";var Rc=3e3,Tc=/* @__PURE__ */Object.freeze([Sc,xc,_c]);function Ic(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()},Rc);s.then(r,r)})}function zc(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 Pc(e,t){if(Tc.length===0)return;let r=await Promise.allSettled(Tc.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 Oc(){/* @__PURE__ */
|
|
46
|
+
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function Ec(e=Oc){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 jc="everfur.branding.v1.";function Fc(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 Ac(e){let t=3421674724,r=2216829733;for(let n of Fc(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 Dc(e){return`${jc}${Ac(e)}`}function Mc(e){return e?JSON.stringify(e):null}async function Lc(e,t){try{let r=await e.getItem(Dc(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 Bc(e,t,r){try{r===null?await e.removeItem(Dc(t)):await e.setItem(Dc(t),r)}catch{}}function Hc(e,t){let r;return{restore(r){Lc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let l=Mc(n);l!==r&&(r=l,Bc(e,t,l))}}}function Uc(){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 Nc(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:Uc(),store:null,disposed:false}}function $c(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function Wc(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return tryResolveClientConfig(r,t===void 0?void 0:{platform:t})}function Vc(e){/* @__PURE__ */
|
|
47
|
+
return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r)}catch{}}})}var qc=/* @__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 ${It} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Gc(e,t,r=Rt){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. `+qc[r])}function Kc(e){/* @__PURE__ */
|
|
48
|
+
return Object.freeze({request(){return Promise.resolve(err($c(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){r.aborted||(yield n)}}}})}var Yc=/* @__PURE__ */new WeakSet;function Qc(){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 Yc.add(t),t}var Jc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new Zc(e,t)}var Xc=6e4,Zc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new K("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=r.telemetry?Vc(r.telemetry):He,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=Kc(l);else if(r.transport!==void 0)o=r.transport;else{let e=Wc(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=Kc(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Oi(this,this.mintScope),this.transport=o,l!==null&&(Gc(l,this.telemetry,t?.platform),this.emit({type:"error",code:$c(l).code,requestId:null})),this.errorPolicy=r.errorPolicy,this.camera=r.camera??Ne,this.upload=r.upload??$r,this.uploadTransport=r.uploadTransport??ll,this.imageCache=r.imageCache??Jc,this.kv=r.storage??Qc(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Ec():Ec(()=>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",ed(e),()=>this.buildChatController(e),td),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${ed(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=wc({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Cc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Hc(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?Nc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=Bi(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-Xc,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Ti(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&Mc(l)===Mc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await Pc(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 Ic({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>zc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>ji(Ei(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(rd(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&Mi(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?rd("prepare"):r===null?null:$c(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(Je(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}return s==="ready"?this.emit({type:"ready"}):s==="failed"&&!i.ok&&r===null&&!this.disposed&&this.emit({type:"error",code:i.error.code,requestId:i.error.requestId??null}),/* @__PURE__ */Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",ed(t),()=>this.buildChatController(t),td,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 ed(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function td(e){e.dispose()}function rd(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function nd(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function ld(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 id(e){return e.ok?e:err(ld(e.error))}function od(e){return{send:async(...t)=>id(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var ad=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),sd=globalThis,ud=sd[ad]??(sd[ad]=createContext(null));ud.displayName??="EverfurContext";function cd(){let e=o(ud);if(e===null)throw new K("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return cd().handle}var dd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),fd=globalThis,hd=fd[dd]??(fd[dd]=createContext(ta));hd.displayName??="EverfurThemeContext";function useEverfurTheme(){return o(hd)}var pd=()=>()=>{},gd=()=>null;function bd(e,t){return i(t?.subscribe??pd,t?.get??gd,t?.get??gd)??e}function EverfurThemeProviderCore(e){let{runtime:t}=cd(),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?md(e.clientTheme):"",m=a(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[b]),y=bd(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||!yd(k)||_a(themeAdjustments({branding:y,clientOverride:m,colorScheme:s}))},[k,y,m,s]),r(hd.Provider,{value:v},e.children)}function md(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function yd(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:vd(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,kd(()=>{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:wd(t)}),[z,j,O,I,v,p]),A=r(EverfurThemeProviderCore,{clientTheme:o??null,seams:h.theme,children:f});return r(ud.Provider,{value:F},h.wrap?h.wrap(A):A)}function vd(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function kd(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function wd(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Cd=2;function Sd(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<Cd)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function xd(){let e=B;return(t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:e=>Sd(n,e)})}}function _d(){let e=y();return e==="dark"?"dark":e==="light"?"light":null}function Rd(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Td(){let[e,t]=l(false);return n(()=>{let e=true,r=m?.isReduceMotionEnabled;if(typeof r=="function"){let n=r.call(m);n!=null&&typeof n.then=="function"&&n.then(r=>{e&&t(r===true)},()=>{})}let n=m?.addEventListener?.("reduceMotionChanged",e=>t(e===true));return()=>{e=false,n?.remove?.()}},[]),e}function Id(){let e=k?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(k);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function zd(e){let t=v?.addEventListener;if(typeof t!="function")return()=>{};let r=t.call(v,"change",e);return()=>r?.remove?.()}function Pd(){return i(zd,Id,Id)}function Od(){try{let e=p?.OS;return typeof e=="string"?e:null}catch{return null}}function Ed(){return Od()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function jd(){let[e,t]=l(false);return n(()=>{let e=true,{query:r,event:n}=Ed(),l=m?.[r];if(typeof l!="function")return()=>{};try{let r=l.call(m);Rd(r)&&Promise.resolve(r).then(r=>{e&&t(r===!0)},()=>{})}catch{}let i=m?.addEventListener,o=typeof i=="function"?i.call(m,n,e=>t(e===true)):void 0;return()=>{e=false,o?.remove?.()}},[]),e}function Fd(){return Od()==="ios"?"Menlo":qo}function Ad(){return globalThis.__DEV__!==false}var Dd=/* @__PURE__ */new Set;function Md(e){if(!Ad()||Dd.has(e))return;Dd.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 Ld(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||Md(e),l}var Bd=/* @__PURE__ */new Set;function Hd(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 Ud=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Nd(e){if(!Ad())return;let t=Hd(e).filter(e=>!Bd.has(e));if(t.length===0)return;for(let e of t)Bd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Ud[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 $d(e){n(()=>{try{Nd(e)}catch{}},[e])}var Wd=/* @__PURE__ */Object.freeze({useColorScheme:_d,useReducedMotion:Td,useTextScale:Pd,useHighContrast:jd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:Fd,isFontRegistered:Ld,useResolvedTheme:$d,isDevelopment:Ad});function Vd(e){return r(M,null,e)}var qd=/* @__PURE__ */Object.freeze({platform:"react-native",...p.OS==="web"?{}:{eventSourceFactory:xd()},wrap:Vd,theme:Wd});function EverfurProvider(e){return r(EverfurProviderCore,{...e,seams:qd})}function useCapability(e){let{runtime:t}=cd(),r=t.entitlements,n=i(r.subscribe,r.getSnapshot,r.getSnapshot);return a(()=>decideCapability(e,n.decisions,{isPending:n.isPending}),[e,n])}function Gd(e){let{runtime:t}=cd(),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 Kd=/* @__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[Kd[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[Kd[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function Yd(e){return e<=450?"regular":e<=650?"medium":"bold"}var Qd={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=Jd.get(e);r===void 0&&(r=/* @__PURE__ */new Map,Jd.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=Xd(e,t);return r.set(t,l),l}var Jd=/* @__PURE__ */new WeakMap;function Xd(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=Yd(Number(n)),i=r.face==="mono"?face(e,Qd[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 Zd(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=Zd(l.type,e??i?.tier??"content"),a=t===void 0?n:{...n,style:[{...textRole(l,t),color:l.color.text.primary,flexShrink:1},n.style]};return r(S,o===void 0?a:{maxFontSizeMultiplier:o,...a})}var ef=t(function(e,t){return r(g,{...e,...t===null?{}:{ref:t}})});var tf=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(tf,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}var rf=48;function nf(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(()=>nf(o),[o]);switch(s){case"enabled":return r;case"pending":return l?/* @__PURE__ */H(HostRender,{render:l,fallback:/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i})}):/* @__PURE__ */H(PendingSkeleton,{capability:t,style:i});case"disabled":return n?/* @__PURE__ */H(HostRender,{render:()=>n(o),fallback:/* @__PURE__ */H(OffState,{decision:o,style:i}),resetKey:o}):/* @__PURE__ */H(OffState,{decision:o,style:i});default:return assertNever(s)}}function PendingSkeleton({capability:e,style:t}){let r=useEverfurTheme(),n=a(()=>lf(r),[r]);/* @__PURE__ */
|
|
49
|
+
return H(w,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */H(w,{style:n.skeletonBar})})}function OffState({decision:e,style:t}){let r=useEverfurTheme(),n=a(()=>lf(r),[r]),l=e.disabled?.reason??"";/* @__PURE__ */
|
|
50
|
+
return H(w,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:l,children:l.length>0?/* @__PURE__ */H(Text,{style:n.offstateText,children:l}):null})}function lf(e){let{color:t,space:r,radius:n,type:l}=e;return b.create({offstate:{minHeight:rf,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:b.hairlineWidth,borderColor:t.brandBorder},offstateText:{...face(e,"regular"),fontSize:l.size.body,lineHeight:Math.round(l.size.body*l.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}var of=createContext(null);function TelevetHostOutlet(){let e=o(of);return e===null?null:/* @__PURE__ */H(e,{})}var af=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function sf(){let e=globalThis,t=e[af];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[af]=r,r}function uf(e){let t=sf();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function cf(e){let t=sf().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 df(e){let t=sf();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function ff(){return sf().snapshot}function hf(){return sf().hosts.length>0}function pf(e){if(!hf())return false;let t=/* @__PURE__ */Object.freeze({...e});return uf({request:t,serial:sf().snapshot.serial+1}),true}function gf(){sf().snapshot.request!==null&&uf({request:null})}function bf(){let e=sf(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],uf({activeHost:e.hosts[0]??null}),t}function mf(e){let t=sf();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;uf(r===null?{activeHost:r,request:null}:{activeHost:r})}function yf(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 vf(e){let[t,r]=l(null);n(()=>{let e=bf();return r(e),()=>{mf(e)}},[]);let o=i(df,ff,ff),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),gf())}),()=>{t=false}},[c,e]),a===null||s===null?null:{module:s,request:a,serial:o.serial,dismiss:gf}}var kf=yf(()=>Promise.resolve($));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let l=vf(kf);if(l===null)return null;let{EverfurTelevetModal:i}=l.module;/* @__PURE__ */
|
|
51
|
+
return H(i,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var wf="Go to the nearest emergency vet now.";var Cf=/* @__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 Sf(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function xf(e){return e?.trim()||Cf.emptyTitlePetFallback}function _f(e,t){return Sf(e,{petName:xf(t)})}var Rf="tel:+18884264435";var Tf=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function If(e){let t=Tf(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var zf=6;function Pf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function Of(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__ */
|
|
52
|
+
return Object.freeze(n)}function Ef(e){let t=Tf(e.title,80),r=Tf(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function jf(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=If(e);t!==null&&r.length<zf&&r.push(t)}let n=Of(t.doses,e=>{let t=Tf(e.label,60),r=Tf(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:Pf(e.minLb??e.min_lb),maxLb:Pf(e.maxLb??e.max_lb)})},zf),l=Of(t.details,Ef,zf),i=t.fit,o=i!==null&&typeof i=="object"&&!Array.isArray(i)?Ef(i):null,a=o!==null&&i.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,s=/* @__PURE__ */Object.freeze({kicker:Tf(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:l,fine:Tf(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 Ff=128;var Af=/* @__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"]),Df=/* @__PURE__ */new Set(["y","c","g","r"]),Mf=/* @__PURE__ */new Set(["done","now","next"]),Lf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,Bf=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,Hf=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,Uf=e=>typeof e=="string"&&Af.has(e)?e:null;function Nf(e){let t=Bf(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var $f=e=>typeof e=="number"&&Number.isInteger(e)?String(e):Bf(e,Ff);function Wf(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Vf(e){/* @__PURE__ */
|
|
53
|
+
return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function qf(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 Gf=(e,t=12,r=300)=>qf(e,e=>Bf(e,r),t);function Kf(e){let t=Lf(e),r=Bf(t?.kicker,120),n=Bf(t?.title,300);if(t===null||r===null||n===null)return null;let l=Lf(t.risk),i=Lf(t.odds),o=Lf(t.quote),a=Lf(t.jump);return Vf({kicker:r,title:n,sources:qf(t.sources,e=>{let t=Bf(Lf(e)?.label,60);return t===null?null:Vf({label:t,kind:Hf(Lf(e)?.kind)})},6),risk:Bf(l?.lead,300)===null?null:Vf({lead:Bf(l?.lead,300),body:Bf(l?.body),kind:Hf(l?.kind)}),odds:Bf(i?.label,120)===null||Bf(i?.from,20)===null||Bf(i?.to,20)===null?null:Vf({label:Bf(i?.label,120),tag:Bf(i?.tag,40),from:Bf(i?.from,20),to:Bf(i?.to,20),toLabel:Bf(i?.toLabel,120)}),quote:Bf(o?.text)===null?null:Vf({kicker:Bf(o?.kicker,120),tag:Bf(o?.tag,40),text:Bf(o?.text)}),jump:Bf(a?.title,300)===null||Bf(a?.go,60)===null?null:Vf({title:Bf(a?.title,300),go:Bf(a?.go,60)}),report:Yf(t.report)})}function Yf(e){let t=Lf(e),r=Bf(t?.label,120),n=Bf(t?.text,1200);return r===null||n===null?null:Vf({label:r,text:n,actions:Gf(t?.actions,5,300)})}function Qf(e){let t=Lf(e),r=Bf(t?.title,300),n=qf(t?.steps,e=>{let t=Lf(e),r=Bf(t?.title,300),n=t?.tone;return r===null?null:Vf({title:r,body:Bf(t?.body),source:Bf(t?.source,200),tone:typeof n=="string"&&Df.has(n)?n:null,icon:Uf(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:Vf({title:r,label:Bf(t?.label,60),steps:n})}function Jf(e){let t=Lf(e),r=Bf(t?.title,300);if(t===null||r===null)return null;let n=Lf(t.rating),l=Lf(t.reviews),i=Lf(t.why),o=Lf(i?.score),a=Lf(t.dose),s=Lf(t.ingredients),u=qf(l?.items,e=>{let t=Lf(e),r=t?.stars,n=Bf(t?.text),l=Bf(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||l===null?null:Vf({stars:Math.round(r),text:n,by:l})},5),c=qf(i?.rows,e=>{let t=Lf(e),r=Bf(t?.chip,40),n=Bf(t?.title,300);return r===null||n===null?null:Vf({chip:r,kind:Hf(t?.kind),title:n,body:Bf(t?.body)})}),d=qf(a?.stats,e=>{let t=Lf(e),r=Bf(t?.value,40),n=Bf(t?.label,120),l=t?.kind;return r===null||n===null?null:Vf({value:r,label:n,kind:l==="weight"||l==="dose"||l==="days"?l:null})},6),f=Gf(s?.items,12,80);return Vf({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:$f(t.productId),partnerSku:Bf(t.partnerSku,200),rating:Bf(n?.value,20)===null?null:Vf({value:Bf(n?.value,20),label:Bf(n?.label,120)}),line:Bf(t.line),reviews:Bf(l?.label,200)===null||u===null?null:Vf({label:Bf(l?.label,200),items:u}),checkoutLine:Bf(t.checkoutLine,300),why:Bf(i?.title,200)===null||c===null?null:Vf({title:Bf(i?.title,200),rows:c,score:Bf(o?.text,200)===null||Bf(o?.value,20)===null?null:Vf({text:Bf(o?.text,200),value:Bf(o?.value,20)})}),dose:Bf(a?.title,200)===null||d===null?null:Vf({title:Bf(a?.title,200),stats:d,note:Bf(a?.note)}),doseLabel:Bf(t.doseLabel,120),ingredients:f===null?null:Vf({label:Bf(s?.label,200),items:f}),proof:Bf(t.proof,300),trust:qf(t.trust,e=>{let t=Lf(e),r=Uf(t?.icon),n=Bf(t?.label,120);return r===null||n===null?null:Vf({icon:r,label:n})},6),more:Bf(t.more,120),fine:Bf(t.fine),checkin:Bf(t.checkin,200),detail:jf(t.detail)??null})}function Xf(e){let t=Lf(e),r=Bf(t?.title,200),n=qf(t?.items,e=>{let t=Lf(e),r=Bf(t?.title,300),n=Bf(t?.body);return r===null||n===null?null:Vf({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:Vf({title:r,items:n})}function Zf(e){let t=Lf(e),r=Bf(t?.title,200),n=Gf(t?.questions,12,300),l=Bf(t?.add,80),i=Bf(t?.added,80);return r===null||n===null||l===null||i===null?null:Vf({title:r,questions:n,add:l,added:i})}function eh(e){let t=Lf(e),r=Bf(t?.title,200),n=qf(t?.items,e=>{let t=Lf(e),r=Bf(t?.key,Ff),n=Bf(t?.title,300),l=Bf(t?.action,80),i=$f(t?.productId),o=Bf(t?.added,80)??(i!==null?l:null);return r===null||n===null||l===null||o===null?null:Vf({key:r,productId:i,title:n,body:Bf(t?.body),price:Bf(t?.price,40),was:Bf(t?.was,40),tag:Bf(t?.tag,40),imageUrl:Nf(t?.imageUrl),icon:Uf(t?.icon),kind:Hf(t?.kind),action:l,added:o,owned:t?.owned===true?true:null,detail:jf(t?.detail)??null})},6);return r===null||n===null?null:Vf({title:r,items:n})}function th(e){let t=Lf(e),r=Bf(t?.kicker,120),n=Bf(t?.title,120);return t===null||r===null||n===null?null:Vf({kicker:r,title:n,icon:Uf(t.icon),track:qf(t.track,e=>{let t=Lf(e),r=Bf(t?.title,120),n=t?.state;return r===null?null:Vf({title:r,detail:Bf(t?.detail,120),state:typeof n=="string"&&Mf.has(n)?n:null,tag:Bf(t?.tag,40)})},6),heading:Bf(t.heading,200),rows:qf(t.rows,e=>{let t=Lf(e),r=Uf(t?.icon),n=Bf(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return Vf({icon:r,label:n,text:"",fromVet:true});let l=Bf(t?.text,300);return l===null?null:Vf({icon:r,label:n,text:l})},6),note:Bf(t.note,300),action:Bf(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=Lf(e),r=Bf(t?.title,300),n=Jf(t?.pick);if(t===null||r===null||n===null)return null;let l=Lf(t.byline);return Vf({eyebrow:Bf(t.eyebrow,120),title:r,subtitle:Bf(t.subtitle,300),subtitleNoRecords:Bf(t.subtitleNoRecords,300),headImageUrl:Nf(t.headImageUrl),byline:Bf(l?.name,120)===null?null:Vf({name:Bf(l?.name,120),role:Bf(l?.role,120),imageUrl:Nf(l?.imageUrl),shortName:Bf(l?.shortName,60)}),focus:Kf(t.focus),routine:Qf(t.routine),pick:n,signs:Xf(t.signs),checkup:Zf(t.checkup),extras:eh(t.extras),wait:th(t.wait),fine:Bf(t.fine),checkoutRows:qf(t.checkoutRows,e=>{let t=Lf(e),r=Uf(t?.icon),n=Bf(t?.label,60),l=Bf(t?.value,200);return r===null||n===null||l===null?null:Vf({icon:r,label:n,value:l})},6)})}function healthPlanPageFromWire(e,t){let r=Lf(e);if(r===null||!("page"in r))return null;let n=Lf(r.pet),l=n?.sex;/* @__PURE__ */
|
|
54
|
+
return Object.freeze({petRef:Bf(r.pet_ref,Ff)??t,pet:/* @__PURE__ */Object.freeze({name:Bf(n?.name,120),species:Bf(n?.species,60),sex:l==="female"||l==="male"?l:null,breed:Bf(n?.breed,120),weightKg:Wf(n?.weight_kg),weightLb:Wf(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 rh(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function nh(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function lh(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<=Ff;function oh(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function ah(e,t,r){if(!ih(t))return err(rh("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${oh(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let l=healthPlanPageFromWire(n.value,t);return l===null?err(nh("healthPlan.page.read")):ok(l)}var sh=/* @__PURE__ */new WeakMap;function uh(e){let t=sh.get(e);if(t!==void 0)return t;let r=ch(e);return sh.set(e,r),r}function ch(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(lh("getPage")));let{services:n}=e.registry,l=od(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return ah(l,t,r)}}}function dh(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function fh(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function hh(e,...t){if(typeof e=="function")try{let r=e(...t);return fh(r)&&Promise.resolve(r).then(void 0,dh),r}catch(e){dh(e);return}}var ph=/* @__PURE__ */new WeakMap;function gh(e){if(typeof e!="function")return;let t=ph.get(e);if(t!==void 0)return t;let r=(...t)=>{hh(e,...t)};return ph.set(e,r),r}function bh(e,...t){let r;try{r=e(...t)}catch(e){return dh(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var mh=6e4;function yh({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=hh(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=a.current;e!==null&&r()-e>=mh&&t()}));return()=>{typeof t=="function"&&hh(t)}},[e]);let s=u(t);n(()=>{Object.is(s.current,t)||(s.current=t,a.current.refresh())},[t])}var vh=mh,kh=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function wh(){let e=globalThis,t=e[kh];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[kh]=r,r}function Ch(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<vh))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(a.get(s)===c&&(e.ok||nd(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}=cd(),i=a(()=>uh(r),[r]),o=e.repository,c=o??i,d=s((e,n)=>o!==void 0||t==null?c.getPage(e):Ch(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()}):nd(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]);yh({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 Sh=/* @__PURE__ */Object.freeze({branding:null}),xh=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>Sh});function _h(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function Rh(e){let{runtime:t}=cd(),r=t?.entitlements??xh,n=s(()=>r.getSnapshot()?.branding??null,[r]),l=bd(i(r.subscribe,n,n),t?.sdkConfigHost?.branding),o=_h(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 Th(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function Ih(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function zh(e){let t=ut(e);return t===null?null:{reached:Cf.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function Ph(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function Oh(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=Ph(r),n=t==="web",l=zh(r);return{tone:"error",title:l!==null?l.reached:e?Cf.turnUnreachableTitle:n?Cf.turnFailedTitleWeb:Cf.turnFailedTitle,body:r.displayMessage,actionLabel:e?Cf.turnStartNewChat:n?Cf.retry:Cf.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:Cf.turnStoppedTitle,body:Cf.turnStoppedBody,actionLabel:Cf.turnRetry,action:"retry"}:null}function Eh(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var jh=3,Fh=/* @__PURE__ */Object.freeze([]);function Ah(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Fh;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===jh))break}/* @__PURE__ */
|
|
55
|
+
return Object.freeze(n)}var Dh=5;function Mh(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 Lh(e,t){if(t===void 0)return Ah(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return Fh;let n=Math.max(1,Math.min(Dh,Math.floor(t.count??jh))),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)||Mh(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__ */
|
|
56
|
+
return Object.freeze(a)}function Bh(e){return e.sender?.displayName??Cf.senderVet}function Hh(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var Uh=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 Nh(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 $h(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===jh&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>Uh.test(e)||Nh(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var Wh="pet_not_registered";function Vh(e){return e!=null&&e.reasonCode===Wh}var qh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function Gh(e,t,r){let{runtime:i,userRef:o,scopeEpoch:c}=cd(),d=s((e,t)=>{let r=i.registry.services.authFor(o);return ji(Ei(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,o,c]),f=a(()=>t===void 0?null:Fi(t),[t]),[h,p]=l({key:null,status:"idle",error:null,registered:null}),g=u(0),b=u(r);b.current=r;let m=e===null||f===null?null:`${String(o)}|${c}|${e}|${f}`,y=s(()=>{if(e===null||t===void 0||m===null)return;let r=++g.current;p({key:m,status:"registering",error:null,registered:null}),d(e,t).then(e=>{r===g.current&&(e.ok?(p({key:m,status:"registered",error:null,registered:e.value}),b.current?.()):p({key:m,status:"failed",error:e.error,registered:null}))})},[d,e,m]);n(()=>{if(m===null){g.current+=1;return}return y(),()=>{g.current+=1}},[m,y]);let v=s(()=>{h.status==="failed"&&y()},[h.status,y]);return a(()=>m===null?qh: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 Kh=/* @__PURE__ */Object.freeze({});function Yh(e){let[t,r]=l(Kh),i=u(null),o=u([]);o.current=e.map(e=>e.id),n(()=>{if(e.length===0){i.current=null,r(e=>e===Kh?e:Kh);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 Qh=/* @__PURE__ */new WeakSet;function Jh(){let e=makeEverfurError("internalError",{retryable:true});return Qh.add(e),err(e)}function Xh(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&Qh.has(t)}var Zh=500;function ep(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,Zh):null}function tp(e,t,r,l){let i=ep(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),!Xh(e)&&d.current===o&&(s.current=o)};Promise.resolve(e(i)).then(r,()=>r(void 0))},[i,o,t,e])}var rp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),np=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),lp=/* @__PURE__ */Object.freeze({...rp,markRead:true}),ip=/* @__PURE__ */Object.freeze({...np,markRead:true});function op(e,t){return e?t?lp:rp:t?ip:np}function ap(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:hh(()=>r()!==!1)===true}function sp(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 up=3e5;function cp(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 dp(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:hh(()=>e.isOffline?.()===!0)===true,h=f(),p=u(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:u}=l.current,h=Nr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:u===true,isOffline:f(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,cp(e)?(s.current=Math.min(s.current===0?d.current*2:s.current*2,up),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=hh(()=>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)hh(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||ap(e,b)&&p.current("poll")},g);return()=>clearInterval(t)},[e,g,b])}var fp=/^efch_[A-Za-z0-9_-]{43}$/,hp="efch";function pp(e){return typeof e=="string"&&fp.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(`${hp}=`))continue;let e=r.slice(hp.length+1);return pp(e)?e:null}return null}var gp=128,bp=/[\u0000-\u001f\u007f]/;function mp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function yp(e){return typeof e!="string"||e.length===0||e.length>gp||bp.test(e)||e.includes("://")?null:e}function vp(e){if(e===null)return null;let t=e.conversation_id,r=yp(e.pet_ref);return typeof t!="string"||!Tn(t)||r===null?null:{conversationId:t,petRef:r}}function kp(e,t,r){return pp(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(vp(mp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(en("internalError",false))):Promise.resolve(ok(null))}function wp(e,t){let r=t?.runtime??null,i=t?.userRef??null,o=pp(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 kp(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 Cp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function Sp(e,t,r){let l=Cp(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 xp=/* @__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 _p(e){let t=e?.replace(/\s+/g," ").trim();return t||xp.untitled}function Rp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function Tp(e){let t=Rp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?xp.newReply.replace("{date}",t):t}function Ip(e,t){return t?`${xp.countLabel}${xp.countSeparator}${e}`:xp.countLabel}function zp(e){return`${e.unreadCount!==null&&e.unreadCount>0?xp.unreadPrefix:""}${xp.openConversation} ${_p(e.title)}`}function Pp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function Op(e,t){let r=Pp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=Pp(_p(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 Ep(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function jp(e){let[t,r]=l(false),[i,o]=l(""),c=e.listConversations,d=u(0),[f,h]=l(()=>Ep(c)),p=f.scope===c?f:Ep(c);n(()=>(d.current+=1,r(false),o(""),h(Ep(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(()=>Op(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 Fp="#111111",Ap="#FFFFFF",Dp=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Fp,pillColor:Ap,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Fp,pillColor:Ap,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Fp,pillColor:Ap,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Fp,pillColor:Ap,showsVetAction:false})});function Mp(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function Lp(e){return Sf(Cf.urgencyGeneralReason,{petName:e?.trim()||Cf.emptyTitlePetFallback})}function Bp(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:Hp(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Lp(t)}:null}return null}function Hp(e){return typeof e=="string"&&e.trim().length>0?e:null}function Up(e){let t=e===null?null:Mp(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:Dp[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:Sf(Cf.dismissBanner,{label:d.label}),dismiss:h,expand:p}),[e,d,t,c,f,h,p])}var Np="everfur.com",$p=2048,Wp=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Vp(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&&Wp.test(e)&&t.add(e)}/* @__PURE__ */
|
|
57
|
+
return Object.freeze([...t])}function qp(e,t){if(e===Np||e.endsWith(`.${Np}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function Gp(e,t){if(typeof e!="string"||e.length===0||e.length>$p||!/^https:\/\//i.test(e))return null;let r=ke(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:qp(r.hostname,t)?r.href:null}function Kp(e){try{Promise.resolve(x.openURL(e)).catch(()=>{})}catch{}}var Yp=createContext(null);function Qp(){return o(Yp)??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=Vp(l===""?[]:l.split(`\n`));/* @__PURE__ */
|
|
58
|
+
return Object.freeze({hosts:e,open:t!==void 0?e=>{hh(t,e,"message")}:Kp})},[l,t]);return r(Yp.Provider,{value:i},n)}var Jp={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function Xp(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function Zp(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r),l={width:e*.82,height:n,borderRadius:n,backgroundColor:t};/* @__PURE__ */
|
|
59
|
+
return U(w,{style:[Xp(e),{gap:e*.22}],...Jp,children:[
|
|
60
60
|
/* @__PURE__ */H(w,{style:l}),
|
|
61
61
|
/* @__PURE__ */H(w,{style:l}),
|
|
62
|
-
/* @__PURE__ */H(w,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=
|
|
63
|
-
return U(w,{style:[
|
|
62
|
+
/* @__PURE__ */H(w,{style:l})]})}function Cross({size:e,color:t,strokeWidth:r,rotate:n}){let l=Zp(e,r),i=e*.78;/* @__PURE__ */
|
|
63
|
+
return U(w,{style:[Xp(e),{transform:[{rotate:n}]}],...Jp,children:[
|
|
64
64
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:i,height:l,borderRadius:l,backgroundColor:t}}),
|
|
65
65
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:l,height:i,borderRadius:l,backgroundColor:t}})]})}function PlusGlyph(e){/* @__PURE__ */
|
|
66
66
|
return H(Cross,{...e,rotate:"0deg"})}function CloseGlyph(e){/* @__PURE__ */
|
|
67
|
-
return H(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
68
|
-
return H(w,{style:
|
|
69
|
-
return H(w,{style:
|
|
70
|
-
return U(w,{style:[
|
|
67
|
+
return H(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r);/* @__PURE__ */
|
|
68
|
+
return H(w,{style:Xp(e),...Jp,children:/* @__PURE__ */H(w,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}var eg={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=Zp(e,r),i=e*.46,o=eg[n];/* @__PURE__ */
|
|
69
|
+
return H(w,{style:Xp(e),...Jp,children:/* @__PURE__ */H(w,{style:{width:i,height:i,borderRightWidth:l,borderBottomWidth:l,borderColor:t,marginTop:i*o.marginTop,marginLeft:i*o.marginLeft,transform:[{rotate:o.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r),l={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};/* @__PURE__ */
|
|
70
|
+
return U(w,{style:[Xp(e),{flexDirection:"row",gap:1}],...Jp,children:[
|
|
71
71
|
/* @__PURE__ */H(w,{style:[l,{borderTopLeftRadius:e*.2}]}),
|
|
72
|
-
/* @__PURE__ */H(w,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
73
|
-
return U(w,{style:
|
|
72
|
+
/* @__PURE__ */H(w,{style:[l,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r),l=e*.5;/* @__PURE__ */
|
|
73
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
74
74
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),
|
|
75
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
76
|
-
return U(w,{style:
|
|
75
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,right:e*.16,width:l,height:l,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r),l=e*.6,i={position:"absolute",width:l,height:l,borderWidth:n,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
|
|
76
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
77
77
|
/* @__PURE__ */H(w,{style:[i,{top:0,left:0}]}),
|
|
78
|
-
/* @__PURE__ */H(w,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=
|
|
79
|
-
return U(w,{style:[
|
|
78
|
+
/* @__PURE__ */H(w,{style:[i,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:r,active:n,rotate:l}){let i=Zp(e,r),o=n?t:"transparent";/* @__PURE__ */
|
|
79
|
+
return U(w,{style:[Xp(e),{transform:[{rotate:l}]}],...Jp,children:[
|
|
80
80
|
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),
|
|
81
81
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),
|
|
82
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
83
|
-
return U(w,{style:[
|
|
82
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:i,borderColor:t,backgroundColor:o,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r);/* @__PURE__ */
|
|
83
|
+
return U(w,{style:[Xp(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...Jp,children:[
|
|
84
84
|
/* @__PURE__ */H(w,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),
|
|
85
|
-
/* @__PURE__ */H(w,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
86
|
-
return U(w,{style:
|
|
85
|
+
/* @__PURE__ */H(w,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r),l=e*.34;/* @__PURE__ */
|
|
86
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
87
87
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.06,width:l,height:l,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),
|
|
88
88
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),
|
|
89
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
90
|
-
return U(w,{style:[
|
|
89
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r);/* @__PURE__ */
|
|
90
|
+
return U(w,{style:[Xp(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...Jp,children:[
|
|
91
91
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),
|
|
92
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
93
|
-
return U(w,{style:
|
|
92
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r);/* @__PURE__ */
|
|
93
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
94
94
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),
|
|
95
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */H(w,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
96
|
-
return U(w,{style:
|
|
95
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */H(w,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(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__ */
|
|
96
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
97
97
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:o,left:o,width:i,height:i,borderRadius:i,borderWidth:n,borderColor:t}}),
|
|
98
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
99
|
-
return U(w,{style:
|
|
98
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:u-n/2,left:u-(s+n)/2,width:s+n,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r);/* @__PURE__ */
|
|
99
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
100
100
|
/* @__PURE__ */H(w,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:n,borderColor:t,borderRadius:n,transform:[{rotate:"45deg"}]}}),
|
|
101
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
102
|
-
return U(w,{style:
|
|
101
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:n,borderRadius:n,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r),l=e*.62;/* @__PURE__ */
|
|
102
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
103
103
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:0,width:l,height:l,borderRadius:l,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */H(w,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),
|
|
104
104
|
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.04,width:l*.5,height:l*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:e,color:t,testID:r}){let n=e*.36;/* @__PURE__ */
|
|
105
|
-
return H(w,{style:
|
|
106
|
-
return H(w,{style:
|
|
107
|
-
return U(w,{style:
|
|
105
|
+
return H(w,{style:Xp(e),testID:r,...Jp,children:/* @__PURE__ */H(w,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:r}){/* @__PURE__ */
|
|
106
|
+
return H(w,{style:Xp(e),testID:r,...Jp,children:/* @__PURE__ */H(w,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=Zp(e,r);/* @__PURE__ */
|
|
107
|
+
return U(w,{style:Xp(e),testID:n,...Jp,children:[
|
|
108
108
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.08,width:e*.26,height:e*.48,borderWidth:l,borderColor:t,borderRadius:e*.13}}),
|
|
109
109
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.38,width:e*.56,height:e*.36,borderBottomWidth:l,borderLeftWidth:l,borderRightWidth:l,borderColor:t,borderBottomLeftRadius:e*.28,borderBottomRightRadius:e*.28}}),
|
|
110
110
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.74,width:l,height:e*.18,backgroundColor:t}})]})}function Ring({size:e,strokeWidth:t,color:r,children:n}){/* @__PURE__ */
|
|
111
|
-
return H(w,{style:[
|
|
112
|
-
return U(w,{style:
|
|
111
|
+
return H(w,{style:[Xp(e),{borderRadius:e/2,borderWidth:t??b.hairlineWidth,borderColor:r}],children:n})}function ArrowUpGlyph({size:e,color:t,strokeWidth:r,testID:n}){let l=Zp(e,r),i=e*.46;/* @__PURE__ */
|
|
112
|
+
return U(w,{style:Xp(e),testID:n,...Jp,children:[
|
|
113
113
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,bottom:e*.12,width:l,borderRadius:l,backgroundColor:t}}),
|
|
114
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
115
|
-
return U(w,{style:
|
|
114
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16+l/2,width:i,height:i,borderLeftWidth:l,borderTopWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r);/* @__PURE__ */
|
|
115
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
116
116
|
/* @__PURE__ */H(w,{style:{width:e*.8,height:e*.6,marginTop:-e*.12,borderWidth:n,borderColor:t,borderRadius:e*.14}}),
|
|
117
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=
|
|
118
|
-
return U(w,{style:
|
|
117
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:r}){let n=Zp(e,r),l=e*.72,i=e/2;/* @__PURE__ */
|
|
118
|
+
return U(w,{style:Xp(e),...Jp,children:[
|
|
119
119
|
/* @__PURE__ */H(w,{style:{width:l,height:l,borderRadius:l/2,borderWidth:n,borderColor:t,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
|
|
120
120
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:e*.16,left:e*.12,width:e*.2,height:e*.2,borderLeftWidth:n,borderBottomWidth:n,borderColor:t}}),
|
|
121
121
|
/* @__PURE__ */H(w,{style:{position:"absolute",top:i-e*.2,left:i-n/2,width:n,height:e*.2+n/2,borderRadius:n,backgroundColor:t}}),
|
|
122
|
-
/* @__PURE__ */H(w,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var
|
|
123
|
-
return H(R,{...o,hitSlop:i??
|
|
124
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
125
|
-
/* @__PURE__ */H(w,{pointerEvents:"box-none",style:[
|
|
122
|
+
/* @__PURE__ */H(w,{style:{position:"absolute",top:i-n/2,left:i-n/2,width:e*.15+n/2,height:n,borderRadius:n,backgroundColor:t}})]})}var tg=/* @__PURE__ */Object.freeze({standard:Xo.standard,emphasized:Xo.emphasized,exit:Xo.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var rg=/* @__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}),ng=/* @__PURE__ */Object.freeze({...rg,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 lg(e){return e.motion.reducedMotion?ng:rg}function ig(e,t){return Math.max(0,t)*e.followUpStaggerMs}function og(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 ag(){let e=useEverfurTheme();return lg(e)}var sg=8;function ug(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function cg(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function dg(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<sg;r+=1){let r=cg(i,t,n);if(r===0)break;i-=(ug(i,t,n)-e)/r}return ug(Math.min(1,Math.max(0,i)),r,l)}}var fg=dg(tg.standard),hg=dg(tg.outQuad),pg=dg(tg.out);function gg(e){let t=u(null);return t.current===null&&(t.current=new F.Value(e)),t.current}function bg(e,t={}){let r=t.risePx??0,l=t.delayMs??0,i=gg(e>0?0:1);return n(()=>{if(e<=0){i.setValue(1);return}let t=F.timing(i,{toValue:1,duration:e,easing:hg,useNativeDriver:true}),r=l>0?F.sequence([F.delay(l),t]):t;return r.start(),()=>r.stop()},[i,e,l]),a(()=>({opacity:i,transform:[{translateY:i.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[i,r])}function FadePresence({visible:e,inMs:t,outMs:r,style:i,children:o}){let[a,s]=l(e),u=gg(e&&t<=0?1:0);return n(()=>{if(e){s(true);let e=F.timing(u,{toValue:1,duration:Math.max(0,t),easing:fg,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(r<=0){s(false);return}let n=F.timing(u,{toValue:0,duration:r,easing:fg,useNativeDriver:true});return n.start(({finished:e})=>{e&&s(false)}),()=>n.stop()},[e,a,t,r,u]),!a&&!e?null:/* @__PURE__ */H(F.View,{style:[i,{opacity:u}],children:o})}var mg=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function yg(e,t){let[r]=l(()=>e?t.bubbleInMs:0),i=r>0,o=gg(i?0:1);n(()=>{if(r<=0)return;let e=F.timing(o,{toValue:1,duration:r,easing:pg,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]})}]}:mg,[i,o,u,s])}function vg(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 kg=12;function PressScale({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:l,hitSlop:i,...o}){let a=ag(),u=gg(1),c=s(e=>{a.pressMs<=0||a.pressScale===1||F.timing(u,{toValue:e,duration:a.pressMs,easing:fg,useNativeDriver:true}).start()},[u,a.pressMs,a.pressScale]);/* @__PURE__ */
|
|
123
|
+
return H(R,{...o,hitSlop:i??kg,style:t,onPressIn:e=>{c(a.pressScale),n?.(e)},onPressOut:e=>{c(1),l?.(e)},children:/* @__PURE__ */H(F.View,{style:[e,{transform:[{scale:u}]}],children:r})})}function wg(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=>og(r,e,s.current.length))},r.revealTickMs);return()=>clearInterval(e)},[i,r]),i?e.slice(0,Math.min(o,e.length)):e}var Cg=false;function Sg(e){e.layoutMs<=0||(Cg||(Cg=true,p.OS==="android"&&typeof E.setLayoutAnimationEnabledExperimental=="function"&&E.setLayoutAnimationEnabledExperimental(true)),j.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function xg(e,t){let r=u(e);r.current!==e&&(r.current=e,Sg(t))}var _g=36,Rg=22,Tg=12,Ig=12,zg=16,Pg="#000",Og="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:r}){let n=useEverfurTheme(),l=L();return e===null?null:/* @__PURE__ */U(I,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[
|
|
124
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Cf.closePreview,style:Eg.backdrop,onPress:r,children:/* @__PURE__ */H(O,{source:{uri:e},style:Eg.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
|
|
125
|
+
/* @__PURE__ */H(w,{pointerEvents:"box-none",style:[Eg.closeWrap,{top:l.top+Ig}],children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf.closePreview,hitSlop:Tg,style:Eg.closeButton,onPress:r,children:/* @__PURE__ */H(CloseGlyph,{size:Rg,color:n.color.surface,strokeWidth:2})})})]})}var Eg=b.create({backdrop:{flex:1,backgroundColor:Pg,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:zg},closeButton:{width:_g,height:_g,borderRadius:_g/2,backgroundColor:Og,alignItems:"center",justifyContent:"center"}});var jg=()=>{};function Fg(){try{return C.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let r=C.currentState==="background";t=C.addEventListener("change",t=>{t==="background"?r=!0:t==="active"&&r&&(r=!1,e())})}catch{return jg}return()=>t.remove()},isVisible:Fg}}function Ag(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 Dg(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function Mg(e){return e?.textColor===void 0?{}:{color:e.textColor}}function Lg(e){switch(e.code){case"too_large":return Sf(Cf.attachmentTooLarge,{max:formatBytes(al),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return Sf(Cf.attachmentTooMany,{max:sl});case"unsupported_type":return Sf(Cf.attachmentUnsupported,{filename:e.filename});case"network":return Cf.attachmentNetwork;case"server":return Sf(Cf.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case"cancelled":return Cf.attachmentCancelled;case"rate_limited":return Cf.attachmentRateLimited;case"quota_exceeded":return Cf.attachmentQuota;case"idempotency_conflict":return Cf.attachmentConflict;case"unknown":return Cf.attachmentUnknown}}function Bg(e,t){return Sf(e>=t?Cf.attachmentsFull:Cf.addAttachment,{used:e,total:t})}var Hg=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:t,userRef:r,scopeEpoch:o}=cd(),c=e.maxPerMessage??sl,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,()=>Hg),[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 Ug=6e3;function Ng(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 $g(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 Wg(e){switch(e){case"permissionDenied":return Cf.micBlocked;case"noSpeech":return Cf.noSpeech;case"unavailable":return Cf.dictationUnavailable}}function Vg(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var qg=["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 Gg(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...qg]){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 Kg(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 Yg(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 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||c!==`${t??""}`||hh(()=>e.write(t,r))},[e,t,r,c,o])}function Qg(e){if(!(p.OS!=="ios"||e===""))try{let t=m?.announceForAccessibility;typeof t=="function"&&t.call(m,e)}catch{}}function AnnounceLine({line:e}){return n(()=>{Qg(e)},[e]),null}var Jg=12,Xg=80,Zg=44,eb=22,tb=.14,rb=18,nb=8,lb=/* @__PURE__ */Object.freeze({photo:Cf.attachmentPhoto,camera:Cf.attachmentCamera});function AttachmentPickerPopover({sources:e,full:t,onPick:r,onClose:n}){let l=useEverfurTheme(),i=a(()=>ib(l),[l]);/* @__PURE__ */
|
|
126
126
|
return U(w,{style:i.anchor,pointerEvents:"box-none",children:[
|
|
127
|
-
/* @__PURE__ */H(R,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:
|
|
127
|
+
/* @__PURE__ */H(R,{style:i.dismissLayer,accessibilityRole:"button",accessibilityLabel:Cf.closeAttachmentPicker,onPress:n}),
|
|
128
128
|
/* @__PURE__ */U(w,{style:i.bubble,children:[
|
|
129
|
-
/* @__PURE__ */H(w,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
130
|
-
/* @__PURE__ */H(w,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */H(PhotoGlyph,{size:
|
|
131
|
-
/* @__PURE__ */H(Text,{tier:"control",style:i.tileLabel,children:
|
|
129
|
+
/* @__PURE__ */H(w,{style:i.tilesRow,children:e.map(e=>/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:lb[e],accessibilityState:{disabled:t},disabled:t,containerStyle:i.tile,style:i.tileInner,onPress:()=>r(e),children:[
|
|
130
|
+
/* @__PURE__ */H(w,{style:i.tileIconWrap,children:e==="photo"?/* @__PURE__ */H(PhotoGlyph,{size:eb,color:l.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */H(CameraGlyph,{size:eb,color:l.color.brandInk,strokeWidth:1.5})}),
|
|
131
|
+
/* @__PURE__ */H(Text,{tier:"control",style:i.tileLabel,children:lb[e]})]},e))}),
|
|
132
132
|
/* @__PURE__ */H(w,{style:i.tail}),
|
|
133
|
-
/* @__PURE__ */H(w,{style:i.tailFill})]})]})}function
|
|
134
|
-
/* @__PURE__ */H(R,{accessibilityRole:d?"button":"image",accessibilityLabel:d?Cf
|
|
135
|
-
/* @__PURE__ */H(O,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */H(w,{style:t.uploadingOverlay,children:/* @__PURE__ */H(P,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */H(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Cf
|
|
136
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf
|
|
137
|
-
return H(w,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Cf
|
|
138
|
-
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(
|
|
139
|
-
/* @__PURE__ */H(R,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?
|
|
133
|
+
/* @__PURE__ */H(w,{style:i.tailFill})]})]})}function ib(e){let t=e.color,r=e.radius;return b.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:tb,shadowRadius:rb,shadowOffset:{width:0,height:nb},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:Xg,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Zg,height:Zg,borderRadius:Zg/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:-Jg/2,width:Jg,height:Jg,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Jg+4,height:2,backgroundColor:t.surfaceCream}})}var ob=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var ab=56,sb=12,ub=14,cb=10,db=.45,fb="rgba(7,193,104,0.55)",hb="rgba(185,28,28,0.55)",pb=200,gb=300,bb=20,mb=22,yb=12,vb="rgba(0,0,0,0.78)",kb=220,wb=100,Cb="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(()=>Sb(s),[s]);return e.length===0&&t===null?null:/* @__PURE__ */U(w,{style:[u.strip,o],children:[e.length>0?/* @__PURE__ */H(w,{style:u.cards,children:e.map(e=>/* @__PURE__ */H(PreviewCard,{row:e,styles:u,onRetry:n,onRemove:l,onPreview:i},e.id))}):null,r?/* @__PURE__ */H(Text,{style:u.rejected,accessibilityRole:"alert",children:Cf.attachmentsFailedBlocked}):null,t!==null?/* @__PURE__ */H(Text,{style:u.rejected,accessibilityRole:"alert",children:Lg(t)}):null]})}function PreviewCard({row:e,styles:t,onRetry:r,onRemove:i,onPreview:o}){let a=useEverfurTheme(),s=e.status==="uploading",c=e.status==="failed",d=e.status==="uploaded",f=u(e.status),[h,p]=l(false);return n(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */U(w,{style:t.card,children:[
|
|
134
|
+
/* @__PURE__ */H(R,{accessibilityRole:d?"button":"image",accessibilityLabel:d?Sf(Cf.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:s,disabled:!d},disabled:!d,style:t.thumbHit,onPress:()=>o(e),children:/* @__PURE__ */U(w,{style:t.thumb,children:[
|
|
135
|
+
/* @__PURE__ */H(O,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),s?/* @__PURE__ */H(w,{style:t.uploadingOverlay,children:/* @__PURE__ */H(P,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */H(SuccessFlash,{styles:t,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Sf(Cf.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:/* @__PURE__ */H(w,{style:t.failedInner,children:/* @__PURE__ */H(CloseGlyph,{size:bb,color:a.color.surface,strokeWidth:2})})}):null,
|
|
136
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Sf(Cf.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>i(e.id),children:/* @__PURE__ */H(CloseGlyph,{size:yb,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:t}){let r=useEverfurTheme(),l=ag(),i=u(null);i.current===null&&(i.current=new F.Value(0));let o=i.current;return n(()=>{let e=F.sequence([F.timing(o,{toValue:1,duration:pb,useNativeDriver:true}),F.delay(l.uploadFlashMs),F.timing(o,{toValue:0,duration:gb,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&t()}),()=>e.stop()},[o,l.uploadFlashMs,t]),/* @__PURE__ */H(F.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:o}],children:/* @__PURE__ */H(CheckGlyph,{size:bb,color:r.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:t}){let r=useEverfurTheme(),n=a(()=>Sb(r),[r]);if(e.length===0)return null;let l=e.length===1;/* @__PURE__ */
|
|
137
|
+
return H(w,{style:l?n.sentSingle:n.sentGrid,children:e.map((e,r)=>/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Sf(Cf.attachedImage,{filename:e.filename}),onPress:()=>t(e),children:/* @__PURE__ */H(O,{source:{uri:e.uri},style:l?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${r}`))})}function Sb(e){let t=e.color,r=e.type;return b.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:ab,height:ab,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:sb,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:b.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...ob,alignItems:"center",justifyContent:"center",backgroundColor:oo(e.color.brandInk,db)??e.color.brandSofter},successOverlay:{...ob,alignItems:"center",justifyContent:"center",backgroundColor:fb},failedOverlay:{...ob,borderRadius:sb,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:hb},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:mb,height:mb,borderRadius:mb/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:kb,height:kb,borderRadius:ub,backgroundColor:Cb},gridImage:{width:wb,height:wb,borderRadius:cb,backgroundColor:Cb}})}var xb="chat attachment upload: the file handle has no uri",_b="chat attachment upload failed";function Rb(e){return{uri:e.uri,name:sanitizeFilename(e.name),type:e.mimeType}}function createRnChatAttachmentTransport(e={}){/* @__PURE__ */
|
|
138
|
+
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(xb));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(_b));return l?.aborted===true?o():je({url:t.upload_url,fields:t.upload_fields,file:Rb(r),signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}var Tb=300,Ib=3e3,zb=120,Pb=44,Ob=120,Eb="88%",jb=520,Fb=2,Ab=.5,Db=1.5,Mb=1.6,Lb=.6,Bb=56,Hb=1.5,Ub=5,Nb=5,$b=36,Wb=20,Vb=14,qb=Pb,Gb=4,Kb=24,Yb=22,Qb=.4,Jb=Pb,Xb=20,Zb=.4,em=480,tm=12,rm=.72,nm=48,lm=1.5,im=1.3,om=1,am=1,sm="12%",um=14,cm=16,dm=28,fm=18,hm="84%",pm=10,gm=15,bm=1.42,mm=4,ym=3,vm=14,km=20;function wm(){let e=useEverfurTheme(),t=a(()=>Cm(e),[e]);return{theme:e,styles:t}}function Cm(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=Math.round(l.size.body*Db),o=Math.round(l.size.body*Mb),a=Math.round(Wb*l.size.body/Vb),s=t.borderRingCream,u=e.slots;return b.create({container:{flex:1,minHeight:zb,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:zb,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:sm,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:em,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:Pb,minWidth:Pb,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...Ag(u.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,...Mg(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:am,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:Pb,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:ym,minHeight:vm},readingDotInline:{width:mm,height:mm,borderRadius:n.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:Pb,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:um,paddingHorizontal:cm,paddingBottom:dm,gap:fm},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:Eb,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:jb,paddingVertical:r.md,paddingHorizontal:r.lg+Fb,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:Ab,borderColor:t.primaryEdge}:{},borderRadius:n.lg,borderBottomRightRadius:n.xs,...Ag(u.userBubble,Ab)},bubbleAssistant:u.assistantBubble?.backgroundColor===void 0?{...Ag(u.assistantBubble,Ab)}:{paddingVertical:r.md,paddingHorizontal:r.lg+Fb,borderRadius:n.lg,...Ag(u.assistantBubble,Ab)},bubbleVet:{maxWidth:jb,paddingVertical:r.md,paddingHorizontal:r.lg+Fb,backgroundColor:t.bubbleVet,borderRadius:n.lg,borderTopLeftRadius:n.xs,...Ag(u.vetBubble,Ab)},bubbleCards:{maxWidth:hm},bubbleUserCards:{paddingVertical:pm,paddingHorizontal:gm},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*bm)},bubblePending:{opacity:Lb},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:l.size.body,lineHeight:i,...Mg(u.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:o,...Mg(u.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:l.size.body,lineHeight:i,...Mg(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:km,height:km,borderRadius:km/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:rm,paddingBottom:r.sm,borderBottomWidth:om,borderBottomColor:s},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:om,borderTopColor:s},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,minHeight:nm,paddingVertical:r.sm+Fb,...u.chip?.backgroundColor!==void 0||u.chip?.borderColor!==void 0?{paddingHorizontal:r.md}:{},...Ag(u.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:l.size.bodyTight,...Mg(u.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,marginTop:r.md},askChip:{minHeight:Pb,maxWidth:"100%",justifyContent:"center",paddingVertical:r.sm,paddingHorizontal:r.lg,borderRadius:n.pill,borderWidth:lm,borderColor:t.brandInk,backgroundColor:t.chatGround,...Ag(u.chip,lm)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*im),...Mg(u.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:r.md,marginTop:r.xs},composer:{marginHorizontal:r.md,marginTop:r.xs,minHeight:Bb,justifyContent:"center",paddingLeft:r.sm,paddingRight:Ub,paddingVertical:Nb,backgroundColor:t.composerFill,borderWidth:Hb,borderColor:t.composerBorder,borderRadius:n.pill,...Ag(u.composerInput,Hb)},composerRow:{flexDirection:"row",alignItems:"center",gap:r.xs,minHeight:$b},dictationError:{...face(e,"regular"),fontSize:l.size.caption,lineHeight:l.size.caption*l.lineHeight.normal,color:t.danger,paddingHorizontal:r.xs},attachControl:{width:Jb,height:Jb,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:Zb},input:{flex:1,minHeight:$b,maxHeight:Ob,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:l.size.body,lineHeight:a,color:t.text.primary,...Mg(u.composerInput)},sendControl:{minHeight:qb,minWidth:qb,alignItems:"center",justifyContent:"center"},sendDisc:{width:qb,height:qb,borderRadius:qb/2,alignItems:"center",justifyContent:"center",...Ag(u.sendButton)},sendControlDisabled:{opacity:Qb},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:l.size.micro,textAlign:"center",paddingBottom:r.xs}})}var Sm=18,xm=28,_m=6,Rm=1200,Tm=.4,Im=.4;function DictationButton({active:e,listening:t,elapsedMs:r,disabled:l=false,onToggle:i}){let o=useEverfurTheme(),s=a(()=>zm(o),[o]);return n(()=>{if(t)try{m.announceForAccessibility(Cf.listening)}catch{}},[t]),/* @__PURE__ */U(w,{style:s.wrap,children:[t?/* @__PURE__ */H(Text,{style:s.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:$g(r)}):null,
|
|
139
|
+
/* @__PURE__ */H(R,{onPress:()=>i(),disabled:l,accessibilityRole:"button",accessibilityLabel:e?Cf.stopDictation:Cf.dictate,accessibilityState:{selected:e,disabled:l},style:[s.button,l?s.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */U(N,{children:[
|
|
140
140
|
/* @__PURE__ */H(Pulse,{style:s.pulse,reduced:o.motion.reducedMotion}),
|
|
141
|
-
/* @__PURE__ */H(StopGlyph,{size:wm,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */H(MicGlyph,{size:km,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=u(new F.Value(1)).current;return n(()=>{if(t)return;let e=F.loop(F.sequence([F.timing(r,{toValue:xm,duration:Sm/2,useNativeDriver:true}),F.timing(r,{toValue:1,duration:Sm/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */H(F.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function Rm(e){let t=e.color,r=e.type.tierSizes.compact.micro;return b.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:xb,height:xb,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:_m},pulse:{position:"absolute",top:Cm,right:Cm,bottom:Cm,left:Cm,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var Tm=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function Im(){let e=globalThis,t=e[Tm];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[Tm]=r,r}function registerEverfurDictation(e){let t=Im();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function zm(){return Im().version??0}function Pm(e){let t=Im(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function Om(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function Em(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function jm(){let e=Im();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||p.OS!=="ios"&&p.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:Em(t())}),e=>typeof e=="object"&&e!==null&&Om(e.box));return r.available&&(e.memo=r.module.box),e.memo}function Fm(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function Am(){try{return Intl.DateTimeFormat().resolvedOptions().locale||Mm}catch{return Mm}}function Dm(e){return e.replace(/_/g,"-").toLowerCase()}var Mm="en-US";function Lm(e=Am()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return Mm;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:Mm}function Bm(e,t){if(t.length===0)return null;let r=e=>t.find(t=>Dm(t)===Dm(e));return r(e)??r(Mm)??t.find(e=>Dm(e).startsWith("en-"))??null}async function Hm(e,t){if(p.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return Bm(t,r??[])??t}catch{return t}}async function Um(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(p.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=Dm(t);return(r??[]).some(e=>Dm(e)===n)?"on_device":"network"}catch{return"network"}}function Nm(){return p.OS!=="android"?true:Number(p.Version)>=$m}var $m=33;function Wm(e,t,r){return{lang:t,interimResults:true,continuous:Nm(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var Vm=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),qm=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Gm(e){return qm.has(e)}var Km=600,Ym=3;function Qm(e,t,r){if(Vm.has(r))return null;let n=Gm(r)?Km:0;return r==="language-not-supported"&&Dm(t)!==Dm(Mm)?{mode:"network",lang:Mm,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Jm(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Xm(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Zm=55e3,ey=3e3,ty=1e3;function ry(e){return ny.has(e)||Gm(e)}var ny=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),ly=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function iy(e){return e.replace(/\s+/g," ").trim()}function oy(e,t,r){let n=iy(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function ay(e){return iy([...e.committed,e.interim].join(" "))}function sy(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,a=e=>i!==null&&i.token===e?i:null;function s(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){s(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&ay(e.transcript)===""&&e.launchedAt-o<ty}function d(e){return e.mode??"none"}function f(e,t){Bg(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){Bg(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(a(e.token)===null)return;u(e);let r=ay(e.transcript),n=e.errorCode;if(n!==null&&!(r&&ry(n))){h(e,Jm(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{a(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),Bg(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(a(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=oy(l.transcript,r,e?.isFinal===true),t.onText(ay(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||Gm(t)))return;let r=ay(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<Ym?Qm(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(a(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){b(l,e.mode);return}s(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(a(l.token)===null||l.userStopped)&&b(l,e.mode)},e.delayMs);return}p(l)}})]}function b(t,r){s(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=ly,t.errorCode=null,g(t);try{e.start(Wm(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function m(t){let r=await Xm(e);if(a(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await Hm(e,t.lang),a(t.token)===null)return;let n=await Um(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Zm),b(t,n))}function y(r){if(!(a(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),ey);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:Lm(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:ly,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),m(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,a=ay(r.transcript);if(u(r),t.onStatus("idle"),!!l){a&&f(r,a),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function uy({enabled:e,input:t,setInput:r,phrases:o,maxLength:c,telemetry:d}){let f=i(Pm,zm,zm),h=a(()=>e?jm():null,[e,f]),p=a(()=>Fm(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=u(t);w.current=t;let S=u(r);S.current=r;let x=u(d);x.current=d;let _=u(""),R=u(c);R.current=c;let T=u(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:sy(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>S.current(Dg(_.current,e,R.current)),onError:e=>{y(e),b("error")}},()=>x.current)});let I=h===null?null:T.current?.controller??null,z=s(()=>{I?.cancel()},[I]),P=s(()=>{if(I!==null){if(I.isActive()){I.stop();return}y(null),k(0),_.current=w.current,I.start(o)}},[I,o]);n(()=>{if(g!=="listening")return;let e=Date.now();k(0);let t=setInterval(()=>k(Date.now()-e),1e3);return()=>clearInterval(t)},[g]),n(()=>{if(g!=="error")return;let e=setTimeout(()=>{y(null),b("idle")},Ag);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=C.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var cy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function dy(){let e=globalThis,t=e[cy];if(t!==void 0)return t;let r=createContext(true);return e[cy]=r,r}var fy=dy();function hy(){return o(fy)}var py=/* @__PURE__ */Object.freeze(["photo"]),gy=52,by=1.5,my=10,yy=14,vy=10,ky=40,wy=20,Cy=.3,Sy=2.5,xy=1,_y=1.5,Ry=38,Ty=22,Iy=3;function zy(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?xf(wf.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):xf(wf.placeholder,t):n==="urgent"?wf.placeholderUrgentWeb:n==="followUp"?wf.placeholderFollowUpWeb:xf(wf.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??sl,transport:r}),l=a(()=>({state:n,sources:e.sources??py,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
|
|
142
|
-
return H(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:c,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:C=false}){let{theme:S,styles:x}=
|
|
143
|
-
return U(w,{style:x.composerOuter,children:[o!==null&&O?/* @__PURE__ */H(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */H(AttachmentStrip,{attachments:X,rejected:M?
|
|
141
|
+
/* @__PURE__ */H(StopGlyph,{size:xm,color:o.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */H(MicGlyph,{size:Sm,color:o.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:t}){let r=u(new F.Value(1)).current;return n(()=>{if(t)return;let e=F.loop(F.sequence([F.timing(r,{toValue:Tm,duration:Rm/2,useNativeDriver:true}),F.timing(r,{toValue:1,duration:Rm/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[r,t]),/* @__PURE__ */H(F.View,{style:[e,{opacity:r}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function zm(e){let t=e.color,r=e.type.tierSizes.compact.micro;return b.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:r,lineHeight:r+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:Pb,height:Pb,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:Im},pulse:{position:"absolute",top:_m,right:_m,bottom:_m,left:_m,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var Pm=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function Om(){let e=globalThis,t=e[Pm];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[Pm]=r,r}function registerEverfurDictation(e){let t=Om();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function Em(){return Om().version??0}function jm(e){let t=Om(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function Fm(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 Am(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function Dm(){let e=Om();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||p.OS!=="ios"&&p.OS!=="android")return e.memo;let r=optionalModule("expo-speech-recognition",()=>({box:Am(t())}),e=>typeof e=="object"&&e!==null&&Fm(e.box));return r.available&&(e.memo=r.module.box),e.memo}function Mm(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function Lm(){try{return Intl.DateTimeFormat().resolvedOptions().locale||Hm}catch{return Hm}}function Bm(e){return e.replace(/_/g,"-").toLowerCase()}var Hm="en-US";function Um(e=Lm()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return Hm;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:Hm}function Nm(e,t){if(t.length===0)return null;let r=e=>t.find(t=>Bm(t)===Bm(e));return r(e)??r(Hm)??t.find(e=>Bm(e).startsWith("en-"))??null}async function $m(e,t){if(p.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return Nm(t,r??[])??t}catch{return t}}async function Wm(e,t){let r=false;try{r=e.supportsOnDeviceRecognition()===!0}catch{r=false}if(!r)return"network";if(p.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=Bm(t);return(r??[]).some(e=>Bm(e)===n)?"on_device":"network"}catch{return"network"}}function Vm(){return p.OS!=="android"?true:Number(p.Version)>=qm}var qm=33;function Gm(e,t,r){return{lang:t,interimResults:true,continuous:Vm(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var Km=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),Ym=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Qm(e){return Ym.has(e)}var Jm=600,Xm=3;function Zm(e,t,r){if(Km.has(r))return null;let n=Qm(r)?Jm:0;return r==="language-not-supported"&&Bm(t)!==Bm(Hm)?{mode:"network",lang:Hm,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function ey(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 ry=55e3,ny=3e3,ly=1e3;function iy(e){return oy.has(e)||Qm(e)}var oy=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),ay=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function sy(e){return e.replace(/\s+/g," ").trim()}function uy(e,t,r){let n=sy(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function cy(e){return sy([...e.committed,e.interim].join(" "))}function dy(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&&cy(e.transcript)===""&&e.launchedAt-o<ly}function d(e){return e.mode??"none"}function f(e,t){Vg(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){Vg(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=cy(e.transcript),n=e.errorCode;if(n!==null&&!(r&&iy(n))){h(e,ey(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()),Vg(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=uy(l.transcript,r,e?.isFinal===true),t.onText(cy(l.transcript))}),e.addListener("error",e=>{if(a(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||Qm(t)))return;let r=cy(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<Xm?Zm(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=ay,t.errorCode=null,g(t);try{e.start(Gm(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 $m(e,t.lang),a(t.token)===null)return;let n=await Wm(e,t.lang);a(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),ry),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),ny);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:Um(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:ay,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=cy(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 fy({enabled:e,input:t,setInput:r,phrases:o,maxLength:c,telemetry:d}){let f=i(jm,Em,Em),h=a(()=>e?Dm():null,[e,f]),p=a(()=>Mm(h),[h]),[g,b]=l("idle"),[m,y]=l(null),[v,k]=l(0),w=u(t);w.current=t;let S=u(r);S.current=r;let x=u(d);x.current=d;let _=u(""),R=u(c);R.current=c;let T=u(null);h!==null&&T.current?.mod!==h&&(T.current?.controller.cancel(),T.current={mod:h,controller:dy(h,{onStatus:e=>{b(t=>e==="idle"&&t==="error"?t:e)},onText:e=>S.current(Ng(_.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")},Ug);return()=>clearTimeout(e)},[g]),n(()=>{if(I===null)return;let e=null;try{e=C.addEventListener("change",e=>{e==="background"&&!I.isPreparing()&&I.cancel()})}catch{}return()=>{e?.remove(),I.cancel()}},[I]);let O=e&&p;return n(()=>{O||I?.cancel()},[O,I]),{supported:O,status:g,active:g==="starting"||g==="listening",error:m,elapsedMs:v,toggle:P,cancel:z}}var hy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function py(){let e=globalThis,t=e[hy];if(t!==void 0)return t;let r=createContext(true);return e[hy]=r,r}var gy=py();function by(){return o(gy)}var my=/* @__PURE__ */Object.freeze(["photo"]),yy=52,vy=1.5,ky=10,wy=14,Cy=10,Sy=40,xy=20,_y=.3,Ry=2.5,Ty=1,Iy=1.5,zy=38,Py=22,Oy=3;function Ey(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?_f(Cf.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):_f(Cf.placeholder,t):n==="urgent"?Cf.placeholderUrgentWeb:n==="followUp"?Cf.placeholderFollowUpWeb:_f(Cf.placeholder,t)}function ComposerWithAttachments({attachments:e,...t}){let r=a(()=>createRnChatAttachmentTransport(),[]),n=useChatAttachments({maxPerMessage:e.maxPerMessage??sl,transport:r}),l=a(()=>({state:n,sources:e.sources??my,pick:e.pick}),[n,e.sources,e.pick]);/* @__PURE__ */
|
|
142
|
+
return H(Composer,{...t,attachments:l})}function Composer({send:e,stop:t,isStreaming:r,conversationId:i,attachments:o,seed:c,draftStore:d,onStage:f,onPreview:h,petName:p,petBreed:g=null,mood:b="ask",dictation:m=false,telemetry:y=null,compact:v=false,petPlaceholder:k=false,dimEmptySend:C=false}){let{theme:S,styles:x}=wm(),_=a(()=>Ly(S),[S]),T=a(()=>By(S),[S]),I=ag(),[z,P]=Kg(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=Ey(S.meta.placeholder,p,k,b,S.meta.placeholderFillsPet===true),$=a(()=>Gg({name:p,breed:g}),[p,g]),W=fy({enabled:m,input:z,setInput:P,phrases:$,maxLength:Hn,telemetry:y}),V=W.cancel,q=W.active;Yg(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=by();n(()=>{K||V()},[K,V]);let Y=o?.state.uploading??false,Q=o?.state.failed??false,J=Y||Q,X=o?.state.attachments??jy;xg(X.length,I);let Z=s(()=>{let t=z.trim();if(t.length===0||J||[...t].length>Hn)return;q&&V();let r=o?.state.s3Keys??Fy;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(),bh(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>Hn,[z]),le=ne||J||z.trim().length===0,ie=ne||J||C&&z.trim().length===0,oe=o!==null&&X.length>=o.state.maxPerMessage,ae=S.slots.sendButton?.textColor??S.color.brandInk,se=S.slots.sendButton?.textColor??S.color.surface;/* @__PURE__ */
|
|
143
|
+
return U(w,{style:x.composerOuter,children:[o!==null&&O?/* @__PURE__ */H(AttachmentPickerPopover,{sources:o.sources,full:oe,onPick:re,onClose:()=>E(false)}):null,o!==null?/* @__PURE__ */H(AttachmentStrip,{attachments:X,rejected:M?My:o.state.rejected,uploadFailed:Q,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:e=>h({uri:e.previewUri,label:e.filename}),style:v?_.tray:T.tray}):null,
|
|
144
144
|
/* @__PURE__ */U(w,{style:v?[x.composer,_.bar,j?_.barFocused:null]:x.composer,children:[W.supported&&W.error!==null?/* @__PURE__ */U(N,{children:[
|
|
145
|
-
/* @__PURE__ */H(Text,{style:x.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:
|
|
146
|
-
/* @__PURE__ */H(AnnounceLine,{line:
|
|
147
|
-
/* @__PURE__ */U(w,{style:x.composerRow,children:[o!==null?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:oe?
|
|
148
|
-
/* @__PURE__ */H(Zd,{style:v?[x.input,_.input]:x.input,onFocus:A,onBlur:D,value:z,onChangeText:ee,placeholder:B,placeholderTextColor:S.slots.composerInput?.textColor??S.color.text.placeholder,accessibilityLabel:wf.composerLabel,onSubmitEditing:Z,returnKeyType:"send",...Ey,...v?jy:null,blurOnSubmit:false,multiline:true,editable:true}),W.supported?/* @__PURE__ */H(DictationButton,{active:W.active,listening:W.status==="listening",elapsedMs:W.elapsedMs,onToggle:W.toggle}):null,r?/* @__PURE__ */H(R,{onPress:te,accessibilityRole:"button",accessibilityLabel:wf.stop,style:x.sendControl,children:/* @__PURE__ */H(w,{style:v?_.disc:x.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */H(StopGlyph,{size:v?wy:$b,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */H(R,{onPress:Z,disabled:le,accessibilityRole:"button",accessibilityLabel:wf.send,accessibilityState:{disabled:le,busy:Y},style:[x.sendControl,ie?v?_.dimmed:x.sendControlDisabled:null],children:v?/* @__PURE__ */H(w,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */H(ArrowUpGlyph,{size:wy,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */H(w,{style:x.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */H(SendGlyph,{size:Nb,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var Py=/* @__PURE__ */Object.freeze([]),Oy=/* @__PURE__ */Object.freeze([]),Ey=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),jy=/* @__PURE__ */Object.freeze(p.OS==="web"?{rows:1}:{}),Fy=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function Ay(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+xy;return b.create({bar:{marginTop:my,marginHorizontal:yy,marginBottom:vy,minHeight:gy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:by,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Sy,paddingLeft:8-(Sy-by),paddingRight:6-(Sy-by)},input:{fontSize:n,lineHeight:Math.round(n*_y),minHeight:Math.round(n*_y),...p.OS==="web"?{outlineStyle:"none"}:null},add:{width:Ry,height:Ry,borderRadius:Ry/2},disc:{width:ky,height:ky,borderRadius:ky/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...zg(r)},dimmed:{opacity:Cy},tray:{marginHorizontal:yy,marginTop:my,paddingBottom:0}})}function Dy(e){return b.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=ud(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[c,d]=l({repository:o,pets:[],loading:true,error:null}),f=c.repository===o?c:{pets:[],loading:true,error:null},h=u(0),p=s(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>Di(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function My(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Ly=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var By=false;function Hy(e,t){return t!==void 0?(fh(t,e),"onStartInApp"):uf(e)==="presented"?"presenter":hf(e)?"experience":(By||(By=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Uy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&Uy.includes(e)}var Ny="/widget/v1/televet/handoffs",$y="/widget/v1/televet/availability",Wy="/widget/v1/televet/chat-entry",Vy=/^[a-z0-9][a-z0-9_-]{0,39}$/,qy=/^[A-Za-z0-9_-]{22}$/;var Gy=32,Ky=128,Yy=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function Qy(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Jy(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Xy(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Vy.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>Yy)return{ok:false,message:`visitRef must be 1..${Yy} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${Uy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Zy(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function ev(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(ov(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>Ky)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Ky} characters`}));i=e}let o=Xy(i,l);if(!o.ok){let e=Qy(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:Ny,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=tv(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!qy.test(d))){let e=Jy("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,h=f?Zy(s.value?.visit):null;if(f&&h===null){let e=Jy("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(ov(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Gy)return Qy(`state must be at most ${Gy} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:$y,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Jy("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:Wy},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function tv(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!iv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var rv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),nv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,lv=/[\s\u0000-\u001f\u007f]/;function iv(e){if(lv.test(e))return false;let t=nv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&rv.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function ov(e,t,r){if(e)try{e.track(t,r)}catch{}}var av=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function sv(e,t,r){let{usState:i,chat:o,scope:a}=r,s=t&&(i!==null||o),u=`${i??""}|${o?"chat":""}`,[c,d]=l(null);if(n(()=>{if(!s)return;let t=true,r=e.current;return d(null),(async()=>{try{if(o&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&d({key:u,open:e})}),()=>{t=false}},[s,u,i,o,a,e]),!s)return null;let f=c!==null&&c.key===u;return{open:f&&c.open,pending:!f}}var uv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function cv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=ud(),o=useCapability("televet"),c=o.enabled&&n!==null,d=t.usState??null,f=t.entry==="chat",h=t.petRef??null,p=t.prefer==="redirect",g=a(()=>{if(t.controller)return t.controller;let{services:e}=r.registry;return ev({auth:e.authFor(n),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[r,n,i,t.controller]),b=u(g);b.current=g;let m=a(()=>({runtime:r,userRef:n,scopeEpoch:i}),[r,n,i]),y=sv(b,c,{usState:d,chat:f,scope:m}),v=c&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(av),S=u(null),x=u({runtime:r,userRef:n,scopeEpoch:i});x.current={runtime:r,userRef:n,scopeEpoch:i};let _=u(g);_.current=g;let R=u(v);R.current=v;let T=s((t,r)=>{if(S.current)return S.current;let n=(e,t)=>(C({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!R.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=x.current,o=_.current;C(uv);let a=(async()=>{let a,s={...k!==null?{returnTo:k}:{},...f?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},u=Object.keys(s).length===0?void 0:s,c=t===void 0?h:t;try{a=await(u===void 0?o.createHandoff(c):o.createHandoff(c,u))}catch{return e.abandon(l.value),n("unknown",null)}let d=x.current;if(d.runtime!==i.runtime||d.userRef!==i.userRef||d.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!a.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let p=await e.finish(l.value,a.value);return p!==null?n(p,null):(C(av),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{S.current===a&&(S.current=null)});return S.current=a,a},[e,h,k,f]),I=s((e,t)=>{if(!R.current)return C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?h:e,n={...r!==null?{petRef:r}:{},...d!==null?{usState:d}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return Hy(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(av),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[h,d]),z=s(e=>p?T(e,null):I(e,null),[p,T,I]),P=s((e,t)=>p?T(void 0,{visitRef:e,intent:t??null}):I(void 0,{visitRef:e,intent:t??null}),[p,T,I]),O=s(e=>p?T(void 0,null):I(void 0,{consultId:e.trim()}),[p,T,I]);return{available:v,isPending:o.isPending||(y?.pending??false),status:w.status,error:w.error,errorReason:w.errorReason,open:z,openVisit:P,joinVisit:O}}var dv=e=>x.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??dv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return cv(n,r)}var fv=44,hv=.6;function VetVisitButtonCore(e){let{petRef:t,label:r,openUrl:n,onOpened:l,onError:i,style:o,labelStyle:s,controller:c,returnTo:d,usState:f,entry:h,visitRef:p,intent:g,onStartInApp:b,prefer:m}=e,y=m==="redirect",v=useVetVisit({...d!==void 0?{returnTo:d}:{},...f!==void 0?{usState:f}:{},...h!==void 0?{entry:h}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...c!==void 0?{controller:c}:{},prefer:y?"redirect":"in-app"}),k=useEverfurTheme(),w=a(()=>pv(k),[k]),C=u(false);if(!v.available)/* @__PURE__ */
|
|
145
|
+
/* @__PURE__ */H(Text,{style:x.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:Wg(W.error)}),
|
|
146
|
+
/* @__PURE__ */H(AnnounceLine,{line:Wg(W.error)})]}):null,
|
|
147
|
+
/* @__PURE__ */U(w,{style:x.composerRow,children:[o!==null?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:oe?Bg(X.length,o.state.maxPerMessage):Cf.attachPhotoOrFileNative,accessibilityState:{disabled:oe,expanded:O},disabled:oe,style:[x.attachControl,v?_.add:null,oe?x.attachControlDisabled:null],hitSlop:v?Oy:void 0,onPress:()=>E(e=>!e),children:/* @__PURE__ */H(UploadGlyph,{size:v?Py:Xb,color:oe?S.color.text.muted:v?S.color.text.primary:S.color.brandInk,strokeWidth:1.75})}):null,
|
|
148
|
+
/* @__PURE__ */H(ef,{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:Cf.composerLabel,onSubmitEditing:Z,returnKeyType:"send",...Ay,...v?Dy:null,blurOnSubmit:false,multiline:true,editable:true}),W.supported?/* @__PURE__ */H(DictationButton,{active:W.active,listening:W.status==="listening",elapsedMs:W.elapsedMs,onToggle:W.toggle}):null,r?/* @__PURE__ */H(R,{onPress:te,accessibilityRole:"button",accessibilityLabel:Cf.stop,style:x.sendControl,children:/* @__PURE__ */H(w,{style:v?_.disc:x.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */H(StopGlyph,{size:v?xy:Yb,color:v?se:ae,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */H(R,{onPress:Z,disabled:le,accessibilityRole:"button",accessibilityLabel:Cf.send,accessibilityState:{disabled:le,busy:Y},style:[x.sendControl,ie?v?_.dimmed:x.sendControlDisabled:null],children:v?/* @__PURE__ */H(w,{style:_.disc,testID:"everfur-send-disc",children:/* @__PURE__ */H(ArrowUpGlyph,{size:xy,color:se,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */H(w,{style:x.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */H(SendGlyph,{size:Kb,color:ae,testID:"everfur-send-glyph"})})})]})]})]})}var jy=/* @__PURE__ */Object.freeze([]),Fy=/* @__PURE__ */Object.freeze([]),Ay=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),Dy=/* @__PURE__ */Object.freeze(p.OS==="web"?{rows:1}:{}),My=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function Ly(e){let t=e.color,r=e.slots.sendButton,n=textRole(e,"body").fontSize+Ty;return b.create({bar:{marginTop:ky,marginHorizontal:wy,marginBottom:Cy,minHeight:yy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:vy,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Ry,paddingLeft:8-(Ry-vy),paddingRight:6-(Ry-vy)},input:{fontSize:n,lineHeight:Math.round(n*Iy),minHeight:Math.round(n*Iy),...p.OS==="web"?{outlineStyle:"none"}:null},add:{width:zy,height:zy,borderRadius:zy/2},disc:{width:Sy,height:Sy,borderRadius:Sy/2,alignItems:"center",justifyContent:"center",backgroundColor:r?.backgroundColor??t.text.primary,...Ag(r)},dimmed:{opacity:_y},tray:{marginHorizontal:wy,marginTop:ky,paddingBottom:0}})}function By(e){return b.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:i}=cd(),o=a(()=>createPetsRepository(e.registry.services.authFor(t)),[e,t,i]),[c,d]=l({repository:o,pets:[],loading:true,error:null}),f=c.repository===o?c:{pets:[],loading:true,error:null},h=u(0),p=s(async()=>{let e=++h.current;d(e=>({...e,repository:o,loading:true,error:null,pets:e.repository===o?e.pets:[]}));let t=await o.list();e===h.current&&d(t.ok?{repository:o,pets:t.value,loading:false,error:null}:e=>({repository:o,pets:e.repository===o?e.pets:[],loading:false,error:t.error}))},[o]);n(()=>(p(),()=>{h.current+=1}),[p]),n(()=>Di(e,()=>{p()}),[e,p]);let g=a(()=>r===null?null:f.pets.find(e=>e.petRef===r)??null,[r,f.pets]);return a(()=>({pets:f.pets,activePet:g,loading:f.loading,error:f.error,refresh:p}),[f.pets,f.loading,f.error,g,p])}function Hy(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Uy=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var Ny=false;function $y(e,t){return t!==void 0?(hh(t,e),"onStartInApp"):cf(e)==="presented"?"presenter":pf(e)?"experience":(Ny||(Ny=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Wy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&Wy.includes(e)}var Vy="/widget/v1/televet/handoffs",qy="/widget/v1/televet/availability",Gy="/widget/v1/televet/chat-entry",Ky=/^[a-z0-9][a-z0-9_-]{0,39}$/,Yy=/^[A-Za-z0-9_-]{22}$/;var Qy=32,Jy=128,Xy=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 Zy(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function ev(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"||!Ky.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>Xy)return{ok:false,message:`visitRef must be 1..${Xy} 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 ${Wy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function rv(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 nv(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(uv(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>Jy)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Jy} characters`}));i=e}let o=tv(i,l);if(!o.ok){let e=Zy(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:Vy,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=lv(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!Yy.test(d))){let e=ev("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?rv(s.value?.visit):null;if(f&&h===null){let e=ev("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"})):(uv(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Qy)return Zy(`state must be at most ${Qy} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:qy,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?ev("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:Gy},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function lv(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||!sv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var iv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ov=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,av=/[\s\u0000-\u001f\u007f]/;function sv(e){if(av.test(e))return false;let t=ov.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"&&iv.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 uv(e,t,r){if(e)try{e.track(t,r)}catch{}}var cv=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function dv(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 fv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function hv(e,t={}){let{runtime:r,userRef:n,scopeEpoch:i}=cd(),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 nv({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=dv(b,c,{usState:d,chat:f,scope:m}),v=c&&(y===null||y.open)&&(!f||h!==null),k=t.returnTo??null,[w,C]=l(cv),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(fv);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(cv),/* @__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 $y(n)===null?(C({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(C(cv),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 pv=e=>x.openURL(e);function useVetVisit(e={}){let{openUrl:t,...r}=e,n=a(()=>{let e=t??pv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[t]);return hv(n,r)}var gv=44,bv=.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(()=>mv(k),[k]),C=u(false);if(!v.available)/* @__PURE__ */
|
|
149
149
|
return U(N,{children:[null,
|
|
150
|
-
/* @__PURE__ */H(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??
|
|
150
|
+
/* @__PURE__ */H(TelevetHostOutlet,{})]});let S=v.status==="opening",x=r??Uy.visitButton;/* @__PURE__ */
|
|
151
151
|
return U(N,{children:[
|
|
152
|
-
/* @__PURE__ */H(R,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}}
|
|
153
|
-
/* @__PURE__ */H(TelevetHostOutlet,{})]})}function
|
|
154
|
-
return H(O,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=
|
|
152
|
+
/* @__PURE__ */H(R,{onPress:()=>{if(!(S||C.current)){if(!y){let e={...t!==void 0?{petRef:t}:{},...f!==void 0?{usState:f}:{},...p!=null?{visitRef:p,intent:g??null}:{}};$y(e,b)===null&&hh(i,"unavailable",null);return}C.current=true,(p==null?v.open():v.openVisit(p,g??null)).then(e=>{e.opened?hh(l,e.flowId??null):e.reason!=="cancelled"&&hh(i,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:x,accessibilityState:{busy:S,disabled:S},style:[w.button,S?w.busy:null,o],children:/* @__PURE__ */H(Text,{style:[w.label,s],children:x})}),
|
|
153
|
+
/* @__PURE__ */H(TelevetHostOutlet,{})]})}function mv(e){let{color:t,space:r,radius:n,type:l,slots:i}=e;return b.create({button:{minHeight:gv,minWidth:gv,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...Ag(i.vetVisitButton)},busy:{opacity:bv},label:{...face(e,"medium"),color:t.onPrimary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.snug,...Mg(i.vetVisitButton)}})}function yv(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=yv(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__ */
|
|
154
|
+
return H(O,{source:{uri:e},style:n,resizeMode:l,...u,onError:()=>{s.onError(),o?.()},...a===void 0?{}:{testID:a}})}function BrandLogo({logoUrl:e,name:t,barStyle:r,logoStyle:n,testID:l}){let i=yv(e);return e===null||!i.shown?null:/* @__PURE__ */H(w,{style:r,...l===void 0?{}:{testID:l},children:/* @__PURE__ */H(O,{source:{uri:e},style:n,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:i.onError})})}var vv=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),kv=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function wv(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return kv;let n=Math.abs(e.leading-e.trailing);if(n<.5)return kv;let l=e.row-t-e.leading-e.trailing,i=Math.min(n,Math.max(0,l-r));return i<.5?kv:e.leading<e.trailing?{leading:e.leading+i,trailing:void 0}:{leading:void 0,trailing:e.trailing+i}}function Cv(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function Sv(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function xv(e){if(e.brightness!=="light")return false;let t=ta.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),l=new Set(Sv(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&Sv(r).every(e=>l.has(e))}function _v(e){let t=(e.brightness==="dark"?na:ta).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 Rv(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function Tv(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function Iv(e){let t=Tv(e.ageYears),r=Rv(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var zv=/* @__PURE__ */Object.freeze([
|
|
155
155
|
/* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
|
|
156
156
|
/* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
|
|
157
157
|
/* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
|
|
158
158
|
/* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
|
|
159
159
|
/* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
|
|
160
|
-
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function
|
|
161
|
-
return H(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */H(w,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */H(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?
|
|
162
|
-
/* @__PURE__ */H(R,{style:
|
|
160
|
+
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function Pv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return zv[t%zv.length]}function Ov(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function Ev(e){return{...Pv(e.petRef),initial:Ov(e.name)}}function jv(e,t,r){let n=Ev(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function Fv(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:t,ringStroke:r}){let n=useEverfurTheme(),l=a(()=>Av(n),[n]),i=t-r*2,o=e===null?null:jv(e,xv(n),{fill:n.color.highlight,ink:n.color.onHighlight}),s=Fv(i);/* @__PURE__ */
|
|
161
|
+
return H(Ring,{size:t,strokeWidth:r,color:n.color.mark,children:/* @__PURE__ */H(w,{style:[l.disc,{width:i,height:i,borderRadius:i/2},o===null?l.discEmpty:{backgroundColor:o.background}],children:/* @__PURE__ */H(Text,{tier:"badge",style:[l.letter,{fontSize:s,lineHeight:Math.round(s*1.2),color:o===null?n.color.text.muted:o.foreground}],children:o===null?Ov(null):o.initial})})})}function Av(e){return b.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function Dv(e,t){let{borderRadius:r,...n}=Ag(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function Mv(e,t){let{backgroundColor:r,borderColor:n,borderWidth:l,borderRadius:i}=Ag(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:l??1},...i===void 0?{}:{borderTopRightRadius:i,borderBottomRightRadius:i}}}var Lv=48,Bv=2,Hv=320,Uv="80%",Nv="rgba(17,17,17,0.45)",$v=18,Wv=22,Vv=12,qv=.4,Gv=44;function Kv(e){return e?.name?.trim()||Cf.yourPet}function PetSwitcherSheet({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:l=null,onClose:i}){let o=useEverfurTheme(),s=a(()=>Yv(o),[o]);return e?/* @__PURE__ */H(I,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"fade",onRequestClose:i,children:/* @__PURE__ */U(w,{style:s.root,children:[
|
|
162
|
+
/* @__PURE__ */H(R,{style:ob,onPress:i,accessibilityRole:"button",accessibilityLabel:Cf.close,children:/* @__PURE__ */H(w,{style:s.backdrop})}),
|
|
163
163
|
/* @__PURE__ */U(w,{style:s.panel,accessibilityViewIsModal:true,children:[
|
|
164
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:
|
|
165
|
-
/* @__PURE__ */H(z,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=
|
|
166
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
167
|
-
/* @__PURE__ */H(PetDisc,{pet:e,size:
|
|
164
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:Cf.yourPets}),
|
|
165
|
+
/* @__PURE__ */H(z,{style:s.list,contentContainerStyle:s.listContent,showsVerticalScrollIndicator:true,children:t.map(e=>{let t=e.petRef===r,l=Kv(e),i=Iv(e);/* @__PURE__ */
|
|
166
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:Sf(t?Cf.petCurrentlyActive:Cf.switchToPet,{name:l}),accessibilityState:{selected:t},style:[s.row,t?s.rowActive:null],onPress:()=>n(e.petRef),children:[
|
|
167
|
+
/* @__PURE__ */H(PetDisc,{pet:e,size:Lv,ringStroke:Bv}),
|
|
168
168
|
/* @__PURE__ */U(w,{style:s.copy,children:[
|
|
169
169
|
/* @__PURE__ */H(Text,{style:s.name,numberOfLines:1,children:l}),
|
|
170
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${
|
|
170
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:s.meta,numberOfLines:1,children:t?`${Cf.activePrefix}${i}`:i})]}),t?/* @__PURE__ */H(CheckGlyph,{size:$v,color:o.color.brandInk}):null]},e.petRef)})}),l!==null?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf.addAnotherPet,style:s.addRow,onPress:l,children:[
|
|
171
171
|
/* @__PURE__ */H(w,{style:s.addDisc,children:/* @__PURE__ */H(Text,{tier:"control",style:s.addPlus,children:"+"})}),
|
|
172
|
-
/* @__PURE__ */H(Text,{style:s.addLabel,children:
|
|
173
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
172
|
+
/* @__PURE__ */H(Text,{style:s.addLabel,children:Cf.addAnotherPet})]}):null,
|
|
173
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf.close,containerStyle:s.closeSlot,style:s.closeButton,onPress:i,children:/* @__PURE__ */H(Text,{tier:"control",style:s.closeText,children:Cf.close})})]})]})}):null}function Yv(e){let t=e.color,r=e.radius,n=Mg(e.slots.dialog);return b.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:Nv},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Wv,borderTopRightRadius:Wv,gap:14,maxHeight:Uv,...Dv(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...n},list:{maxHeight:Hv,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:Gv,paddingHorizontal:8},addDisc:{width:Lv,height:Lv,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:Bv,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:qv},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:Vv,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:qv}})}var Qv=44,Jv=36,Xv=22,Zv=20,ek=9,tk=1.5,rk=6,nk=35,lk=1.75,ik=12.4,ak=.5,sk=8,uk=28,ck=160,dk=16,fk=8;function hk(e,t){return Hy(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(()=>pk(f),[f]),[p,g]=l(false),b=hk(e.pets,t),m=b!==null&&(e.pets.length>=2||u!==void 0),y=t??b?.petRef??null,v=Kv(b),[k,C]=l(vv),S=s(e=>t=>{let r=t.nativeEvent.layout.width;C(t=>Cv(t,e,r))},[]),x=a(()=>S("row"),[S]),_=a(()=>S("leading"),[S]),R=a(()=>S("trailing"),[S]),T=2*dk+2*(f.slots.header?.borderColor!==void 0?1:0)+2*fk,I=wv(k,T,ck),z=t=>{g(false),e.setActivePet(t),hh(o,t)},P=u===void 0?null:()=>{g(false),hh(u)};/* @__PURE__ */
|
|
174
174
|
return U(N,{children:[
|
|
175
175
|
/* @__PURE__ */U(w,{style:h.row,onLayout:x,children:[
|
|
176
|
-
/* @__PURE__ */H(w,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */U(w,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
177
|
-
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${
|
|
178
|
-
/* @__PURE__ */H(MenuGlyph,{size:
|
|
176
|
+
/* @__PURE__ */H(w,{style:[h.leading,I.leading===void 0?null:{minWidth:I.leading}],children:/* @__PURE__ */U(w,{style:h.sideContent,onLayout:_,children:[i!==void 0?/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:xp.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:i,children:/* @__PURE__ */H(EditGlyph,{size:Zv,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
|
|
177
|
+
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:r?`${Cf.openHistoryNative}${Cf.newReplySuffix}`:Cf.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:n,children:[
|
|
178
|
+
/* @__PURE__ */H(MenuGlyph,{size:Xv,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),r?/* @__PURE__ */H(w,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
|
|
179
179
|
/* @__PURE__ */H(w,{style:h.centre,pointerEvents:"box-none",children:/* @__PURE__ */H(BrandLogo,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,barStyle:h.logoBar,logoStyle:h.logo})}),
|
|
180
180
|
/* @__PURE__ */H(w,{style:[h.trailing,I.trailing===void 0?null:{minWidth:I.trailing}],children:/* @__PURE__ */U(w,{style:h.trailingContent,onLayout:R,children:[y===null?null:/* @__PURE__ */H(VetVisitButtonCore,{entry:"chat",petRef:y,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:h.vetEntry,labelStyle:h.vetEntryLabel}),
|
|
181
|
-
/* @__PURE__ */H(w,{style:h.right,children:m?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf
|
|
182
|
-
/* @__PURE__ */H(PetDisc,{pet:b,size:
|
|
183
|
-
/* @__PURE__ */H(w,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */H(PlusGlyph,{size:
|
|
184
|
-
/* @__PURE__ */H(w,{style:h.avatarWrap,accessible:true,accessibilityLabel:
|
|
185
|
-
/* @__PURE__ */H(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */H(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>
|
|
186
|
-
return H(w,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */H(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function
|
|
187
|
-
/* @__PURE__ */Object.freeze({key:"inaccurate",label:
|
|
188
|
-
/* @__PURE__ */Object.freeze({key:"outdated",label:
|
|
189
|
-
/* @__PURE__ */Object.freeze({key:"unsafe",label:
|
|
190
|
-
/* @__PURE__ */Object.freeze({key:"unclear",label:
|
|
191
|
-
/* @__PURE__ */Object.freeze({key:"other",label:
|
|
192
|
-
/* @__PURE__ */Object.freeze({sentiment:"up",label:
|
|
193
|
-
/* @__PURE__ */Object.freeze({sentiment:"down",label:
|
|
181
|
+
/* @__PURE__ */H(w,{style:h.right,children:m?/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:Sf(Cf.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
|
|
182
|
+
/* @__PURE__ */H(PetDisc,{pet:b,size:nk,ringStroke:lk}),
|
|
183
|
+
/* @__PURE__ */H(w,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */H(PlusGlyph,{size:sk,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&b===null?
|
|
184
|
+
/* @__PURE__ */H(w,{style:h.avatarWrap,accessible:true,accessibilityLabel:Cf.yourPet,children:/* @__PURE__ */H(Ring,{size:nk,strokeWidth:lk,color:f.color.mark,children:/* @__PURE__ */H(w,{style:h.placeholderDisc})})}):/* @__PURE__ */H(w,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:b===null?Cf.yourPet:v,children:/* @__PURE__ */H(PetDisc,{pet:b,size:nk,ringStroke:lk})})})]})}),
|
|
185
|
+
/* @__PURE__ */H(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:b?.petRef??null,onSelect:z,onAddPet:P,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */H(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:t}){let r=useEverfurTheme(),n=a(()=>pk(r),[r]);/* @__PURE__ */
|
|
186
|
+
return H(w,{style:t==="header"?n.textingEntryRowHeader:n.textingEntryRowThread,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:n.textingEntrySlot,style:n.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */H(Text,{tier:"control",style:n.vetEntryLabel,numberOfLines:1,children:e.label})})})}function pk(e){let t=e.color,r=nk-lk*2,n=e.slots.header;return b.create({vetEntry:{minHeight:Qv,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:b.hairlineWidth,borderColor:t.controlEdge},vetEntryLabel:{...face(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},textingEntrySlot:{borderRadius:e.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:dk,paddingBottom:10,backgroundColor:n?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:dk,paddingTop:e.space.sm},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:dk,paddingVertical:10,backgroundColor:t.surface,...Ag(n)},iconSlot:{borderRadius:Jv/2},iconButton:{width:Jv,height:Jv,borderRadius:Jv/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:rk,right:rk,width:ek,height:ek,borderRadius:ek,backgroundColor:t.danger,borderWidth:tk,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:fk,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:uk,width:ck,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:nk/2},avatarWrap:{width:nk,height:nk,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ik,height:ik,borderRadius:ik/2,borderWidth:ak,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var gk=/* @__PURE__ */Object.freeze([
|
|
187
|
+
/* @__PURE__ */Object.freeze({key:"inaccurate",label:Cf.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
188
|
+
/* @__PURE__ */Object.freeze({key:"outdated",label:Cf.feedbackReasonOutdated,feedbackType:"outdated"}),
|
|
189
|
+
/* @__PURE__ */Object.freeze({key:"unsafe",label:Cf.feedbackReasonUnsafe,feedbackType:"dangerous"}),
|
|
190
|
+
/* @__PURE__ */Object.freeze({key:"unclear",label:Cf.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
191
|
+
/* @__PURE__ */Object.freeze({key:"other",label:Cf.feedbackReasonOther,feedbackType:"not_helpful"})]),bk=/* @__PURE__ */Object.freeze([
|
|
192
|
+
/* @__PURE__ */Object.freeze({sentiment:"up",label:Cf.feedbackHelpful}),
|
|
193
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:Cf.feedbackNotHelpful})]);function mk(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function yk(e,t){if(e==="down"&&t!==null){let e=gk.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return mk(e)}var vk=44,kk="rgba(17,17,17,0.55)",wk=26,Ck=36,Sk=4,xk=20,_k=38,Rk=18,Tk=12;function FeedbackReasons({visible:e,onSubmit:t,onSkip:r}){let n=useEverfurTheme(),i=a(()=>Ik(n),[n]),[o,s]=l(null),[u,c]=l(""),[d,f]=l(false),[h,g]=l(false),b=()=>{s(null),c(""),f(false),g(false)},m=()=>{d||(b(),r())},y=async()=>{if(d)return;f(true),g(false);let e=u.trim();await t(o,e.length>0?e:null)?b():(f(false),g(true))};if(!e)return null;let v=[...u].length>Bn;/* @__PURE__ */
|
|
194
194
|
return H(I,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:m,children:/* @__PURE__ */U(_,{behavior:p.OS==="ios"?"padding":void 0,style:i.root,children:[
|
|
195
|
-
/* @__PURE__ */H(R,{style:i.scrim,onPress:m,accessibilityRole:"button",accessibilityLabel:
|
|
195
|
+
/* @__PURE__ */H(R,{style:i.scrim,onPress:m,accessibilityRole:"button",accessibilityLabel:Cf.feedbackSkipA11y}),
|
|
196
196
|
/* @__PURE__ */U(w,{style:i.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
|
|
197
197
|
/* @__PURE__ */H(w,{style:i.handle}),
|
|
198
198
|
/* @__PURE__ */U(w,{style:i.header,children:[
|
|
199
|
-
/* @__PURE__ */H(w,{style:i.iconBadge,children:/* @__PURE__ */H(ThumbGlyph,{size:
|
|
199
|
+
/* @__PURE__ */H(w,{style:i.iconBadge,children:/* @__PURE__ */H(ThumbGlyph,{size:Rk,color:n.color.brandInk,active:false,rotate:"180deg"})}),
|
|
200
200
|
/* @__PURE__ */U(w,{style:i.headerText,children:[
|
|
201
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:
|
|
202
|
-
/* @__PURE__ */H(Text,{style:i.subtitle,children:
|
|
203
|
-
/* @__PURE__ */H(w,{style:i.options,children:
|
|
201
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:i.title,accessibilityRole:"header",children:Cf.feedbackTitle}),
|
|
202
|
+
/* @__PURE__ */H(Text,{style:i.subtitle,children:Cf.feedbackSubtitle})]})]}),
|
|
203
|
+
/* @__PURE__ */H(w,{style:i.options,children:gk.map(e=>{let t=o===e.key;/* @__PURE__ */
|
|
204
204
|
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[i.option,t?i.optionSelected:null],onPress:()=>s(t=>t===e.key?null:e.key),children:[
|
|
205
205
|
/* @__PURE__ */H(Text,{style:[i.optionLabel,t?i.optionLabelSelected:null],children:e.label}),
|
|
206
|
-
/* @__PURE__ */H(w,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */H(CheckGlyph,{size:
|
|
206
|
+
/* @__PURE__ */H(w,{style:[i.radio,t?i.radioSelected:null],children:t?/* @__PURE__ */H(CheckGlyph,{size:Tk,color:n.color.surface,strokeWidth:2}):null})]},e.key)})}),
|
|
207
207
|
/* @__PURE__ */U(w,{style:i.inputWrap,children:[
|
|
208
|
-
/* @__PURE__ */H(
|
|
208
|
+
/* @__PURE__ */H(ef,{style:i.input,placeholder:Cf.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:Cf.feedbackNotesPlaceholder,value:u,onChangeText:c,multiline:true,editable:!d}),u.length>0?/* @__PURE__ */H(Text,{tier:"compact",style:[i.counter,v?i.counterOver:null],children:`${[...u].length}/${Bn}`}):null]}),h?/* @__PURE__ */H(Text,{style:i.failed,accessibilityRole:"alert",children:Cf.feedbackFailed}):null,
|
|
209
209
|
/* @__PURE__ */U(w,{style:i.actions,children:[
|
|
210
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
211
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
210
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf.feedbackSubmit,accessibilityState:{busy:d,disabled:d||v},disabled:d||v,style:[i.submit,d||v?i.submitDisabled:null],onPress:()=>{y()},children:/* @__PURE__ */H(Text,{tier:"control",style:i.submitLabel,children:Cf.feedbackSubmit})}),
|
|
211
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:Cf.feedbackSkipA11y,hitSlop:8,onPress:m,style:i.skip,children:/* @__PURE__ */H(Text,{tier:"control",style:i.skipLabel,children:Cf.feedbackSkip})})]})]})]})})}function Ik(e){let t=e.color,r=e.type,n=e.radius,l=e.slots,i=Mg(l.dialog);return b.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ob,backgroundColor:kk},sheet:{backgroundColor:t.surface,borderTopLeftRadius:wk,borderTopRightRadius:wk,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...Dv(l.dialog)},handle:{alignSelf:"center",width:Ck,height:Sk,borderRadius:Sk/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:_k,height:_k,borderRadius:_k/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight,...i},subtitle:{...face(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted,...i},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:b.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...Ag(l.chip,b.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.text.primary,...Mg(l.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:xk,height:xk,borderRadius:xk/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",...Ag(l.input,1),...Mg(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,...Ag(l.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...Mg(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 zk=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function Pk(){let e=globalThis,t=e[zk];if(t!==void 0)return t;let r={factory:createContext(null),home:createContext(null)};return e[zk]=r,r}var Ok=Pk().factory,Ek=Pk().home;function jk(){return o(Ok)}function Fk(){return o(Ek)?.kit??null}function Ak(){return o(Ek)}var Dk=15,Mk=8;function HistoryBar({bar:e,history:t,empty:r,unread:n,extra:l}){let i=useEverfurTheme(),o=Fk(),s=a(()=>o!==null?Hk(i,o):Uk(i),[i,o]),u=t.cursor===null?t.rows.length:0,c=t=>{let r=e.renderIcon;if(r!==void 0)/* @__PURE__ */return H(HostRender,{render:()=>r(t),fallback:null});if(o===null)return null;let n=String(b.flatten(s.label).color??i.color.linkInk);return t==="history"?/* @__PURE__ */H(HistoryGlyph,{size:Bk,color:n,strokeWidth:1.8}):/* @__PURE__ */H(EditGlyph,{size:Bk,color:n,strokeWidth:1.8})};/* @__PURE__ */
|
|
212
212
|
return U(w,{style:s.bar,testID:"everfur-history-bar",children:[
|
|
213
|
-
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?
|
|
213
|
+
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:u>0?`${e.chats} ${u}`:e.chats,accessibilityState:{expanded:t.open},onPress:t.open?t.close:t.show,style:s.control,hitSlop:o!==null?Lk:void 0,children:[c("history"),
|
|
214
214
|
/* @__PURE__ */H(Text,{tier:"control",style:s.label,children:e.chats}),u>0?/* @__PURE__ */H(w,{style:s.count,children:/* @__PURE__ */H(Text,{tier:"badge",style:s.countText,children:String(u)})}):null,n?/* @__PURE__ */H(w,{style:s.dot,testID:"everfur-chat-history-bar-unread"}):null]}),e.extra??null,l??null,
|
|
215
|
-
/* @__PURE__ */H(w,{style:s.spacer}),r?null:/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?
|
|
216
|
-
/* @__PURE__ */H(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var
|
|
215
|
+
/* @__PURE__ */H(w,{style:s.spacer}),r?null:/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:t.newConversation,style:s.control,hitSlop:o!==null?Lk:void 0,children:[c("edit"),
|
|
216
|
+
/* @__PURE__ */H(Text,{tier:"control",style:s.label,children:e.newChat})]})]})}var Lk=4,Bk=18;function Hk(e,t){return{...Uk(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 Uk(e){let t=e.color,r=e.space;return b.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:Pb},label:{...face(e,"bold"),fontSize:Dk,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:Mk,height:Mk,borderRadius:Mk/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var Nk=.88,$k=420,Wk=58,Vk="rgba(17,17,17,0.28)",qk=.15,Gk=14,Kk=12,Yk=44,Qk=16,Jk=14,Xk=12,Zk=14,ew=8,tw=2,rw=.5,nw=dg(tg.standard);function lw(e){return Math.min(Math.round(e*Nk),$k)}function HistoryDrawer({chat:e,history:t}){let[r,n]=l(t.open),i=s(()=>n(false),[]);return t.open&&!r&&n(true),r?/* @__PURE__ */H(DrawerModal,{chat:e,history:t,onHidden:i}):null}function DrawerModal({chat:e,history:t,onHidden:r}){let l=useEverfurTheme(),i=a(()=>iw(l),[l]),o=ag(),s=L(),{width:c}=A(),d=lw(c),f=t.open,h=u(null);h.current===null&&(h.current=new F.Value(o.drawerMs<=0&&f?1:0));let g=h.current;n(()=>{if(!f&&o.drawerMs<=0){r();return}let e=F.timing(g,{toValue:f?1:0,duration:o.drawerMs,easing:nw,useNativeDriver:true});return e.start(({finished:e})=>{e&&!f&&r()}),()=>e.stop()},[f,g,o.drawerMs,r]);let b=g.interpolate({inputRange:[0,1],outputRange:[-d,0]}),m=t.filtered,y=t.rows.length===0,v=t.cursor===null&&!t.loading&&t.error===null,k=y&&t.loading?/* @__PURE__ */U(w,{style:i.emptyCard,accessibilityLabel:xp.loading,accessibilityState:{busy:true},children:[
|
|
217
217
|
/* @__PURE__ */H(P,{color:i.emptyTitle.color}),
|
|
218
|
-
/* @__PURE__ */H(Text,{style:i.emptyBody,children:
|
|
219
|
-
/* @__PURE__ */H(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:
|
|
218
|
+
/* @__PURE__ */H(Text,{style:i.emptyBody,children:xp.loading})]}):y&&t.error!==null?/* @__PURE__ */U(w,{style:i.emptyCard,children:[
|
|
219
|
+
/* @__PURE__ */H(Text,{style:i.emptyTitle,accessibilityRole:"alert",children:xp.loadFailed}),
|
|
220
220
|
/* @__PURE__ */H(Text,{style:i.emptyBody,children:t.error}),
|
|
221
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
222
|
-
/* @__PURE__ */H(Text,{style:i.emptyTitle,children:
|
|
223
|
-
/* @__PURE__ */H(Text,{style:i.emptyBody,children:
|
|
224
|
-
/* @__PURE__ */H(Text,{style:i.noMatch,children:
|
|
221
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:xp.retry,containerStyle:i.retrySlot,style:i.retryButton,onPress:()=>{t.load()},children:/* @__PURE__ */H(Text,{tier:"control",style:i.retryText,children:xp.retry})})]}):t.emptyKind==="empty"?/* @__PURE__ */U(w,{style:i.emptyCard,children:[
|
|
222
|
+
/* @__PURE__ */H(Text,{style:i.emptyTitle,children:xp.empty}),
|
|
223
|
+
/* @__PURE__ */H(Text,{style:i.emptyBody,children:xp.emptyBody})]}):
|
|
224
|
+
/* @__PURE__ */H(Text,{style:i.noMatch,children:xp.noMatch}),C=!t.searching&&t.loadingMore?/* @__PURE__ */H(w,{style:i.loadMoreFooter,children:/* @__PURE__ */H(Text,{style:i.loadMoreLabel,children:xp.loadingMore})}):null;/* @__PURE__ */
|
|
225
225
|
return H(I,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:/* @__PURE__ */U(w,{style:i.root,children:[
|
|
226
|
-
/* @__PURE__ */H(R,{style:
|
|
227
|
-
/* @__PURE__ */H(F.View,{style:[i.panel,{width:d,paddingTop:Math.max(
|
|
226
|
+
/* @__PURE__ */H(R,{style:ob,onPress:t.close,accessibilityRole:"button",accessibilityLabel:xp.closeA11y,children:/* @__PURE__ */H(F.View,{style:[i.backdrop,{opacity:g}]})}),
|
|
227
|
+
/* @__PURE__ */H(F.View,{style:[i.panel,{width:d,paddingTop:Math.max(Wk,s.top+l.space.md),transform:[{translateX:b}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */U(_,{style:i.keyboardAvoider,behavior:p.OS==="ios"?"padding":"height",children:[
|
|
228
228
|
/* @__PURE__ */U(w,{style:i.header,children:[
|
|
229
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:
|
|
230
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
231
|
-
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
229
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:i.heading,accessibilityRole:"header",children:xp.heading}),
|
|
230
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:xp.newChat,style:i.newChat,onPress:t.newConversation,children:/* @__PURE__ */H(Text,{tier:"control",style:i.newChatLabel,children:xp.newChat})}),
|
|
231
|
+
/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:xp.close,hitSlop:0,style:i.closeButton,onPress:t.close,children:/* @__PURE__ */H(CloseGlyph,{size:Qk,color:l.color.text.muted,strokeWidth:1.75})})]}),
|
|
232
232
|
/* @__PURE__ */U(w,{style:i.searchPill,children:[
|
|
233
|
-
/* @__PURE__ */H(SearchGlyph,{size:
|
|
234
|
-
/* @__PURE__ */H(
|
|
235
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:i.countLabel,children:
|
|
236
|
-
/* @__PURE__ */H(D,{data:m,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */H(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:m.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:C,onEndReached:t.loadMore,onEndReachedThreshold:
|
|
237
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
233
|
+
/* @__PURE__ */H(SearchGlyph,{size:Zk,color:l.color.text.muted,strokeWidth:1.5}),
|
|
234
|
+
/* @__PURE__ */H(ef,{value:t.query,onChangeText:e=>t.setQuery(e.replace(/^\s+/,"")),style:i.searchInput,placeholder:xp.searchPlaceholder,placeholderTextColor:l.color.text.placeholder,accessibilityLabel:xp.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
|
|
235
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:i.countLabel,children:Ip(t.rows.length,v)}),t.error!==null&&!y?/* @__PURE__ */H(w,{style:i.errorCard,children:/* @__PURE__ */H(Text,{style:i.errorText,accessibilityRole:"alert",children:t.error})}):null,
|
|
236
|
+
/* @__PURE__ */H(D,{data:m,keyExtractor:e=>e.id,renderItem:({item:r})=>/* @__PURE__ */H(Row,{row:r,active:r.id===e.conversationId,disabled:t.loading,styles:i,onPress:()=>{t.resume(r.id)}}),contentContainerStyle:m.length===0?i.listEmpty:i.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:k,ListFooterComponent:C,onEndReached:t.loadMore,onEndReachedThreshold:rw})]})})]})})}function Row({row:e,active:t,disabled:r,styles:n,onPress:l}){let i=e.unreadCount!==null&&e.unreadCount>0,o=Tp(e);/* @__PURE__ */
|
|
237
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:zp(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:l,children:[
|
|
238
238
|
/* @__PURE__ */U(w,{style:n.itemRow,children:[
|
|
239
|
-
/* @__PURE__ */H(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:
|
|
239
|
+
/* @__PURE__ */H(Text,{tier:"control",style:n.itemTitle,numberOfLines:1,children:_p(e.title)}),i?/* @__PURE__ */H(w,{style:n.unreadDot}):null]}),o!==null?/* @__PURE__ */H(Text,{tier:"compact",style:n.itemMeta,numberOfLines:1,children:o}):null]})}function iw(e){let t=e.color,r=e.space,n=e.type,l=e.slots,i=t.text.primary,o=Mg(l.card);return b.create({root:{flex:1},backdrop:{flex:1,backgroundColor:Vk},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:r.lg,borderRightWidth:b.hairlineWidth,borderRightColor:t.borderRingCream,gap:r.md,...Mv(l.dialog,b.hairlineWidth)},keyboardAvoider:{flex:1,gap:r.md},header:{flexDirection:"row",alignItems:"center",gap:r.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:n.size.subtitle,color:i,...Mg(l.dialog)},newChat:{minHeight:Yk,justifyContent:"center",paddingHorizontal:r.xs},newChatLabel:{...face(e,"bold"),fontSize:Gk,color:t.brandInk},closeButton:{width:Yk,height:Yk,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,...Ag(l.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:n.size.bodyTight,color:t.text.primary,padding:0,...Mg(l.input)},countLabel:{...face(e,"mono"),fontSize:Kk,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:oo(t.highlight,qk)??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:ew,height:ew,borderRadius:ew/2,backgroundColor:t.danger},errorCard:{borderRadius:Xk,borderWidth:b.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:r.md},errorText:{...face(e,"regular"),fontSize:n.size.caption,color:t.danger},emptyCard:{borderRadius:Jk,padding:r.md+tw,gap:r.xs+tw,backgroundColor:t.surfaceSubtle,borderWidth:b.hairlineWidth,borderColor:t.borderRingCream,...Ag(l.card,b.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:n.size.bodyTight,color:i,...o},emptyBody:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.secondary,...o},noMatch:{...face(e,"regular"),fontSize:n.size.bodyTight,color:t.text.muted,paddingVertical:r.sm},retrySlot:{marginTop:r.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:r.md+tw,paddingVertical:r.sm,borderWidth:1,borderColor:t.brandInk,...Ag(l.primaryButton)},retryText:{...face(e,"bold"),fontSize:n.size.caption,color:t.brandInk,...Mg(l.primaryButton)},loadMoreFooter:{paddingVertical:r.md+tw,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:n.size.caption,color:t.text.muted}})}function ow(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 aw(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function sw(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=ow(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 uw="rgba(38,37,35,0.38)",cw=28,dw=40,fw=5,hw=11,pw=10.5,gw=36,bw=11,mw=14,yw=15,vw=13.5,kw=48,ww=2,Cw=1.3,Sw=.12,xw=16,_w=8,Rw="80%";function Tw(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */H(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:t,sheet:r}){let n=useEverfurTheme(),l=a(()=>Iw(n),[n]),i=L(),o=a(()=>sw(t.rows),[t.rows]);if(!t.open)return null;let s=n.color,u=r?.title?.trim(),c=u!==void 0&&u!==""?u:xp.heading;/* @__PURE__ */
|
|
240
240
|
return H(I,{visible:true,transparent:true,animationType:"slide",onRequestClose:t.close,children:/* @__PURE__ */U(w,{style:l.root,children:[
|
|
241
|
-
/* @__PURE__ */H(R,{style:[
|
|
241
|
+
/* @__PURE__ */H(R,{style:[ob,l.scrim],onPress:t.close,accessibilityRole:"button",accessibilityLabel:xp.closeA11y}),
|
|
242
242
|
/* @__PURE__ */U(w,{style:[l.sheet,{paddingBottom:Math.max(40,i.bottom+n.space.lg)}],accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
|
|
243
243
|
/* @__PURE__ */H(w,{style:l.grab}),
|
|
244
244
|
/* @__PURE__ */U(w,{style:l.top,children:[
|
|
245
245
|
/* @__PURE__ */H(Text,{tier:"compact",style:l.kicker,accessibilityRole:"header",children:c}),
|
|
246
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
247
|
-
/* @__PURE__ */U(z,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */U(w,{style:l.state,accessibilityLabel:
|
|
246
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:xp.closeA11y,onPress:t.close,style:l.close,children:Tw(r,"close",/* @__PURE__ */H(CloseGlyph,{size:22,color:s.text.primary,strokeWidth:2}))})]}),
|
|
247
|
+
/* @__PURE__ */U(z,{style:l.scroll,contentContainerStyle:l.scrollContent,keyboardShouldPersistTaps:"handled",children:[t.loading&&t.rows.length===0?/* @__PURE__ */U(w,{style:l.state,accessibilityLabel:xp.loading,accessibilityState:{busy:true},children:[
|
|
248
248
|
/* @__PURE__ */H(P,{color:s.brandInk}),
|
|
249
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:l.mono,children:
|
|
250
|
-
/* @__PURE__ */H(Text,{style:l.stateText,accessibilityRole:"alert",children:
|
|
251
|
-
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
252
|
-
return U(R,{accessibilityRole:"button",accessibilityLabel:
|
|
253
|
-
/* @__PURE__ */H(w,{style:l.icon,children:
|
|
249
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:l.mono,children:xp.loading})]}):null,t.error!==null?/* @__PURE__ */U(w,{style:l.state,children:[
|
|
250
|
+
/* @__PURE__ */H(Text,{style:l.stateText,accessibilityRole:"alert",children:xp.loadFailed}),
|
|
251
|
+
/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:xp.retry,onPress:()=>{t.load()},style:l.link,children:/* @__PURE__ */H(Text,{tier:"control",style:l.linkText,children:xp.retry})})]}):null,!t.loading&&t.error===null&&t.rows.length===0?/* @__PURE__ */H(Text,{style:[l.stateText,l.state],children:xp.empty}):null,o.map((n,i)=>/* @__PURE__ */U(h,{children:[n.day?/* @__PURE__ */H(Text,{tier:"compact",style:[l.mono,l.day,i===0?l.dayFirst:null],children:n.day}):null,n.rows.map(n=>{let i=n.id===e.conversationId,o=n.unreadCount!==null&&n.unreadCount>0,a=aw(n.updatedAt);/* @__PURE__ */
|
|
252
|
+
return U(R,{accessibilityRole:"button",accessibilityLabel:zp(n),accessibilityState:{selected:i},onPress:()=>{t.resume(n.id)},style:[l.row,i?l.rowCurrent:null],children:[
|
|
253
|
+
/* @__PURE__ */H(w,{style:l.icon,children:Tw(r,"chat",/* @__PURE__ */H(ChatBubbleGlyph,{size:19,color:s.linkInk,strokeWidth:1.75}))}),
|
|
254
254
|
/* @__PURE__ */U(w,{style:l.rowWords,children:[
|
|
255
|
-
/* @__PURE__ */H(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:
|
|
256
|
-
/* @__PURE__ */U(w,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */H(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */H(w,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:
|
|
257
|
-
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:
|
|
258
|
-
/* @__PURE__ */H(Text,{tier:"control",style:l.newChatText,children:
|
|
255
|
+
/* @__PURE__ */H(Text,{tier:"control",style:l.rowTitle,numberOfLines:1,children:_p(n.title)}),n.preview!==void 0?/* @__PURE__ */H(Text,{tier:"compact",style:l.preview,numberOfLines:1,children:n.preview}):null]}),
|
|
256
|
+
/* @__PURE__ */U(w,{style:l.rowEnd,children:[a!==null?/* @__PURE__ */H(Text,{tier:"compact",style:[l.mono,l.time,o?l.timeUnread:null],children:a}):null,o?/* @__PURE__ */H(w,{style:l.unreadDot,testID:`everfur-history-sheet-unread-${String(n.id)}`}):null]})]},String(n.id))})]},n.day)),t.cursor!==null&&!t.loadingMore?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:xp.more,onPress:t.loadMore,style:l.link,children:/* @__PURE__ */H(Text,{tier:"control",style:l.linkText,children:xp.more})}):null]}),
|
|
257
|
+
/* @__PURE__ */U(R,{accessibilityRole:"button",accessibilityLabel:xp.newChat,onPress:t.newConversation,style:l.newChat,children:[Tw(r,"edit",/* @__PURE__ */H(EditGlyph,{size:18,color:n.slots.primaryButton?.textColor??s.onPrimary,strokeWidth:1.75})),
|
|
258
|
+
/* @__PURE__ */H(Text,{tier:"control",style:l.newChatText,children:xp.newChat})]})]})]})})}function Iw(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:pw,letterSpacing:pw*.06,textTransform:"uppercase",color:t.text.muted};return b.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:uw},sheet:{maxHeight:Rw,backgroundColor:t.surface,borderTopLeftRadius:cw,borderTopRightRadius:cw,paddingTop:10,paddingHorizontal:20},grab:{width:dw,height:fw,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...n,fontSize:hw,letterSpacing:hw*.08,flexShrink:1},close:{width:Pb,height:Pb,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:Pb/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:r.xs},mono:n,day:{marginTop:r.lg,marginBottom:r.xs},dayFirst:{marginTop:ww},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:Pb,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:mw,minHeight:Pb},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:gw,height:gw,borderRadius:bw,backgroundColor:oo(t.linkInk,Sw)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:yw,lineHeight:yw*Cw,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:pw*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:_w,height:_w,borderRadius:_w/2,backgroundColor:t.danger},newChat:{marginTop:r.lg,minHeight:kw,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...Ag(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:xw,color:t.onPrimary,...Mg(e.slots.primaryButton)}})}var zw="Close",Pw=/* @__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:`${Ow(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function Ow(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={...Pw,...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()===""?zw: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()===""?zw:s,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function Ew(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function jw(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var Fw=20,Aw=14,Dw=16,Mw=18,Lw=22,Bw=15,Hw=12,Uw=24,Nw=15,$w=14.5,Ww=21,Vw=14.5,qw=18,Gw=9,Kw=36,Yw=14,Qw=15,Jw=8,Xw=40;function TopCard({card:e,open:t,onOpenChange:r,ask:n}){let l=useEverfurTheme(),i=Fk(),o=a(()=>i!==null?eC(i):tC(l),[l,i]),s=a(()=>Ag(l.slots.card),[l.slots.card]);if(!t)return null;let u=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:Cf.close,c=e.action,d=e.ask,f=/* @__PURE__ */H(CloseGlyph,{size:i!==null?HOME_CLOSE_GLYPH(i):qw,color:i!==null?String(i.text(".ask-focus__x").color):l.color.text.primary,strokeWidth:2});/* @__PURE__ */
|
|
259
259
|
return U(w,{style:[o.card,s],testID:"everfur-top-card",children:[
|
|
260
260
|
/* @__PURE__ */U(w,{style:o.kickerRow,children:[
|
|
261
|
-
/* @__PURE__ */H(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */H(w,{style:o.badge,children:/* @__PURE__ */H(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */H(R,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?
|
|
261
|
+
/* @__PURE__ */H(Text,{tier:"control",style:o.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */H(w,{style:o.badge,children:/* @__PURE__ */H(Text,{tier:"compact",style:o.badgeText,numberOfLines:1,children:e.badge})}):null,u!==null?/* @__PURE__ */H(R,{onPress:()=>r(false),accessibilityRole:"button",accessibilityLabel:u,style:o.close,hitSlop:i!==null?Zw:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */H(HostRender,{render:()=>e.renderIcon?.("close"),fallback:f}):f}):null]}),
|
|
262
262
|
/* @__PURE__ */H(Text,{tier:"heading",style:o.title,accessibilityRole:"header",children:e.title}),e.lead!==void 0||e.body!==void 0?/* @__PURE__ */U(w,{style:o.finding,children:[
|
|
263
263
|
/* @__PURE__ */H(w,{style:o.dot}),
|
|
264
|
-
/* @__PURE__ */U(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */H(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */U(w,{style:o.actions,children:[c!==void 0?/* @__PURE__ */H(R,{onPress:()=>{
|
|
265
|
-
return U(R,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?
|
|
264
|
+
/* @__PURE__ */U(Text,{style:o.findingText,children:[e.lead!==void 0?/* @__PURE__ */H(Text,{style:o.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,c!==void 0||d!==void 0?/* @__PURE__ */U(w,{style:o.actions,children:[c!==void 0?/* @__PURE__ */H(R,{onPress:()=>{hh(c.onPress)},accessibilityRole:"button",accessibilityLabel:c.label,style:o.action,hitSlop:i!==null?Zw:void 0,children:/* @__PURE__ */H(Text,{tier:"control",style:o.actionText,children:c.label})}):null,d!==void 0?/* @__PURE__ */H(R,{onPress:()=>n(d.prompt),accessibilityRole:"button",accessibilityLabel:d.label,style:o.ask,hitSlop:i!==null?Zw:void 0,children:/* @__PURE__ */H(Text,{tier:"control",style:o.askText,children:d.label})}):null]}):null]})}function TopCardPill({card:e,open:t,onOpenChange:r}){let n=useEverfurTheme(),l=Fk(),i=a(()=>l!==null?eC(l):tC(n),[n,l]);if(t||e.closeLabel===void 0)return null;let o=e.pill??e.kicker;/* @__PURE__ */
|
|
265
|
+
return U(R,{onPress:()=>r(true),accessibilityRole:"button",accessibilityLabel:o,accessibilityState:{expanded:false},style:i.pill,hitSlop:l!==null?Zw:void 0,testID:"everfur-top-card-pill",children:[
|
|
266
266
|
/* @__PURE__ */H(w,{style:i.pillDot}),
|
|
267
|
-
/* @__PURE__ */H(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var Qw=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:$w};function Jw(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),l=typeof n.height=="number"?n.height:Ww;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-l)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function Xw(e){let t=e.color,r=e.space;return b.create({card:{paddingTop:Ew,paddingHorizontal:jw,paddingBottom:jw,borderRadius:Ow,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:xb-8},kicker:{...Pw(e),fontSize:Dw,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:Lw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:Mw,color:t.text.secondary},close:{width:xb,height:xb,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:xb/2},title:{...Pw(e),fontSize:Fw,lineHeight:Aw,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:Ww,height:Ww,borderRadius:Ww/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:Hw,lineHeight:Uw,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(Yw,xb),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:Bw,color:t.onPrimary},ask:{minHeight:xb,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:Nw,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(Vw,xb),paddingHorizontal:qw,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:Kw,height:Kw,borderRadius:Kw/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:Gw,color:t.danger,flexShrink:1}})}var Zw=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),eC=/* @__PURE__ */new WeakMap;function tC(e){let t=eC.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...Zw},i=(e,t)=>so(e,t,eo(t),rC),o=(e,t)=>contrastRatio(e,t)>=rC?e:Zi(t,rC),a=[l.card,l.paper].map(e=>io(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return eC.set(e,u),u}var rC=4.5;function nC(e,t){for(let r of t)if(contrastRatio(r,e)>=rC)return r;return Zi(e,rC)}function lC(e,t,r){let n=oo(e,t);return(n===null?null:io(n,r))??r}function iC(e){let t=tC(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:nC(t.accent,[t.ink,t.onAccent]),accent2:lC(t.accent,.75,n),accent4:lC(t.accent,.17,n),accentChip:lC(t.accent,.47,n),link:t.link,linkChip:lC(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var oC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),aC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),sC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],uC=17,cC=1.5,dC=400,fC=700;function hC(e){return e<=450?"regular":e<=650?"medium":"bold"}function pC(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function gC(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:pC(r)}}let n=t==="$serif"?headingFace(e,hC(r)):face(e,hC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:pC(r)}}function bC(e,t,r={}){let n=iC(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},a=/* @__PURE__ */new Map,s=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),s=a.get(l);if(s!==void 0)return s;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return a.set(l,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=s(e),l={};for(let[e,t]of Object.entries(n))oC.has(e)||aC.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of sC){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let a=n.shadow;if(Array.isArray(a)){let[e,t,r,n]=a;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=s(r),a=typeof o.fontSize=="number"?o.fontSize:uC,u=typeof o.lh=="number"?o.lh:cC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...gC(e,f,c),fontSize:a,lineHeight:Math.round(a*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*a*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(dC,e),strong:(...e)=>f(fC,e),icon:(...e)=>{let t=s(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=s([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=s(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>s(t)[e]}}var mC={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},yC=16;var vC=4e3,kC=.5;function wC(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function CC(e,t,r){if(e.length===0)return r;let n=wC(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=kC*e.length+1;for(let o of l)if(wC(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=b.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=u({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[c,d]=l(null),f=c!==null&&c.key===o?c.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=CC(t,l,(e.ch+kC)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
268
|
-
return U(w,{style:
|
|
267
|
+
/* @__PURE__ */H(Text,{tier:"control",style:i.pillText,numberOfLines:1,children:o})]})}var Zw=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:qw};function eC(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:Gw;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 b.create({card:{paddingTop:Aw,paddingHorizontal:Dw,paddingBottom:Dw,borderRadius:Fw,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Pb-8},kicker:{...jw(e),fontSize:Bw,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:Uw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:Hw,color:t.text.secondary},close:{width:Pb,height:Pb,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:Pb/2},title:{...jw(e),fontSize:Mw,lineHeight:Lw,color:t.text.primary,marginTop:r.xs},finding:{flexDirection:"row",gap:r.sm,marginTop:r.xs+2},dot:{width:Gw,height:Gw,borderRadius:Gw/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:$w,lineHeight:Ww,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.lg,marginTop:14},action:{minHeight:Math.max(Xw,Pb),paddingHorizontal:r.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:Nw,color:t.onPrimary},ask:{minHeight:Pb,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:Vw,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:r.sm,minHeight:Math.max(Kw,Pb),paddingHorizontal:Yw,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:Jw,height:Jw,borderRadius:Jw/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:Qw,color:t.danger,flexShrink:1}})}var rC=/* @__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"}),nC=/* @__PURE__ */new WeakMap;function lC(e){let t=nC.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,...rC},i=(e,t)=>so(e,t,eo(t),iC),o=(e,t)=>contrastRatio(e,t)>=iC?e:Zi(t,iC),a=[l.card,l.paper].map(e=>io(r.brandSoft,e)??e),s={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,a)},u=/* @__PURE__ */Object.freeze({...l,...s});return nC.set(e,u),u}var iC=4.5;function oC(e,t){for(let r of t)if(contrastRatio(r,e)>=iC)return r;return Zi(e,iC)}function aC(e,t,r){let n=oo(e,t);return(n===null?null:io(n,r))??r}function sC(e){let t=lC(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:oC(t.accent,[t.ink,t.onAccent]),accent2:aC(t.accent,.75,n),accent4:aC(t.accent,.17,n),accentChip:aC(t.accent,.47,n),link:t.link,linkChip:aC(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 uC=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),cC=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),dC=["paddingTop","paddingRight","paddingBottom","paddingLeft"],fC=17,hC=1.5,pC=400,gC=700;function bC(e){return e<=450?"regular":e<=650?"medium":"bold"}function mC(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function yC(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:mC(r)}}let n=t==="$serif"?headingFace(e,bC(r)):face(e,bC(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:mC(r)}}function vC(e,t,r={}){let n=sC(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))uC.has(e)||cC.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 dC){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:fC,u=typeof o.lh=="number"?o.lh:hC,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...yC(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(pC,e),strong:(...e)=>f(gC,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 kC={".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"]}},wC=16;var CC=4e3,SC=.5;function xC(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 _C(e,t,r){if(e.length===0)return r;let n=xC(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=SC*e.length+1;for(let o of l)if(xC(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:t,measureCh:r}){let n=a(()=>e.split(/\s+/).filter(e=>e!==""),[e]),i=b.flatten(t),o=[e,i.fontFamily,i.fontSize,i.fontWeight,i.letterSpacing].join("|"),s=u({key:"",ch:null,line:null,words:[]});s.current.key!==o&&(s.current={key:o,ch:null,line:null,words:n.map(()=>null)});let[c,d]=l(null),f=c!==null&&c.key===o?c.value:null,h=()=>{let e=s.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,n=t.reduce((e,t)=>e+t,0),l=t.length>1?Math.max(0,(e.line-n)/(t.length-1)):0,i=_C(t,l,(e.ch+SC)*r);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{s.current.key===o&&(e(s.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
268
|
+
return U(w,{style:RC.wrap,children:[
|
|
269
269
|
/* @__PURE__ */H(Text,{tier:"heading",style:f===null?t:[t,{maxWidth:f}],accessibilityRole:"header",children:e}),
|
|
270
|
-
/* @__PURE__ */H(w,{style:
|
|
270
|
+
/* @__PURE__ */H(w,{style:RC.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */U(w,{style:RC.probeRow,children:[
|
|
271
271
|
/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.ch=t}),children:"0"}),
|
|
272
|
-
/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var
|
|
273
|
-
return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:
|
|
272
|
+
/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.line=t}),children:n.join(" ")}),n.map((e,r)=>/* @__PURE__ */H(Text,{tier:"heading",style:t,onLayout:p((e,t)=>{e.words[r]=t}),children:e},`${r}:${e}`))]})})]})}var RC=b.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:CC,flexDirection:"row",alignItems:"flex-start"}});function TC(e){return{kit:vC(e,kC),Title:BalancedTitle,titleCh:wC}}var IC=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function zC(){let e=globalThis,t=e[IC];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[IC]=r,r}var PC=e=>{let t=zC();return t.listeners.add(e),()=>t.listeners.delete(e)},OC=()=>zC().count>0;function useHostPoweredBy(){return i(PC,OC,OC)}var EC=/* @__PURE__ */Object.freeze({}),jC=100,FC=20;function AC(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 DC(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=AC(n,l.y,l.height,v.get("window").height);if(i!==null){c(e=>e!==null&&e.chatTop===i.chatTop&&e.parentTop===i.parentTop?e:i);return}t>=FC||(f.current=setTimeout(()=>{f.current=null,e(t+1)},jC))})},[]),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}:EC,probeRef:null,topInWindow:null};let n=o?.parentTop??0;return{avoidingProps:r?{keyboardVerticalOffset:e,onLayout:b}:n>0?{keyboardVerticalOffset:n,onLayout:b}:{onLayout:b},probeRef:i,topInWindow:o?.chatTop??null}},[t,r,e,o,b])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */H(w,{ref:e,collapsable:false,pointerEvents:"none",style:MC})}var MC=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function LC(){let[e,t]=l(false);return n(()=>{let e=T;if(typeof e?.addListener!="function")return;let r=p.OS==="ios",n=e.addListener(r?"keyboardWillShow":"keyboardDidShow",()=>t(true)),l=e.addListener(r?"keyboardWillHide":"keyboardDidHide",()=>t(false));return()=>{n.remove(),l.remove()}},[]),e}function BC(e,t,r){return so(e,t,eo(t),r)}function HC(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=_v(t),l=r?n.warning:n.info,i=xv(t)&&!l?e:UC(e,t,r);return NC(i,t.slots.banner)}function UC(e,t,r){let n=t.color,l=io(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,i=r?n.cautionAccent:n.infoEdge,o=BC(io(i,n.surface)??i,[n.surface,n.chatGround],xo),a=BC(r?n.warningStrong:n.info,[l,n.surface],bo);/* @__PURE__ */
|
|
273
|
+
return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:a,reasonColor:BC(n.text.primary,[l],bo),pillColor:n.surface})}function NC(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 $C(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 WC=.75,VC=1.5,qC=.4,GC=4,KC=1.5,YC=22,QC=14,JC=8,XC=20,ZC=10,eS=13,tS=12,rS=15,nS=44,lS=14,iS=1.25,oS=14,aS=6,sS=2;function uS(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:oo(r.danger,qC)??r.danger,borderWidth:VC},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:WC,...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(()=>cS(o),[o]),u=ag(),c=e.tier===null?null:HC(e.tier,o),d=e.source;/* @__PURE__ */
|
|
274
274
|
return U(N,{children:[
|
|
275
275
|
/* @__PURE__ */H(FadePresence,{visible:e.showBanner&&c!==null,inMs:u.bannerInMs,outMs:u.bannerOutMs,style:s.pinned,children:c!==null&&d!==null?/* @__PURE__ */H(BannerCard,{tier:c,reason:d.reason,surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:l,styles:s,compact:i}):null}),
|
|
276
|
-
/* @__PURE__ */H(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
276
|
+
/* @__PURE__ */H(FadePresence,{visible:e.showCompactIcon,inMs:u.iconInMs,outMs:u.iconOutMs,style:s.indicatorRow,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf.showLatestVetAlert,hitSlop:ZC,onPress:e.expand,children:/* @__PURE__ */H(InfoGlyph,{size:XC,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=uS(u,e),d=/* @__PURE__ */H(VetAction,{tier:e,paint:c,petRef:n,onFindVet:i,vet:o,styles:a}),f=r.showVetAction?l!==void 0?/* @__PURE__ */H(HostRender,{render:()=>l(e.level),fallback:d,resetKey:e.level}):d:null,h=c.action!==null?/* @__PURE__ */H(PoisonControl,{paint:c.action,styles:a}):null,p=e.level==="emergency"&&i===void 0,g=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
|
|
277
277
|
return U(w,{...g?{accessibilityRole:"alert"}:{accessibilityLiveRegion:"polite"},style:[a.card,c.card,s?a.cardCompact:null],testID:s?"chat-urgency-compact":void 0,children:[
|
|
278
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */H(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?
|
|
279
|
-
return H(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
280
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:u?
|
|
281
|
-
/* @__PURE__ */H(MapPinGlyph,{size:
|
|
282
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=
|
|
283
|
-
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
284
|
-
/* @__PURE__ */H(MapPinGlyph,{size:
|
|
285
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:
|
|
286
|
-
/* @__PURE__ */H(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */H(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:
|
|
287
|
-
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:
|
|
278
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[a.label,{color:c.label}],children:e.label}),t!==null?/* @__PURE__ */H(Text,{style:[a.reason,{color:c.reason}],numberOfLines:s?sS:void 0,accessibilityLabel:s?t:void 0,children:t}):null,p?/* @__PURE__ */H(Text,{style:[a.reason,a.erLine,{color:c.reason}],children:Cf.goToNearestEmergencyVet}):null,f!==null||h!==null?/* @__PURE__ */U(w,{style:a.actions,children:[f,h]}):null,r.dismissLabel!==null?/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:r.dismissLabel,hitSlop:JC,containerStyle:a.closeSlot,style:a.closeButton,onPress:r.dismiss,children:/* @__PURE__ */H(CloseGlyph,{size:QC,color:c.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let r=()=>{try{x.openURL(Rf).catch(()=>{})}catch{}};/* @__PURE__ */
|
|
279
|
+
return H(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:r,children:/* @__PURE__ */H(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:Cf.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:l,styles:i}){let o=useEverfurTheme(),a=useVetVisit($C(r,l)),s=a.status==="opening",u=!a.available&&n!==void 0,c=a.available?()=>{a.open()}:n!==void 0?()=>{hh(n,e.level)}:null;if(c===null)return null;let d=t.action;if(d!==null){let e=u?Cf.nearestEmergencyVet:Cf.findVet,t=Dg(o.slots.vetVisitButton)?.textColor??d.ink;/* @__PURE__ */
|
|
280
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:u?Cf.nearestEmergencyVet:Cf.findVetA11y,accessibilityState:{busy:s},hitSlop:0,style:[i.action,{backgroundColor:d.fill,borderColor:d.edge},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
|
|
281
|
+
/* @__PURE__ */H(MapPinGlyph,{size:eS,color:t,strokeWidth:1.5}),
|
|
282
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[i.actionLabel,{color:t}],children:e})]})}let f=Dg(o.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
|
|
283
|
+
return U(PressScale,{accessibilityRole:"button",accessibilityLabel:Cf.findVetA11y,accessibilityState:{busy:s},style:[i.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},i.findVetSlotBox,s?i.findVetBusy:null],onPress:c,children:[
|
|
284
|
+
/* @__PURE__ */H(MapPinGlyph,{size:eS,color:f,strokeWidth:1.5}),
|
|
285
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[i.findVetLabel,{color:f}],children:Cf.findVet})]})}function cS(e){let t=Dg(e.slots.vetVisitButton),r=e.space,n=e.type;return b.create({pinned:{marginTop:0,marginBottom:r.xs,paddingHorizontal:r.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:r.lg+GC,paddingVertical:r.lg,gap:r.sm},cardCompact:{paddingVertical:r.md,gap:r.xs},label:{...face(e,"bold"),fontSize:n.size.body,paddingRight:YC},reason:{...face(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*KC),paddingRight:YC},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm},action:{flexDirection:"row",alignItems:"center",gap:aS,minHeight:nS,paddingHorizontal:lS,borderRadius:e.radius.pill,borderWidth:iS},actionLabel:{...face(e,"bold"),fontSize:oS},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...Ag(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:tS,lineHeight:rS},closeSlot:{position:"absolute",top:r.md,right:r.md},closeButton:{width:YC,height:YC,borderRadius:YC/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:r.lg,paddingTop:2,paddingBottom:r.xs}})}function dS(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=Di(e,()=>{i()});return()=>{n=false,o()}},[c,e,t,r,i]),c}var fS=/* @__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}=cd(),d=e?.petRef??o??null,f=e?.conversationId??null,h=dS(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():fS,[m]),w=i(v,k,k),C=s((e,t)=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?pS(m,m.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>y.current===m):Promise.resolve(bS()),[m]),S=s(e=>m&&y.current===m&&!m.getSnapshot().isBootstrapping?pS(m,m.askEverfur(e),()=>y.current===m):Promise.resolve(bS()),[m]),x=s(()=>m&&y.current===m?pS(m,m.retryLast(),()=>y.current===m):Promise.resolve(bS()),[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:hS,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,yk(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=()=>{},hS=/* @__PURE__ */Object.freeze({});async function pS(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(gS(n.messages))}function gS(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 bS(){return Jh()}function mS(){let e=useEverfurPets(),{handle:t}=cd(),r=s(e=>t.setActivePet(e),[t]);return a(()=>({...e,setActivePet:r}),[e,r])}function yS(){try{let e=m?.announceForAccessibility;typeof e=="function"&&e.call(m,Cf.answered)}catch{}}function vS(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"&&yS()}t.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var kS=/* @__PURE__ */Object.freeze({kind:"live"}),wS=/* @__PURE__ */Object.freeze({kind:"folded"});function CS(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=xn(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function SS(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=CS(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=CS(l);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===l.id){t.set(l.id,kS),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(l.id,wS);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 xS(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var _S=864e5,RS=365;function TS(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/_S)-Math.floor(r/_S);return l<1||l>RS?null:l}function IS(e){return CS(e)?.dueDay||null}function zS(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=yv(e);return n.shown?/* @__PURE__ */U(w,{style:r.assistantSender,testID:"everfur-assistant-sender",children:[
|
|
286
|
+
/* @__PURE__ */H(BrandImage,{uri:e,decorative:true,style:r.assistantAvatar,resizeMode:"cover",onError:n.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */H(Text,{tier:"control",style:[r.assistantName,r.assistantNameInRow],children:Cf.assistantName}):null]}):t?/* @__PURE__ */H(Text,{tier:"control",style:r.assistantName,children:Cf.assistantName}):null}var PS=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),OS="#C8BEB4";function ES(e){return e?PS[e.toUpperCase()]??OS:OS}function jS(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function FS(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function AS(e){let t=FS(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function DS(e,t){let r=FS(e.source_name)??FS(e.sourceName),n=FS(e.section),l=FS(e.authority_tier)??FS(e.authorityTier),i=jS(l),o=r??FS(e.title)??`Source ${t+1}`,a=FS(e.monograph_chunk_id)??FS(e.chunkId),s=[n,i].filter(e=>e!==null).join(" · ");/* @__PURE__ */
|
|
287
|
+
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:s.length===0?null:s,url:AS(e.url),excerpt:FS(e.excerpt),tierColor:ES(l),key:`${o}-${a??"none"}-${t}`})}function MS(e){return e===void 0||e.length===0?LS:/* @__PURE__ */Object.freeze(e.map((e,t)=>DS(e,t)))}var LS=/* @__PURE__ */Object.freeze([]);function BS(e){return e===1?`1 ${Cf.sourceSingular}`:`${e} ${Cf.sourcePlural}`}function HS(e,t){return`${t?Cf.hideSources:Cf.showSources} ${BS(e)}`}function US(e){return[e.url!==null?`${Cf.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function NS(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var $S=/^\s*[-*]\s+(\S.*)$/,WS=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function VS(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=$S.exec(t),o=e===null?WS.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 qS(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 GS(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function KS(e){return hardenHttpsUrl(e.trim())}function YS(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?[]:GS(t.followUpActions,{answer:r.text,question:qS(e.messages,r.id),messageId:r.id})}var QS=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,JS=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${$p}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${$p}})`,"gi"),XS=/https:\/\//i,ZS=`.,;:!?'"`;function ex(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&XS.test(e)}function tx(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):lx(r,e,t)},l=0;QS.lastIndex=0;for(let t=QS.exec(e);t!==null;t=QS.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 rx(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(ZS.includes(r))t-=1;else if(r===")"&&nx(e,"(",t)<nx(e,")",t))t-=1;else break}return e.slice(0,t)}function nx(e,t,r){let n=0;for(let l=0;l<r;l+=1)e[l]===t&&(n+=1);return n}function lx(e,t,r){if(!XS.test(t)){e.push({kind:"text",text:t});return}let n=0;JS.lastIndex=0;for(let l=JS.exec(t);l!==null;l=JS.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?Gp(o,r):null,c=l[0].length;else if(a!==void 0)s=rx(a),u=Gp(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,JS.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var ix=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function ox(e,t){return t===void 0||!ex(e,t.hosts)?false:tx(e,t.hosts).some(e=>e.kind==="link")}function ax(e,t,r){let n=r?.hosts;return ex(e,n)?tx(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
|
|
288
288
|
return H(Text,{style:t.bold,children:e.text},n);case"italic":return t.italic?/* @__PURE__ */H(Text,{style:t.italic,children:e.text},n):e.text;case"code":return t.code?/* @__PURE__ */H(Text,{style:t.code,children:e.text},n):e.text;case"link":{if(r===void 0)return e.text;let{href:t}=e;/* @__PURE__ */
|
|
289
|
-
return H(Text,{style:
|
|
290
|
-
return H(w,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */H(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?
|
|
289
|
+
return H(Text,{style:ix,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var sx=10.5,ux=16,cx=12,dx=38,fx=11,hx=15,px=22,gx=32,bx=13.5,mx=14,yx=15,vx=16,kx=13,wx=13,Cx=26,Sx=21,xx=42,_x=1,Rx=.06,Tx=.07,Ix=.12,zx="45%";function Px(){let e=useEverfurTheme(),t=a(()=>Ox(e),[e]);return{theme:e,styles:t}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */H(ChevronGlyph,{size:vx,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */H(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:r,styles:n}=Px();if(e.render!==void 0){let r=e.render;/* @__PURE__ */
|
|
290
|
+
return H(w,{style:[n.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */H(HostRender,{render:r,fallback:null})})}let l=e.value!==void 0,i=t?.styles,o=[n.card,l?i?.cardStat:null,e.variant!==void 0?i?.cardVariant?.[e.variant]:null],a=e.tile?.tone,s=e.pill?.tone,u=e.tile?.imageUrl!==void 0?KS(e.tile.imageUrl):null,c=/* @__PURE__ */U(N,{children:[l?null:/* @__PURE__ */H(w,{style:[n.tile,a!==void 0?i?.tileTone?.[a]:null],children:u!==null?/* @__PURE__ */H(O,{source:{uri:u},style:n.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
|
|
291
291
|
/* @__PURE__ */U(w,{style:n.cardWords,children:[
|
|
292
292
|
/* @__PURE__ */H(Text,{tier:"control",style:n.cardTitle,children:e.title}),e.meta!==void 0?/* @__PURE__ */H(Text,{tier:"compact",style:n.cardMeta,children:e.meta}):null]}),l?/* @__PURE__ */U(Text,{tier:"control",style:n.stat,children:[e.value?.amount,e.value?.unit!==void 0?/* @__PURE__ */H(Text,{style:n.statUnit,children:e.value.unit}):null]}):/* @__PURE__ */U(N,{children:[e.pill!==void 0?/* @__PURE__ */H(w,{style:[n.pill,s!==void 0?i?.pillTone?.[s]:null],children:/* @__PURE__ */H(Text,{tier:"badge",style:[n.pillText,s!==void 0?i?.pillToneText?.[s]:null],numberOfLines:1,ellipsizeMode:"tail",children:e.pill.label})}):null,e.onPress!==void 0?/* @__PURE__ */H(Chevron,{options:t,color:r.color.text.muted}):null]})]});if(e.onPress!==void 0){let t=e.onPress;/* @__PURE__ */
|
|
293
|
-
return H(R,{onPress:()=>{
|
|
294
|
-
return H(w,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=
|
|
293
|
+
return H(R,{onPress:()=>{hh(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:o,children:c})}/* @__PURE__ */
|
|
294
|
+
return H(w,{style:o,children:c})}function CardsAnswer({message:e,text:t,streaming:r,messages:n,options:l,sentiment:i,onSentiment:o,sender:s,footer:u,onOpenUrl:c}){let{styles:d}=Px(),f=a(()=>({answer:e.text,question:qS(n,e.id),messageId:e.id}),[e.text,e.id,n]),h=!r&&e.pending!==true,p=h?GS(l?.cards,f):[],g=a(()=>h?MS(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=Qp(),k=h?v:void 0;/* @__PURE__ */
|
|
295
295
|
return U(w,{style:d.answer,testID:"everfur-answer-cards",children:[b!==void 0?/* @__PURE__ */U(w,{style:d.byline,children:[b.icon??null,
|
|
296
296
|
/* @__PURE__ */H(Text,{tier:"compact",style:d.bylineText,children:b.label})]}):s,
|
|
297
|
-
/* @__PURE__ */H(w,{style:d.body,children:
|
|
297
|
+
/* @__PURE__ */H(w,{style:d.body,children:NS(t).flatMap((e,t)=>VS(e).map((e,r)=>{let n=`${t}-${r}`;return e.kind==="text"?/* @__PURE__ */H(Text,{style:d.paragraph,children:ax(e.text,y,k)},n):/* @__PURE__ */H(w,{style:d.list,children:e.items.map((t,r)=>/* @__PURE__ */U(w,{style:d.listItem,children:[
|
|
298
298
|
/* @__PURE__ */H(Text,{style:d.paragraph,children:e.ordered?`${e.start+r}.`:"•"}),
|
|
299
|
-
/* @__PURE__ */H(Text,{style:[d.paragraph,d.listText],children:
|
|
300
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:d.label,children:
|
|
299
|
+
/* @__PURE__ */H(Text,{style:[d.paragraph,d.listText],children:ax(t,y,k)})]},r))},n)}))}),p.length>0?/* @__PURE__ */H(w,{style:d.cards,children:p.map(e=>/* @__PURE__ */H(AnswerCard,{card:e,options:l},e.key))}):null,g.length>0?/* @__PURE__ */U(w,{style:d.cards,accessibilityLabel:BS(g.length),children:[
|
|
300
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:d.label,children:Cf.sourcesHeading}),g.map(e=>{let t=e.url;/* @__PURE__ */
|
|
301
301
|
return H(AnswerCard,{card:{key:e.key,title:e.title,...e.meta!==null?{meta:e.meta}:{},tile:{icon:/* @__PURE__ */H(SourceTileGlyph,{})},...c!==void 0&&t!==null?{onPress:()=>c(t)}:{}},options:l},e.key)})]}):null,h&&m!==null&&o!==void 0?/* @__PURE__ */U(w,{style:[d.feedback,l?.styles?.feedback],children:[
|
|
302
302
|
/* @__PURE__ */H(FeedbackChip,{label:m.helpful,on:i==="up",onPress:()=>o("up"),styles:d,host:l?.styles}),
|
|
303
303
|
/* @__PURE__ */H(FeedbackChip,{label:m.notHelpful,on:i==="down",onPress:()=>o("down"),styles:d,host:l?.styles})]}):null,h?u(m===null):null]})}function SourceTileGlyph(){let e=useEverfurTheme();/* @__PURE__ */
|
|
304
|
-
return H(BookGlyph,{size:
|
|
305
|
-
return H(R,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(
|
|
304
|
+
return H(BookGlyph,{size:Sx,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:r,styles:n,host:l}){/* @__PURE__ */
|
|
305
|
+
return H(R,{onPress:r,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[n.chip,l?.feedbackChip,t?n.chipOn:null],hitSlop:(Pb-gx)/2,children:/* @__PURE__ */H(Text,{tier:"control",style:[n.chipText,l?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:t,label:r,actions:n,options:l}){let{theme:i,styles:o}=Px();if(e.length===0&&n.length===0)return null;let a=l?.styles,s=r??Cf.followUpsHeadingNative;/* @__PURE__ */
|
|
306
306
|
return U(w,{style:[o.followUps,a?.followUps],accessibilityLabel:s,testID:"everfur-cards-follow-ups",children:[
|
|
307
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */U(R,{onPress:()=>{
|
|
307
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:[o.label,a?.followUpsLabel],accessibilityRole:"header",children:s}),n.map(e=>/* @__PURE__ */U(R,{onPress:()=>{hh(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:_x,style:[o.row,o.rowAction,a?.followUp,a?.followUpAction],children:[e.icon??null,
|
|
308
308
|
/* @__PURE__ */H(Text,{tier:"control",style:[o.rowText,o.rowTextAction,a?.followUpText,a?.followUpActionText],children:e.label}),
|
|
309
|
-
/* @__PURE__ */H(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */U(R,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:
|
|
309
|
+
/* @__PURE__ */H(Chevron,{options:l,color:i.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */U(R,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:_x,style:[o.row,a?.followUp],children:[
|
|
310
310
|
/* @__PURE__ */H(Text,{tier:"control",style:[o.rowText,a?.followUpText],children:e}),
|
|
311
|
-
/* @__PURE__ */H(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=
|
|
312
|
-
return H(w,{style:t.byline,children:/* @__PURE__ */H(Text,{tier:"compact",style:t.bylineText,children:e})})}function
|
|
313
|
-
return U(w,{style:c.card,accessibilityLabel:
|
|
311
|
+
/* @__PURE__ */H(Chevron,{options:l,color:i.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=Px();/* @__PURE__ */
|
|
312
|
+
return H(w,{style:t.byline,children:/* @__PURE__ */H(Text,{tier:"compact",style:t.bylineText,children:e})})}function Ox(e){let t=e.color,r=e.space,n={...face(e,"mono"),fontSize:sx,textTransform:"uppercase",color:t.text.muted},l={borderWidth:1,borderColor:t.borderRingCream},i={borderWidth:1,borderColor:oo(t.text.primary,Rx)??t.borderRingCream},o={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:Tx,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=Mg(e.slots.chip);return b.create({answer:{gap:r.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...n,letterSpacing:sx*.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:cx,borderRadius:ux,backgroundColor:t.surface,...i,...o,minHeight:Pb,...Ag(e.slots.card)},tile:{width:dx,height:dx,borderRadius:fx,backgroundColor:oo(t.linkInk,Ix)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:dx,height:dx},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:hx,lineHeight:Math.round(hx*1.25),color:t.text.primary,...Mg(e.slots.card)},cardMeta:{...n,letterSpacing:sx*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:px,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:sx+2,color:t.text.muted},pill:{minHeight:Cx,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:zx},pillText:{...face(e,"bold"),fontSize:wx,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,alignItems:"center"},chip:{minHeight:gx,paddingHorizontal:12,borderRadius:e.radius.pill,...l,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...Ew(e),fontSize:bx,color:t.text.primary,...chipInk},followUps:{gap:r.sm,alignSelf:"stretch",marginTop:r.xs},label:{...face(e,"bold"),fontSize:kx,lineHeight:Math.round(kx*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:xx,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:mx,backgroundColor:t.surface,...i},rowAction:{},rowText:{...Ew(e),flex:1,fontSize:yx,lineHeight:Math.round(yx*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var Ex=/* @__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"})}),jx=/* @__PURE__ */Object.freeze(Er.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:Ex.answers[e]})));function Fx(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 Ax=44,Dx=.6,Mx=/* @__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(()=>Lx(u),[u]),d=Fx(t??Mx,t===null?null:r),f=d.answer!==null||d.pending!==null,h=t!==null&&r!==null&&d.answerable,p=t===null?null:TS(t.openedAt,IS(e));/* @__PURE__ */
|
|
313
|
+
return U(w,{style:c.card,accessibilityLabel:Ex.eyebrow,onLayout:o,children:[
|
|
314
314
|
/* @__PURE__ */U(w,{style:c.head,children:[
|
|
315
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:c.eyebrow,children:
|
|
316
|
-
return H(R,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */H(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */H(Text,{style:c.logged,children:
|
|
315
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:c.eyebrow,children:Ex.eyebrow}),p!==null?/* @__PURE__ */H(Text,{tier:"compact",style:c.headDay,children:Sf(Ex.day,{day:p})}):null]}),s?/* @__PURE__ */H(R,{onPress:s,accessibilityRole:"button",accessibilityLabel:e.text,style:c.open,children:/* @__PURE__ */H(Text,{style:[c.question,c.openText],children:e.text})}):/* @__PURE__ */H(Text,{style:c.question,accessibilityRole:"text",children:e.text}),h?/* @__PURE__ */H(w,{style:[c.row,d.pending?c.rowPending:null],children:jx.map(({answer:e,label:t})=>{let r=(d.pending??d.answer)===e;/* @__PURE__ */
|
|
316
|
+
return H(R,{onPress:()=>d.choose(e),disabled:f,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r,disabled:f,busy:d.pending===e},style:[c.pill,r?c.pillSelected:null],children:/* @__PURE__ */H(Text,{tier:"control",style:[c.pillLabel,r?c.pillLabelSelected:null],children:t})},e)})}):null,d.answer!==null?/* @__PURE__ */H(Text,{style:c.logged,children:Ex.logged}):null,d.escalated?/* @__PURE__ */H(CheckinFindVet,{petRef:n??null,onFindVet:l,vet:i,styles:c}):null,t?.resolutionText?/* @__PURE__ */H(Text,{style:c.resolution,children:t.resolutionText}):null,d.error?/* @__PURE__ */H(Text,{style:c.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:r,styles:n}){return useVetVisit($C(e,r)).available&&e!==null?/* @__PURE__ */H(VetVisitButtonCore,{entry:"chat",petRef:e,label:Ex.findVet,...r?.returnTo!==void 0?{returnTo:r.returnTo}:{},...r?.usState!==void 0?{usState:r.usState}:{},...r?.prefer!==void 0?{prefer:r.prefer}:{},style:n.findVet,labelStyle:n.findVetLabel}):t===void 0?null:/* @__PURE__ */H(R,{onPress:t,accessibilityRole:"button",accessibilityLabel:Ex.findVet,style:n.findVet,children:/* @__PURE__ */H(Text,{tier:"control",style:n.findVetLabel,children:Ex.findVet})})}function Lx(e){let t=e.color,r=e.space,n=e.radius,l=e.type,i=Dg(e.slots.card),o=Mg(i);return b.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:b.hairlineWidth,borderColor:t.brandBorder,...Ag(i,b.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:l.size.caption,letterSpacing:l.letterSpacing.eyebrow,textTransform:"uppercase",...o},question:{...face(e,"regular"),color:t.text.primary,fontSize:l.size.body,lineHeight:l.size.body*l.lineHeight.normal,...o},open:{minHeight:Ax,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:Dx},pill:{flex:1,minHeight:Ax,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:Ax,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 Bx=244,Hx=8,Ux=13,Nx=14,$x=.3,Wx=-.24,Vx=22,qx=10,Gx=15;function CitationCards({citations:e,onOpenUrl:t}){let r=useEverfurTheme(),n=a(()=>Kx(r),[r]),i=a(()=>MS(e),[e]),[o,s]=l(false);if(i.length===0)return null;let u=i.length;/* @__PURE__ */
|
|
317
317
|
return U(w,{style:n.block,children:[
|
|
318
|
-
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:
|
|
319
|
-
/* @__PURE__ */H(BookGlyph,{size:
|
|
320
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:n.toggleLabel,children:
|
|
321
|
-
/* @__PURE__ */H(ChevronGlyph,{size:
|
|
322
|
-
return H(F.View,{style:l,children:/* @__PURE__ */H(z,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */H(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=
|
|
318
|
+
/* @__PURE__ */U(PressScale,{accessibilityRole:"button",accessibilityLabel:HS(u,o),accessibilityState:{expanded:o},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>s(e=>!e),children:[
|
|
319
|
+
/* @__PURE__ */H(BookGlyph,{size:Ux,color:r.color.brandInk,strokeWidth:1.5}),
|
|
320
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:n.toggleLabel,children:BS(u)}),
|
|
321
|
+
/* @__PURE__ */H(ChevronGlyph,{size:Ux,color:r.color.brandInk,strokeWidth:1.5,direction:o?"up":"down"})]}),o?/* @__PURE__ */H(Deck,{cards:i,styles:n,open:t}):null]})}function Deck({cards:e,styles:t,open:r}){let n=ag(),l=bg(n.citationsInMs,{risePx:n.citationsRisePx});/* @__PURE__ */
|
|
322
|
+
return H(F.View,{style:l,children:/* @__PURE__ */H(z,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */H(Card,{card:e,styles:t,open:r},e.key))})})}function Card({card:e,styles:t,open:r}){let n=useEverfurTheme(),l=e.url!==null&&r!==void 0,i=US(l?e:{...e,url:null}),o=/* @__PURE__ */U(N,{children:[
|
|
323
323
|
/* @__PURE__ */U(w,{style:t.cardHeader,children:[
|
|
324
324
|
/* @__PURE__ */H(w,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),
|
|
325
|
-
/* @__PURE__ */H(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */H(ArrowUpRightGlyph,{size:
|
|
325
|
+
/* @__PURE__ */H(Text,{style:[t.cardTitle,l?t.cardTitleLink:null],numberOfLines:2,children:e.title}),l?/* @__PURE__ */H(ArrowUpRightGlyph,{size:Nx,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */H(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */H(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let n=e.url;/* @__PURE__ */
|
|
326
326
|
return H(PressScale,{accessibilityRole:"link",accessibilityLabel:i,style:t.card,onPress:()=>r(n),children:o})}/* @__PURE__ */
|
|
327
|
-
return H(w,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function
|
|
328
|
-
/* @__PURE__ */U(w,{style:[c.row,f?c.rowUser:c.rowAssistant],children:[h!==null?/* @__PURE__ */H(Text,{tier:"compact",style:c.timestamp,children:h}):null,p?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:b?
|
|
329
|
-
/* @__PURE__ */H(Text,{style:c.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:
|
|
330
|
-
/* @__PURE__ */H(AnnounceLine,{line:
|
|
327
|
+
return H(w,{accessible:true,accessibilityRole:"text",accessibilityLabel:i,style:t.card,children:o})}function Kx(e){let t=e.color,r=e.space,n=e.radius,l=e.type.size,i=Mg(e.slots.card);return b.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:l.micro,lineHeight:l.micro,letterSpacing:$x,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:Bx,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2,...Ag(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:Hx,height:Hx,borderRadius:n.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:l.bodyTight,lineHeight:Vx,color:t.text.primary,letterSpacing:Wx,...i},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:l.nano,lineHeight:qx,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...i},cardExcerpt:{...face(e,"regular"),fontSize:l.tiny,lineHeight:Gx,color:t.text.muted,...i}})}var Yx=15,Qx=44,Jx=16,Xx=/* @__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(()=>Zx(s),[s]),d=ag(),f=e.role==="user",h=a(()=>zS(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&&(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__ */U(w,{style:c.wrap,children:[
|
|
328
|
+
/* @__PURE__ */U(w,{style:[c.row,f?c.rowUser:c.rowAssistant],children:[h!==null?/* @__PURE__ */H(Text,{tier:"compact",style:c.timestamp,children:h}):null,p?/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:b?Cf.copied:f?Cf.copyUserMessage:Cf.copyAssistantMessage,onPress:v,style:c.iconHit,children:b?/* @__PURE__ */H(CheckGlyph,{size:Yx,color:s.color.success,strokeWidth:2}):/* @__PURE__ */H(CopyGlyph,{size:Yx,color:s.color.text.timestamp,strokeWidth:1.5})}):null,g?bk.map(({sentiment:e,label:t})=>/* @__PURE__ */H(R,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:r===e},onPress:()=>i?.(e),style:c.iconHit,children:/* @__PURE__ */H(ThumbGlyph,{size:Yx,color:r===e?s.color.sentiment[e]:s.color.text.timestamp,active:r===e,rotate:Xx[e],strokeWidth:1.5})},e)):null]}),o==="thanks"?/* @__PURE__ */H(Text,{style:c.thanks,accessibilityLiveRegion:"polite",children:Cf.feedbackThanks}):null,o==="failed"?/* @__PURE__ */U(N,{children:[
|
|
329
|
+
/* @__PURE__ */H(Text,{style:c.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:Cf.feedbackFailed}),
|
|
330
|
+
/* @__PURE__ */H(AnnounceLine,{line:Cf.feedbackFailed})]}):null]})}function Zx(e){let t=e.type;return b.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:Jx,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:Qx,height:Qx,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 e_=16,t_=10,r_=12,n_=10,l_=2,i_=.06,o_=34,a_=9,s_=10.5,u_=.06,c_=15,d_=19.5,f_=14,h_=19.6;function OpeningCard({card:e,onLayout:t}){let r=useEverfurTheme(),n=a(()=>p_(r),[r]),l=e.styles;/* @__PURE__ */
|
|
331
331
|
return U(w,{testID:"everfur-opening-card",onLayout:t,accessible:true,accessibilityLabel:[e.kicker,e.title,e.body].filter(e=>e!==void 0).join(", "),style:[n.card,l?.card],children:[e.icon!==void 0?/* @__PURE__ */H(w,{style:[n.icon,l?.icon],children:e.icon}):null,
|
|
332
332
|
/* @__PURE__ */U(w,{style:n.words,children:[
|
|
333
333
|
/* @__PURE__ */H(Text,{tier:"compact",style:[n.kicker,l?.kicker],children:e.kicker}),
|
|
334
|
-
/* @__PURE__ */H(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */H(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function
|
|
334
|
+
/* @__PURE__ */H(Text,{tier:"control",style:[n.title,l?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */H(Text,{style:[n.body,l?.body],children:e.body}):null]})]})}function p_(e){let t=e.color;return b.create({card:{flexDirection:"row",alignItems:"flex-start",gap:n_,paddingVertical:t_,paddingHorizontal:r_,alignSelf:"stretch",borderRadius:e_,backgroundColor:t.surface,borderWidth:1,borderColor:oo(t.text.primary,i_)??t.borderRingCream},icon:{flexShrink:0,width:o_,height:o_,borderRadius:a_,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:l_},kicker:{...face(e,"mono"),fontSize:s_,letterSpacing:s_*u_,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:c_,lineHeight:d_,color:t.text.primary},body:{...face(e,"regular"),fontSize:f_,lineHeight:h_,color:t.text.secondary}})}var g_="#10462E",b_="Book a video visit",m_="#000000",y_="#83E0B4",v_=/* @__PURE__ */Object.freeze([
|
|
335
335
|
/* @__PURE__ */Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
336
|
-
/* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:
|
|
337
|
-
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:
|
|
338
|
-
/* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function
|
|
339
|
-
return Object.freeze(
|
|
336
|
+
/* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:y_,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
337
|
+
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:g_,brandEdge:true,borderWidth:1}),
|
|
338
|
+
/* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function k_(e,t){return e?null:{fill:t.fill,ink:t.ink}}var w_=8;function C_(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function S_(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=w_)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=C_(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:l,ink:l===null?null:C_(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var x_=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function __(e){return e==null?e:e.replace(x_,"").trim()}var R_=/* @__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 T_(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return R_.has(t)}function I_(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function z_(e){let t=e?.name?.trim()||Cf.emptyTitlePetFallback;return Sf(Cf.emptyTitle,{petName:t})}function P_(e){let t=e.toLowerCase();return t===I_("dog").toLowerCase()||t===I_("cat").toLowerCase()}function O_(e){let t=__(e);if(T_(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return P_(r)?null:r}function E_(e,t=g_,r){let n=canonicalPetSpecies(e?.species),l=e?.name?.trim()||null,i=O_(e?.breed),o=Tv(e?.ageYears),a=o===null?null:String(o),s=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
|
|
339
|
+
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=Sf(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 j_=44,F_=0,A_={top:3,bottom:3},D_=1,M_=.28,L_=2,B_=2,H_=1.3,U_=-.015,N_=/* @__PURE__ */Object.freeze([
|
|
340
340
|
/* @__PURE__ */Object.freeze({tint:"#FFE7A1",ink:"#262523"}),
|
|
341
341
|
/* @__PURE__ */Object.freeze({tint:"#C8F4F8",ink:"#262523"}),
|
|
342
342
|
/* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
|
|
343
|
-
/* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()
|
|
343
|
+
/* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:i,emptyState:o,centered:s=false}){let u=useEverfurTheme(),c=a(()=>$_(u),[u]),d=a(()=>S_(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}})):E_(e,u.color.brandInk,{vetPrepLabel:b_}).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"?N_:[])).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(()=>k_(xv(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=o?.title?.trim(),v=y!==void 0&&y!==""?y:z_(e),k=Fk(),C=Ak(),S=k!==null&&C!==null?/* @__PURE__ */H(C.Title,{text:v,style:[c.title,k.text(".serif",".ask-empty h2"),c.centerText],measureCh:C.titleCh}):/* @__PURE__ */H(Text,{tier:"heading",style:s?[c.title,c.centerText]:c.title,accessibilityRole:"header",children:v});/* @__PURE__ */
|
|
344
344
|
return U(w,{style:k!==null?c.homeBlock:c.block,children:[S,
|
|
345
|
-
/* @__PURE__ */H(w,{style:k!==null?[c.list,c.listCentered,k.view(".ask-chips",".ask-empty .ask-chips")]:s?[c.list,c.listCentered]:c.list,accessibilityLabel:
|
|
346
|
-
return H(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,
|
|
345
|
+
/* @__PURE__ */H(w,{style:k!==null?[c.list,c.listCentered,k.view(".ask-chips",".ask-empty .ask-chips")]:s?[c.list,c.listCentered]:c.list,accessibilityLabel:Cf.suggestions,children:g.map(({prompt:i,send:o,paint:a,cycleDefault:u},f)=>/* @__PURE__ */H(Chip,{prompt:i,send:o,themed:a??(d!==null?m:b),index:f,petRef:t,onSend:r,onVetPrep:n,vet:l,pet:e,styles:c,tinted:a!==null&&u!==true,soft:a!==null,centered:s},i.id))})]})}function Chip({prompt:e,send:t,themed:r,index:n,pet:l,petRef:i,onSend:o,onVetPrep:a,vet:s,styles:u,tinted:c,soft:d,centered:f}){let h=ag(),p=bg(h.followUpInMs,{delayMs:ig(h,n),risePx:h.promptRisePx}),g=Fk(),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?A_:F_,w=r===null?u.chipSlotLabel===null?v:[...v,u.chipSlotLabel]:c?[...v,...u.chipSlotLabel===null?[]:[u.chipSlotLabel],{color:r.ink}]:[...v,{color:r.ink},...u.chipSlotLabel===null?[]:[u.chipSlotLabel]];return e.intent==="vet_report"?a!==void 0?/* @__PURE__ */H(F.View,{style:p,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>{hh(a,l)},children:/* @__PURE__ */H(Text,{tier:"compact",style:w,children:e.label})})}):i===null?null:/* @__PURE__ */H(F.View,{style:p,children:/* @__PURE__ */H(VetVisitButtonCore,{entry:"chat",petRef:i,label:e.label,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:[u.chip,b,y],labelStyle:w})}):/* @__PURE__ */H(F.View,{style:p,children:/* @__PURE__ */H(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:k,style:[u.chip,b,y],onPress:()=>o(t),children:/* @__PURE__ */H(Text,{tier:"compact",style:w,children:e.label})})})}function $_(e){let t=Dg(e.slots.chip),r=Mg(t);return{chipSlot:t===void 0?null:Ag(t,D_),chipSlotLabel:r.color===void 0?null:r,...W_(e)}}function W_(e){let t=e.color,r=e.space,n=e.type;return b.create({block:{gap:r.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:n.size.heading,lineHeight:Math.round(n.size.heading*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.size.heading*U_,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:r.sm+L_},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:D_,borderColor:"transparent"},chip:{borderRadius:e.radius.pill,paddingHorizontal:r.lg+B_,paddingVertical:r.sm,minHeight:j_,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:D_,borderColor:oo(t.brandInk,M_)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*H_),color:m_,textAlign:"left"}})}var V_=1e3,q_=150,G_=.25,K_=.5,Y_=3;function TypingIndicator({petName:e=null,inline:t=false}){let{theme:r,styles:l}=wm(),i=r.motion.reducedMotion,o=_f(Cf.reading,e),a=u(Array.from({length:Y_},()=>new F.Value(0))).current;return n(()=>{if(i)return;let e=a.map((e,t)=>F.loop(F.sequence([F.delay(t*q_),F.timing(e,{toValue:1,duration:V_*.4,useNativeDriver:true}),F.timing(e,{toValue:0,duration:V_*.6,useNativeDriver:true}),F.delay((Y_-t-1)*q_)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[i,a]),/* @__PURE__ */H(w,{style:t?l.readingInline:l.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:o,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:a.map((e,r)=>/* @__PURE__ */H(F.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[t?l.readingDotInline:l.readingDot,i?{opacity:K_}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[G_,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},r))})}function Q_(e,t,r){let n=e-r,l=t!=null?Math.min(n,t):n;return Math.max(0,l)}function J_(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 X_(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 Z_=16;function eR(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=J_(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=Q_(e,r,96)}let r=X_(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=X_(h.current+Z_-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 tR(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */H(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */H(LoadingState,{})}):/* @__PURE__ */H(LoadingState,{});case"empty":/* @__PURE__ */
|
|
346
|
+
return H(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,renderEmptyHeader:r.renderEmptyHeader});case"error":/* @__PURE__ */
|
|
347
347
|
return H(ErrorState,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case"populated":/* @__PURE__ */
|
|
348
|
-
return H(PopulatedState,{messages:t.messages,prompts:
|
|
349
|
-
return U(z,{contentContainerStyle:[f
|
|
350
|
-
/* @__PURE__ */H(w,{style:
|
|
348
|
+
return H(PopulatedState,{messages:t.messages,prompts:Lh(t,r.followUpPolicy),actions:r.answerCards?YS(t,r.answerCards):nR,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}=wm(),[r,i]=l(false);return n(()=>{let e=setTimeout(()=>i(true),Tb);return()=>clearTimeout(e)},[]),/* @__PURE__ */H(w,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:Cf.loading,children:r?/* @__PURE__ */H(P,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:l,top:i,topCard:o,pendingCheckin:a,starterPrompts:s,emptyState:u,centered:c,renderEmptyHeader:d}){let{styles:f}=wm(),h=Fk(),p=d===void 0?null:/* @__PURE__ */H(w,{testID:"everfur-empty-header",children:/* @__PURE__ */H(HostRender,{render:()=>d({ask:r}),fallback:null})});if(h!==null){let{minHeight:c,...d}=h.view(".ask-empty");/* @__PURE__ */
|
|
349
|
+
return U(z,{contentContainerStyle:[d,f.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:iR,nestedScrollEnabled:true,accessibilityLabel:Cf.empty,children:[i!=null?/* @__PURE__ */H(w,{style:h.view(".ask-top"),children:i}):null,a,o??null,p,
|
|
350
|
+
/* @__PURE__ */H(w,{style:h.view(".ask-start"),children:/* @__PURE__ */H(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:true})})]})}
|
|
351
351
|
/* @__PURE__ */
|
|
352
|
-
return U(z,{contentContainerStyle:
|
|
353
|
-
/* @__PURE__ */H(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})
|
|
354
|
-
/* @__PURE__ */H(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??
|
|
352
|
+
return U(z,{contentContainerStyle:f.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:iR,nestedScrollEnabled:true,accessibilityLabel:Cf.empty,children:[i??null,a,o??null,p,
|
|
353
|
+
/* @__PURE__ */H(QuickPrompts,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:l,starterPrompts:s,emptyState:u,centered:c})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:r}){let{styles:n}=wm();return e.length===0?null:/* @__PURE__ */U(w,{style:n.followUps,children:[
|
|
354
|
+
/* @__PURE__ */H(Text,{tier:"compact",style:n.followUpsHeading,accessibilityRole:"header",children:r??Cf.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */H(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:l}=wm(),i=ag(),o=bg(i.followUpInMs,{delayMs:ig(i,t)});/* @__PURE__ */
|
|
355
355
|
return H(F.View,{style:o,children:/* @__PURE__ */U(PressScale,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[l.followUpSlot,t>0?l.followUpSlotRuled:null],style:l.followUpRow,children:[
|
|
356
356
|
/* @__PURE__ */H(Text,{tier:"control",style:l.followUpText,children:e}),
|
|
357
|
-
/* @__PURE__ */H(PlusGlyph,{size:
|
|
357
|
+
/* @__PURE__ */H(PlusGlyph,{size:oR,color:n.slots.chip?.textColor??n.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:r}){let{styles:n}=wm(),l=Vh(e)?gh(r):void 0,i=zh(e);/* @__PURE__ */
|
|
358
358
|
return U(w,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[i!==null?/* @__PURE__ */H(Text,{style:n.errorText,testID:"everfur-chat-cap-reached",children:i.reached}):null,
|
|
359
|
-
/* @__PURE__ */H(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */H(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */H(R,{onPress:l,accessibilityRole:"button",accessibilityLabel:
|
|
360
|
-
return U(z,{ref:
|
|
359
|
+
/* @__PURE__ */H(Text,{style:n.errorText,children:e.displayMessage}),i!==null&&i.guidance!==null?/* @__PURE__ */H(Text,{style:n.errorText,testID:"everfur-chat-cap-guidance",children:i.guidance}):null,l!==void 0?/* @__PURE__ */H(R,{onPress:l,accessibilityRole:"button",accessibilityLabel:Cf.addPet,style:n.retryButton,children:/* @__PURE__ */H(Text,{tier:"control",style:n.retryLabel,children:Cf.addPet})}):null,e.retryable?/* @__PURE__ */H(R,{onPress:t,accessibilityRole:"button",accessibilityLabel:Cf.retry,style:n.retryButton,children:/* @__PURE__ */H(Text,{tier:"control",style:n.retryLabel,children:Cf.retry})}):null]})}function PopulatedState({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:l,onCopy:i,sentimentByMessage:o,onSentiment:s,feedbackNote:u,imagesByMessage:c,onPreview:d,notice:f,reconnecting:h,onRetry:p,onStartNew:g,petRef:b,onFindVet:m,vet:y,onOpenUrl:v,petName:k,actions:C,answerCards:S,threadTop:x,pendingCheckin:_,threadAside:T,threadAsideKey:I,followUpLabel:P,openingCard:O,earlier:E}){let{styles:j}=wm(),F=ag();xg(e.length,F);let A=a(()=>xS(SS(e)),[e]),D=Eh(e,n),M=e[e.length-1],L=T??null,B=eR(e,n,L===null?null:I??"shown"),N=vg(e),$=e[0],W=O!==void 0&&$!==void 0&&$.role==="user"&&$.text.trim()===O.prompt?$.id:null;/* @__PURE__ */
|
|
360
|
+
return U(z,{ref:B.ref,style:j.list,contentContainerStyle:S!==null?j.listContentCards:j.listContent,accessibilityLabel:Cf.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:iR,nestedScrollEnabled:true,onLayout:B.onLayout,onContentSizeChange:B.onContentSizeChange,onScroll:B.onScroll,scrollEventThrottle:lR,onScrollBeginDrag:B.onScrollBeginDrag,onScrollEndDrag:B.onScrollEnd,onMomentumScrollEnd:B.onScrollEnd,children:[x??null,_,E!==null?/* @__PURE__ */H(R,{onPress:()=>{E.load()},disabled:E.loading,accessibilityRole:"button",accessibilityLabel:E.loading?xp.loadingEarlier:xp.earlier,accessibilityState:{disabled:E.loading,busy:E.loading},hitSlop:Gb,style:j.earlierButton,children:/* @__PURE__ */H(Text,{tier:"compact",style:j.earlierLabel,children:E.loading?xp.loadingEarlier:xp.earlier})}):null,e.map(t=>t.id===W&&O!==void 0?/* @__PURE__ */H(OpeningCard,{card:O.card,onLayout:B.rowLayout(t.id)},t.id):t.checkin&&A.has(t.id)?/* @__PURE__ */H(CheckinCard,{message:t,checkin:t.checkin,onAnswer:l,petRef:b,onFindVet:m,vet:y,onLayout:B.rowLayout(t.id)},t.id):/* @__PURE__ */H(MessageRow,{onLayout:B.rowLayout(t.id),message:t,revealing:n&&t===M&&t.role==="assistant",onCopy:i,sentiment:t.responseId===void 0?null:o[String(t.responseId)]??null,onSentiment:s,note:t.responseId!==void 0&&u?.responseId===String(t.responseId)?u.kind:null,images:c[t.id]??rR,onPreview:d,onOpenUrl:v,entering:N(t.id),answerCards:S,messages:e},t.id)),h?/* @__PURE__ */H(Text,{tier:"compact",style:j.reconnectingCaption,accessibilityRole:"text",children:Cf.reconnecting}):null,D?/* @__PURE__ */H(TypingIndicator,{petName:k,inline:S!==null}):null,f!==null?/* @__PURE__ */H(TurnNoticeCard,{notice:f,onRetry:p,onStartNew:g}):null,S!==null?/* @__PURE__ */H(CardsFollowUps,{prompts:t,onSelectPrompt:r,label:P,actions:C,options:S}):/* @__PURE__ */H(FollowUps,{prompts:t,onSelectPrompt:r,label:P}),L!==null?/* @__PURE__ */H(w,{onLayout:B.asideLayout,children:L}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=wm(),l=e.tone==="error";/* @__PURE__ */
|
|
361
361
|
return U(w,{style:[n.turnNotice,l?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
|
|
362
362
|
/* @__PURE__ */H(Text,{tier:"control",style:[n.turnNoticeTitle,l?n.turnNoticeTitleError:null],children:e.title}),
|
|
363
363
|
/* @__PURE__ */H(Text,{tier:"compact",style:n.turnNoticeBody,children:e.body}),e.guidance!==void 0?/* @__PURE__ */H(Text,{tier:"compact",style:n.turnNoticeBody,testID:"everfur-chat-cap-guidance",children:e.guidance}):null,
|
|
364
|
-
/* @__PURE__ */H(R,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:
|
|
364
|
+
/* @__PURE__ */H(R,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Gb,style:n.turnNoticeAction,children:/* @__PURE__ */H(Text,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}var rR=/* @__PURE__ */Object.freeze([]),nR=/* @__PURE__ */Object.freeze([]),lR=16,iR=p.OS==="ios"?"interactive":"on-drag",oR=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}=wm(),b=ag(),m=yg(d,b),y=wg(e.text,t,b),v=e.role==="user",k=e.role==="vet",C=e.role==="assistant",S=Qp(),x=C&&!t?S:void 0,_=x!==void 0&&ox(e.text,x),R=C&&!p.meta.hidePoweredBy,T=v?Cf.senderUser:k?Bh(e):R?Cf.assistantName:Cf.senderAssistant,I=k?zS(e.createdAt):null,z=s(t=>l(e,t),[l,e]),P=e.pending!==true,O=C&&p.meta.assistantAvatarUrl!==null?/* @__PURE__ */H(AssistantSender,{avatarUrl:p.meta.assistantAvatarUrl,named:R,styles:g}):R?f!==null?/* @__PURE__ */H(CardsByline,{label:Cf.assistantName}):/* @__PURE__ */H(Text,{tier:"control",style:g.assistantName,children:Cf.assistantName}):null,E=f!==null;return C&&f!==null?/* @__PURE__ */H(F.View,{style:[g.rowBlock,m],onLayout:c,accessibilityLabel:`${T}: ${e.text}`,children:/* @__PURE__ */H(CardsAnswer,{message:e,text:y,streaming:t,messages:h,options:f,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,sender:O,onOpenUrl:u,footer:t=>/* @__PURE__ */H(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:t&&e.responseId!==void 0?z:void 0,note:i})})}):/* @__PURE__ */U(w,{style:[g.rowBlock,v?g.rowBlockUser:g.rowBlockAssistant],onLayout:c,children:[
|
|
365
365
|
/* @__PURE__ */H(w,{style:[g.row,v?g.rowUser:g.rowAssistant],accessible:!_,accessibilityRole:_?void 0:"text",accessibilityLabel:_?void 0:`${T}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:/* @__PURE__ */U(F.View,{style:[g.bubble,E?g.bubbleCards:null,v?g.bubbleSideUser:null,m],children:[O,k?/* @__PURE__ */U(w,{style:g.vetHeader,children:[
|
|
366
366
|
/* @__PURE__ */H(Text,{tier:"control",style:g.vetSender,children:T}),I!==null?/* @__PURE__ */H(Text,{tier:"compact",style:g.vetTime,children:I}):null]}):null,
|
|
367
367
|
/* @__PURE__ */U(w,{style:[v?g.bubbleUser:k?g.bubbleVet:g.bubbleAssistant,v&&E?g.bubbleUserCards:null,e.pending?g.bubblePending:null],children:[v&&o.length>0?/* @__PURE__ */H(SentImages,{images:o,onPreview:e=>a({uri:e.uri,label:e.filename})}):null,
|
|
368
|
-
/* @__PURE__ */H(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:C?
|
|
368
|
+
/* @__PURE__ */H(Text,{style:v?E?[g.bubbleTextUser,g.bubbleTextUserCards]:g.bubbleTextUser:k?g.bubbleTextVet:g.bubbleTextAssistant,children:C?ax(y,{bold:g.bubbleBold,italic:g.bubbleItalic,code:g.bubbleCode},x):e.text})]})]})}),C&&!t?/* @__PURE__ */H(CitationCards,{citations:e.citations,onOpenUrl:u}):null,P&&!(v&&f!==null)?/* @__PURE__ */H(MessageFooter,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:z,note:i}):null]})}var aR=/* @__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"&&aR.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function sR(){let{runtime:e}=cd(),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 uR=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function cR(e,t,r=false){let[n,i]=l(null);if(!e)return uR;let o=/* @__PURE__ */H(AskRunner,{ready:textingAskThreadReady(t),onAsk:i,entry:r}),a=r&&n!==null&&n.canOpen?{label:W.textingAskLines(n).accept,onOpen:n.open}:null;if(n===null||n.stage==="hidden"||n.stage==="dismissed")return{runner:o,line:null,entry:null,stage:null,headerEntry:a};let s=W.textingAskLines(n),u=/* @__PURE__ */H(AskLine,{stage:n.stage,text:n.stage==="verified"?s.verified:s.line,accept:s.accept,dismiss:s.dismiss,onAccept:n.accept,onDismiss:n.dismiss}),c=n.stage==="enrolling"?/* @__PURE__ */H(W.ChatTextingAskComposer,{ask:n}):null;return{runner:o,line:u,entry:c,stage:n.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:t,entry:r}){let{userRef:l}=cd(),i=sR(),o=l!==null&&i;return n(()=>{o||t(null)},[o,t]),o?/* @__PURE__ */H(W.ChatTextingAskController,{enabled:true,ready:e,onAsk:t,entry:r}):null}function AskLine({stage:e,text:t,accept:r,dismiss:n,onAccept:l,onDismiss:i}){let{theme:o,styles:a}=wm(),s=!o.meta.hidePoweredBy,u=s?Cf.assistantName:Cf.senderAssistant,c=o.meta.assistantAvatarUrl!==null?/* @__PURE__ */H(AssistantSender,{avatarUrl:o.meta.assistantAvatarUrl,named:s,styles:a}):s?/* @__PURE__ */H(Text,{tier:"control",style:a.assistantName,children:Cf.assistantName}):null;/* @__PURE__ */
|
|
369
369
|
return U(w,{style:[a.rowBlock,a.rowBlockAssistant],testID:`everfur-texting-ask-${e}`,children:[
|
|
370
370
|
/* @__PURE__ */H(w,{style:[a.row,a.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${u}: ${t}`,children:/* @__PURE__ */U(w,{style:a.bubble,children:[c,
|
|
371
|
-
/* @__PURE__ */H(w,{style:a.bubbleAssistant,children:/* @__PURE__ */H(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */H(w,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */H(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */H(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function
|
|
372
|
-
return H(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */H(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */H(ChatBody,{...e})})})}function
|
|
373
|
-
return H(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=
|
|
374
|
-
return H(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:c,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:g,attachments:b,pet:m,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:C,initialAskKey:S,composerSeed:x,lifecycle:R,refreshIntervalMs:T,refreshesBlankThread:I,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:B,historySheet:$,historyBar:W,starterPrompts:V,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:J}){let{presentation:X,isLocked:isLocked,planPage:Z,planPetRef:ee}=e,{theme:te,styles:re}=
|
|
375
|
-
/* @__PURE__ */H(TopCard,{card:Je,open:Xe,onOpenChange:Ze,ask:et}),at===void 0?ot:null]}),dt=at!==void 0,ft=he.load,ht=he.open;n(()=>{dt&&!ht&&ft()},[dt,ht,ce.conversationId,ft]);let pt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:Se,draftStore:P,onStage:Pe.stage,onPreview:Ee,petName:ye?.name??null,petBreed:ye?.breed??null,compact:X.chatComposerStyle==="compact",petPlaceholder:X.chatComposerPlaceholder==="pet_name",dimEmptySend:X.chatSendButton==="dim_when_empty",mood:
|
|
371
|
+
/* @__PURE__ */H(w,{style:a.bubbleAssistant,children:/* @__PURE__ */H(Text,{style:a.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */H(w,{style:a.askChips,children:[{label:r,onPress:l,testID:"everfur-texting-ask-accept"},{label:n,onPress:i,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */H(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:a.askChip,testID:e.testID,children:/* @__PURE__ */H(Text,{tier:"control",style:a.askChipText,children:e.label})},e.testID))}):null]})}function dR(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),t=globalThis;return t[e]??(t[e]=createContext(null))}var fR=/* @__PURE__ */dR();function hR(e){return typeof e=="object"&&e!==null&&e.ok===true}function pR(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:ut(t.error)}function gR(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(hR(e)){r?.();return}let t=n===void 0?null:pR(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__ */
|
|
372
|
+
return H(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */H(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */H(ChatBody,{...e})})})}function bR(){try{return cd()}catch{return null}}function mR(e){return Th({...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=bR();return t===null?/* @__PURE__ */H(ChatBodyAlone,{...e}):/* @__PURE__ */H(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let t=mR(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__ */
|
|
373
|
+
return H(ChatSurface,{...e,settings:l})}function ChatBodyInProvider({activePet:e,telemetry:t,...r}){let{presentation:n,isLocked:isLocked}=Rh(mR(r)),l=Gd("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__ */
|
|
374
|
+
return H(ChatSurface,{...r,settings:c})}function ChatSurface({settings:e,petRef:t,conversationId:r,style:i,renderPending:o,onCopy:c,onPetChange:d,onVetPrep:f,onFindVet:h,renderVetAction:g,attachments:b,pet:m,onAddPet:y,checkinTarget:v,handoffToken:k,initialAsk:C,initialAskKey:S,composerSeed:x,lifecycle:R,refreshIntervalMs:T,refreshesBlankThread:I,openUnreadOnRefresh:z,draftStore:P,vetReturnTo:O,vetUsState:E,vetPrefer:j,onOpenUrl:F,keyboardVerticalOffset:A,topCard:D,onOpenHealthPlan:M,answerCards:B,historySheet:$,historyBar:W,starterPrompts:V,emptyState:q,header:G=true,textingEntry:K=true,renderEmptyHeader:Y,followUpPolicy:Q,initialAskCard:J}){let{presentation:X,isLocked:isLocked,planPage:Z,planPetRef:ee}=e,{theme:te,styles:re}=wm(),ne=jk()??(X.chatAnswerStyle==="cards"?TC:null),le=a(()=>ne===null?null:ne(te),[ne,te]),ie=useHostPoweredBy(),oe=ag(),ae=a(()=>Hh(t,r),[t,r]),se=useEverfurChat(ae),ue=gR(se.send),ce=a(()=>ue===se.send?se:{...se,send:ue},[se,ue]),de=Ih(ce),fe=mS(),he=jp(ce),pe=L(),ge=Oh(ce,"web"),be=a(()=>h===void 0?void 0:()=>{hh(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=hk(fe.pets,ce.petRef),ve=a(()=>Bp(ce.messages,ye?.name??null),[ce.messages,ye?.name]),ke=Up(ve);vS(ce),xg(ke.showBanner,oe);let we=bR(),Ce=wp(k,we);Sp(ce.openCheckin,v??Ce,{petRef:ce.petRef,pinned:t!==void 0,ready:!ce.isBootstrapping,selectPet:e=>{fe.setActivePet(e),hh(d,e)}}),tp(ce.askEverfur,ce.isBootstrapping,C,S);let Se=a(()=>ep(x),[x]),xe=a(()=>ep(C),[C]),_e=a(()=>J!==void 0&&xe!==null?{card:J,prompt:xe}:void 0,[J,xe]),Re=a(()=>R===void 0?createAppStateLifecycle():R??void 0,[R]);dp(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?.(op(z===true,ap(Re,Fg)))??Promise.resolve()},{intervalMs:T===void 0?3e4:T,isVisibleFallback:Fg}),sp({isStreaming:ce.isStreaming,status:ce.status,conversationId:ce.conversationId===null?null:String(ce.conversationId),unreadCount:ce.unreadCount,markRead:ce.markRead},()=>ap(Re,Fg));let Te=ce.pendingCheckin??null,Ie=Te===null?null:/* @__PURE__ */H(w,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */H(CheckinCard,{message:Te.message,checkin:Te.checkin,onAnswer:ce.petRef?ce.answerCheckin:null,petRef:ce.petRef,onFindVet:be,vet:me,onOpen:()=>{ce.resumeConversation(Te.conversationId)}})}),ze=(ce.hasUnreadThreads??false)||he.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(ce.unreadCount??0)>0,Pe=Yh(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},Ib):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=>{hh(F,e,"citation")},[F]),Ve=p.OS==="ios"?"padding":void 0,qe=DC(A,Ve!==void 0),Ge=qe.topInWindow===null?pe.top:Math.max(0,pe.top-qe.topInWindow),Ke=LC(),Ye=a(()=>M===void 0?void 0:()=>{hh(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(()=>$h(Q,X,isLocked("chatFollowUpCount")),[Q,X,isLocked]),rt=X.chatAnswerStyle==="cards",nt=a(()=>rt&&ce.messages.length===0?kR(ce.suggestedPrompts):void 0,[rt,ce.messages.length,ce.suggestedPrompts]),lt=X.chatHistoryStyle==="sheet",it=ce.messages.length===0,ot=Je!==void 0?/* @__PURE__ */H(TopCardPill,{card:Je,open:Xe,onOpenChange:Ze}):null,at=W??(G?void 0:wR),st=at!==void 0?/* @__PURE__ */H(HistoryBar,{bar:at,history:he,empty:it,unread:ze,extra:ot}):null,ut=X.chatHistoryBar==="scroll"&&(de==="empty"||de==="populated"),ct=Je===void 0?null:/* @__PURE__ */U(N,{children:[
|
|
375
|
+
/* @__PURE__ */H(TopCard,{card:Je,open:Xe,onOpenChange:Ze,ask:et}),at===void 0?ot:null]}),dt=at!==void 0,ft=he.load,ht=he.open;n(()=>{dt&&!ht&&ft()},[dt,ht,ce.conversationId,ft]);let pt={send:ce.send,stop:ce.stop,isStreaming:ce.isStreaming,conversationId:ce.conversationId,seed:Se,draftStore:P,onStage:Pe.stage,onPreview:Ee,petName:ye?.name??null,petBreed:ye?.breed??null,compact:X.chatComposerStyle==="compact",petPlaceholder:X.chatComposerPlaceholder==="pet_name",dimEmptySend:X.chatSendButton==="dim_when_empty",mood:CR(de,ke.source?.level??null),dictation:X.chatComposerMic,telemetry:e.telemetry},gt=cR(X.chatTextingAsk&&e.inProvider,ce,K),bt=b!==void 0&&X.chatComposerUpload,mt=!X.chatGeneralBanner&&ke.source?.level==="general";
|
|
376
376
|
/* @__PURE__ */
|
|
377
|
-
return H(
|
|
377
|
+
return H(Ek.Provider,{value:le,children:/* @__PURE__ */U(_,{style:[re.container,{paddingTop:Ge},i],behavior:Ve,...qe.avoidingProps,children:[
|
|
378
378
|
/* @__PURE__ */H(KeyboardOffsetProbe,{probeRef:qe.probeRef}),G?/* @__PURE__ */H(ChatHeader,{pets:fe,petRef:ce.petRef,historyUnread:ze,onOpenHistory:he.show,onNewChat:he.newConversation,onPetChange:d,onAddPet:y,vet:me,textingEntry:gt.headerEntry}):null,m!==void 0?/* @__PURE__ */H(PetSetupNotice,{petRef:t??null,pet:m,onRegistered:fe.refresh}):null,!G&>.headerEntry!==null?/* @__PURE__ */H(TextingEntryRow,{entry:gt.headerEntry,place:"thread"}):null,ut?null:st,mt?null:/* @__PURE__ */H(UrgencyBanner,{surface:ke,petRef:ce.petRef,renderVetAction:g,onFindVet:h,vet:me,compact:Ke}),
|
|
379
|
-
/* @__PURE__ */H(w,{style:re.body,children:
|
|
379
|
+
/* @__PURE__ */H(w,{style:re.body,children:tR(de,ce,{notice:ge,vet:me,onCheckinFindVet:be,onSelectPrompt:$e,renderPending:o,shownPet:ye,onVetPrep:f,onCopy:c,onSentiment:He,feedbackNote:De,imagesByMessage:Pe.byMessage,onPreview:Ee,onAddPet:y,onOpenUrl:We,threadTop:ut?st:null,pendingCheckin:Ie,topCard:ct,starterPrompts:V??nt,emptyState:q,emptyCentered:X.chatAnswerStyle==="cards",followUpPolicy:tt,answerCards:X.chatAnswerStyle==="cards"?B??yR:null,threadAside:gt.line,threadAsideKey:gt.stage,renderEmptyHeader:Y,openingCard:_e})}),gt.runner,gt.entry!==null?/* @__PURE__ */H(w,{style:re.composerOuter,children:/* @__PURE__ */H(w,{style:re.askEntry,children:gt.entry})}):bt&&b!==void 0?/* @__PURE__ */H(ComposerWithAttachments,{...pt,attachments:b}):/* @__PURE__ */H(Composer,{...pt,attachments:null}),te.meta.hidePoweredBy||ie?null:/* @__PURE__ */H(Text,{tier:"compact",style:re.poweredBy,accessibilityRole:"text",accessibilityLabel:Cf.poweredBy,children:Cf.poweredBy}),lt?/* @__PURE__ */H(HistorySheet,{chat:ce,history:he,sheet:$}):/* @__PURE__ */H(HistoryDrawer,{chat:ce,history:he}),
|
|
380
380
|
/* @__PURE__ */H(FeedbackReasons,{visible:Fe!==null,onSubmit:Ue,onSkip:Ne}),
|
|
381
381
|
/* @__PURE__ */H(AttachmentImageLightbox,{uri:Oe?.uri??null,label:Oe?.label??"",onClose:je}),
|
|
382
|
-
/* @__PURE__ */H(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=
|
|
382
|
+
/* @__PURE__ */H(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:r}){let{styles:n}=wm(),l=Gh(e,t,r);return l.status!=="failed"||l.error===null?null:/* @__PURE__ */U(w,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[
|
|
383
383
|
/* @__PURE__ */H(Text,{tier:"compact",style:n.setupNoticeText,children:l.error.displayMessage}),
|
|
384
|
-
/* @__PURE__ */H(R,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:
|
|
385
|
-
return H(
|
|
384
|
+
/* @__PURE__ */H(R,{onPress:l.retry,accessibilityRole:"button",accessibilityLabel:Cf.retry,hitSlop:Gb,children:/* @__PURE__ */H(Text,{tier:"control",style:n.setupNoticeAction,children:Cf.retry})})]})}var yR=/* @__PURE__ */Object.freeze({}),vR=3;function kR(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===vR)break}return t.length>0?/* @__PURE__ */Object.freeze(t):void 0}var wR=/* @__PURE__ */Object.freeze({chats:xp.heading,newChat:xp.newChat});function CR(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
|
|
385
|
+
return H(of.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */H(EverfurChatCore,{...e})})}var SR=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function xR(e,t){let{runtime:r,userRef:l,activePet:o,scopeEpoch:u}=cd(),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?SR: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]),dp(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 xR(e.petRef,r)}function useEverfurPetProfile(e){let{runtime:t,userRef:r,scopeEpoch:i}=cd(),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:Wd,children:e.children})}export{us as APPEARANCE_PRESETS,ss as APPEARANCE_PRESET_NAMES,cs as APPEARANCE_SIZE_RANGES,CapabilityGate,EverfurChat,K as EverfurConfigError,EverfurProvider,EverfurThemeProvider,G as EverfurThrownError,Mo as PHONE_TEXT_SCALE_CAPS,po as THEME_SLOT_KEYS,go as THEME_SLOT_KEYS_BY_SLOT,ho as THEME_SLOT_NAMES,Fo as TYPE_ROLE_DEFAULTS,jo 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};
|