@everfur/sdk 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +350 -0
- package/README.md +24 -16
- package/dist/{Chat-DQOsAumH.d.cts → Chat-Cb3Y8VwS.d.cts} +3 -3
- package/dist/{Chat-CFi5cNUF.d.ts → Chat-ClhB_8sp.d.ts} +3 -3
- package/dist/{DepthViews-D81c95Ra.d.cts → DepthViews-BSkuUGBB.d.ts} +1 -1
- package/dist/{DepthViews-C409ubw-.d.cts → DepthViews-CSCS-tZg.d.ts} +1 -1
- package/dist/{DepthViews-es8mIK0w.d.ts → DepthViews-CW1z8pnl.d.cts} +1 -1
- package/dist/{DepthViews-uilL1NJZ.d.ts → DepthViews-DDiPxyzg.d.cts} +1 -1
- package/dist/{ErrorPolicyPort-D22LUVrK.d.ts → ErrorPolicyPort-DwSnmGcX.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-D6CybiqJ.d.cts → ErrorPolicyPort-NFDPe-5w.d.cts} +1 -1
- package/dist/{EverfurError-DmELDpXp.d.cts → EverfurError-pEXDbUJ1.d.cts} +9 -1
- package/dist/{EverfurError-DmELDpXp.d.ts → EverfurError-pEXDbUJ1.d.ts} +9 -1
- package/dist/{EverfurResult-ZtH-YV1h.d.cts → EverfurResult-dtl8ERAw.d.cts} +1 -1
- package/dist/{EverfurResult-SGvHKsCB.d.ts → EverfurResult-sKkoXew0.d.ts} +1 -1
- package/dist/IntakeMedia-BFZfBLjB.d.cts +116 -0
- package/dist/{IntakeMedia-BcjjUizr.d.ts → IntakeMedia-BH0fYDT2.d.cts} +19 -2
- package/dist/{IntakeMedia-CL_S2tZE.d.cts → IntakeMedia-Bavl7E4Z.d.ts} +19 -2
- package/dist/IntakeMedia-C8GlN_GK.d.ts +116 -0
- package/dist/animations/index.cjs +109 -1
- package/dist/animations/index.d.cts +6 -6
- package/dist/animations/index.d.ts +6 -6
- package/dist/animations/index.js +109 -1
- package/dist/{attachments-B2GjBgvF.d.cts → attachments-BD70jZZL.d.cts} +3 -3
- package/dist/{attachments-SF88N654.d.ts → attachments-CC7aHpwZ.d.ts} +7 -7
- package/dist/{attachments-DNaSbmA3.d.ts → attachments-DAUy3vPR.d.ts} +3 -3
- package/dist/{attachments-DI710no4.d.cts → attachments-DaOaIBNf.d.cts} +7 -7
- package/dist/{bookingCopy-D2N3RhsV.d.ts → bookingCopy-CUW9Gdzc.d.ts} +15 -7
- package/dist/{bookingCopy-xlXxORCA.d.cts → bookingCopy-oEjqkiNA.d.cts} +15 -7
- package/dist/{branding-Bio5MM6g.d.cts → branding-aGleD_ki.d.ts} +99 -6
- package/dist/{branding-ytH4jJq1.d.ts → branding-ctD0B2Th.d.cts} +99 -6
- package/dist/{callRoom-7wrE3RP2.d.ts → callRoom-B1qq_D-4.d.ts} +1 -1
- package/dist/{callRoom-B_EqaUzx.d.cts → callRoom-DfZTWFXh.d.cts} +1 -1
- package/dist/{casesRepository-B-md8h1S.d.cts → casesRepository-Bzs7aw4t.d.cts} +2 -2
- package/dist/{casesRepository-CC6951TK.d.ts → casesRepository-CywqL6mj.d.ts} +2 -2
- package/dist/chat/index.cjs +335 -1
- package/dist/chat/index.d.cts +12 -12
- package/dist/chat/index.d.ts +12 -12
- package/dist/chat/index.js +335 -1
- package/dist/client/index.cjs +115 -11
- package/dist/client/index.d.cts +14 -14
- package/dist/client/index.d.ts +14 -14
- package/dist/client/index.js +115 -11
- package/dist/{config-BM0sv5jx.d.ts → config-BysLVhku.d.ts} +3 -3
- package/dist/{config-Daa1plhQ.d.cts → config-EZzEyS-c.d.cts} +3 -3
- package/dist/consent/index.cjs +112 -1
- package/dist/consent/index.d.cts +9 -9
- package/dist/consent/index.d.ts +9 -9
- package/dist/consent/index.js +112 -1
- package/dist/{context-DQHtwcHN.d.cts → context-DUwYArkM.d.cts} +9 -9
- package/dist/{context-CDV2pwGI.d.ts → context-DpfgbnOU.d.ts} +9 -9
- package/dist/{copy-BEx5F71o.d.cts → copy-DK4r9oGz.d.cts} +5 -5
- package/dist/{copy-Cl1l-qmY.d.ts → copy-LxZGnFXJ.d.ts} +5 -5
- package/dist/core/index.cjs +140 -13
- package/dist/core/index.d.cts +19 -19
- package/dist/core/index.d.ts +19 -19
- package/dist/core/index.js +140 -13
- package/dist/{depth-CAAwiStc.d.cts → depth-DAd77kRe.d.cts} +7 -6
- package/dist/{depth-DfNRVtrV.d.ts → depth-Mk7quUNa.d.ts} +7 -6
- package/dist/{entitlementRepository-CVWvND1P.d.ts → entitlementRepository-CrD0O7VR.d.ts} +4 -4
- package/dist/{entitlementRepository-DPvWjV-N.d.cts → entitlementRepository-Dra_4FU_.d.cts} +4 -4
- package/dist/{identity-DUlshgow.d.cts → identity-75whJXyP.d.cts} +2 -2
- package/dist/{identity-BhT7oJDS.d.ts → identity-BiyMDMrR.d.ts} +2 -2
- package/dist/index.cjs +365 -12
- package/dist/index.d.cts +19 -19
- package/dist/index.d.ts +19 -19
- package/dist/index.js +365 -12
- package/dist/{models-DSqA5Ahs.d.ts → models-CrbUwbuS.d.ts} +1 -1
- package/dist/{models-Bn2z0NNo.d.cts → models-DzvqEjMm.d.cts} +1 -1
- package/dist/notifications/index.cjs +94 -2
- package/dist/notifications/index.d.cts +5 -5
- package/dist/notifications/index.d.ts +5 -5
- package/dist/notifications/index.js +94 -2
- package/dist/{pets-Bneph9m1.d.cts → pets-DoXxTw4x.d.cts} +2 -2
- package/dist/{pets-DjcLmRrW.d.ts → pets-W2BuLYko.d.ts} +2 -2
- package/dist/{petsRepository-BwxmfX_s.d.ts → petsRepository-ByMzq1Z9.d.ts} +2 -2
- package/dist/{petsRepository-BnVre3q7.d.cts → petsRepository-yyoo0k2I.d.cts} +2 -2
- package/dist/photo/index.cjs +131 -1
- package/dist/photo/index.d.cts +3 -3
- package/dist/photo/index.d.ts +3 -3
- package/dist/photo/index.js +131 -1
- package/dist/{ports-BPKxFOSe.d.cts → ports-BeVJYP0_.d.cts} +7 -7
- package/dist/{ports-Di9rdLO9.d.ts → ports-zYl8S_lI.d.ts} +7 -7
- package/dist/records/depth/index.cjs +200 -2
- package/dist/records/depth/index.d.cts +11 -11
- package/dist/records/depth/index.d.ts +11 -11
- package/dist/records/depth/index.js +200 -2
- package/dist/records/index.cjs +742 -4
- package/dist/records/index.d.cts +22 -14
- package/dist/records/index.d.ts +22 -14
- package/dist/records/index.js +742 -4
- package/dist/{requestFunnel-CiSX2pun.d.ts → requestFunnel-BPeBZdKp.d.ts} +5 -5
- package/dist/{requestFunnel-DMR_1T3O.d.cts → requestFunnel-DHeSzCT6.d.cts} +5 -5
- package/dist/{runtimeTypes-CkMFCbHW.d.ts → runtimeTypes-Cc207nbn.d.ts} +7 -7
- package/dist/{runtimeTypes-2gJ5hYoE.d.cts → runtimeTypes-DgMizQKz.d.cts} +7 -7
- package/dist/server/events/index.cjs +92 -2
- package/dist/server/events/index.d.cts +4 -4
- package/dist/server/events/index.d.ts +4 -4
- package/dist/server/events/index.js +92 -2
- package/dist/server/index.cjs +95 -2
- package/dist/server/index.d.cts +5 -5
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +95 -2
- package/dist/televet/booking/index.cjs +396 -4
- package/dist/televet/booking/index.d.cts +24 -127
- package/dist/televet/booking/index.d.ts +24 -127
- package/dist/televet/booking/index.js +396 -4
- package/dist/televet/call/index.cjs +71 -1
- package/dist/televet/call/index.d.cts +3 -3
- package/dist/televet/call/index.d.ts +3 -3
- package/dist/televet/call/index.js +71 -1
- package/dist/televet/index.cjs +101 -1
- package/dist/televet/index.d.cts +25 -8
- package/dist/televet/index.d.ts +25 -8
- package/dist/televet/index.js +101 -1
- package/dist/{bookingTypes-D4pD3tHs.d.ts → televetGlobal-C5dTUACe.d.cts} +34 -1
- package/dist/{bookingTypes-D4pD3tHs.d.cts → televetGlobal-CnjrfhT4.d.ts} +34 -1
- package/dist/testing/index.cjs +98 -7
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +98 -7
- package/dist/testing/rn/index.cjs +101 -1
- package/dist/testing/rn/index.d.cts +13 -13
- package/dist/testing/rn/index.d.ts +13 -13
- package/dist/testing/rn/index.js +101 -1
- package/dist/testing/web/index.cjs +95 -1
- package/dist/testing/web/index.d.cts +14 -14
- package/dist/testing/web/index.d.ts +14 -14
- package/dist/testing/web/index.js +95 -1
- package/dist/{timelineRows-D3171ksh.d.ts → timelineRows-D22vGN9t.d.ts} +1 -1
- package/dist/{timelineRows-DDnz4gx2.d.cts → timelineRows-DUQIWSjc.d.cts} +1 -1
- package/dist/{tokens-BYtbKwFh.d.cts → tokens-RAKZj7M8.d.cts} +89 -5
- package/dist/{tokens-BYtbKwFh.d.ts → tokens-RAKZj7M8.d.ts} +89 -5
- package/dist/{typeStyle-BqfwxZH4.d.cts → typeStyle-DVj8iCC1.d.ts} +30 -3
- package/dist/{typeStyle-DKz02DGU.d.ts → typeStyle-Nt7w0rhE.d.cts} +30 -3
- package/dist/{useRecordsDepth-Z9FF5X4E.d.ts → useRecordsDepth-C0Qfoghi.d.ts} +7 -6
- package/dist/{useRecordsDepth-COJ0wSYK.d.cts → useRecordsDepth-Mbysp548.d.cts} +7 -6
- package/dist/{useVetVisit-Ds8f1peV.d.cts → useVetVisit-BQX_aTJs.d.cts} +2 -2
- package/dist/{useVetVisit-BsjoDO-n.d.ts → useVetVisit-RPBOabl8.d.ts} +2 -2
- package/dist/video/index.cjs +122 -1
- package/dist/video/index.d.cts +3 -3
- package/dist/video/index.d.ts +3 -3
- package/dist/video/index.js +122 -1
- package/dist/{view-nRy6SitU.d.cts → view-CskIgOFV.d.cts} +5 -5
- package/dist/{view-DoQEHXJR.d.ts → view-DqKXtxEZ.d.ts} +5 -5
- package/dist/web/consent/index.cjs +111 -1
- package/dist/web/consent/index.d.cts +9 -9
- package/dist/web/consent/index.d.ts +9 -9
- package/dist/web/consent/index.js +111 -1
- package/dist/web/index.cjs +326 -14
- package/dist/web/index.d.cts +29 -23
- package/dist/web/index.d.ts +29 -23
- package/dist/web/index.js +326 -14
- package/dist/web/notifications/index.cjs +95 -2
- package/dist/web/notifications/index.d.cts +7 -7
- package/dist/web/notifications/index.d.ts +7 -7
- package/dist/web/notifications/index.js +95 -2
- package/dist/web/records/depth/index.cjs +170 -2
- package/dist/web/records/depth/index.d.cts +11 -11
- package/dist/web/records/depth/index.d.ts +11 -11
- package/dist/web/records/depth/index.js +170 -2
- package/dist/web/records/index.cjs +691 -4
- package/dist/web/records/index.d.cts +34 -37
- package/dist/web/records/index.d.ts +34 -37
- package/dist/web/records/index.js +691 -4
- package/dist/web/records/upload/index.cjs +3 -0
- package/dist/web/records/upload/index.d.cts +23 -0
- package/dist/web/records/upload/index.d.ts +23 -0
- package/dist/web/records/upload/index.js +3 -0
- package/dist/web/televet/booking/index.cjs +425 -4
- package/dist/web/televet/booking/index.d.cts +25 -39
- package/dist/web/televet/booking/index.d.ts +25 -39
- package/dist/web/televet/booking/index.js +425 -4
- package/dist/web/televet/call/index.cjs +28 -1
- package/dist/web/televet/call/index.d.cts +2 -2
- package/dist/web/televet/call/index.d.ts +2 -2
- package/dist/web/televet/call/index.js +28 -1
- package/dist/web/televet/index.cjs +102 -4
- package/dist/web/televet/index.d.cts +22 -11
- package/dist/web/televet/index.d.ts +22 -11
- package/dist/web/televet/index.js +102 -4
- package/package.json +20 -4
- package/web/records/upload/native-blocked.cjs +12 -0
- package/web/records/upload/package.json +8 -0
- package/dist/televetGlobal-CEk0_cW9.d.cts +0 -34
- package/dist/televetGlobal-Cs9Wbqsy.d.ts +0 -34
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,365 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),react=require('react'),reactNativeSafeAreaContext=require('react-native-safe-area-context'),fb=require('react-native-sse'),reactNative=require('react-native'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var fb__default=/*#__PURE__*/_interopDefault(fb);var Xf=Object.defineProperty;var i=(e,t)=>Xf(e,"name",{value:t,configurable:true});function Ce(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(Ce,"hasLoneSurrogate");function gt(e){return [...e].length}i(gt,"serverLength");function L(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(L,"ok");function v(e){return Object.freeze({ok:false,error:e})}i(v,"err");function Qf(e){return e.ok}i(Qf,"isOk");function Zf(e){return !e.ok}i(Zf,"isErr");var Wr=class Wr extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,Wr.prototype);}};i(Wr,"EverfurThrownError");var jr=Wr;function Jf(e){if(e.ok)return e.value;throw new jr(e.error)}i(Jf,"unwrap");var Gr=class Gr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Gr.prototype);}};i(Gr,"EverfurConfigError");var re=Gr;var As=128,Os=128,Fs=/[\u0000-\u001F\u007F]/,em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tm(e){let t=e,r=gt(t);if(r===0||r>Os)throw new re("invalid-argument",`petRef must be 1..${Os} characters`);if(Fs.test(t))throw new re("invalid-argument","petRef must be printable (no control characters)");return t}i(tm,"petRef");function rm(e){let t=e,r=gt(t);if(r===0||r>As)throw new re("invalid-argument",`userRef must be 1..${As} characters`);if(t.includes("@"))throw new re("invalid-argument","userRef must not contain '@'");if(Fs.test(t))throw new re("invalid-argument","userRef must be printable (no control characters)");return t}i(rm,"userRef");function nm(e){if(!em.test(e))throw new re("invalid-argument","conversationId must be a UUID");return e}i(nm,"conversationId");var ao=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(ao.map(e=>e.wireCode));var om=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),Ls=Object.freeze(ao.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:om[e.wireCode]}))),im=new Map(Ls.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),sm=Object.freeze(["http_envelope",...[...new Set(Ls.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Kr(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...sm]){let o=im.get(n+r);if(o)return o}}i(Kr,"contractErrorFor");function am(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(am,"contractDocUrl");function Ns(e){return null}i(Ns,"publishedDocUrl");var lm=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function lo(e){return lm[e]}i(lo,"categoryFor");function Fe(e){let t=Kr(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":case "TELEVETRATELIMITED":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Fe,"fromWire");function Ds(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(Ds,"fromHttpStatus");var um=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Ge(e){return um.has(e)}i(Ge,"isAutoRetryable");var dm=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function uo(e){return Ge(e)||dm.has(e)}i(uo,"isRetryableCode");function qr(e,t=false){return t||Ge(e)}i(qr,"shouldRetry");var cm=500,co=8e3,rr=4;function $r(e,t=Math.random){let r=Math.max(0,e),n=Math.min(cm*2**r,co);return Math.floor(t()*n)}i($r,"backoffDelayMs");function Us(e){return e==="conversationNotFound"}i(Us,"canRecreateOnNotFound");var pm=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function Dt(e){return pm[e]}i(Dt,"userFacingError");function Vs(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Vs,"defineHidden");var fm=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Kr(t?.wireCode,t?.wireEnvelope),n={code:e,category:lo(e),retryable:t?.retryable??uo(e),displayMessage:Dt(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&fm.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&Vs(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Vs(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");var Hs="application/pdf",Yr=Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]);zod.z.object({features:zod.z.record(zod.z.boolean()),upload_content_types:zod.z.array(zod.z.string()).nullish(),share_audiences:zod.z.unknown().optional()});var mm=i(e=>Yr.includes(e),"isPhotoType");function po(e,t){return e===Hs||t!==void 0&&mm(e)&&t.includes(e)}i(po,"isAcceptedUploadType");var Bs=Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function zs(e){return po(e,Yr)?Bs[e]:Bs["application/pdf"]}i(zs,"recordsUploadFilename");var ym="file",fo="multipart upload failed";function Xr(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(ym,e.file);}catch{return Promise.reject(new Error(fo))}return e.fetch!==void 0?bm(e.fetch,e.url,t,e.signal):hm(e.url,t,e.signal)}i(Xr,"postRnMultipart");function gm(e){return e>=200&&e<300}i(gm,"stored");function hm(e,t,r){return new Promise((n,o)=>{let s=globalThis.XMLHttpRequest;if(typeof s!="function"||r?.aborted===true){o(new Error(fo));return}let a=null,l=i(()=>{a!==null&&r?.removeEventListener("abort",a);},"release"),u=i(()=>{l(),o(new Error(fo));},"fail");try{let d=new s;d.open("POST",e),d.withCredentials=!1,d.onload=()=>{l(),n(gm(d.status));},d.onerror=u,d.ontimeout=u,d.onabort=u,r!==void 0&&(a=i(()=>{try{d.abort();}finally{u();}},"onAbort"),r.addEventListener("abort",a,{once:!0})),d.send(t);}catch{u();}})}i(hm,"postWithXhr");function bm(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(o=>o.ok)}i(bm,"postWithFetch");var vm="records upload: the file handle has no uri",Em="records upload failed";function Cm(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(vm));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(Em)),"failed");return o?.aborted===true?a():Xr({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:zs(r.mimeType),type:Rm(r.mimeType)},signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(Cm,"createRnRecordsUploadTransport");function Rm(e){return po(e,Yr)?e:"application/pdf"}i(Rm,"partType");var Qr=Object.freeze({track(){},trackExpectedFailure(){}});var js=Object.freeze({shouldRetry(e,t){return Ge(e)&&t<rr},maxAttempts(){return rr}});var Ws=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function at(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(at,"assertNever");function Gs(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Gs,"acceptedFrame");function Ks(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(Ks,"heartbeatFrame");function qs(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(qs,"deltaFrame");function $s(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i($s,"doneFrame");function ye(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(ye,"errorFrame");function Ys(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Ys,"analysisStartedFrame");function Xs(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Xs,"analysisCompleteFrame");function Qs(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Qs,"unknownFrame");function Zs(e,t,r){let n=null,o=null,s=false,a=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new re("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:Pm(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(s)throw new re("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:a()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(Zs,"createIdentityProvider");function Pm(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(Pm,"expiryMs");function yo(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(yo,"newSessionId");function km(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(km,"authHeaders");function nr(e,t){return {...e,headers:{...xm(e.headers),...km(t)}}}i(nr,"withAuthHeaders");function xm(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(xm,"stripAuthHeaders");async function Js(e,t){if(t.mode==="anonymous")return t.transport.request(nr(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return v(mo())}let n=await t.transport.request(nr(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return v(mo())}let s=await t.transport.request(nr(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?v(mo(s.error.httpStatus)):s}i(Js,"authedSend");function mo(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(mo,"authRejectedError");var ea=`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",a);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",a);try{e.close();}catch{}}}return i(l,"cleanup"),Ym(r.source,l)}i($m,"eventSourceByteSource");async function*Ym(e,t){try{yield*e;}finally{t();}}i(Ym,"sourceWithCleanup");function Xm(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(a=>{r=a;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(Xm,"createByteQueue");async function Qm(e,t){let r=t.fetchImpl??fa(),n=ma(t.config.apiBaseUrl,e.path,e.query),o=ya(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=ny(qm),a=oy(s.signal,e.signal),l;try{l=await r(n,ga({...e,signal:a},o));}catch(d){return v(vo(d))}finally{s.cancel();}let u=await ha(l);return l.ok?L(u):v(ey(l.status,u,ca(l)))}i(Qm,"requestJson");function da(e){return {request:i(t=>Qm(t,e),"request"),stream:i((t,r)=>Zm(ry(t,r),e),"stream")}}i(da,"createHttpTransport");async function*Zm(e,t){let r=ma(t.config.apiBaseUrl,e.path,e.query),n=ya(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Jm(e,n));yield*Zr($m(l),()=>ty(l));return}let o=t.fetchImpl??fa(),s;try{s=await o(r,ga(e,n));}catch(l){yield aa("",true,Ca(l));return}let a=ca(s);if(!s.ok){let l=await ha(s),u=ba(l)??pa(s.status),d=Ea(l)||Ge(Fe(u));yield aa(u,d,va(l),a);return}if(s.body){yield*Zr(sa(s.body),a);return}yield*Zr(sa(null),a);}i(Zm,"streamFrames");function Jm(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Jm,"buildEventSourceInit");function ey(e,t,r){let n=ba(t),o=n?Fe(n):Ds(e),s=va(t);return D(o,{httpStatus:e,...Ea(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...la(t)?{reasonCode:la(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(ey,"errorFromResponse");function vo(e){return D("internalError",{retryable:true,wireMessage:Ca(e)})}i(vo,"networkError");function ca(e){let t=e.headers.get(ua);return typeof t=="string"&&t.length>0?t:null}i(ca,"requestIdOf");function ty(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(ua);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(ty,"eventSourceRequestId");function pa(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(pa,"statusToWireCode");function aa(e,t,r,n=null){return ye({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(aa,"syntheticErrorFrame");function fa(){let e=globalThis.fetch;if(typeof e!="function")throw new re("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(fa,"getGlobalFetch");function ma(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(a=>a[1]!==void 0).map(([a,l])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(l))}`).join("&");s&&(o+=`?${s}`);}return o}i(ma,"buildUrl");function ya(e,t,r,n){let o={...ia(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(ya,"mergeHeaders");function ga(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(ga,"buildInit");function ry(e,t){return e.signal?e:{...e,signal:t}}i(ry,"withSignal");function ny(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(ny,"timeoutSignal");function oy(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(oy,"mergeAbortSignals");async function ha(e){try{return await e.json()}catch{return null}}i(ha,"safeJson");function la(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(la,"extractReasonCode");function ba(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(ba,"extractWireCode");function va(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(va,"extractWireMessage");function Ea(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Ea,"extractRetryable");function Ca(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Ca,"describeCause");var iy=3e4,sy=co*2,ay="idempotency-key",ly=new Set(["POST","PUT","PATCH","DELETE"]),uy=Object.freeze({onEvent(){}}),dy=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function cy(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(cy,"seededIdempotencyKey");function Ie(e){let t=e.observer??uy,r=e.timers??dy,n=e.rng??Math.random,o=e.sleep??((f,m)=>Py(f,r,m)),s=e.maxAttempts??rr,a=e.unaryTimeoutMs??iy,l=e.newIdempotencyKey??fy(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,h){let T=h?.maxAttempts,b=Math.max(1,T??s),S=h?.idempotent??ly.has(m.method),P=h?.idempotencyKey===void 0?null:cy(h.idempotencyKey),k=S?P??l():null,x=py(m,k),y=0;for(;;){let _=i(H=>Object.freeze({call:f,method:m.method,path:m.path,attempt:y,...k?{idempotencyKey:k}:{},...H}),"stamp");u(_({phase:"attempt"}));let A=Sy(a,r),O=Ty(A.signal,m.signal),F;try{F=await Js({...x,signal:O.signal},e.auth);}catch(H){F=v(vo(H));}finally{O.dispose(),A.cancel();}if(F.ok)return u(_({phase:"settled",ok:true,reason:"ok"})),F;let C=F.error,w=yy(C,y,{maxAttempts:b,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...T!==void 0?{perCallMaxAttempts:T}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),I={ok:false,code:C.code,reason:w.reason,...C.httpStatus!==void 0?{httpStatus:C.httpStatus}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};if(!w.retry)return u(_({phase:"settled",...I})),v(C);if(u(_({phase:"retry",...I,delayMs:w.delayMs})),await o(w.delayMs,m.signal),m.signal?.aborted===true)return u(_({phase:"settled",...I,reason:"aborted"})),v(C);y+=1;}}i(d,"send");async function c(f){return nr(f,await Ry(e.auth))}i(c,"authorize");async function*p(f,m,h){u(Object.freeze({call:f,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,h);}catch{yield ye({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(Ie,"createRequestFunnel");function py(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==ay&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(py,"assembleHeaders");function fy(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(fy,"defaultIdempotencyKeyFactory");var my=10;function yy(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=gy(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!Ge(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(my,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=hy(e,r.now);return u!==null?u>sy?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:$r(t,r.rng)}}i(yy,"decideRetry");function gy(e){let t=e.code==="unknown"?Fe(Cy(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(gy,"throttleKind");function hy(e,t){let r=vy(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=by(e.raw);return n===null?null:Math.round(n*1e3)}i(hy,"retryOverrideMs");function by(e){for(let t of Eo(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(by,"findRetryAfterSeconds");function vy(e){for(let t of Eo(e)){let r=t.resets_at,n=Ey(r);if(n!==null)return n}return null}i(vy,"findResetsAt");function Eo(e){if(!Ra(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Ra(n)&&t.push(n);}return t}i(Eo,"candidateScopes");function Ey(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(Ey,"parseInstantMs");function Cy(e){for(let t of Eo(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Cy,"rawWireCode");function Ra(e){return typeof e=="object"&&e!==null}i(Ra,"isRecord");async function Ry(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Ry,"resolveDeviceAuth");function Sy(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Sy,"boundedSignal");function Ty(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(Ty,"mergeSignals");function Py(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(Py,"delayAbortable");var en=Object.freeze(["better","same","worse"]),Ro=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sa(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i(Sa,"invalid");function Co(){return v(D("internalError",{retryable:false}))}i(Co,"malformed");function Ta(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Ce(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Ta,"petPath");var Ke=i(e=>typeof e=="string"?e:null,"str"),Pa=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function ka(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ke(t.case_id),n=Ke(t.status);if(r===null||n===null)return null;let o=Ke(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Ke(t.body_location),lastResponse:o!==null&&en.includes(o)?o:null,checkInDueAt:Ke(t.check_in_due_at),openedAt:Ke(t.opened_at),resolvedAt:Ke(t.resolved_at),resolutionText:Ke(t.resolution_text),checkinAskCount:Pa(t.checkin_ask_count),checkinAnswerCount:Pa(t.checkin_answer_count)})}i(ka,"caseFromWire");function xa(e){return {async list(t,r){let n=Ta(t);if(typeof n!="string")return v(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return v(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return Co();let a=s.map(ka);return a.every(l=>l!==null)?L(Object.freeze(a)):Co()},async checkin(t,r,n,o){let s=Ta(t);if(typeof s!="string")return v(s);if(typeof r!="string"||!Ro.test(r))return Sa("case_id must be a UUID");if(!en.includes(n))return Sa("response must be one of better, same, worse");let a=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!a.ok)return v(a.error);let l=typeof a.value=="object"&&a.value!==null?a.value:{},u=ka(l.case);return u===null?Co():L(Object.freeze({case:u,ctaDeepLink:Ke(l.cta_deep_link)}))}}}i(xa,"createCasesRepositoryOver");var _a=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var wa=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function rn(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(rn,"delayAbortable");function nn(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(nn,"mergeSignals");var So=class So{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?nn(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(So,"MediaStore");var tn=So;function Po(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(Po,"makeUser");function ko(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(ko,"makeAssistant");function sr(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(sr,"stripPending");function Ia(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(Ia,"appendText");function xo(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(xo,"finalizeAssistant");function Aa(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(Aa,"freezeSnapshot");function U(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(U,"makeError");function _o(e){let t=Fe(e.code);return D(t,{retryable:e.retryable||qr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(_o,"errorFromFrame");function Me(e){return ye({code:ky(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Me,"synthErrorFrame");function ky(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return at(e)}}i(ky,"canonicalWireCode");function Oa(e){let t=Array.isArray(e)?e:To(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!To(n))continue;let o=ir(n.category)??ir(n.title)??"",s=xy(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(Oa,"parsePromptCategories");function wo(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(wo,"flattenPrompts");function To(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(To,"isPlainObject");function ir(e){return typeof e=="string"?e:null}i(ir,"asStr");function xy(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(To(r)){let n=ir(r.text)??ir(r.prompt)??ir(r.title);n!==null&&t.push(n);}return t}i(xy,"asPromptTextList");function Fa(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(Fa,"defaultIdFactory");function Ma(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Ma,"defaultIdempotencyFactory");var Na={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*Da(e,t,r,n){let o=e[Symbol.asyncIterator](),s=La(t.overallMs,n),a=La(t.idleMs,n),l=Iy(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([u,a.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield wy();return}if(d.tag==="idle"||d.tag==="overall"){yield _y();return}let c=d.value;if(c.done||(a.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{a.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(Da,"withWatchdog");function _y(){return ye({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(_y,"synthTimeoutFrame");function wy(){return ye({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(wy,"synthStreamErrorFrame");function La(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(La,"deadline");function Iy(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Iy,"abortPromise");var Ay="checkin",Oy=/^\d{4}-\d{2}-\d{2}$/,on="watching";function Ua(e){return e.status!=null&&e.status!==on}i(Ua,"isCheckinSettled");function Va(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(Va,"isLiveAskAnswered");function Io(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Ay||n===void 0||o===void 0||!Ro.test(n)||!Oy.test(o)?null:{caseId:n,dueDay:o}}i(Io,"parseCheckinOrigin");function Ba(e){return Io(e)?.caseId??null}i(Ba,"parseCheckinOriginRef");function Oo(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return v(D("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Ce(o))return v(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),L(r.length?`?${r.join("&")}`:"")}i(Oo,"historyQuery");function lr(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(lr,"validConversationId");function Vt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(Vt,"object");function Ha(e){return e==null||typeof e=="string"&&e.length>0&&!Ce(e)}i(Ha,"cursor");function ar(){return v(D("internalError",{retryable:false}))}i(ar,"malformed");function za(e){let t=Vt(e);if(!t||!Array.isArray(t.conversations)||!Ha(t.next_cursor))return ar();let r=[];for(let n of t.conversations){let o=Vt(n);if(!o||typeof o.conversation_id!="string"||!lr(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return ar();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return ar();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return L(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(za,"mapConversationPage");function ja(e){let t=Vt(e);if(!t||!Array.isArray(t.messages)||!Ha(t.next_cursor))return ar();let r=[],n=new Set;for(let o of t.messages){let s=Vt(o);if(!s||typeof s.message_id!="string"||!lr(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return ar();if(s.role!=="user"&&s.role!=="assistant"&&s.role!=="vet"||n.has(s.message_id))continue;if(n.add(s.message_id),s.role==="vet"){r.push(Fy(s,s.message_id,s.content,s.created_at));continue}let a=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,l=s.role==="assistant"?Ba(a):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:My(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Ly(s.citations)}:{},...a!==null?{proactiveOriginRef:a}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return L(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(ja,"mapMessagePage");function Fy(e,t,r,n){let o=Vt(e.sender),s=Ao(o?.display_name)??Ao(e.sender_display_name),a=Ao(o?.specialty);return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:Object.freeze({displayName:s,specialty:a})})}i(Fy,"vetMessage");function Ao(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!Ce(t)?t:null}i(Ao,"trimmedText");function My(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(My,"normalizeUrgency");function Ly(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=Vt(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let a=n[s];(typeof a=="string"||a===null)&&(o[s]=a);}return [Object.freeze(o)]}))}i(Ly,"historyCitations");var Fo=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Bt=4e3;var Ht=4e3;function Wa(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:U("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:U("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(Wa,"validateImageKeys");function Lo(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:U("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Ht?{reason:"too_long",error:U("validationFailed",false,`message is ${r} characters; the server accepts at most ${Ht}`)}:null}i(Lo,"validateMessageText");function Ga(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ga,"urgencyTier");async function*ur(e){yield e;}i(ur,"singleFrameStream");async function*Ka(){}i(Ka,"emptyStream");var Ny=6e4,Dy=18e4,Uy=24,Vy=512,By=false;function qa(e){return new No(e)}i(qa,"createChatController");var Do=class Do extends tn{constructor(r){super(Aa({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??Ie({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=xa(this.funnel),this.telemetry=r.telemetry??Qr,this.errorPolicy=r.errorPolicy??js,this.timers=r.timers??Na,this.rng=r.rng??Math.random,this.newId=r.newId??Fa(),this.makeIdempotencyKey=r.makeIdempotencyKey??Ma(),this.budget={idleMs:r.budget?.idleMs??Ny,overallMs:r.budget?.overallMs??Dy};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=U(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):ur(Me(u))}let a=Lo(r)??Wa(s.imageS3Keys);if(a!==null)return this.telemetry.track("chat.send.rejected",{reason:a.reason}),this.patch({status:"error",isStreaming:false,error:a.error}),o?(o.onError(a.error),()=>{}):ur(Me(a.error));if(o)return this.driveWithHandlers(r,s,o);let l=this.beginTurn(r,s);return this.runTurn(l,s.signal)}askEverfur(r,n){if(this.disposed)return ur(Me(U("accessDenied",false)));let o=Lo(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),ur(Me(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):Ka()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,Po(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?sr(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(r=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=r,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:r,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}newConversation(){this.disposed||this.resetThread(this.scopePrompts);}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(wo(r));this.bootstrapPrompts=n,this.scopePrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=Oo(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return v(U("accessDenied",false));if(!a.ok)return a;let l=za(a.value);if(l.ok){for(let c of l.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let u=this.snapshot.conversationId,d=u===null?void 0:this.unreadByConversation.get(u);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?L(n):v(u.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return v(s.error);let a=s.value.conversations[0];if(a===void 0)return L(null);let l=await this.resumeConversation(a.id);return l.ok?L(a.id):v(l.error)}async markRead(r){if(this.disposed)return v(U("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return L(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?v(U("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),L(void 0)):v(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return v(U("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Ce(r))return v(U("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Fo.includes(n))return v(U("validationFailed",false,`feedback_type must be one of ${Fo.join(", ")}`));let a=typeof o=="string"?o.trim():"";if([...a].length>Bt)return v(U("validationFailed",false,`notes is over ${Bt} characters`));let l={feedback_type:n};a.length>0&&(l.notes=a);let u=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},s?.signal);if(!this.alive(u)||this.disposed)return v(U("accessDenied",false));if(!d.ok)return v(d.error);let c=d.value?.feedback_id;return L(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return v(U("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return v(U("validationFailed",false,"a check-in needs the pet the case belongs to"));let a=this.epoch,l=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(a)||this.disposed)return v(U("accessDenied",false));if(!l.ok)return l;let u=l.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...u!==null?{openedAt:u}:{}}),c=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,checkin:d}):p)}),l}async getMessages(r,n){if(!lr(r))return v(U("validationFailed",false));let o=Oo(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return v(U("accessDenied",false));let a=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?v(U("accessDenied",false)):a.ok?ja(a.value):a}async resumeConversation(r){if(this.disposed)return v(U("accessDenied",false));if(!lr(r))return v(U("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),L(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===on).map(d=>d.caseId)),a=new Map(o.value.map(d=>[d.caseId,d])),l=false,u=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;l=true;let p=a.get(c.caseId),f=c.openedAt??p?.openedAt??null,m=s.has(c.caseId),h=p!==void 0&&(!m||Va({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:m?on:p?.status??"resolved",answer:c.answer??h,resolutionText:c.resolutionText??p?.resolutionText??null,...f!==null?{openedAt:f}:{}})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return L(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(!o.ok)return v(o.error);let s=new Set(this.snapshot.messages.map(l=>l.id)),a=o.value.messages.filter(l=>!s.has(l.id));return a.length>0&&this.patch({messages:[...this.snapshot.messages,...a]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),L(void 0)}async loadOlderMessages(){if(this.disposed)return v(U("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return L(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return v(U("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let a=new Set(this.snapshot.messages.map(u=>u.id)),l=s.value.messages.filter(u=>!a.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),L(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Me(n.error));}async primeConversation(r){if(this.disposed)return v(U("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?v(U("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);return n.ok?n.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n.value)).ok?L(n.value):L(this.snapshot.conversationId):n.error.code==="accessDenied"||n.error.httpStatus===403?L(null):v(n.error)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return v(n.error);let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?L(null):L(o.id)}async createConversation(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let a=await s.settled;return !this.alive(n)||this.disposed?v(U("accessDenied",false)):(!a.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),a)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.conversation_id??s.value?.id;return typeof a!="string"||a.length===0?v(U("internalError",true)):L(a)}async getPrompts(r){let n=this.epoch;if(this.disposed)return v(U("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Ce(o))return v(D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",a=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?v(U("accessDenied",false)):a.ok?L(Oa(a.value)):v(a.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,a=nn(s.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,a),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of u){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,Po(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,a=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=u?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let b=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;b.ok&&b.value!==null&&this.snapshot.conversationId===null&&this.adoptConversation(b.value);}if(u&&this.snapshot.conversationId===null){let b=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!b.ok){yield*this.emitTerminal(r,b.error,Me(b.error));return}this.adoptConversation(b.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let b=U("internalError",!0);yield*this.emitTerminal(r,b,Me(b));return}this.clearAssistantInProgress(r);let p=new AbortController,f=nn(o.signal,p.signal),m=null;try{let b;try{b=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let P=this.authRejected();yield*this.emitTerminal(r,P,Me(P));return}if(o.signal.aborted||!this.alive(o.epoch))return;let S=this.funnel.stream("chat.send",b,f);for await(let P of Da(S,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(P.kind==="error"&&P.terminal){m=P;break}if(this.applyFrame(P,r),yield P,P.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(m===null){if(this.snapshot.status==="complete")return;let b=U("streamIncomplete",!0);yield*this.emitTerminal(r,b,Me(b));return}let h=Fe(m.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let b=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!b){let S=this.authRejected();yield*this.emitTerminal(r,S,m);return}this.patch({reconnecting:!0});continue}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let b=this.authRejected();yield*this.emitTerminal(r,b,m);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,_o(m),m);return}if(Us(h)&&!a){a=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let T=m.retryable&&qr(h,!0);if(By&&T&&s+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(r,_o(m),m);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return at(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(a=>a.id===n.userMessageId&&a.pending===true?sr(a):a);this.patch({status:"streaming",isStreaming:true,messages:[...s,ko(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Vy){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},Uy);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(a=>a.id===o?Ia(a,n):a);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?xo(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?sr(d):d),xo(ko(l,"",this.stamp()),r)];}let a=wo([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=a.length>0?Object.freeze(a):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,a=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(s)||this.disposed||a!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=Ga(l.value?.urgency),d=typeof l.value?.reason=="string"?l.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?sr(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return U("authRejected",false)}};i(Do,"ChatControllerImpl");var No=Do;async function Xa(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],a=false,l=false,u=false,d=null,c=null,p=o?r.resumeConversation(o).then(x=>x.ok?L(o):v(x.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,h]=await Promise.all([p,f]),T=null;if(m.ok)T=m.value,m.value!==null&&s.push(m.value),m.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let x=m.error;c=x,$a(x)?(l=true,d=x):(Ya(x)&&(a=true),u=true);}let b=[];h.ok?b=h.value:S(h.error);function S(x){$a(x)?(l=true,d===null&&(d=x)):Ya(x)&&(a=true);}i(S,"recordAuthSignals");let P=d!==null?d.displayMessage:null;return Object.freeze({conversationId:T,petRef:n,suggestedPrompts:b,error:P,warning:P===null&&T===null&&u?Hy:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:a,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Xa,"bootstrapChat");var Hy="Chat is ready. Your first message will start the conversation.";function $a(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i($a,"isUnauthorized");function Ya(e){return e.httpStatus===403||e.code==="accessDenied"}i(Ya,"isForbidden");var Uo=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Qa(e){return e!==Uo}i(Qa,"isUploadTransportAvailable");var zy=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var sn=10*1024*1024,an=5,dr=120,jy="/widget/v1/uploads/initiate";function Wy(e){return typeof e=="string"&&zy.includes(e.trim().toLowerCase())}i(Wy,"isAttachmentMime");function Vo(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=dr)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,dr);let n=t.slice(r);return n.length>=dr?t.slice(0,dr):`${t.slice(0,r).slice(0,dr-n.length)}${n}`}i(Vo,"sanitizeFilename");function Bo(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(Bo,"formatBytes");var cr=i(e=>Object.freeze({ok:true,value:e}),"ok"),Ae=i(e=>Object.freeze({ok:false,error:e}),"err");function ue(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(ue,"failure");function Gy(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i(Gy,"attachmentSize");function Ky(e){let t=Vo(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!Wy(r))return Ae(ue("unsupported_type",false,t));let n=Gy(e);return n===null?Ae(ue("unknown",false,t)):n>sn?Ae(ue("too_large",false,t,{sizeBytes:n})):cr(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Ky,"validateAttachment");function qy(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),a=r(t.s3_key);if(o===null||s===null||a===null)return null;let l={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[d,c]of Object.entries(u))typeof c=="string"&&(l[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(l),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??sn,s3_key:a,purpose:r(t.purpose)})}i(qy,"parsePolicy");function $y(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return ue("quota_exceeded",false,t,{cause:e});case "rateLimited":return ue("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return ue("idempotency_conflict",true,t,{cause:e});case "validationFailed":return ue("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return ue("network",true,t,{cause:e});default:return r===429?ue("rate_limited",true,t,{cause:e}):r===503?ue("network",true,t,{cause:e}):r===void 0?ue("network",true,t,{cause:e}):ue("server",e.retryable,t,{httpStatus:r,cause:e})}}i($y,"initiateFailure");async function Yy(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:jy,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return Ae($y(n.error,t.filename));let o=qy(n.value);return o===null?Ae(ue("server",false,t.filename)):cr(o)}i(Yy,"initiateAttachmentUpload");async function Xy(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return Ae(ue("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),cr(void 0)}catch{return o()?Ae(ue("cancelled",true,r.filename)):Ae(ue("server",true,r.filename))}}i(Xy,"uploadAttachmentBytes");var Qy=2,Zy=3,Jy=Object.freeze([1e3,2e3,4e3]),Za=0;function eg(){return Za+=1,`attachment-${Za}`}i(eg,"defaultNewId");function Ja(e){let t=Math.max(1,e.concurrency??Qy),r=Math.max(1,e.maxAttempts??Zy),n=e.backoffMs??Jy,o=Math.max(1,e.maxPerMessage??an),s=e.timers??wa,a=e.newId??eg,l=Qa(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),h=false,T=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(y=>{let _=u.get(y);return _===void 0?[]:[_.state]}))});for(let y of f)y();},"publish"),b=i((y,_)=>{y.state=Object.freeze({...y.state,..._}),T();},"patch"),S=i(()=>{for(;!h&&p.size<t&&c.length>0;){let y=c.shift(),_=u.get(y);_!==void 0&&(p.add(y),P(_).finally(()=>{p.delete(y),S();}));}},"pump"),P=i(async y=>{let{attachment:_}=y;for(;y.attempts<r;){if(h||y.controller.signal.aborted)return;y.attempts+=1;let A=y.controller.signal;b(y,{status:"uploading",error:null,progress:0});let O=await Yy(e.funnel,_,{signal:A});if(h||A.aborted)return;let F;if(!O.ok)F=Ae(O.error);else {let H=await Xy(e.transport,O.value,_,{signal:A,onProgress:i(Q=>{!A.aborted&&y.state.status==="uploading"&&b(y,{progress:tg(Q)});},"onProgress")});if(h||A.aborted)return;F=H.ok?cr(O.value.s3_key):Ae(H.error);}if(F.ok){b(y,{status:"uploaded",s3Key:F.value,error:null,progress:1});return}let C=F.error,w=C.retryable&&y.attempts<r;if(b(y,{status:w?"uploading":"failed",error:C,progress:0}),!w)return;let I=n[Math.min(y.attempts-1,n.length-1)]??0;await rn(I,A,s);}},"run"),k=i(y=>{c.push(y.state.id),S();},"enqueue"),x={available:l,subscribe(y){return f.add(y),()=>{f.delete(y);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(y=>y.status==="uploading")},get s3Keys(){return m.attachments.flatMap(y=>y.status==="uploaded"&&y.s3Key!==null?[y.s3Key]:[])},add(y){let _=Ky(y);if(!_.ok)return _;if(h||d.length>=o)return Ae(ue("too_many",false,_.value.filename));let A=a(),O={attachment:_.value,controller:new AbortController,attempts:0,state:Object.freeze({id:A,filename:_.value.filename,previewUri:y.uri,contentType:_.value.contentType,sizeBytes:_.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(A,O),d.push(A),T(),k(O),cr(O.state)},retry(y){let _=u.get(y);_===void 0||h||_.state.status!=="failed"||(_.controller=new AbortController,_.attempts=0,b(_,{status:"uploading",error:null,progress:0,s3Key:null}),k(_));},remove(y){let _=u.get(y);if(_===void 0)return;_.controller.abort(),u.delete(y);let A=d.indexOf(y);A>=0&&d.splice(A,1);let O=c.indexOf(y);O>=0&&c.splice(O,1),T();},clear(){for(let y of [...d])x.remove(y);},dispose(){h=true;for(let y of u.values())y.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return x}i(Ja,"createAttachmentQueue");function tg(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(tg,"clamp");var el=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function pr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(el,t)?el[t]:null}i(pr,"canonicalPetSpecies");var tl=50,rg=128,Ho=120,rl=120,ng=2e3,nl=120,og=80,sl=new Set(["male","female","unknown"]),al=new Set(["day","month","year"]),ll=new Set(["low","medium","high","athletic"]),ul=new Set(["indoor","outdoor","both"]),dl=new Set(["mild","moderate","severe"]),ig=/^(\d{4})-(\d{2})-(\d{2})$/,cl=[["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"]],pl=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...cl,...pl].map(([e])=>e));function sg(e){let t=ig.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(sg,"isRealDate");var mr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),ag=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),un=i((e,t)=>typeof t=="string"&&sg(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Le=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Ce(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=gt(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),lg={sex:mr(sl),spayedNeutered:ag,birthDate:un,birthDatePrecision:mr(al),activityLevel:mr(ll),indoorOutdoor:mr(ul),foodBrand:Le(nl),foodType:Le(nl),microchipId:Le(og)},zo=["ref","ref",false,Le(rg,{required:true,trimmed:true})],jo=["notes","notes",false,Le(ng,{trimmed:true})],ol=[zo,["name","name",true,Le(Ho,{required:true,trimmed:true})],["dose","dose",false,Le(rl,{trimmed:true})],["frequency","frequency",false,Le(rl,{trimmed:true})],["startDate","start_date",false,un],["endDate","end_date",false,un],jo],ug={allergies:[zo,["allergen","allergen",true,Le(Ho,{required:true,trimmed:true})],["severity","severity",false,mr(dl)],jo],medications:ol,supplements:ol,conditions:[zo,["conditionName","condition_name",true,Le(Ho,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,un],jo]};function dg(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[u,d,c,p]of ug[e]){let f=o[u];if(f==null){if(c)return {error:`${n}.${u} is required`};f===null&&(s[d]=null);continue}let m=p(`${n}.${u}`,f);if(m!==null)return {error:m};s[d]=f;}let a=s.start_date,l=s.end_date;return typeof a=="string"&&typeof l=="string"&&l<a?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(dg,"itemToWire");function cg(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>tl)return {error:`${e} has ${t.length} items; the server accepts at most ${tl}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=dg(e,o,t[o]);if("error"in s)return s;let a=s.item.ref;if(typeof a=="string"){let l=a.trim();if(n.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};n.add(l);}r.push(s.item);}return {items:r}}i(cg,"listToWire");function fl(e,t){let r=e,n={};for(let[a,l]of cl){let u=r[a];if(u!==void 0){if(u!==null){let d=lg[a](a,u);if(d!==null)return {error:d}}n[l]=u;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[a,l]of pl){let u=r[a];if(u===void 0)continue;let d=cg(a,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&pr(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(fl,"petHealthToWire");var ie=i(e=>typeof e=="string"?e:null,"str"),fr=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),pg=i(e=>typeof e=="boolean"?e:null,"bool");function ln(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(ln,"itemsFromWire");function il(e){let t=ie(e.name);return t===null||t.length===0?null:Object.freeze({ref:ie(e.ref),name:t,dose:ie(e.dose),frequency:ie(e.frequency),startDate:ie(e.start_date),endDate:ie(e.end_date),notes:ie(e.notes)})}i(il,"medicationFromWire");function ml(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:fr(sl,e.sex),spayedNeutered:pg(e.spayed_neutered),birthDate:ie(e.birth_date),birthDatePrecision:fr(al,e.birth_date_precision),activityLevel:fr(ll,e.activity_level),indoorOutdoor:fr(ul,e.indoor_outdoor),foodBrand:ie(e.food_brand),foodType:ie(e.food_type),microchipId:ie(e.microchip_id),allergies:ln(e.allergies,r=>{let n=ie(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:ie(r.ref),allergen:n,severity:fr(dl,r.severity),notes:ie(r.notes)})}),medications:ln(e.medications,il),supplements:ln(e.supplements,il),conditions:ln(e.conditions,r=>{let n=ie(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:ie(r.ref),conditionName:n,diagnosedDate:ie(r.diagnosed_date),notes:ie(r.notes)})})})}i(ml,"petHealthFromWire");var hl=100,bl=50,vl=100,El=50,Cl=500,fg=128,mg=6e4;function De(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(De,"invalid");function ht(e,t,r){if(typeof t!="string")return De(`${e} must be a string`);let n=gt(t);return n<=r?null:De(`${e} is ${n} characters; the server accepts at most ${r}`)}i(ht,"checkString");function dn(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:De(`${e} must be a finite number between 0 and ${r}`)}i(dn,"outOfRange");function yl(e,t){if(typeof e!="string")return De("pet_ref must be a string");if(e.trim().length===0)return De("pet_ref must not be blank");if(Ce(e))return De("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return De("profile must be an object");let r=[ht("pet_ref",e,fg)];return t?.name!==void 0&&r.push(ht("name",t.name,hl)),t?.species!==void 0&&r.push(ht("species",t.species,bl)),t?.breed!==void 0&&r.push(ht("breed",t.breed,vl)),t?.ageYears!==void 0&&r.push(dn("age_years",t.ageYears,El)),t?.weightKg!==void 0&&r.push(dn("weight_kg",t.weightKg,Cl)),r.find(n=>n!==null)??null}i(yl,"validate");function Rl(e,t){let r=fl(e,t);return "error"in r?{error:De(r.error)}:r}i(Rl,"healthToWire");function yg(e){if(typeof e!="object"||e===null)return {error:De("patch must be an object")};let t=e,r=[["name","name",s=>ht("name",s,hl)],["species","species",s=>ht("species",s,bl)],["breed","breed",s=>ht("breed",s,vl)],["ageYears","age_years",s=>dn("age_years",s,El)],["weightKg","weight_kg",s=>dn("weight_kg",s,Cl)]],n={};for(let[s,a,l]of r){let u=t[s];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}n[a]=u;}}let o=Rl(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:De("patch must change at least one field")}:{body:n})}i(yg,"patchToWire");function gg(e){if(e==null)return {body:{}};let t=Rl(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(gg,"toWire");var Ne=i(e=>typeof e=="string"?e:null,"str"),cn=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function gl(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Ne(r.pet_ref)??t,name:Ne(r.name),species:Ne(r.species),breed:Ne(r.breed),ageYears:cn(r.age_years),weightKg:cn(r.weight_kg)})}i(gl,"fromWire");function Sl(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ne(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Ne(t.pet_id),petRef:r,name:Ne(t.name),species:Ne(t.species),breed:Ne(t.breed),ageYears:cn(t.age_years),weightKg:cn(t.weight_kg),updatedAt:Ne(t.updated_at)})}i(Sl,"widgetPetFromWire");function hg(e){let t=Sl(e);return t===null?null:Object.freeze({...t,...ml(e)})}i(hg,"widgetPetProfileFromWire");function bg(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=Sl(r);return n===null?[]:[n]}))}i(bg,"petListFromWire");function lt(e){return vg(Ie({auth:e}),Ie({auth:e,unaryTimeoutMs:mg}))}i(lt,"createPetsRepository");function vg(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>yl(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?L(bg(s.value)):v(s.error)},async registerPet(o,s,a){let l=yl(o,s);if(l!==null)return v(l);let u=gg(s);if("error"in u)return v(u.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",a?.signal?{...c,signal:a.signal}:c);return p.ok?L(gl(p.value,o)):v(p.error)},async updatePet(o,s,a){let l=n(o);if(typeof l!="string")return v(l);let u=yg(s);if("error"in u)return v(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},a?.signal));return d.ok?L(gl(d.value,o)):v(d.error)},async getPetProfile(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${a}/profile`},s?.signal));if(!l.ok)return v(l.error);let u=hg(l.value);return u===null?v(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):L(u)},async deletePet(o,s){let a=n(o);if(typeof a!="string")return v(a);let l=await e.send("pets.deletePet",r({method:"DELETE",path:a},s?.signal));return l.ok?L(void 0):v(l.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?L(void 0):v(s.error)}}}i(vg,"createPetsRepositoryOver");var Go=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function Eg(e){return Go[e]}i(Eg,"requires");function Tl(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(Go))for(let a of Go[s])o.has(a)||(o.add(a),n.push(Object.freeze({resource:a,granted:false,disabled:r})));return Object.freeze(n)}i(Tl,"deniedDecisionsFor");function Pl(e,t,r){let n=Eg(e),o=new Map;for(let l of t)o.set(l.resource,l);if(r?.isPending===true&&n.some(l=>!o.has(l)))return Wo({name:e,enabled:false,isPending:true,limits:{}});let s=Cg(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?Wo({name:e,enabled:true,isPending:false,limits:s}):Wo({name:e,enabled:false,isPending:false,limits:s,disabled:Rg(n,o)})}i(Pl,"decideCapability");function Cg(e,t){let r={};for(let n of e){let o=t.get(n)?.limits;if(o)for(let[s,a]of Object.entries(o)){let l=r[s];r[s]=l===void 0?a:Math.min(l,a);}}return r}i(Cg,"mergeLimits");function Rg(e,t){for(let r of e){let n=t.get(r)?.disabled;if(n)return Object.freeze({reason:n.reason,level:n.level,recoverable:n.recoverable})}return Object.freeze({reason:Dt("accessDenied"),level:"user_entitlement",recoverable:false})}i(Rg,"disabledFor");function Wo(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(Wo,"freezeDecision");function Z(e){let t=X(e);return t===null?null:Tg(t)}i(Z,"parseColor");function X(e){if(typeof e=="number")return kl(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Ko(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Ko(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Sg(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=Ko(t);if(r!==null)return r}return /^\d+$/.test(t)?kl(Number.parseInt(t,10)):null}i(X,"toRgba");function Ko(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:qo(t[0]),g:qo(t[1]),b:qo(t[2]),a:1};if(t.length===6)return {r:bt(t,0),g:bt(t,2),b:bt(t,4),a:1};if(t.length===8){let r=bt(t,0);return {r:bt(t,2),g:bt(t,4),b:bt(t,6),a:r/255}}return null}i(Ko,"fromHex");function Sg(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(u=>u.trim());if(n.length<3)return null;let o=$o(Number(n[0])),s=$o(Number(n[1])),a=$o(Number(n[2]));if(o===null||s===null||a===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:s,b:a,a:l}}i(Sg,"fromRgbFunc");function kl(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(kl,"argbIntToRgba");function bt(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(bt,"byte");function qo(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(qo,"dup");function $o(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i($o,"clampByte");function Tg(e){if(e.a>=1)return qe(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Tg,"normalizeRgba");function qe(e,t,r){return `#${Yo(e)}${Yo(t)}${Yo(r)}`.toUpperCase()}i(qe,"rgbToHex");function Yo(e){return e.toString(16).padStart(2,"0")}i(Yo,"hex2");var Pg="#111111",zt="#FFFFFF",pn="#000000";function _l(e){let t=X(e);if(t===null)return zt;let r=vt(t),n=vt({r:17,g:17,b:17}),o=vt({r:255,g:255,b:255});return Zo(r,o)>=Zo(r,n)?zt:Pg}i(_l,"readableOn");function jt(e,t){let r=_l(e);return se(r,e)>=t?r:se(zt,e)>=se(pn,e)?zt:pn}i(jt,"legibleOn");function Re(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,se(r,o)),Number.POSITIVE_INFINITY),"worst");return t(zt)>=t(pn)?zt:pn}i(Re,"poleForGrounds");function vt(e){let t=Xo(e.r/255),r=Xo(e.g/255),n=Xo(e.b/255);return .2126*t+.7152*r+.0722*n}i(vt,"relativeLuminance");function Xo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(Xo,"linearize");function Zo(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(Zo,"luminanceContrast");function se(e,t){let r=X(e),n=X(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},s=r.a>=1?r:wl(r,o);return Zo(vt(s),vt(o))}i(se,"contrastRatio");function wl(e,t){let r=e.a,n=i((o,s)=>Math.round(o*r+s*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(wl,"composite");function Ue(e,t){let r=X(e),n=X(t);if(r===null||n===null)return null;let o=r.a>=1?r:wl(r,{...n});return qe(o.r,o.g,o.b)}i(Ue,"flattenOnto");function ut(e,t){let r=X(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return `rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}i(ut,"withAlpha");var xl=.05;function yr(e,t,r,n){let o=t[0];if(o===void 0)return r;let s=i(d=>t.every(c=>se(d,c)>=n),"reads");if(X(e)===null)return r;if(s(e))return e;let a=Ue(e,o),l=a===null?null:X(a),u=X(r);if(l===null||u===null)return r;for(let d=1;d<1/xl;d+=1){let c=d*xl,p=i((m,h)=>Math.round(m+(h-m)*c),"mix"),f=qe(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(s(f))return f}return r}i(yr,"pushToContrast");function Il(e,t,r){let n=e/255,o=t/255,s=r/255,a=Math.max(n,o,s),l=Math.min(n,o,s),u=(a+l)/2;if(a===l)return {h:0,s:0,l:u};let d=a-l,c=d/(1-Math.abs(2*u-1)),p;return a===n?(p=(o-s)/d*60,p<0&&(p=p+360)):a===o?p=((s-n)/d+2)*60:p=((n-o)/d+4)*60,{h:p,s:c,l:u}}i(Il,"rgbToHsl");function Jo(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,s=t/60,a=o*(1-Math.abs(s%2-1)),l=n-o/2,u=Math.floor(s)%6,d=[[o,a,0],[a,o,0],[0,o,a],[0,a,o],[a,0,o],[o,0,a]],[c,p,f]=d[u];return {r:Qo(c+l),g:Qo(p+l),b:Qo(f+l)}}i(Jo,"hslToRgb");function Qo(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(Qo,"channel");var $e=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link"]),kg=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),J=4.5,xg=Object.freeze({});function _g(e){return $e.includes(e)}i(_g,"isSlotName");function wg(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(wg,"parseRadius");function Al(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!_g(n)||o===null||typeof o!="object")continue;let s=Ig(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(Al,"parseThemeSlots");function fn(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(fn,"pick");function Ig(e){let t={},r=Z(fn(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=Z(fn(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=wg(fn(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=Z(fn(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Ig,"parseSlot");function mn(e,t){return t===null||Object.keys(t).length===0?e??xg:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(mn,"mergeThemeSlots");var gr=3;function Ag(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>Ue(e,r)??r)}i(Ag,"seatsOf");function Og(e,t){let r=Re(e);return e.every(n=>se(r,n)>=t)}i(Og,"someInkReads");function Fg(e,t){let r=t[0];return r===void 0?null:Ue(e,r)}i(Fg,"collapseUnsatisfiableFill");function Mg(e){let t=jt(e[0],J);return e.every(r=>se(t,r)>=J)?t:Re(e)}i(Mg,"inkFor");function Ol(e,t){let r=false,n={};for(let o of $e){let s=e[o];if(s===void 0)continue;let a=s.backgroundColor,l=t?.[o]??[],u=Ag(a,l),d={...s},c=false;if(a!==void 0&&u.length>1&&!Og(u,J)){let p=Fg(a,l);p!==null&&(d.backgroundColor=p,u=[p],c=true);}if(u.length>0){let p=s.textColor;if(a!==void 0)(p===void 0||u.some(f=>se(p,f)<J))&&(d.textColor=Mg(u),c=true);else if(p!==void 0){let f=yr(p,u,Re(u),J);f!==p&&(d.textColor=f,c=true);}if(s.borderColor!==void 0){let f=yr(s.borderColor,u,Re(u),gr);f!==s.borderColor&&(d.borderColor=f,c=true);}}n[o]=c?Object.freeze(d):s,r=r||c;}return r?Object.freeze(n):e}i(Ol,"guardSlotContrast");function Ye(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))Ye(e[t]);}return e}i(Ye,"deepFreeze");var gn=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Ml={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Ll={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Fl={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},Lg={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Ng={regular:"400",medium:"500",bold:"700"},Dg={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},ei=0,Et="System",Ve="monospace",Ug=["content","heading","control","compact","badge"];function Vg(e){let t={};for(let r of Ug)t[r]=e;return t}i(Vg,"authoredTierSizes");function Nl(){return {family:Et,mono:Ve,fontUrl:null,families:{regular:Et,medium:Et,bold:Et,mono:Ve,monoMedium:Ve,monoBold:Ve},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Fl,tierSizes:Vg(Fl),lineHeight:Lg,weight:Ng,letterSpacing:Dg,scale:1,maxScale:ei,scaleCaps:gn}}i(Nl,"baseType");var Dl={},Ct=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function yn(e){return `cubic-bezier(${e.join(", ")})`}i(yn,"cssCubicBezier");var Ul={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:yn(Ct.standard),emphasized:yn(Ct.emphasized),exit:yn(Ct.exit)},reducedMotion:false},Bg={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},Be=Ye({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Bg,space:Ml,radius:Ll,type:Nl(),motion:Ul,slots:Dl}),Hg={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},Rt=Ye({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Hg,space:Ml,radius:Ll,type:Nl(),motion:Ul,slots:Dl});function St(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(St,"textGrounds");function Vl(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(Vl,"controlGrounds");function ti(e){return [e.chatGround,e.surface,e.surfaceCream]}i(ti,"linkGrounds");function Bl(e,t){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...Hl(e,t)]}i(Bl,"statusGrounds");function Hl(e,t){return [Ue(t,e.surface)??e.surface,Ue(t,e.surfaceCream)??e.surfaceCream]}i(Hl,"washGrounds");function zg(e){return [e.composerFill,e.chatGround]}i(zg,"composerGrounds");var jg=new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function Wg(e,t){let r=new Set(St(t));return St(e).every(n=>r.has(n))}i(Wg,"onCompiledGrounds");function zl(e){let t=e.color,r=(e.brightness==="dark"?Rt:Be).color,n=(e.brightness==="dark"?Be:Rt).color,o=St(t),s=Re(o)!==Re(St(r)),a=Wg(t,r),l=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,u=i((T,b,S,P,k,x)=>{let y=b===S&&(T!=="errorRed"||l);return y&&a&&jg.has(T)?b:yr(y&&s?P:b,k,Re(k),x)},"ink"),d=i((T,b,S)=>u(`text.${T}`,t.text[T],r.text[T],n.text[T],b,S),"text"),c=i((T,b,S,P)=>u(T,b,r[T],n[T],S,P),"token"),p=i(T=>s&&t[T]===r[T]?n[T]:t[T],"tint"),f=t.primary,m=jt(f,J),h=c("danger",t.danger,[...o,...Hl(t,t.badgeBgCritical)],J);return {...t,onPrimary:m,onAccent:jt(t.accent,J),onDanger:se(m,h)>=J?m:jt(h,J),brandSoft:p("brandSoft"),brandSofter:p("brandSofter"),brandBorder:p("brandBorder"),borderHairlineGreen:p("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,o,J),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,ti(t),J),text:{...t.text,primary:d("primary",o,J),secondary:d("secondary",o,J),muted:d("muted",o,J),metaCool:d("metaCool",o,J),timestamp:d("timestamp",o,J),placeholder:d("placeholder",Vl(t),gr)},danger:h,errorRed:c("errorRed",t.errorRed,Bl(t,t.badgeBgCritical),J),warningStrong:c("warningStrong",t.warningStrong,Bl(t,t.badgeBgCaution),J),composerBorder:c("composerBorder",t.composerBorder,zg(t),gr),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,Vl(t),gr)}}i(zl,"guardInks");var Gg="#23272C",jl=4.5,Kg=.6,ri=.9,qg=.02,$g="#FFFFFF",Yg="#111111";function Xg(e){return se(e,Gg)>=jl&&Math.max(se(e,$g),se(e,Yg))>=jl}i(Xg,"readsOnDark");function ql(e){let t=X(e);if(t===null)return null;let{h:r,s:n,l:o}=Il(t.r,t.g,t.b),s=Math.min(Math.max(o,Kg),ri);for(let l=0;;l+=1){let u=s+l*qg;if(u>ri)break;let d=Jo({h:r,s:n,l:u}),c=qe(d.r,d.g,d.b);if(Xg(c))return c}let a=Jo({h:r,s:n,l:ri});return qe(a.r,a.g,a.b)}i(ql,"deriveDarkVariant");var Qg=7,Wl=.05,Zg="#000000",Gl="#FFFFFF";function Jg(e,t,r,n){let o=Ue(e,t);if(o===null)return r;if(se(o,t)>=n)return o;let s=X(o),a=X(r);if(s===null||a===null)return r;for(let l=1;l<1/Wl;l+=1){let u=l*Wl,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=qe(d(s.r,a.r),d(s.g,a.g),d(s.b,a.b));if(se(c,t)>=n)return c}return r}i(Jg,"pushContrast");function eh(e,t){let r=St(e),n=r[0],o=Kl(n);for(let s of r){let a=Kl(s);(t?a>o:a<o)&&(n=s,o=a);}return n}i(eh,"hardestGround");function Kl(e){let t=X(e);return t===null?0:vt(t)}i(Kl,"luminanceOf");function dt(e,t){return Ue(e,t)??Z(e)??t}i(dt,"solid");function $l(e){let t=e.color,r=Re(St(t))===Gl,n=r?Gl:Zg,o=eh(t,r),s=i(l=>Jg(l,o,n,Qg),"text"),a={...t,brandSoft:dt(t.brandSoft,t.surface),brandSofter:dt(t.brandSofter,t.surface),brandBorder:s(t.brandBorder),borderHairlineGreen:s(t.borderHairlineGreen),brandBorderStrong:s(t.brandBorderStrong),brandInk:s(t.brandInk),linkInk:s(t.linkInk),borderRingCream:s(t.borderRingCream),composerBorder:s(t.composerBorder),text:{primary:s(t.text.primary),secondary:s(t.text.secondary),muted:s(t.text.muted),placeholder:s(t.text.placeholder),onBrand:t.text.onBrand,metaCool:s(t.text.metaCool),timestamp:s(t.text.timestamp)},badgeBgPositive:dt(t.badgeBgPositive,t.surface),badgeBgCaution:dt(t.badgeBgCaution,t.surface),badgeBgCritical:dt(t.badgeBgCritical,t.surface),badgeBgNeutral:dt(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:dt(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:dt(t.checkupCardConcernBg,t.surface)};return Ye({...e,highContrast:true,color:a})}i($l,"deriveHighContrast");var oi=Object.freeze({cream:.03,subtle:.07,ring:.16}),th=oi.cream,rh=oi.subtle,nh=oi.ring,oh=10;function ni(e,t,r){let n=X(e),o=X(t);if(n===null||o===null)return null;let s=i((a,l)=>Math.round(a+(l-a)*r),"at");return qe(s(n.r,o.r),s(n.g,o.g),s(n.b,o.b))}i(ni,"mix");function Yl(e){if(e===null)return {};let t=Re([e]),r=ni(e,t,th),n=ni(e,t,rh),o=ni(e,t,nh);return r===null||n===null||o===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:o}}i(Yl,"surfaceFamily");function Xl(e){if(e===null)return {};let t=X(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}i(Xl,"dangerFamily");function Ql(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let o={};for(let[s,a]of Object.entries(r.type.size))o[s]=Math.max(oh,Math.round(a*n*10)/10);return o}i(Ql,"typeSizesFor");function Zl(e,t,r){if(e===null)return t;let n=e/r.space.xs,o=i(a=>Math.round(a*n),"s"),s=r.space;return {xs:o(s.xs),sm:o(s.sm),md:o(s.md),lg:o(s.lg),xl:o(s.xl),xxl:o(s.xxl)}}i(Zl,"spaceFor");function Jl(e,t){let r=e/t.radius.md,n=i(s=>Math.round(s*r),"s"),o=t.radius;return {tile:n(o.tile),xs:n(o.xs),sm:n(o.sm),md:n(o.md),lg:n(o.lg),xl:n(o.xl),pill:o.pill}}i(Jl,"radiiFor");var eu=Object.freeze(["everfur","minimal","night"]),tu=Object.freeze({everfur:Object.freeze({}),minimal:Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:Object.freeze({colorScheme:"dark"})}),br=Object.freeze({fontSizeBase:Object.freeze({min:12,max:20,default:14}),borderRadius:Object.freeze({min:0,max:32,default:14}),spacingUnit:Object.freeze({min:3,max:6,default:4})});function hn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(hn,"isRecord");function ih(e){return typeof e=="string"&&eu.includes(e.trim().toLowerCase())}i(ih,"isPreset");function hr(e,t){let r=e[t];return r??void 0}i(hr,"present");var sh=16;function ah(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>sh)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}i(ah,"parsePx");var lh=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],uh=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function ii(e){if(!hn(e))return null;let t=ih(e.theme)?tu[e.theme.trim().toLowerCase()]:{},r=hn(e.variables)?e.variables:{},n={...t};for(let[p,f]of Object.entries(r))f!=null&&(n[p]=f);let o={},s=hr(n,"colorScheme"),a=typeof s=="string"?s.trim().toLowerCase():null;(a==="light"||a==="dark"||a==="auto")&&(o.color_scheme=a);let l=a==="dark"?"_dark":"";for(let[p,f]of lh){let m=hr(n,p);m!==void 0&&(o[`${f}${l}`]=m);}let u=hr(n,"colorDanger");u!==void 0&&(o[`danger_color${l}`]=u);let d=hr(n,"fontFamily");typeof d=="string"&&d.trim().length>0&&(o.font_family=d.trim());for(let[p,f]of uh){let m=ah(hr(n,p));m!==void 0&&(o[f]=m);}let c=e.rules;if(hn(c)){let p={};for(let f of $e){let m=c[f];hn(m)&&(p[f]=m);}Object.keys(p).length>0&&(o.slots=p);}return Object.keys(o).length===0?null:Object.freeze(o)}i(ii,"expandAppearance");var iu=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit"]),vr="slots.",su=Object.freeze([1,2]);function vn(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(vn,"isEmptyBranding");function au(e){let t=e?.schemaVersion??null;return t===null||su.includes(t)}i(au,"isKnownBrandingSchema");function lu(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(lu,"lockedFieldsOf");function dh(e){return e==="hide_powered_by"||iu.includes(e)?true:e.startsWith(vr)&&$e.includes(e.slice(vr.length))}i(dh,"isThemeLockName");function Xe(e){if(e===null||typeof e!="object")return null;let t=e,r=ru(t),n=ii(j(t,"appearance")),o=n===null?r:ch(ru(n),r);return vn(o)?null:Object.freeze(o)}i(Xe,"parseClientBranding");function ch(e,t){let r={...e};for(let[o,s]of Object.entries(t))s!=null&&(r[o]=s);let n=mn(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}i(ch,"overlayFlat");function ru(e){return {displayName:Tt(j(e,"display_name","displayName")),logoUrl:Tt(j(e,"logo_url","logoUrl")),primaryColor:Z(j(e,"primary_color","primaryColor")),accentColor:Z(j(e,"accent_color","accentColor")),brightness:yh(j(e,"brightness","color_scheme","colorScheme")),fontFamily:Tt(j(e,"font_family","fontFamily")),fontUrl:Tt(j(e,"font_url","fontUrl")),fonts:nu(j(e,"fonts")),fontUrls:nu(j(e,"font_urls","fontUrls")),placeholder:Tt(j(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:ph(j(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:Z(j(e,"primary_color_dark","primaryColorDark")),accentColorDark:Z(j(e,"accent_color_dark","accentColorDark")),surfaceStyle:ou(j(e,"surface_style","surfaceStyle"),fh),radiusScale:ou(j(e,"radius_scale","radiusScale"),mh),logoUrlDark:Tt(j(e,"logo_url_dark","logoUrlDark")),slots:Al(j(e,"slots")),accessibilityMaxFontScale:hh(j(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:vh(j(e,"locked_fields","lockedFields")),schemaVersion:bh(j(e,"schema_version","schemaVersion")),backgroundColor:Z(j(e,"background_color","backgroundColor")),backgroundColorDark:Z(j(e,"background_color_dark","backgroundColorDark")),textColor:Z(j(e,"text_color","textColor")),textColorDark:Z(j(e,"text_color_dark","textColorDark")),dangerColor:Z(j(e,"danger_color","dangerColor")),dangerColorDark:Z(j(e,"danger_color_dark","dangerColorDark")),fontSizeBase:si(j(e,"font_size_base","fontSizeBase"),br.fontSizeBase),borderRadius:si(j(e,"border_radius","borderRadius"),br.borderRadius),spacingUnit:si(j(e,"spacing_unit","spacingUnit"),br.spacingUnit)}}i(ru,"parseFlat");function si(e,t){let r=bn(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}i(si,"parseClamped");function ph(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(ph,"parseBool");function j(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(j,"pick");function Tt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Tt,"parseNonEmptyString");var Er=["regular","medium","bold","mono","monoMedium","monoBold"];function nu(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of Er){let o=Tt(j(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(nu,"parseFaceMap");var fh=["white","cream","subtle"],mh=["sharp","default","round"];function ou(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(ou,"parseEnum");function yh(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(yh,"parseBrightness");function bn(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(bn,"parseNumber");var gh=1,uu=3.1;function hh(e){let t=bn(e);return t===null?null:t<=0?0:Math.min(uu,Math.max(gh,t))}i(hh,"parseMaxFontScale");function bh(e){if(e==null)return null;let t=bn(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(bh,"parseSchemaVersion");function ai(e){let t=e.trim();return t.startsWith(vr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(ai,"toWireName");function vh(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=ai(r);dh(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(vh,"parseLockedFields");function li(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(li,"hardenHttpsUrl");function du(e,t){if(t===null||vn(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Rt:Be:e,n=r.brightness==="dark"?Rt:Be,o=r.brightness==="dark",s=o?t.primaryColorDark??ui(t.primaryColor):t.primaryColor,a=o?t.accentColorDark??ui(t.accentColor):t.accentColor,l=s??r.color.primary,u=a??r.color.accent,d=s!==null&&Th(t,l,n,o),c=d?n.color.primary:l,p=s!==null&&!d?X(c):null,f=i(k=>Math.round(k+(255-k)*.4),"lift"),m=p!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:d?Ph(n,r.color.text):{},h=(o?t.backgroundColorDark:t.backgroundColor)??null,T=Yl(h),b={...r.color,...T},S=(o?t.textColorDark:t.textColor)??null,P={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...m,...T,...Xl((o?t.dangerColorDark??ui(t.dangerColor??null):t.dangerColor)??null),...S!==null?{text:{...m.text??r.color.text,primary:S}}:{},...Sh(t.surfaceStyle??null,b),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:Zl(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Jl(t.borderRadius,n):xh(t.radiusScale??null,r.radius,n),type:{...r.type,...Rh(r.type,t),size:Ql(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:mn(r.slots,t.slots??null)};return Ye(P)}i(du,"withServerBranding");var Eh={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Ch=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function di(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(di,"isMonoFace");function Rh(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},s={...e.namedFaces},a={...e.fontUrls};for(let l of Er){let u=Eh[l].map(p=>r[p]).find(p=>p!==void 0),d=di(l)?null:t.fontFamily;u!==void 0?(o[l]=u,s[l]=true):d!==null&&(o[l]=d,s[l]=false);let c=n[l]??(l==="regular"?t.fontUrl:null)??null;c!==null?a[l]=c:u!==void 0&&delete a[l];}for(let l of Ch)for(let u of l)s[u]&&l.some(d=>d!==u&&o[d]===o[u])&&(s[u]=false);return {family:o.regular,mono:o.mono,fontUrl:a.regular??null,families:o,namedFaces:s,fontUrls:a}}i(Rh,"mergeFaces");function ui(e){return e===null?null:ql(e)}i(ui,"darkVariantOf");function Sh(e,t){if(e===null)return {};let r=t;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(Sh,"surfaceOf");function cu(e,t){return e==null?false:Z(e)===Z(t)}i(cu,"sameColor");function Th(e,t,r,n){return cu(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&cu(e.primaryColor,Be.color.primary)}i(Th,"isCompiledPrimary");function Ph(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(Ph,"compiledBrandFamily");var kh={sharp:.5,default:1,round:1.5};function xh(e,t,r){if(e===null)return t;let n=kh[e],o=r.radius,s=i(a=>Math.round(a*n),"s");return {tile:s(o.tile),xs:s(o.xs),sm:s(o.sm),md:s(o.md),lg:s(o.lg),xl:s(o.xl),pill:o.pill}}i(xh,"radiusOf");var _h="Everfur",wh=.5;function ci(e){let t=e?.branding??null,r=au(t)?t:null,n=Mh(e?.clientOverride??null,lu(r)),o=e?.colorScheme==="dark"?"dark":"light",s=n?.brightness??r?.brightness??"light",u=du((s==="auto"?o:s)==="dark"?Rt:Be,pu(r)),d=du(u,pu(n));return jh(d,e)}i(ci,"resolveTheme");function Ih(e,t,r){return ci({...r,branding:Xe(t),clientOverride:Xe(e)})}i(Ih,"previewTheme");function Ah(e){return e==="placeholder"?"chat_placeholder":ai(e)}i(Ah,"wireNameOf");var Oh={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function Fh(e,t){return t.has(Ah(e))?true:(Oh[e]??[]).some(r=>t.has(r))}i(Fh,"isLocked");function Mh(e,t){if(e===null)return null;let r=false,n={...e};for(let a of Object.keys(e))(e[a]??null)!==null&&(Fh(a,t)||a==="lockedFields")&&(n[a]=null,r=true);let o=n.slots??null;if(o!==null){let a={},l=false;for(let u of $e){let d=o[u];d!==void 0&&(t.has(`${vr}${u}`)?l=true:a[u]=d);}l&&(n.slots=Object.keys(a).length===0?null:Object.freeze(a),r=true);}if(!r)return e;let s=Object.freeze(n);return vn(s)?null:s}i(Mh,"withoutFields");function pu(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(pu,"withoutBrightness");function Lh(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(Lh,"scaledSizes");function Nh(e){return e===void 0||!Number.isFinite(e)?1:Math.max(wh,e)}i(Nh,"effectiveScale");var fu=["content","heading","control","compact","badge"];function Dh(e){if(!(e>0))return gn;let t={};for(let r of fu){let n=gn[r];t[r]=n===0?0:Math.min(n,e);}return t}i(Dh,"tierCaps");function Uh(e,t){return t>0?Math.min(e,t):e}i(Uh,"capped");function Vh(e,t,r,n){let o={};for(let s of fu)o[s]=n?Lh(e,Uh(t,r[s])):e;return o}i(Vh,"sizesByTier");function Bh(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:ti(e)}}i(Bh,"slotGrounds");function Hh(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Hh,"registration");function zh(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},s={...e.namedFaces};for(let a of Er)!(o[a]===Et||o[a]===Ve)&&r!==void 0&&Hh(r,o[a])===false&&(o[a]=di(a)?Ve:Et,s[a]=false),n!==null&&di(a)&&o[a]===Ve&&(o[a]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:s}}i(zh,"platformFaces");function jh(e,t){let r=e.meta.displayName.trim().length===0?_h:e.meta.displayName,n=li(e.meta.logoUrl),o={};for(let h of Er){let T=e.type.fontUrls[h];T!==void 0&&(o[h]=li(T));}let s=o.regular??null,l=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,u=Number.isFinite(e.type.maxScale)?e.type.maxScale:ei,d=Nh(t?.textScale),c=Dh(u),p=Vh(e.type.size,d,c,t?.scaleTypeSizes===true),f=zl(e),m={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:f,space:e.space,radius:e.radius,type:{...e.type,...zh(e.type,t),fontUrl:s,fontUrls:o,size:p.content,tierSizes:p,scale:d,maxScale:u,scaleCaps:c},motion:l,slots:Ol(e.slots,Bh(f))};return t?.highContrast===true?$l(Ye(m)):Ye(m)}i(jh,"finalize");var mu="/widget/v1/entitlements",Wh=304,Gh=Object.freeze({kind:"notModified"});async function gu(e,t={},r=Ie({auth:e})){let n=await r.send("entitlements.fetch",qh(t));return n.ok?$h(n.value):n.error.httpStatus===Wh?Gh:{kind:"failed",error:n.error}}i(gu,"fetchEntitlements");var Kh=64;function qh(e){let t={};return pi(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Kh?{method:"GET",path:mu,headers:t,query:{region:e.region}}:{method:"GET",path:mu,headers:t}}i(qh,"buildRequest");function $h(e){if(e===null||typeof e!="object"||!pi(e.revision))return yu();let t=typeof e.region=="string"?e.region:"",r=pi(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Xh(e.capabilities),branding:Yh(e),livemode:e.livemode!==false})}i($h,"parseUpdated");function Yh(e){let t=Xe(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=Xe(r.branding);return n!==null?n:Xe(r)}return null}i(Yh,"parseBranding");function Xh(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Qh(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Xh,"mapCapabilities");function Qh(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Qh,"isEnabled");function yu(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(yu,"malformed");function pi(e){return typeof e=="number"&&Number.isFinite(e)}i(pi,"isFiniteNumber");var Zh=30;function hu(e){let t=e.scheduler??Jh,r=e.resolve??gu,n=Math.max(1,e.floorSeconds??Zh),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),a=false,l=false,u=null,d=null,c=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),m=i(S=>{l||!a||(c=Math.max(n,S),u=t.set(()=>{u=null,b();},c*1e3));},"schedule"),h=null,T=i(async()=>{if(l)return null;let S=p;e.onFetch?.();let P=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},k;try{k=await r(e.authFor(),P);}catch(x){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:eb(x)}),!l&&S===p&&(e.onSettled?.(),m(s())),null}if(l||S!==p)return null;switch(k.kind){case "updated":d=k.revision,e.update(k.decisions,k.branding??null,k.livemode!==false),m(k.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:k.error.code}),m(s());break;default:m(s());}return e.onSettled?.(),k},"tick"),b=i(()=>{let S=T().finally(()=>{h===S&&(h=null);});return h=S,S},"run");return {start(){a||l||(a=true,b());},prime(){return l?Promise.resolve(null):h??b()},stop(){l||(l=true,p++,f());},refresh(){l||!a||(p++,d=null,f(),b());}}}i(hu,"createEntitlementPoller");var Jh={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function eb(e){return e instanceof Error?e.message:"poll failed"}i(eb,"describe");var bu="everfur.notifications.device";var tb=3e3,vu=Object.freeze([bu]);function Eu(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),a=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),l=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:a.length});}catch{}},"report"),u=Promise.allSettled(a).then(d=>{let c=d.filter(p=>p.status==="rejected").length;c>0&&l("failed",c);});return new Promise(d=>{let c=false,p=i(()=>{c||(c=true,clearTimeout(f),d());},"finish"),f=setTimeout(()=>{c||l("timeout",a.length),p();},tb);u.then(p,p);})}i(Eu,"startBeforeLogoutHooks");function Cu(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let a={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:a,userRef:t.userRef,sessionId:o}}i(Cu,"graceAuth");async function Ru(e,t){if(vu.length===0)return;let r=await Promise.allSettled(vu.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Ru,"sweepPerUserKv");function rb(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(rb,"compiledDefaultDecisions");function fi(e=rb){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null,...o.livemode===false?{livemode:false}:{}}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(fi,"createEntitlementStore");function mi(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(mi,"notConfiguredError");function Su(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 oa(r,t===void 0?void 0:{platform:t})}i(Su,"tryResolveClient");function Tu(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Tu,"guardTelemetry");var nb=Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${Jr} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Pu(e,t,r=ho){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
|
|
12
|
-
[everfur] Every Everfur capability will render its off-state until this is fixed. `+nb[r]);}i(Pu,"reportConfigFailure");function yi(e){return Object.freeze({request(){return Promise.resolve(v(mi(e)))},stream(t,r){let n=ye({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(yi,"refusingTransport");function ku(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(ku,"createInMemoryKv");var xu=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function Iu(e,t){return new hi(e,t)}i(Iu,"createEverfurRuntime");var ob=6e4,bi=class bi{constructor(t,r){this.sessionId=yo();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new re("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Tu(n.telemetry):Qr;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=bo(n?.publishableKey),a=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)l=yi(s);else if(n.transport!==void 0)l=n.transport;else {let c=Su(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=da({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,l=yi(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=l,s!==null&&Pu(s,this.telemetry,r?.platform),this.errorPolicy=n.errorPolicy,this.camera=n.camera??Ws,this.upload=n.upload??_a,this.uploadTransport=n.uploadTransport??Uo,this.imageCache=n.imageCache??xu,this.kv=n.storage??ku(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?fi():fi(()=>Tl("sdk_config",Dt("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",gi(c),()=>this.buildChatController(c),_u),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${gi(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,f,m)=>this.acquireInternal(c,p,f,m),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!a);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Zs(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-ob,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return hu({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n,o)=>this.updateEntitlements({decisions:r,isPending:false,branding:n,...o===false?{livemode:o}:{}}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let a=`${this.epoch}|${t}|${r}`,l=this.entries.get(a);if(l)return s||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(a,{controller:u,refCount:1,warm:s}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=qa({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Xa(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=yo(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Ru(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Eu({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Cu({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?v(wu(t)):r(lt(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(a=>(s.result=a,a))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?wu("prepare"):n===null?null:mi(n),s=this.identity,[a,l,u]=await Promise.all([o?v(o):s===null?L(void 0):s.currentToken().then(()=>L(void 0),()=>v(D("authRejected",{retryable:false}))),o?v(o):this.primeEntitlements(),t===null?void 0:o?v(o):this.primeChat(t)]),d=a.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:a,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?v(t.error):L(void 0):v(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",gi(r),()=>this.buildChatController(r),_u,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?v(o.cause):L(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(bi,"EverfurRuntimeImpl");var hi=bi;function gi(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(gi,"chatScopeKey");function _u(e){e.dispose();}i(_u,"disposeChat");function wu(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(wu,"disposedError");var Au=Symbol.for("@everfur/sdk#EverfurContext@v1"),Ou=globalThis,En=Ou[Au]??(Ou[Au]=react.createContext(null));En.displayName??="EverfurContext";function ee(){let e=react.useContext(En);if(e===null)throw new re("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ee,"useEverfurContext");function Fu(){return ee().handle}i(Fu,"useEverfur");var Mu=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Lu=globalThis,Cr=Lu[Mu]??(Lu[Mu]=react.createContext(Be));Cr.displayName??="EverfurThemeContext";function N(){return react.useContext(Cr)}i(N,"useEverfurTheme");function Cn(e){let{runtime:t}=ee(),r=t.entitlements,n=react.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),s=e.seams.useReducedMotion(),a=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,d=e.seams.platformMonoFamily?.(),c=e.seams.isFontRegistered,p=e.clientTheme?cb(e.clientTheme):"",f=react.useMemo(()=>e.clientTheme?Xe(e.clientTheme):null,[p]),m=n.branding??null,h=react.useMemo(()=>ci({branding:m,clientOverride:f,colorScheme:o,reducedMotion:s,textScale:a,scaleTypeSizes:u,highContrast:l,...d===void 0?{}:{platformMonoFamily:d},...c===void 0?{}:{isFontRegistered:c}}),[m,f,o,s,a,u,l,d,c]);return e.seams.useResolvedTheme?.(h),react.createElement(Cr.Provider,{value:h},e.children)}i(Cn,"EverfurThemeProviderCore");function cb(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(cb,"stableKey");function Bu(e){let{config:t,user:r,activePet:n,theme:o,warmUp:s,children:a,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,d=react.useRef(null),c=react.useRef(null),[p,f]=react.useReducer(w=>w+1,0),m=react.useRef(null),h=react.useRef(void 0),T=r?.userRef??null;h.current!==T&&(h.current!==void 0&&(m.current=null),h.current=T);let b=m.current!==null?m.current.user:r??null,S=react.useRef(null),P=react.useRef(void 0),k=n??null;P.current!==k&&(P.current!==void 0&&(S.current=null),P.current=k);let x=S.current!==null?S.current.pet:n??null;(d.current===null||d.current.key!==u||d.current.runtime.isDisposed)&&(d.current!==null&&!d.current.runtime.isDisposed&&(c.current=d.current.runtime),d.current={key:u,runtime:Iu({config:l.withDefaults?l.withDefaults(t):t,user:b,activePet:x,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let y=d.current.runtime,_=react.useRef(null);react.useEffect(()=>{let w=d.current?.runtime;w===void 0||!w.isDisposed||_.current!==w&&(_.current=w,f());}),react.useEffect(()=>{let w=c.current;w!==null&&(c.current=null,w.dispose());});let A=b?.userRef??null;react.useLayoutEffect(()=>{y.setUser(b);},[y,A]),react.useLayoutEffect(()=>{y.setActivePet(x);},[y,x]),react.useEffect(()=>()=>y.dispose(),[y]),react.useEffect(()=>{s==="onMount"&&y.prepare(x===null?{}:{petRef:x});},[y,s,A,x]);let O=react.useMemo(()=>({setUser:i(w=>{m.current={user:w},y.setUser(w),f();},"setUser"),setActivePet:i(w=>{S.current={pet:w},y.setActivePet(w),f();},"setActivePet"),open:i(w=>y.open(w),"open"),prepare:i(w=>y.prepare(w),"prepare"),registerPet:i((w,I)=>y.registerPet(w,I),"registerPet"),updatePet:i((w,I)=>y.updatePet(w,I),"updatePet"),deletePet:i(w=>y.deletePet(w),"deletePet"),eraseUserData:i(()=>y.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let w=y.logout();return f(),w},"logout")}),[y,f]),F=react.useMemo(()=>({runtime:y,handle:O,userRef:A,activePet:x,scopeEpoch:y.scopeEpoch}),[y,O,A,x,p]),C=react.createElement(Cn,{clientTheme:o??null,seams:l.theme,children:a});return react.createElement(En.Provider,{value:F},l.wrap?l.wrap(C):C)}i(Bu,"EverfurProviderCore");var mb=2;function yb(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<mb)return null;let n;try{n=r.getResponseHeader(t);}catch{return null}return typeof n=="string"&&n.length>0?n:null}i(yb,"readEventSourceResponseHeader");function Hu(){let e=fb__default.default;return (t,r)=>{let n=new e(t,{method:r.method,headers:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return Object.assign(n,{getResponseHeader:i(o=>yb(n,o),"getResponseHeader")})}}i(Hu,"createRnEventSourceFactory");function vb(){let e=reactNative.useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}i(vb,"useRnColorScheme");function Eb(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Eb,"isThenable");function Cb(){let[e,t]=react.useState(false);return react.useEffect(()=>{let r=true,n=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof n=="function"){let s=n.call(reactNative.AccessibilityInfo);s!=null&&typeof s.then=="function"&&s.then(a=>{r&&t(a===true);},()=>{});}let o=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",s=>t(s===true));return ()=>{r=false,o?.remove?.();}},[]),e}i(Cb,"useRnReducedMotion");function Wu(){let e=reactNative.PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(reactNative.PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}i(Wu,"readFontScale");function Rb(e){let t=reactNative.Dimensions?.addEventListener;if(typeof t!="function")return ()=>{};let r=t.call(reactNative.Dimensions,"change",e);return ()=>r?.remove?.()}i(Rb,"subscribeFontScale");function Sb(){return react.useSyncExternalStore(Rb,Wu,Wu)}i(Sb,"useRnTextScale");function $u(){try{let e=reactNative.Platform?.OS;return typeof e=="string"?e:null}catch{return null}}i($u,"platformOS");function Tb(){return $u()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}i(Tb,"contrastSignal");function Pb(){let[e,t]=react.useState(false);return react.useEffect(()=>{let r=true,{query:n,event:o}=Tb(),a=reactNative.AccessibilityInfo?.[n];if(typeof a!="function")return ()=>{};try{let d=a.call(reactNative.AccessibilityInfo);Eb(d)&&Promise.resolve(d).then(c=>{r&&t(c===!0);},()=>{});}catch{}let l=reactNative.AccessibilityInfo?.addEventListener,u=typeof l=="function"?l.call(reactNative.AccessibilityInfo,o,d=>t(d===true)):void 0;return ()=>{r=false,u?.remove?.();}},[]),e}i(Pb,"useRnHighContrast");function kb(){return $u()==="ios"?"Menlo":Ve}i(kb,"rnPlatformMonoFamily");function xb(){return globalThis.__DEV__!==false}i(xb,"isDevelopment");var Gu=new Set;function _b(e){if(!xb()||Gu.has(e))return;Gu.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`);}catch{}}i(_b,"warnUnregisteredFace");function wb(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t);}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let o=n.includes(e);return o||_b(e),o}i(wb,"rnIsFontRegistered");var Sn=Object.freeze({useColorScheme:vb,useReducedMotion:Cb,useTextScale:Sb,useHighContrast:Pb,scaleTypeSizes:false,platformMonoFamily:kb,isFontRegistered:wb});function Ab(e){return react.createElement(reactNativeSafeAreaContext.SafeAreaProvider,null,e)}i(Ab,"wrapInSafeArea");var Ob=Object.freeze({platform:"react-native",eventSourceFactory:Hu(),wrap:Ab,theme:Sn});function Fb(e){return react.createElement(Bu,{...e,seams:Ob})}i(Fb,"EverfurProvider");function Wt(e){let{runtime:t}=ee(),r=t.entitlements,n=react.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return react.useMemo(()=>Pl(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Wt,"useCapability");function Vb(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Vb,"tierMultiplier");function E({tier:e="content",...t}){let{type:r}=N(),n=Vb(r,e);return react.createElement(reactNative.Text,n===void 0?t:{maxFontSizeMultiplier:n,...t})}i(E,"Text");var Gt=react.forwardRef(i(function(t,r){return react.createElement(reactNative.TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Bb=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function R(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Bb[t]]}}i(R,"face");var Ei=class Ei extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,n){return Object.is(r.resetKey,n.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(Ei,"HostRenderBoundary");var vi=Ei;function zb({render:e}){return e()}i(zb,"RenderHost");function xt({render:e,fallback:t,resetKey:r}){return react.createElement(vi,{fallback:t,resetKey:r,children:react.createElement(zb,{render:e})})}i(xt,"HostRender");var jb=48;function Wb(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Wb,"selectView");function Si(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:s}=e,a=Wt(t),l=react.useMemo(()=>Wb(a),[a]);switch(l){case "enabled":return r;case "pending":return o?jsxRuntime.jsx(xt,{render:o,fallback:jsxRuntime.jsx(Ju,{capability:t,style:s})}):jsxRuntime.jsx(Ju,{capability:t,style:s});case "disabled":return n?jsxRuntime.jsx(xt,{render:()=>n(a),fallback:jsxRuntime.jsx(ed,{decision:a,style:s}),resetKey:a}):jsxRuntime.jsx(ed,{decision:a,style:s});default:return at(l)}}i(Si,"CapabilityGate");function Ju({capability:e,style:t}){let r=N(),n=react.useMemo(()=>td(r),[r]);return jsxRuntime.jsx(reactNative.View,{style:[n.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsxRuntime.jsx(reactNative.View,{style:n.skeletonBar})})}i(Ju,"PendingSkeleton");function ed({decision:e,style:t}){let r=N(),n=react.useMemo(()=>td(r),[r]),o=e.disabled?.reason??"";return jsxRuntime.jsx(reactNative.View,{style:[n.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:o,children:o.length>0?jsxRuntime.jsx(E,{style:n.offstateText,children:o}):null})}i(ed,"OffState");function td(e){let{color:t,space:r,radius:n,type:o}=e;return reactNative.StyleSheet.create({offstate:{minHeight:jb,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:n.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...R(e,"regular"),fontSize:o.size.body,lineHeight:Math.round(o.size.body*o.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}})}i(td,"makeStyles");var g=Object.freeze({placeholder:"Ask anything about {petName}\u2026",placeholderFollowUpWeb:"Ask a follow-up\u2026",placeholderUrgentWeb:"Tell us what\u2019s happening\u2026",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur\u2019s assistant isn\u2019t a vet and doesn\u2019t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}\u2019s records\u2026",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn\u2019t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting\u2026",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");function Gb(e){return e?.trim()||g.emptyTitlePetFallback}i(Gb,"petNameSlot");function Tn(e,t){return K(e,{petName:Gb(t)})}i(Tn,"forPet");var rd="tel:+18884264435";var Ti=Object.freeze([Object.freeze({key:"inaccurate",label:g.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:g.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:g.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:g.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:g.feedbackReasonOther,feedbackType:"not_helpful"})]),nd=Object.freeze([Object.freeze({sentiment:"up",label:g.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:g.feedbackNeutral}),Object.freeze({sentiment:"down",label:g.feedbackNotHelpful})]);function Kb(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Kb,"sentimentToFeedbackType");function od(e,t){if(e==="down"&&t!==null){let r=Ti.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Kb(e)}i(od,"feedbackTypeFor");var Xb=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function Rr(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=ee(),s=e?.petRef??n??null,a=e?.conversationId??null,l=react.useMemo(()=>({runtime:t,userRef:r,petRef:s,conversationId:a,scopeEpoch:o}),[t,r,s,a,o]),[u,d]=react.useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:s,conversationId:a}),p=react.useRef(null);react.useEffect(()=>{let F=t.registry.acquireChat({userRef:r,petRef:s,conversationId:a});return p.current=F,d({scope:l,controller:F}),()=>{p.current=null,d(C=>C?.controller===F?null:C),t.registry.releaseChat(F);}},[t,r,s,a,o,l]);let f=react.useCallback(F=>c?c.subscribe(F):Qb,[c]),m=react.useCallback(()=>c?c.getSnapshot():Xb,[c]),h=react.useSyncExternalStore(f,m,m),T=react.useCallback((F,C)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?ki(c,c.send(F,C?.imageS3Keys===void 0?{}:{imageS3Keys:C.imageS3Keys}),()=>p.current===c):Promise.resolve(xi()),[c]),b=react.useCallback(F=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?ki(c,c.askEverfur(F),()=>p.current===c):Promise.resolve(xi()),[c]),S=react.useCallback(()=>c&&p.current===c?ki(c,c.retryLast(),()=>p.current===c):Promise.resolve(xi()),[c]),P=react.useCallback(()=>{c&&p.current===c&&c.stop();},[c]),k=react.useCallback(()=>{c&&p.current===c&&c.newConversation();},[c]),[x,y]=react.useState({controller:null,byMessage:{}}),_=x.controller===c?x.byMessage:Zb,A=react.useCallback(async(F,C,w,I)=>{if(!c||p.current!==c)return v(D("accessDenied"));let H=String(F),Q=x.controller===c?x.byMessage[H]:void 0;if(Q===C&&w==null)return y(Y=>{let we={...Y.controller===c?Y.byMessage:{}};return delete we[H],{controller:c,byMessage:we}}),L(Object.freeze({feedbackId:""}));y(Y=>({controller:c,byMessage:{...Y.controller===c?Y.byMessage:{},[H]:C}}));let oe=await c.submitFeedback(F,od(C,w??null),I??null);return p.current!==c?v(D("accessDenied")):(oe.ok||y(Y=>{let we={...Y.controller===c?Y.byMessage:{}};return Q===void 0?delete we[H]:we[H]=Q,{controller:c,byMessage:we}}),oe)},[c,x]),O=react.useMemo(()=>{let F=i(async C=>{if(!c||p.current!==c)return v(D("accessDenied"));let w=await C(c);return p.current===c?w:v(D("accessDenied"))},"run");return {listConversations:i(C=>F(w=>w.listConversations({...s?{petRef:s}:{},...C})),"listConversations"),getMessages:i((C,w)=>F(I=>I.getMessages(C,w)),"getMessages"),resumeConversation:i(C=>F(w=>w.resumeConversation(C)),"resumeConversation"),loadOlderMessages:i(()=>F(C=>C.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>F(C=>C.markRead()),"markRead"),refreshActiveThread:i(()=>F(C=>C.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((C,w)=>F(I=>I.answerCheckin(C,w)),"answerCheckin"),openCheckin:i(C=>F(w=>w.openCheckin(C)),"openCheckin")}},[c,s]);return react.useMemo(()=>({status:h.status,messages:h.messages,conversationId:h.conversationId,petRef:s,error:h.error,isStreaming:h.isStreaming,isBootstrapping:h.isBootstrapping,historyCursor:h.historyCursor??null,isLoadingHistory:h.isLoadingHistory??false,stopped:h.stopped??false,reconnecting:h.reconnecting??false,...O,suggestedPrompts:h.suggestedPrompts,unreadCount:h.unreadCount,hasUnreadThreads:h.hasUnreadThreads??false,newConversation:k,sentimentByMessage:_,feedback:A,send:T,askEverfur:b,retryLast:S,stop:P}),[h,s,T,b,S,P,O,k,_,A])}i(Rr,"useEverfurChat");var Qb=i(()=>{},"NOOP_UNSUBSCRIBE"),Zb=Object.freeze({});async function ki(e,t,r){for await(let o of t);if(!r())return v(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?v(n.error):L(Jb(n.messages))}i(ki,"driveToResult");function Jb(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}i(Jb,"lastAssistantResponseId");function xi(){return v(D("internalError",{retryable:true}))}i(xi,"notReadyError");function ld(e){switch(e.code){case "too_large":return K(g.attachmentTooLarge,{max:Bo(sn),filename:e.filename,size:Bo(e.sizeBytes??0)});case "too_many":return K(g.attachmentTooMany,{max:an});case "unsupported_type":return K(g.attachmentUnsupported,{filename:e.filename});case "network":return g.attachmentNetwork;case "server":return K(g.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return g.attachmentCancelled;case "rate_limited":return g.attachmentRateLimited;case "quota_exceeded":return g.attachmentQuota;case "idempotency_conflict":return g.attachmentConflict;case "unknown":return g.attachmentUnknown}}i(ld,"attachmentErrorMessage");function ud(e,t){return K(e>=t?g.attachmentsFull:g.addAttachment,{used:e,total:t})}i(ud,"attachControlLabel");var nv=Object.freeze({attachments:Object.freeze([])});function Pn(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=ee(),o=e.maxPerMessage??an,s=react.useCallback(()=>{let{services:y}=t.registry;return Ja({funnel:Ie({auth:y.authFor(r),...y.errorPolicy?{errorPolicy:y.errorPolicy}:{}}),transport:e.transport??y.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.transport]),a=react.useMemo(()=>e.queue??s(),[e.queue,s]),l=react.useRef(new WeakSet),[u,d]=react.useState(null),c=u!==null&&u.of===a?u.queue:a;react.useEffect(()=>{if(c!==e.queue){if(l.current.has(c)){d({of:a,queue:s()});return}return ()=>{c.dispose(),l.current.add(c);}}},[c,a,s,e.queue]);let p=react.useSyncExternalStore(c.subscribe,c.getSnapshot,()=>nv),[f,m]=react.useState(null),h=react.useCallback(y=>{let A=(Array.isArray(y)?y:[y]).map(F=>c.add(F)),O=A.find(F=>!F.ok);return O!==void 0&&!O.ok&&m(O.error),A},[c,m]),T=react.useCallback(y=>c.retry(y),[c]),b=react.useCallback(y=>c.remove(y),[c]),S=react.useCallback(()=>c.clear(),[c]),P=react.useCallback(()=>m(null),[m]),k=p.attachments.some(y=>y.status==="uploading"),x=p.attachments.some(y=>y.status==="failed");return react.useMemo(()=>({available:c.available,attachments:p.attachments,maxPerMessage:o,uploading:k,failed:x,blocked:k||x,s3Keys:p.attachments.flatMap(y=>y.status==="uploaded"&&y.s3Key!==null?[y.s3Key]:[]),rejected:f,add:h,retry:T,remove:b,clear:S,dismissRejected:P}),[c.available,p,o,k,x,f,h,T,b,S,P])}i(Pn,"useChatAttachments");var sv="pet_not_registered";function pd(e){return e!=null&&e.reasonCode===sv}i(pd,"isPetNotRegistered");var av=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function fd(e,t,r){let{runtime:n,userRef:o,scopeEpoch:s}=ee(),a=react.useCallback(()=>lt(n.registry.services.authFor(o)),[n,o,s]),l=react.useMemo(()=>t===void 0?null:wi(t),[t]),[u,d]=react.useState({key:null,status:"idle",error:null,registered:null}),c=react.useRef(0),p=react.useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${s}|${e}|${l}`,m=react.useCallback(()=>{if(e===null||t===void 0||f===null)return;let T=++c.current;d({key:f,status:"registering",error:null,registered:null}),a().registerPet(e,t).then(b=>{T===c.current&&(b.ok?(d({key:f,status:"registered",error:null,registered:b.value}),p.current?.()):d({key:f,status:"failed",error:b.error,registered:null}));});},[a,e,f]);react.useEffect(()=>{if(f===null){c.current+=1;return}return m(),()=>{c.current+=1;}},[f,m]);let h=react.useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return react.useMemo(()=>f===null?av:u.key!==f?{status:"registering",error:null,registered:null,retry:h}:{status:u.status,error:u.error,registered:u.registered,retry:h},[f,u,h])}i(fd,"useChatPetRegistration");function wi(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(wi).join(",")}]`:`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>`${JSON.stringify(r)}:${wi(n)}`).join(",")}}`}i(wi,"stableKey");var Ii=Object.freeze({});function yd(e){let[t,r]=react.useState(Ii),n=react.useRef(null),o=react.useRef([]);o.current=e.map(a=>a.id),react.useEffect(()=>{if(e.length===0){n.current=null,r(u=>u===Ii?u:Ii);return}let a=n.current;if(a===null)return;let l=e.find(u=>u.role==="user"&&!a.known.has(u.id));l!==void 0&&(n.current=null,r(u=>({...u,[l.id]:a.images})));},[e]);let s=react.useCallback(a=>{n.current=a.length===0?null:{images:a,known:new Set(o.current)};},[]);return react.useMemo(()=>({byMessage:t,stage:s}),[t,s])}i(yd,"useSentImages");var fv=500;function Ai(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,fv):null}i(Ai,"sanitizeSeedPrompt");function hd(e,t,r){let n=Ai(r),o=react.useRef(e);o.current=e;let s=react.useRef(null);react.useEffect(()=>{if(n===null||t||s.current===n)return;let a=o.current;a!==void 0&&(s.current=n,Promise.resolve(a(n)).catch(()=>{}));},[n,t]);}i(hd,"useInitialAsk");function mv(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}i(mv,"isCoalesced");function bd(e,t){let r=t.activeConversationId;return r===null||r.length===0?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:mv(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(bd,"decideChatRefresh");function Oi(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Oi,"reportHostFailure");function yv(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(yv,"isThenable");function $(e,...t){if(typeof e=="function")try{let r=e(...t);return yv(r)&&Promise.resolve(r).then(void 0,Oi),r}catch(r){Oi(r);return}}i($,"callHost");var vd=new WeakMap;function Ed(e){if(typeof e!="function")return;let t=vd.get(e);if(t!==void 0)return t;let r=i((...n)=>{$(e,...n);},"guarded");return vd.set(e,r),r}i(Ed,"guardHost");function qt(e,...t){let r;try{r=e(...t);}catch(n){return Oi(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(qt,"callHostAsync");function Rd(e,t){let r=react.useRef(t);r.current=t;let n=react.useRef(null),o=react.useRef(null),s=e?.isOffline===void 0?false:$(()=>e.isOffline?.()===!0)===true,a=react.useRef(()=>{});a.current=l=>{let{conversationId:u,isTurnInFlight:d,refresh:c}=r.current,p=bd(l,{activeConversationId:u,isTurnInFlight:d,isOffline:s,lastRefresh:n.current,now:Date.now()});if(p.action!=="skip"){if(p.action==="defer"){o.current!=="announced"&&(o.current=l);return}o.current=null,n.current={conversationId:p.conversationId,at:Date.now()},c!==void 0&&Promise.resolve(c()).catch(()=>{});}},react.useEffect(()=>{if(t.isTurnInFlight||s)return;let l=o.current;l!==null&&a.current(l);},[t.isTurnInFlight,s]),react.useEffect(()=>{if(e===void 0)return;let l=[],u=i((d,c)=>{if(d===void 0)return;let p=$(()=>d(()=>{a.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let d of l)$(d);}},[e]);}i(Rd,"useChatLifecycle");function hv(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(hv,"targetKey");function Td(e,t){let r=hv(t),n=react.useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=react.useRef(null);react.useEffect(()=>{if(r===null||o.current===r)return;o.current=r;let{openCheckin:s,target:a}=n.current;s===void 0||a===void 0||Promise.resolve(s(a)).catch(()=>{});},[r]);}i(Td,"useCheckinTarget");function xd(e,t,r){let[n,o]=react.useState({send:e,conversationId:t,text:r??"",seeded:r??null}),s=n.send===e&&(n.conversationId===null||n.conversationId===t);react.useEffect(()=>{o(l=>{let u=l.send===e&&(l.conversationId===null||l.conversationId===t),d=u?l.text:"",c=u?l.seeded:null,p=r!=null&&r!==c&&d.length===0;return {send:e,conversationId:t,text:p?r:d,seeded:p?r:c}});},[e,t,r]);let a=react.useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [s?n.text:"",a]}i(xd,"useChatDraft");function _d(e,t,r,n){let o=react.useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let s=react.useRef(null),[a,l]=react.useState(null);react.useEffect(()=>{if(e===void 0)return;let u=`${t??""}`;if(s.current===u)return;s.current=u;let d=true;return (async()=>{let c=await qt(()=>e.read(t));if(!d)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{d=false;}},[e,t]),react.useEffect(()=>{e===void 0||a!==`${t??""}`||$(()=>e.write(t,r));},[e,t,r,a]);}i(_d,"usePersistedDraft");var q=Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats\u2026",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" \xB7 ",newReply:"New reply \xB7 {date}",retry:"Try again",retryA11y:"Retry loading chats",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages\u2026",openConversation:"Open conversation",unreadPrefix:"Unread. "});function xn(e){let t=e?.replace(/\s+/g," ").trim();return t||q.untitled}i(xn,"conversationTitle");function Sv(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}i(Sv,"conversationDate");function Id(e){let t=Sv(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?q.newReply.replace("{date}",t):t}i(Id,"conversationMeta");function Ad(e,t){return t?`${q.countLabel}${q.countSeparator}${e}`:q.countLabel}i(Ad,"historyCountLabel");function Od(e){return `${e.unreadCount!==null&&e.unreadCount>0?q.unreadPrefix:""}${q.openConversation} ${xn(e.title)}`}i(Od,"openConversationLabel");function wd(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(wd,"normalizeForSearch");function Tv(e,t){let r=wd(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let s=wd(xn(o.title)),a=s.indexOf(r);if(a<0)continue;let l=a===0?0:s.charAt(a-1)===" "?1:2;n[l]?.push(o);}return n.flat()}i(Tv,"filterConversations");function Li(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(Li,"fresh");function Fd(e){let[t,r]=react.useState(false),[n,o]=react.useState(""),s=e.listConversations,a=react.useRef(0),[l,u]=react.useState(()=>Li(s)),d=l.scope===s?l:Li(s);react.useEffect(()=>(a.current+=1,r(false),o(""),u(Li(s)),()=>{a.current+=1;}),[s]);let c=react.useCallback(async k=>{let x=++a.current,y=k!==void 0;u(A=>({...A,scope:s,loading:!y,loadingMore:y,error:null}));let _=await e.listConversations(k?{cursor:k}:void 0);if(x===a.current){if(!_.ok){u(A=>({...A,loading:false,loadingMore:false,error:_.error.displayMessage}));return}u(A=>{let O=k&&A.scope===s?A.rows:[],F=new Set(O.map(C=>C.id));return {scope:s,loading:false,loadingMore:false,error:null,rows:[...O,..._.value.conversations.filter(C=>!F.has(C.id))],cursor:_.value.nextCursor===k?null:_.value.nextCursor}});}},[e.listConversations,s]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{a.current+=1,r(false);},"close"),m=i(async k=>{let x=++a.current;u(_=>({..._,loading:true,error:null}));let y=await e.resumeConversation(k);x===a.current&&(u(_=>({..._,loading:false,error:y.ok?null:y.error.displayMessage})),y.ok&&r(false));},"resume"),h=i(async()=>{let k=a.current,x=await e.loadOlderMessages();k===a.current&&!x.ok&&u(y=>({...y,error:x.error.displayMessage}));},"earlier"),T=i(()=>{e.newConversation(),a.current+=1,r(false);},"newConversation"),b=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),S=react.useMemo(()=>Tv(d.rows,n),[d.rows,n]),P=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:h,newConversation:T,loadMore:b,query:n,setQuery:o,searching:P,filtered:S,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(Fd,"useHistoryPanel");var _n="#111111",wn="#FFFFFF",xv=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:_n,pillColor:wn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:_n,pillColor:wn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:_n,pillColor:wn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:_n,pillColor:wn,showsVetAction:false})});function _v(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(_v,"urgencySignature");function wv(e){return K(g.urgencyGeneralReason,{petName:e?.trim()||g.emptyTitlePetFallback})}i(wv,"generalUrgencyReason");function Nd(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let o=n.urgencyLevel;return o?{messageId:n.id,level:o,reason:Iv(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:wv(t)}:null}return null}i(Nd,"latestUrgencySource");function Iv(e){return typeof e=="string"&&e.trim().length>0?e:null}i(Iv,"shownReason");function Dd(e){let t=e===null?null:_v(e),[r,n]=react.useState(null),[o,s]=react.useState(false);react.useEffect(()=>s(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:xv[e.level],d=e!==null&&!l&&e.level!=="general",c=react.useCallback(()=>{t!==null&&n(t),s(false);},[t]),p=react.useCallback(()=>s(true),[]);return react.useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:d,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(g.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Dd,"useUrgencySurface");function Ud(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Ud,"selectView");function Av(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(Av,"needsNewConversation");function Vd(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let n=Av(r),o=t==="web";return {tone:"error",title:n?g.turnUnreachableTitle:o?g.turnFailedTitleWeb:g.turnFailedTitle,body:r.displayMessage,actionLabel:n?g.turnStartNewChat:o?g.retry:g.turnRetry,action:n?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:g.turnStoppedTitle,body:g.turnStoppedBody,actionLabel:g.turnRetry,action:"retry"}:null}i(Vd,"turnNotice");function Bd(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(Bd,"awaitingAssistant");var Ov=3,Fv=Object.freeze([]);function Hd(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Fv;let r=new Set,n=[];for(let o of e.suggestedPrompts){let s=o.trim(),a=s.replace(/\s+/g," ").toLowerCase();if(!(a.length===0||r.has(a))&&(r.add(a),n.push(s),n.length===Ov))break}return Object.freeze(n)}i(Hd,"visibleFollowUps");function zd(e){return e.sender?.displayName??g.senderVet}i(zd,"vetSenderLabel");function jd(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(jd,"buildChatOpts");var fe={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function de(e){return {width:e,height:e,alignItems:"center",justifyContent:"center"}}i(de,"box");function be(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}i(be,"stroke");function Wd({size:e,color:t,strokeWidth:r}){let n=be(e,r),o={width:e*.82,height:n,borderRadius:n,backgroundColor:t};return jsxRuntime.jsxs(reactNative.View,{style:[de(e),{gap:e*.22}],...fe,children:[jsxRuntime.jsx(reactNative.View,{style:o}),jsxRuntime.jsx(reactNative.View,{style:o}),jsxRuntime.jsx(reactNative.View,{style:o})]})}i(Wd,"MenuGlyph");function Gd({size:e,color:t,strokeWidth:r,rotate:n}){let o=be(e,r),s=e*.78;return jsxRuntime.jsxs(reactNative.View,{style:[de(e),{transform:[{rotate:n}]}],...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}i(Gd,"Cross");function In(e){return jsxRuntime.jsx(Gd,{...e,rotate:"0deg"})}i(In,"PlusGlyph");function Qe(e){return jsxRuntime.jsx(Gd,{...e,rotate:"45deg"})}i(Qe,"CloseGlyph");function pt({size:e,color:t,strokeWidth:r}){let n=be(e,r);return jsxRuntime.jsx(reactNative.View,{style:de(e),...fe,children:jsxRuntime.jsx(reactNative.View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:n,borderRightWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})})}i(pt,"CheckGlyph");var Lv={down:{rotate:"45deg",marginTop:-0.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-0.4}};function Kd({size:e,color:t,strokeWidth:r,direction:n}){let o=be(e,r),s=e*.46,a=Lv[n];return jsxRuntime.jsx(reactNative.View,{style:de(e),...fe,children:jsxRuntime.jsx(reactNative.View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:s*a.marginTop,marginLeft:s*a.marginLeft,transform:[{rotate:a.rotate}]}})})}i(Kd,"ChevronGlyph");function qd({size:e,color:t,strokeWidth:r}){let n=be(e,r),o={width:e*.42,height:e*.7,borderWidth:n,borderColor:t,borderRadius:n};return jsxRuntime.jsxs(reactNative.View,{style:[de(e),{flexDirection:"row",gap:1}],...fe,children:[jsxRuntime.jsx(reactNative.View,{style:[o,{borderTopLeftRadius:e*.2}]}),jsxRuntime.jsx(reactNative.View,{style:[o,{borderTopRightRadius:e*.2}]})]})}i(qd,"BookGlyph");function $d({size:e,color:t,strokeWidth:r}){let n=be(e,r),o=e*.5;return jsxRuntime.jsxs(reactNative.View,{style:de(e),...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:e*.78,height:n,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:n,borderRightWidth:n,borderColor:t}})]})}i($d,"ArrowUpRightGlyph");function Yd({size:e,color:t,strokeWidth:r}){let n=be(e,r),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:n,borderColor:t,borderRadius:e*.14};return jsxRuntime.jsxs(reactNative.View,{style:de(e),...fe,children:[jsxRuntime.jsx(reactNative.View,{style:[s,{top:0,left:0}]}),jsxRuntime.jsx(reactNative.View,{style:[s,{bottom:0,right:0}]})]})}i(Yd,"CopyGlyph");function An({size:e,color:t,strokeWidth:r,active:n,rotate:o}){let s=be(e,r),a=n?t:"transparent";return jsxRuntime.jsxs(reactNative.View,{style:[de(e),{transform:[{rotate:o}]}],...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}i(An,"ThumbGlyph");function Xd({size:e,color:t,strokeWidth:r}){let n=be(e,r);return jsxRuntime.jsxs(reactNative.View,{style:[de(e),{borderRadius:e/2,borderWidth:n,borderColor:t}],...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{width:n,height:n,borderRadius:n,backgroundColor:t,marginBottom:e*.1}}),jsxRuntime.jsx(reactNative.View,{style:{width:n,height:e*.34,borderRadius:n,backgroundColor:t}})]})}i(Xd,"InfoGlyph");function Qd({size:e,color:t,strokeWidth:r}){let n=be(e,r),o=e*.34;return jsxRuntime.jsxs(reactNative.View,{style:de(e),...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.1,width:n,height:e*.56,borderRadius:n,backgroundColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderBottomLeftRadius:n,borderBottomRightRadius:n}})]})}i(Qd,"UploadGlyph");function Zd({size:e,color:t,strokeWidth:r}){let n=be(e,r);return jsxRuntime.jsxs(reactNative.View,{style:[de(e),{borderWidth:n,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:n,borderLeftWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(Zd,"PhotoGlyph");function Jd({size:e,color:t,strokeWidth:r}){let n=be(e,r);return jsxRuntime.jsxs(reactNative.View,{style:de(e),...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:n,borderLeftWidth:n,borderRightWidth:n,borderColor:t,borderTopLeftRadius:n,borderTopRightRadius:n}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:n,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:jsxRuntime.jsx(reactNative.View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:n,borderColor:t}})})]})}i(Jd,"CameraGlyph");function ec({size:e,color:t,strokeWidth:r}){let n=be(e,r),o=e*.66;return jsxRuntime.jsxs(reactNative.View,{style:de(e),...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,left:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t}}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:e*.02,right:e*.02,width:n,height:e*.4,borderRadius:n,backgroundColor:t,transform:[{rotate:"-45deg"}]}})]})}i(ec,"SearchGlyph");function Ni({size:e,color:t,strokeWidth:r}){let n=be(e,r),o=e*.62;return jsxRuntime.jsxs(reactNative.View,{style:de(e),...fe,children:[jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:n,borderColor:t,alignItems:"center",justifyContent:"center"},children:jsxRuntime.jsx(reactNative.View,{style:{width:n*1.4,height:n*1.4,borderRadius:n,backgroundColor:t}})}),jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:e*.04,width:o*.5,height:o*.5,borderRightWidth:n,borderBottomWidth:n,borderColor:t,transform:[{rotate:"45deg"}]}})]})}i(Ni,"MapPinGlyph");function tc({size:e,color:t,testID:r}){let n=e*.36;return jsxRuntime.jsx(reactNative.View,{style:de(e),testID:r,...fe,children:jsxRuntime.jsx(reactNative.View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:n,borderBottomWidth:n,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}i(tc,"SendGlyph");function rc({size:e,color:t,testID:r}){return jsxRuntime.jsx(reactNative.View,{style:de(e),testID:r,...fe,children:jsxRuntime.jsx(reactNative.View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}i(rc,"StopGlyph");function On({size:e,strokeWidth:t,color:r,children:n}){return jsxRuntime.jsx(reactNative.View,{style:[de(e),{borderRadius:e/2,borderWidth:t??reactNative.StyleSheet.hairlineWidth,borderColor:r}],children:n})}i(On,"Ring");var $t=Object.freeze({standard:Ct.standard,emphasized:Ct.emphasized,exit:Ct.exit,outQuad:Object.freeze([.25,.46,.45,.94]),out:Object.freeze([.23,1,.32,1])});var nc=Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),Nv=Object.freeze({...nc,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 oc(e){return e.motion.reducedMotion?Nv:nc}i(oc,"chatMotion");function Fn(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(Fn,"followUpDelayMs");function ic(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}i(ic,"nextRevealLength");function te(){let e=N();return oc(e)}i(te,"useChatMotion");var Bv=8;function ac(e,t,r){return ((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}i(ac,"bezierComponent");function Hv(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}i(Hv,"bezierSlope");function Tr(e){let[t,r,n,o]=e;return s=>{if(s<=0)return 0;if(s>=1)return 1;let a=s;for(let l=0;l<Bv;l+=1){let u=Hv(a,t,n);if(u===0)break;a-=(ac(a,t,n)-s)/u;}return ac(Math.min(1,Math.max(0,a)),r,o)}}i(Tr,"bezierEasing");var Di=Tr($t.standard),zv=Tr($t.outQuad),jv=Tr($t.out);function Ln(e){let t=react.useRef(null);return t.current===null&&(t.current=new reactNative.Animated.Value(e)),t.current}i(Ln,"useAnimatedValue");function Yt(e,t={}){let r=t.risePx??0,n=t.delayMs??0,o=Ln(e>0?0:1);return react.useEffect(()=>{if(e<=0)return;let s=reactNative.Animated.timing(o,{toValue:1,duration:e,easing:zv,useNativeDriver:true}),a=n>0?reactNative.Animated.sequence([reactNative.Animated.delay(n),s]):s;return a.start(),()=>a.stop()},[o,e,n]),react.useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[r,0]})}]}),[o,r])}i(Yt,"useFadeIn");function Bi({visible:e,inMs:t,outMs:r,style:n,children:o}){let[s,a]=react.useState(e),l=Ln(e&&t<=0?1:0);return react.useEffect(()=>{if(e){a(true);let d=reactNative.Animated.timing(l,{toValue:1,duration:Math.max(0,t),easing:Di,useNativeDriver:true});return d.start(),()=>d.stop()}if(!s)return;if(r<=0){a(false);return}let u=reactNative.Animated.timing(l,{toValue:0,duration:r,easing:Di,useNativeDriver:true});return u.start(({finished:d})=>{d&&a(false);}),()=>u.stop()},[e,s,t,r,l]),!s&&!e?null:jsxRuntime.jsx(reactNative.Animated.View,{style:[n,{opacity:l}],children:o})}i(Bi,"FadePresence");var Wv=Object.freeze({opacity:1,transform:Object.freeze([{translateY:0},{scale:1}])});function cc(e,t){let[r]=react.useState(()=>e?t.bubbleInMs:0),n=r>0,o=Ln(n?0:1);react.useEffect(()=>{if(r<=0)return;let l=reactNative.Animated.timing(o,{toValue:1,duration:r,easing:jv,useNativeDriver:true});return l.start(),()=>l.stop()},[r,o]);let s=t.bubbleFromScale,a=t.bubbleRisePx;return react.useMemo(()=>n?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[a,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:Wv,[n,o,a,s])}i(cc,"useBubbleEnter");function pc(e){let t=react.useRef(null),r=react.useRef(null),n=e[0]?.id??null;if(t.current===null||r.current!==n){let s=t.current===null;t.current=new Map(e.map(a=>[a.id,s&&a.pending===true])),r.current=n;}let o=t.current;for(let s of e)o.has(s.id)||o.set(s.id,true);return react.useCallback(s=>o.get(s)===true,[o])}i(pc,"useEnteringRows");var Gv=12;function z({style:e,containerStyle:t,children:r,onPressIn:n,onPressOut:o,hitSlop:s,...a}){let l=te(),u=Ln(1),d=react.useCallback(c=>{l.pressMs<=0||l.pressScale===1||reactNative.Animated.timing(u,{toValue:c,duration:l.pressMs,easing:Di,useNativeDriver:true}).start();},[u,l.pressMs,l.pressScale]);return jsxRuntime.jsx(reactNative.Pressable,{...a,hitSlop:s??Gv,style:t,onPressIn:c=>{d(l.pressScale),n?.(c);},onPressOut:c=>{d(1),o?.(c);},children:jsxRuntime.jsx(reactNative.Animated.View,{style:[e,{transform:[{scale:u}]}],children:r})})}i(z,"PressScale");function fc(e,t,r){let n=t&&r.revealTickMs>0,[o,s]=react.useState(0),a=react.useRef(e);return a.current=e,react.useEffect(()=>{if(!n)return;let l=setInterval(()=>{s(u=>ic(r,u,a.current.length));},r.revealTickMs);return ()=>clearInterval(l)},[n,r]),n?e.slice(0,Math.min(o,e.length)):e}i(fc,"useRevealedText");var lc=false;function Kv(e){e.layoutMs<=0||(lc||(lc=true,reactNative.Platform.OS==="android"&&typeof reactNative.UIManager.setLayoutAnimationEnabledExperimental=="function"&&reactNative.UIManager.setLayoutAnimationEnabledExperimental(true)),reactNative.LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}));}i(Kv,"animateLayout");function Pr(e,t){let r=react.useRef(e);r.current!==e&&(r.current=e,Kv(t));}i(Pr,"useAnimateLayoutOn");var Hi=36,Jv=22,eE=12,tE=12,rE=16,nE="#000",oE="rgba(0,0,0,0.45)";function mc({uri:e,label:t,onClose:r}){let n=N(),o=reactNativeSafeAreaContext.useSafeAreaInsets();return e===null?null:jsxRuntime.jsxs(reactNative.Modal,{visible:true,animationType:n.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:r,children:[jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:g.closePreview,style:Nn.backdrop,onPress:r,children:jsxRuntime.jsx(reactNative.Image,{source:{uri:e},style:Nn.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),jsxRuntime.jsx(reactNative.View,{pointerEvents:"box-none",style:[Nn.closeWrap,{top:o.top+tE}],children:jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:g.closePreview,hitSlop:eE,style:Nn.closeButton,onPress:r,children:jsxRuntime.jsx(Qe,{size:Jv,color:n.color.surface,strokeWidth:2})})})]})}i(mc,"AttachmentImageLightbox");var Nn=reactNative.StyleSheet.create({backdrop:{flex:1,backgroundColor:nE,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:rE},closeButton:{width:Hi,height:Hi,borderRadius:Hi/2,backgroundColor:oE,alignItems:"center",justifyContent:"center"}});var Dn=12,uE=80,zi=44,yc=22,dE=.14,cE=18,pE=8,gc=Object.freeze({photo:g.attachmentPhoto,camera:g.attachmentCamera});function hc({sources:e,full:t,onPick:r,onClose:n}){let o=N(),s=react.useMemo(()=>fE(o),[o]);return jsxRuntime.jsxs(reactNative.View,{style:s.anchor,pointerEvents:"box-none",children:[jsxRuntime.jsx(reactNative.Pressable,{style:s.dismissLayer,accessibilityRole:"button",accessibilityLabel:g.closeAttachmentPicker,onPress:n}),jsxRuntime.jsxs(reactNative.View,{style:s.bubble,children:[jsxRuntime.jsx(reactNative.View,{style:s.tilesRow,children:e.map(a=>jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:gc[a],accessibilityState:{disabled:t},disabled:t,containerStyle:s.tile,style:s.tileInner,onPress:()=>r(a),children:[jsxRuntime.jsx(reactNative.View,{style:s.tileIconWrap,children:a==="photo"?jsxRuntime.jsx(Zd,{size:yc,color:o.color.brandInk,strokeWidth:1.5}):jsxRuntime.jsx(Jd,{size:yc,color:o.color.brandInk,strokeWidth:1.5})}),jsxRuntime.jsx(E,{tier:"control",style:s.tileLabel,children:gc[a]})]},a))}),jsxRuntime.jsx(reactNative.View,{style:s.tail}),jsxRuntime.jsx(reactNative.View,{style:s.tailFill})]})]})}i(hc,"AttachmentPickerPopover");function fE(e){let t=e.color,r=e.radius;return reactNative.StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:dE,shadowRadius:cE,shadowOffset:{width:0,height:pE},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:uE,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:zi,height:zi,borderRadius:zi/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...R(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-Dn/2,width:Dn,height:Dn,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Dn+4,height:2,backgroundColor:t.surfaceCream}})}i(fE,"makeStyles");var Pe=Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var vc=56,Ec=12,gE=14,hE=10,bE=.45,vE="rgba(7,193,104,0.55)",EE="rgba(185,28,28,0.55)",CE=200,RE=300,_c=20,Wi=22,SE=12,TE="rgba(0,0,0,0.78)",Cc=220,Rc=100,Sc="rgba(255,255,255,0.15)";function wc({attachments:e,rejected:t,uploadFailed:r=false,onRetry:n,onRemove:o,onPreview:s}){let a=N(),l=react.useMemo(()=>Ac(a),[a]);return e.length===0&&t===null?null:jsxRuntime.jsxs(reactNative.View,{style:l.strip,children:[e.length>0?jsxRuntime.jsx(reactNative.View,{style:l.cards,children:e.map(u=>jsxRuntime.jsx(PE,{row:u,styles:l,onRetry:n,onRemove:o,onPreview:s},u.id))}):null,r?jsxRuntime.jsx(E,{style:l.rejected,accessibilityRole:"alert",children:g.attachmentsFailedBlocked}):null,t!==null?jsxRuntime.jsx(E,{style:l.rejected,accessibilityRole:"alert",children:ld(t)}):null]})}i(wc,"AttachmentStrip");function PE({row:e,styles:t,onRetry:r,onRemove:n,onPreview:o}){let s=N(),a=e.status==="uploading",l=e.status==="failed",u=e.status==="uploaded",d=react.useRef(e.status),[c,p]=react.useState(false);return react.useEffect(()=>{let f=d.current;d.current=e.status,e.status==="uploaded"&&f==="uploading"&&p(true);},[e.status]),jsxRuntime.jsxs(reactNative.View,{style:t.card,children:[jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:u?"button":"image",accessibilityLabel:u?K(g.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:a,disabled:!u},disabled:!u,style:t.thumbHit,onPress:()=>o(e),children:jsxRuntime.jsxs(reactNative.View,{style:t.thumb,children:[jsxRuntime.jsx(reactNative.Image,{source:{uri:e.previewUri},style:t.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),a?jsxRuntime.jsx(reactNative.View,{style:t.uploadingOverlay,children:jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:s.color.surface})}):null,c?jsxRuntime.jsx(kE,{styles:t,onDone:()=>p(false)}):null]})}),l?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:K(g.retryUpload,{filename:e.filename}),style:t.failedOverlay,onPress:()=>r(e.id),children:jsxRuntime.jsx(reactNative.View,{style:t.failedInner,children:jsxRuntime.jsx(Qe,{size:_c,color:s.color.surface,strokeWidth:2})})}):null,jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:K(g.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:t.removeSlot,style:t.removeButton,onPress:()=>n(e.id),children:jsxRuntime.jsx(Qe,{size:SE,color:s.color.surface,strokeWidth:1.5})})]})}i(PE,"PreviewCard");function kE({styles:e,onDone:t}){let r=N(),n=te(),o=react.useRef(null);o.current===null&&(o.current=new reactNative.Animated.Value(0));let s=o.current;return react.useEffect(()=>{let a=reactNative.Animated.sequence([reactNative.Animated.timing(s,{toValue:1,duration:CE,useNativeDriver:true}),reactNative.Animated.delay(n.uploadFlashMs),reactNative.Animated.timing(s,{toValue:0,duration:RE,useNativeDriver:true})]);return a.start(({finished:l})=>{l&&t();}),()=>a.stop()},[s,n.uploadFlashMs,t]),jsxRuntime.jsx(reactNative.Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:s}],children:jsxRuntime.jsx(pt,{size:_c,color:r.color.surface,strokeWidth:2})})}i(kE,"SuccessFlash");function Ic({images:e,onPreview:t}){let r=N(),n=react.useMemo(()=>Ac(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsxRuntime.jsx(reactNative.View,{style:o?n.sentSingle:n.sentGrid,children:e.map((s,a)=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:K(g.attachedImage,{filename:s.filename}),onPress:()=>t(s),children:jsxRuntime.jsx(reactNative.Image,{source:{uri:s.uri},style:o?n.singleImage:n.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${s.uri}-${a}`))})}i(Ic,"SentImages");function Ac(e){let t=e.color,r=e.type;return reactNative.StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:vc,height:vc,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:Ec,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...Pe,alignItems:"center",justifyContent:"center",backgroundColor:ut(e.color.brandInk,bE)??e.color.brandSofter},successOverlay:{...Pe,alignItems:"center",justifyContent:"center",backgroundColor:vE},failedOverlay:{...Pe,borderRadius:Ec,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:EE},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:Wi,height:Wi,borderRadius:Wi/2,backgroundColor:TE,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...R(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:Cc,height:Cc,borderRadius:gE,backgroundColor:Sc},gridImage:{width:Rc,height:Rc,borderRadius:hE,backgroundColor:Sc}})}i(Ac,"makeStyles");var xE="chat attachment upload: the file handle has no uri",_E="chat attachment upload failed";function wE(e){return {uri:e.uri,name:Vo(e.name),type:e.mimeType}}i(wE,"filePartOf");function Oc(e={}){return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(xE));let{signal:o,onProgress:s}=n,a=i(()=>Promise.reject(new Error(_E)),"failed");return o?.aborted===true?a():Xr({url:t.upload_url,fields:t.upload_fields,file:wE(r),signal:o,fetch:e.fetch}).then(l=>{if(!l)return a();s?.(1);},a)}})}i(Oc,"createRnChatAttachmentTransport");function Un(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=ee(),o=react.useMemo(()=>lt(e.registry.services.authFor(t)),[e,t,n]),[s,a]=react.useState({repository:o,pets:[],loading:true,error:null}),l=s.repository===o?s:{pets:[],loading:true,error:null},u=react.useRef(0),d=react.useCallback(async()=>{let p=++u.current;a(m=>({...m,repository:o,loading:true,error:null,pets:m.repository===o?m.pets:[]}));let f=await o.list();p===u.current&&a(f.ok?{repository:o,pets:f.value,loading:false,error:null}:m=>({repository:o,pets:m.repository===o?m.pets:[],loading:false,error:f.error}));},[o]);react.useEffect(()=>(d(),()=>{u.current+=1;}),[d]);let c=react.useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return react.useMemo(()=>({pets:l.pets,activePet:c,loading:l.loading,error:l.error,refresh:d}),[l.pets,l.loading,l.error,c,d])}i(Un,"useEverfurPets");function Fc(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(Fc,"headerPetOf");function me(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(me,"slotBox");function Vn(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(Vn,"ownGroundSlot");function ke(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(ke,"slotText");var Mc=Object.freeze({visitButton:"Vet"});var Lc=Symbol.for("@everfur/sdk/televet");function Ze(){let e=globalThis,t=e[Lc];if(t!==void 0)return t;let r={presenter:null,snapshot:Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:new Set,dailyRegistered:false};return e[Lc]=r,r}i(Ze,"televetGlobal");function Bn(e){let t=Ze();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(Bn,"publish");function Nc(e){let t=Ze().presenter;if(t===null)return "absent";try{return t(e)===!1?"declined":"presented"}catch(r){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",r),"threw"}}i(Nc,"callTelevetPresenter");function Dc(e){let t=Ze();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(Dc,"subscribeTelevetExperience");function $i(){return Ze().snapshot}i($i,"televetExperienceSnapshot");function ME(){return Ze().hosts.length>0}i(ME,"hasTelevetHost");function Uc(e){if(!ME())return false;let t=Object.freeze({...e});return Bn({request:t,serial:Ze().snapshot.serial+1}),true}i(Uc,"presentTelevetExperience");function Yi(){Ze().snapshot.request!==null&&Bn({request:null});}i(Yi,"dismissTelevetExperience");function Vc(){let e=Ze(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Bn({activeHost:e.hosts[0]??null}),t}i(Vc,"claimTelevetHost");function Bc(e){let t=Ze();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;Bn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(Bc,"releaseTelevetHost");var Hc=false;function Hn(e,t){return t!==void 0?($(t,e),"onStartInApp"):Nc(e)==="presented"?"presenter":Uc(e)?"experience":(Hc||(Hc=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(Hn,"openVetVisitInApp");function Wc(e){let t=null;return ()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null);}),r}}i(Wc,"memoizeTelevetLoader");function Gc(e){let[t,r]=react.useState(null);react.useEffect(()=>{let d=Vc();return r(d),()=>{Bc(d);}},[]);let n=react.useSyncExternalStore(Dc,$i,$i),s=t!==null&&n.activeHost===t?n.request:null,[a,l]=react.useState(null),u=s!==null&&a===null;return react.useEffect(()=>{if(!u)return;let d=true;return e().then(c=>{d&&l(()=>c);},c=>{d&&(console.warn("[everfur] The in-app vet visit could not load its screens.",c),Yi());}),()=>{d=false;}},[u,e]),s===null||a===null?null:{module:a,request:s,serial:n.serial,dismiss:Yi}}i(Gc,"useTelevetExperienceHost");var NE=Wc(()=>import('@everfur/sdk/televet/booking'));function xr(){let e=Gc(NE);if(e===null)return null;let{EverfurTelevetModal:t}=e.module;return jsxRuntime.jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(xr,"EverfurTelevetHost");var Xi=Object.freeze(["visit","join","summary","messages"]);function Qi(e){return typeof e=="string"&&Xi.includes(e)}i(Qi,"isVetVisitIntent");var UE="/widget/v1/televet/handoffs",VE="/widget/v1/televet/availability",BE="/widget/v1/televet/chat-entry",HE=/^[a-z0-9][a-z0-9_-]{0,39}$/,zE=/^[A-Za-z0-9_-]{22}$/;var Kc=32,qc=128,$c=64;function Ji(e){let t=e.httpStatus;switch(e.code){case "sessionRequired":return "sessionRequired";case "authExpired":case "authRejected":return "authRejected";case "sdkUpdateRequired":return "sdkUpdateRequired";case "validationFailed":return "invalidRequest";case "rateLimited":case "quotaExceeded":return "rateLimited";}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}i(Ji,"vetVisitErrorReasonOf");function Yc(e){return v(D("validationFailed",{retryable:false,wireMessage:e}))}i(Yc,"invalid");function Zi(e){return v(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(Zi,"unusable");function jE(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!HE.test(n))return {ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n;}let o=t?.entry;if(o!=null){if(o!=="chat"||e===void 0)return {ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=o;}let s=t?.visitRef,a=t?.intent,l=s!=null;if(l){let u=typeof s=="string"?s.trim():"";if(u.length<1||[...u].length>$c)return {ok:false,message:`visitRef must be 1..${$c} characters`};r.visit_ref=u;}if(a!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!Qi(a))return {ok:false,message:`intent must be one of ${Xi.join(", ")}`};r.intent=a;}return {ok:true,body:r}}i(jE,"handoffBody");function WE(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!Qi(r)?null:Object.freeze({visitRef:t,intent:r})}i(WE,"parseVisitEcho");function Qc(e){let t=e.funnel??Ie({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(Xc(r,"televet.visit.handoff_failed",{reason:Ji(o)}),v(o)),"failed");return {async createHandoff(o,s){let a;if(o!=null){let b=typeof o=="string"?[...o].length:0;if(b<1||b>qc)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${qc} characters`}));a=o;}let l=jE(a,s);if(!l.ok){let b=Yc(l.message);return b.ok?b:n(b.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:UE,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=GE(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!zE.test(f))){let b=Zi("the handoff response carried no usable return flow id");return b.ok?b:n(b.error)}let m=u.visit_ref!==void 0,h=m?WE(d.value?.visit):null;if(m&&h===null){let b=Zi("the handoff response did not confirm the visit it opens");return b.ok?b:n(b.error)}let T=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...h!==null?{visit:h}:{}});return T===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Xc(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),L(T))},async checkAvailability(o){if(typeof o!="string"||o.length>Kc)return Yc(`state must be at most ${Kc} characters`);let s=await t.send("televet.visit.availability",{method:"POST",path:VE,body:{state:o}},{idempotent:false,maxAttempts:1});if(!s.ok)return v(s.error);let a=s.value?.available;return typeof a!="boolean"?Zi("the availability response carried no usable answer"):L(Object.freeze({available:a}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:BE},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(Qc,"createVetVisitController");function GE(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||!YE(t)?null:Object.freeze({url:t,expiresAt:r})}i(GE,"parseHandoff");var KE=new Set(["localhost","127.0.0.1","[::1]"]),qE=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,$E=/[\s\u0000-\u001f\u007f]/;function YE(e){if($E.test(e))return false;let t=qE.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let o=n.replace(/:\d+$/,"").toLowerCase(),s=r==="https",a=r==="http"&&KE.has(o);if(!s&&!a)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(YE,"isOpenableVisitUrl");function Xc(e,t,r){if(e)try{e.track(t,r);}catch{}}i(Xc,"safeTrack");var es=Object.freeze({status:"idle",error:null,errorReason:null});function QE(e,t,r){let{usState:n,chat:o,scope:s}=r,a=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,d]=react.useState(null);if(react.useEffect(()=>{if(!a)return;let p=true,f=e.current;return d(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let h=await f.checkAvailability(n);return h.ok&&h.value.available}catch{return false}},"ask")().then(h=>{p&&d({key:l,open:h});}),()=>{p=false;}},[a,l,n,o,s,e]),!a)return null;let c=u!==null&&u.key===l;return {open:c&&u.open,pending:!c}}i(QE,"usePreflight");var ZE=Object.freeze({status:"opening",error:null,errorReason:null});function ep(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=ee(),s=Wt("televet"),a=s.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",d=t.petRef??null,c=t.prefer==="redirect",p=react.useMemo(()=>{if(t.controller)return t.controller;let{services:w}=r.registry;return Qc({auth:w.authFor(n),telemetry:w.telemetry,...w.errorPolicy?{errorPolicy:w.errorPolicy}:{}})},[r,n,o,t.controller]),f=react.useRef(p);f.current=p;let m=react.useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),h=QE(f,a,{usState:l,chat:u,scope:m}),T=a&&(h===null||h.open)&&(!u||d!==null),b=t.returnTo??null,[S,P]=react.useState(es),k=react.useRef(null),x=react.useRef({runtime:r,userRef:n,scopeEpoch:o});x.current={runtime:r,userRef:n,scopeEpoch:o};let y=react.useRef(p);y.current=p;let _=react.useRef(T);_.current=T;let A=react.useCallback((w,I)=>{if(k.current)return k.current;let H=i((he,st)=>(P({status:he==="cancelled"?"idle":"error",error:st,errorReason:he==="cancelled"?null:he}),Object.freeze({opened:false,reason:he,error:st})),"fail");if(!_.current)return Promise.resolve(H("unavailable",null));let Q=e.prepare();if(!Q.ok)return Promise.resolve(H(Q.reason,null));let oe=x.current,Y=y.current;P(ZE);let it=(async()=>{let he,st={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...I!==null?{visitRef:I.visitRef}:{},...I!==null&&I.intent!==null&&I.intent!==void 0?{intent:I.intent}:{}},Vr=Object.keys(st).length===0?void 0:st,Br=w===void 0?d:w;try{he=await(Vr===void 0?Y.createHandoff(Br):Y.createHandoff(Br,Vr));}catch{return e.abandon(Q.value),H("unknown",null)}let Lt=x.current;if(Lt.runtime!==oe.runtime||Lt.userRef!==oe.userRef||Lt.scopeEpoch!==oe.scopeEpoch)return e.abandon(Q.value),H("cancelled",null);if(!he.ok)return e.abandon(Q.value),H(Ji(he.error),he.error);let Jt=await e.finish(Q.value,he.value);return Jt!==null?H(Jt,null):(P(es),Object.freeze(he.value.flowId===void 0?{opened:true}:{opened:true,flowId:he.value.flowId}))})().finally(()=>{k.current===it&&(k.current=null);});return k.current=it,it},[e,d,b,u]),O=react.useCallback((w,I)=>{if(!_.current)return P({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let H=w===void 0?d:w,Q={...H!==null?{petRef:H}:{},...l!==null?{usState:l}:{},...I!==null?{visitRef:I.visitRef,intent:I.intent}:{}};return Hn(Q)===null?(P({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(P(es),Promise.resolve(Object.freeze({opened:true})))},[d,l]),F=react.useCallback(w=>c?A(w,null):O(w,null),[c,A,O]),C=react.useCallback((w,I)=>c?A(void 0,{visitRef:w,intent:I??null}):O(void 0,{visitRef:w,intent:I??null}),[c,A,O]);return {available:T,isPending:s.isPending||(h?.pending??false),status:S.status,error:S.error,errorReason:S.errorReason,open:F,openVisit:C}}i(ep,"useVetVisitWith");var tC=i(e=>reactNative.Linking.openURL(e),"defaultOpenUrl");function jn(e={}){let{openUrl:t,...r}=e,n=react.useMemo(()=>{let o=t??tC;return {prepare:i(()=>({ok:true,value:null}),"prepare"),async finish(s,a){try{return await o(a.url),null}catch{return "openFailed"}},abandon:i(()=>{},"abandon")}},[t]);return ep(n,r)}i(jn,"useVetVisit");var tp=44,sC=.6;function Zt(e){let{petRef:t,label:r,openUrl:n,onOpened:o,onError:s,style:a,labelStyle:l,controller:u,returnTo:d,usState:c,entry:p,visitRef:f,intent:m,onStartInApp:h,prefer:T}=e,b=T==="redirect",S=jn({...d!==void 0?{returnTo:d}:{},...c!==void 0?{usState:c}:{},...p!==void 0?{entry:p}:{},...t!==void 0?{petRef:t}:{},...n!==void 0?{openUrl:n}:{},...u!==void 0?{controller:u}:{},prefer:b?"redirect":"in-app"}),P=N(),k=react.useMemo(()=>aC(P),[P]),x=react.useRef(false);if(!S.available)return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[null,jsxRuntime.jsx(xr,{})]});let y=S.status==="opening",_=r??Mc.visitButton;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(reactNative.Pressable,{onPress:i(()=>{if(!(y||x.current)){if(!b){let O={...t!==void 0?{petRef:t}:{},...c!==void 0?{usState:c}:{},...f!=null?{visitRef:f,intent:m??null}:{}};Hn(O,h)===null&&$(s,"unavailable",null);return}x.current=true,(f==null?S.open():S.openVisit(f,m??null)).then(O=>{O.opened?$(o,O.flowId??null):O.reason!=="cancelled"&&$(s,O.reason,O.error);}).finally(()=>{x.current=false;});}},"onPress"),accessibilityRole:"button",accessibilityLabel:_,accessibilityState:{busy:y,disabled:y},style:[k.button,y?k.busy:null,a],children:jsxRuntime.jsx(E,{style:[k.label,l],children:_})}),jsxRuntime.jsx(xr,{})]})}i(Zt,"VetVisitButton");function aC(e){let{color:t,space:r,radius:n,type:o,slots:s}=e;return reactNative.StyleSheet.create({button:{minHeight:tp,minWidth:tp,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.primary,...me(s.vetVisitButton)},busy:{opacity:sC},label:{...R(e,"medium"),color:t.onPrimary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.snug,...ke(s.vetVisitButton)}})}i(aC,"makeStyles");function ts(e){return pr(e)==="cat"?"cat":"dog"}i(ts,"speciesOf");function rs(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(rs,"petAgeYears");function ip(e){let t=rs(e.ageYears),r=ts(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(ip,"formatPetMeta");var op=Object.freeze([Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),Object.freeze({background:"#fbc558",foreground:"#10462e"}),Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function lC(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return op[t%op.length]}i(lC,"pickInitialsPalette");function ns(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(ns,"getInitial");function sp(e){return {...lC(e.petRef),initial:ns(e.name)}}i(sp,"petInitials");function pC(e){return Math.max(12,Math.round(e*.42))}i(pC,"letterSize");function wr({pet:e,size:t,ringStroke:r}){let n=N(),o=react.useMemo(()=>fC(n),[n]),s=t-r*2,a=e===null?null:sp(e),l=pC(s);return jsxRuntime.jsx(On,{size:t,strokeWidth:r,color:n.color.success,children:jsxRuntime.jsx(reactNative.View,{style:[o.disc,{width:s,height:s,borderRadius:s/2},a===null?o.discEmpty:{backgroundColor:a.background}],children:jsxRuntime.jsx(E,{tier:"badge",style:[o.letter,{fontSize:l,lineHeight:Math.round(l*1.2),color:a===null?n.color.text.muted:a.foreground}],children:a===null?ns(null):a.initial})})})}i(wr,"PetDisc");function fC(e){return reactNative.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...R(e,"bold"),textAlign:"center",includeFontPadding:false}})}i(fC,"makeStyles");var is=48,up=2,vC=320,EC="80%",CC="rgba(17,17,17,0.45)",RC=18,ap=22,SC=12,lp=.4,TC=44;function ss(e){return e?.name?.trim()||g.yourPet}i(ss,"petDisplayName");function dp({visible:e,pets:t,activePetRef:r,onSelect:n,onAddPet:o=null,onClose:s}){let a=N(),l=react.useMemo(()=>PC(a),[a]);return e?jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:a.motion.reducedMotion?"none":"fade",onRequestClose:s,children:jsxRuntime.jsxs(reactNative.View,{style:l.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:Pe,onPress:s,accessibilityRole:"button",accessibilityLabel:g.close,children:jsxRuntime.jsx(reactNative.View,{style:l.backdrop})}),jsxRuntime.jsxs(reactNative.View,{style:l.panel,accessibilityViewIsModal:true,children:[jsxRuntime.jsx(E,{tier:"heading",style:l.title,accessibilityRole:"header",children:g.yourPets}),jsxRuntime.jsx(reactNative.ScrollView,{style:l.list,contentContainerStyle:l.listContent,showsVerticalScrollIndicator:true,children:t.map(u=>{let d=u.petRef===r,c=ss(u),p=ip(u);return jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:K(d?g.petCurrentlyActive:g.switchToPet,{name:c}),accessibilityState:{selected:d},style:[l.row,d?l.rowActive:null],onPress:()=>n(u.petRef),children:[jsxRuntime.jsx(wr,{pet:u,size:is,ringStroke:up}),jsxRuntime.jsxs(reactNative.View,{style:l.copy,children:[jsxRuntime.jsx(E,{style:l.name,numberOfLines:1,children:c}),jsxRuntime.jsx(E,{tier:"compact",style:l.meta,numberOfLines:1,children:d?`${g.activePrefix}${p}`:p})]}),d?jsxRuntime.jsx(pt,{size:RC,color:a.color.brandInk}):null]},u.petRef)})}),o!==null?jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:g.addAnotherPet,style:l.addRow,onPress:o,children:[jsxRuntime.jsx(reactNative.View,{style:l.addDisc,children:jsxRuntime.jsx(E,{tier:"control",style:l.addPlus,children:"+"})}),jsxRuntime.jsx(E,{style:l.addLabel,children:g.addAnotherPet})]}):null,jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:g.close,containerStyle:l.closeSlot,style:l.closeButton,onPress:s,children:jsxRuntime.jsx(E,{tier:"control",style:l.closeText,children:g.close})})]})]})}):null}i(dp,"PetSwitcherSheet");function PC(e){let t=e.color,r=e.radius;return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:CC},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:ap,borderTopRightRadius:ap,gap:14,maxHeight:EC},title:{...R(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk},list:{maxHeight:vC,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:TC,paddingHorizontal:8},addDisc:{width:is,height:is,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:up,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...R(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...R(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...R(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...R(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:lp},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:SC,backgroundColor:t.brandSoft},closeText:{...R(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:lp}})}i(PC,"makeStyles");var _C=44,Gn=36,wC=22,as=9,IC=1.5,pp=6,wt=35,Kn=1.75,ls=12.4,AC=.5,OC=8,FC=28,MC=160;function ds(e,t){return Fc(e,t)}i(ds,"headerPet");function mp({pets:e,petRef:t,historyUnread:r,onOpenHistory:n,onPetChange:o,onAddPet:s,vet:a}){let l=N(),u=react.useMemo(()=>NC(l),[l]),[d,c]=react.useState(false),p=ds(e.pets,t),f=e.pets.length>=2,m=t??p?.petRef??null,h=ss(p),T=i(S=>{c(false),e.setActivePet(S),$(o,S);},"select"),b=s===void 0?null:()=>{c(false),$(s);};return jsxRuntime.jsxs(reactNative.View,{style:u.row,children:[jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:r?`${g.openHistoryNative}${g.newReplySuffix}`:g.openHistoryNative,containerStyle:u.iconSlot,style:u.iconButton,onPress:n,children:[jsxRuntime.jsx(Wd,{size:wC,color:l.color.text.primary,strokeWidth:2}),r?jsxRuntime.jsx(reactNative.View,{style:u.unreadDot,pointerEvents:"none"}):null]}),jsxRuntime.jsx(reactNative.View,{style:u.center,pointerEvents:"box-none",children:jsxRuntime.jsx(LC,{logoUrl:l.meta.logoUrl,name:l.meta.displayName,styles:u})}),m===null?null:jsxRuntime.jsx(Zt,{entry:"chat",petRef:m,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:u.vetEntry,labelStyle:u.vetEntryLabel}),jsxRuntime.jsx(reactNative.View,{style:u.right,children:f?jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:K(g.switchActivePet,{name:h}),containerStyle:u.avatarSlot,style:u.avatarWrap,onPress:()=>c(true),children:[jsxRuntime.jsx(wr,{pet:p,size:wt,ringStroke:Kn}),jsxRuntime.jsx(reactNative.View,{style:u.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:jsxRuntime.jsx(In,{size:OC,color:l.color.brandInk,strokeWidth:2})})]}):e.loading&&p===null?jsxRuntime.jsx(reactNative.View,{style:u.avatarWrap,accessible:true,accessibilityLabel:g.yourPet,children:jsxRuntime.jsx(On,{size:wt,strokeWidth:Kn,color:l.color.success,children:jsxRuntime.jsx(reactNative.View,{style:u.placeholderDisc})})}):jsxRuntime.jsx(reactNative.View,{style:u.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:p===null?g.yourPet:h,children:jsxRuntime.jsx(wr,{pet:p,size:wt,ringStroke:Kn})})}),jsxRuntime.jsx(dp,{visible:d,pets:e.pets,activePetRef:p?.petRef??null,onSelect:T,onAddPet:b,onClose:()=>c(false)})]})}i(mp,"ChatHeader");function LC({logoUrl:e,name:t,styles:r}){let[n,o]=react.useState(null);return e===null||n===e?null:jsxRuntime.jsx(reactNative.View,{style:r.logoBar,children:jsxRuntime.jsx(reactNative.Image,{source:{uri:e},style:r.logo,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:()=>o(e)})})}i(LC,"BrandLogo");function NC(e){let t=e.color,r=wt-Kn*2;return reactNative.StyleSheet.create({vetEntry:{minHeight:_C,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},vetEntryLabel:{...R(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:16,paddingVertical:10,backgroundColor:t.surface},iconSlot:{borderRadius:Gn/2},iconButton:{width:Gn,height:Gn,borderRadius:Gn/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:pp,right:pp,width:as,height:as,borderRadius:as,backgroundColor:t.danger,borderWidth:IC,borderColor:t.surface},center:{...Pe,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:e.space.lg},logo:{height:FC,width:MC},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:wt/2},avatarWrap:{width:wt,height:wt,position:"relative"},placeholderDisc:{width:r,height:r,borderRadius:r/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ls,height:ls,borderRadius:ls/2,borderWidth:AC,borderColor:t.success,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}i(NC,"makeStyles");var hp=44,HC="rgba(17,17,17,0.55)",bp=26,zC=36,vp=4,cs=20,ps=38,jC=18,WC=12;function Ep({visible:e,onSubmit:t,onSkip:r}){let n=N(),o=react.useMemo(()=>GC(n),[n]),[s,a]=react.useState(null),[l,u]=react.useState(""),[d,c]=react.useState(false),[p,f]=react.useState(false),m=i(()=>{a(null),u(""),c(false),f(false);},"reset"),h=i(()=>{d||(m(),r());},"skip"),T=i(async()=>{if(d)return;c(true),f(false);let S=l.trim();await t(s,S.length>0?S:null)?m():(c(false),f(true));},"submit");if(!e)return null;let b=[...l].length>Bt;return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:n.motion.reducedMotion?"none":"slide",onRequestClose:h,children:jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:reactNative.Platform.OS==="ios"?"padding":void 0,style:o.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:o.scrim,onPress:h,accessibilityRole:"button",accessibilityLabel:g.feedbackSkipA11y}),jsxRuntime.jsxs(reactNative.View,{style:o.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[jsxRuntime.jsx(reactNative.View,{style:o.handle}),jsxRuntime.jsxs(reactNative.View,{style:o.header,children:[jsxRuntime.jsx(reactNative.View,{style:o.iconBadge,children:jsxRuntime.jsx(An,{size:jC,color:n.color.brandInk,active:false,rotate:"180deg"})}),jsxRuntime.jsxs(reactNative.View,{style:o.headerText,children:[jsxRuntime.jsx(E,{tier:"heading",style:o.title,accessibilityRole:"header",children:g.feedbackTitle}),jsxRuntime.jsx(E,{style:o.subtitle,children:g.feedbackSubtitle})]})]}),jsxRuntime.jsx(reactNative.View,{style:o.options,children:Ti.map(S=>{let P=s===S.key;return jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:S.label,accessibilityState:{selected:P},style:[o.option,P?o.optionSelected:null],onPress:()=>a(k=>k===S.key?null:S.key),children:[jsxRuntime.jsx(E,{style:[o.optionLabel,P?o.optionLabelSelected:null],children:S.label}),jsxRuntime.jsx(reactNative.View,{style:[o.radio,P?o.radioSelected:null],children:P?jsxRuntime.jsx(pt,{size:WC,color:n.color.surface,strokeWidth:2}):null})]},S.key)})}),jsxRuntime.jsxs(reactNative.View,{style:o.inputWrap,children:[jsxRuntime.jsx(Gt,{style:o.input,placeholder:g.feedbackNotesPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:g.feedbackNotesPlaceholder,value:l,onChangeText:u,multiline:true,editable:!d}),l.length>0?jsxRuntime.jsx(E,{tier:"compact",style:[o.counter,b?o.counterOver:null],children:`${[...l].length}/${Bt}`}):null]}),p?jsxRuntime.jsx(E,{style:o.failed,accessibilityRole:"alert",children:g.feedbackFailed}):null,jsxRuntime.jsxs(reactNative.View,{style:o.actions,children:[jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:g.feedbackSubmit,accessibilityState:{busy:d,disabled:d||b},disabled:d||b,style:[o.submit,d||b?o.submitDisabled:null],onPress:()=>{T();},children:jsxRuntime.jsx(E,{tier:"control",style:o.submitLabel,children:g.feedbackSubmit})}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:g.feedbackSkipA11y,hitSlop:8,onPress:h,style:o.skip,children:jsxRuntime.jsx(E,{tier:"control",style:o.skipLabel,children:g.feedbackSkip})})]})]})]})})}i(Ep,"FeedbackReasons");function GC(e){let t=e.color,r=e.type,n=e.radius,o=e.slots;return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...Pe,backgroundColor:HC},sheet:{backgroundColor:t.surface,borderTopLeftRadius:bp,borderTopRightRadius:bp,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14},handle:{alignSelf:"center",width:zC,height:vp,borderRadius:vp/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:ps,height:ps,borderRadius:ps/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...R(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:r.letterSpacing.tight},subtitle:{...R(e,"regular"),fontSize:r.size.body,lineHeight:r.size.body*r.lineHeight.relaxed,color:t.text.muted},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:n.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder,backgroundColor:t.surface},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...R(e,"medium"),fontSize:r.size.body,color:t.text.primary},optionLabelSelected:{color:t.brandInk},radio:{width:cs,height:cs,borderRadius:cs/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,...R(e,"regular"),fontSize:r.size.body,color:t.text.primary,textAlignVertical:"top"},counter:{...R(e,"mono"),alignSelf:"flex-end",fontSize:r.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...R(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:hp,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:n.pill,backgroundColor:t.brand,...me(o.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...R(e,"medium"),fontSize:r.size.body,color:t.onPrimary,...ke(o.primaryButton)},skip:{minHeight:hp,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...R(e,"medium"),fontSize:r.size.body,color:t.text.muted}})}i(GC,"makeStyles");var oR=.88,iR=420,sR=58,aR="rgba(17,17,17,0.28)",lR=.15,uR=14,dR=12,fs=44,cR=16,pR=14,fR=12,mR=14,ms=8,mt=2,yR=.5,gR=Tr($t.standard);function hR(e){return Math.min(Math.round(e*oR),iR)}i(hR,"drawerPanelWidth");function Rp({chat:e,history:t}){let[r,n]=react.useState(t.open),o=react.useCallback(()=>n(false),[]);return t.open&&!r&&n(true),r?jsxRuntime.jsx(bR,{chat:e,history:t,onHidden:o}):null}i(Rp,"HistoryDrawer");function bR({chat:e,history:t,onHidden:r}){let n=N(),o=react.useMemo(()=>ER(n),[n]),s=te(),a=reactNativeSafeAreaContext.useSafeAreaInsets(),{width:l}=reactNative.useWindowDimensions(),u=hR(l),d=t.open,c=react.useRef(null);c.current===null&&(c.current=new reactNative.Animated.Value(s.drawerMs<=0&&d?1:0));let p=c.current;react.useEffect(()=>{if(!d&&s.drawerMs<=0){r();return}let P=reactNative.Animated.timing(p,{toValue:d?1:0,duration:s.drawerMs,easing:gR,useNativeDriver:true});return P.start(({finished:k})=>{k&&!d&&r();}),()=>P.stop()},[d,p,s.drawerMs,r]);let f=p.interpolate({inputRange:[0,1],outputRange:[-u,0]}),m=t.filtered,h=t.rows.length===0,T=t.cursor===null&&!t.loading&&t.error===null,b=h&&t.loading?jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,accessibilityLabel:q.loading,accessibilityState:{busy:true},children:[jsxRuntime.jsx(reactNative.ActivityIndicator,{color:o.emptyTitle.color}),jsxRuntime.jsx(E,{style:o.emptyBody,children:q.loading})]}):h&&t.error!==null?jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,children:[jsxRuntime.jsx(E,{style:o.emptyTitle,accessibilityRole:"alert",children:q.loadFailed}),jsxRuntime.jsx(E,{style:o.emptyBody,children:t.error}),jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:q.retryA11y,containerStyle:o.retrySlot,style:o.retryButton,onPress:()=>{t.load();},children:jsxRuntime.jsx(E,{tier:"control",style:o.retryText,children:q.retry})})]}):t.emptyKind==="empty"?jsxRuntime.jsxs(reactNative.View,{style:o.emptyCard,children:[jsxRuntime.jsx(E,{style:o.emptyTitle,children:q.empty}),jsxRuntime.jsx(E,{style:o.emptyBody,children:q.emptyBody})]}):jsxRuntime.jsx(E,{style:o.noMatch,children:q.noMatch}),S=!t.searching&&t.loadingMore?jsxRuntime.jsx(reactNative.View,{style:o.loadMoreFooter,children:jsxRuntime.jsx(E,{style:o.loadMoreLabel,children:q.loadingMore})}):null;return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:t.close,children:jsxRuntime.jsxs(reactNative.View,{style:o.root,children:[jsxRuntime.jsx(reactNative.Pressable,{style:Pe,onPress:t.close,accessibilityRole:"button",accessibilityLabel:q.closeA11y,children:jsxRuntime.jsx(reactNative.Animated.View,{style:[o.backdrop,{opacity:p}]})}),jsxRuntime.jsx(reactNative.Animated.View,{style:[o.panel,{width:u,paddingTop:Math.max(sR,a.top+n.space.md),transform:[{translateX:f}]}],accessibilityViewIsModal:true,children:jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:o.keyboardAvoider,behavior:reactNative.Platform.OS==="ios"?"padding":"height",children:[jsxRuntime.jsxs(reactNative.View,{style:o.header,children:[jsxRuntime.jsx(E,{tier:"heading",style:o.heading,accessibilityRole:"header",children:q.heading}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:q.newChat,style:o.newChat,onPress:t.newConversation,children:jsxRuntime.jsx(E,{tier:"control",style:o.newChatLabel,children:q.newChat})}),jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:q.close,hitSlop:0,style:o.closeButton,onPress:t.close,children:jsxRuntime.jsx(Qe,{size:cR,color:n.color.text.muted,strokeWidth:1.75})})]}),jsxRuntime.jsxs(reactNative.View,{style:o.searchPill,children:[jsxRuntime.jsx(ec,{size:mR,color:n.color.text.muted,strokeWidth:1.5}),jsxRuntime.jsx(Gt,{value:t.query,onChangeText:P=>t.setQuery(P.replace(/^\s+/,"")),style:o.searchInput,placeholder:q.searchPlaceholder,placeholderTextColor:n.color.text.placeholder,accessibilityLabel:q.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),jsxRuntime.jsx(E,{tier:"compact",style:o.countLabel,children:Ad(t.rows.length,T)}),t.error!==null&&!h?jsxRuntime.jsx(reactNative.View,{style:o.errorCard,children:jsxRuntime.jsx(E,{style:o.errorText,accessibilityRole:"alert",children:t.error})}):null,jsxRuntime.jsx(reactNative.FlatList,{data:m,keyExtractor:P=>P.id,renderItem:({item:P})=>jsxRuntime.jsx(vR,{row:P,active:P.id===e.conversationId,disabled:t.loading,styles:o,onPress:()=>{t.resume(P.id);}}),contentContainerStyle:m.length===0?o.listEmpty:o.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:b,ListFooterComponent:S,onEndReached:t.loadMore,onEndReachedThreshold:yR})]})})]})})}i(bR,"DrawerModal");function vR({row:e,active:t,disabled:r,styles:n,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0,a=Id(e);return jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:Od(e),accessibilityState:{selected:t,disabled:r},disabled:r,style:[n.item,t?n.itemActive:null],onPress:o,children:[jsxRuntime.jsxs(reactNative.View,{style:n.itemRow,children:[jsxRuntime.jsx(E,{tier:"control",style:n.itemTitle,numberOfLines:1,children:xn(e.title)}),s?jsxRuntime.jsx(reactNative.View,{style:n.unreadDot}):null]}),a!==null?jsxRuntime.jsx(E,{tier:"compact",style:n.itemMeta,numberOfLines:1,children:a}):null]})}i(vR,"Row");function ER(e){let t=e.color,r=e.space,n=e.type,o=e.slots,s=t.text.primary;return reactNative.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:aR},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:r.lg,borderRightWidth:reactNative.StyleSheet.hairlineWidth,borderRightColor:t.borderRingCream,gap:r.md},keyboardAvoider:{flex:1,gap:r.md},header:{flexDirection:"row",alignItems:"center",gap:r.sm},heading:{...R(e,"bold"),flex:1,fontSize:n.size.subtitle,color:s},newChat:{minHeight:fs,justifyContent:"center",paddingHorizontal:r.xs},newChatLabel:{...R(e,"bold"),fontSize:uR,color:t.brandInk},closeButton:{width:fs,height:fs,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:r.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:r.md+mt,paddingVertical:r.sm+mt,borderWidth:1,borderColor:t.borderRingCream},searchInput:{...R(e,"regular"),flex:1,fontSize:n.size.bodyTight,color:t.text.primary,padding:0},countLabel:{...R(e,"mono"),fontSize:dR,color:t.text.muted},list:{gap:r.xs,paddingBottom:r.xl},listEmpty:{flexGrow:1},item:{paddingVertical:r.sm+mt,paddingHorizontal:r.sm,borderRadius:e.radius.md,gap:mt},itemActive:{backgroundColor:ut(t.scanButtonPink,lR)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:r.sm},itemTitle:{...R(e,"bold"),flex:1,fontSize:n.size.bodyTight,color:s},itemMeta:{...R(e,"regular"),fontSize:n.size.caption,color:t.text.muted},unreadDot:{width:ms,height:ms,borderRadius:ms/2,backgroundColor:t.danger},errorCard:{borderRadius:fR,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:r.md},errorText:{...R(e,"regular"),fontSize:n.size.caption,color:t.danger},emptyCard:{borderRadius:pR,padding:r.md+mt,gap:r.xs+mt,backgroundColor:t.surfaceSubtle,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.borderRingCream},emptyTitle:{...R(e,"bold"),fontSize:n.size.bodyTight,color:s},emptyBody:{...R(e,"regular"),fontSize:n.size.caption,color:t.text.secondary},noMatch:{...R(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+mt,paddingVertical:r.sm,borderWidth:1,borderColor:t.brandInk,...me(o.primaryButton)},retryText:{...R(e,"bold"),fontSize:n.size.caption,color:t.brandInk,...ke(o.primaryButton)},loadMoreFooter:{paddingVertical:r.md+mt,alignItems:"center"},loadMoreLabel:{...R(e,"regular"),fontSize:n.size.caption,color:t.text.muted}})}i(ER,"makeStyles");var kR=Object.freeze({}),xR=100,_R=20;function wR(e,t,r,n){return ![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}i(wR,"readWindowTops");function Sp(e,t){let r=typeof e=="number"&&Number.isFinite(e),n=react.useRef(null),[o,s]=react.useState(null),a=react.useRef(null),l=react.useRef(null),u=react.useRef(true),d=react.useCallback(()=>{l.current!==null&&clearTimeout(l.current),l.current=null;},[]);react.useEffect(()=>(u.current=true,()=>{u.current=false,d();}),[d]);let c=react.useCallback(i(function f(m){n.current?.measureInWindow((h,T)=>{let b=a.current;if(!u.current||b===null)return;let S=wR(T,b.y,b.height,reactNative.Dimensions.get("window").height);if(S!==null){s(P=>P!==null&&P.chatTop===S.chatTop&&P.parentTop===S.parentTop?P:S);return}m>=_R||(l.current=setTimeout(()=>{l.current=null,f(m+1);},xR));});},"measureAt"),[]),p=react.useCallback(f=>{let{y:m,height:h}=f.nativeEvent.layout;a.current={y:m,height:h},d(),c(0);},[c,d]);return react.useMemo(()=>{if(!t)return {avoidingProps:r?{keyboardVerticalOffset:e}:kR,probeRef:null,topInWindow:null};let f=o?.parentTop??0;return {avoidingProps:r?{keyboardVerticalOffset:e,onLayout:p}:f>0?{keyboardVerticalOffset:f,onLayout:p}:{onLayout:p},probeRef:n,topInWindow:o?.chatTop??null}},[t,r,e,o,p])}i(Sp,"useChatKeyboardOffset");function Tp({probeRef:e}){return e===null?null:jsxRuntime.jsx(reactNative.View,{ref:e,collapsable:false,pointerEvents:"none",style:IR})}i(Tp,"KeyboardOffsetProbe");var IR=Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function Pp(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}i(Pp,"chatVetVisitOptions");var LR=.75,NR=1.5,DR=.4,UR=4,VR=1.5,Or=22,BR=14,HR=8,zR=20,jR=10,xp=13,WR=12,GR=15,KR=44,qR=14,$R=1.25,YR=14,XR=6;function QR(e,t){let r=e.color;return t.level==="emergency"?{card:{backgroundColor:r.badgeBgCritical,borderColor:ut(r.danger,DR)??r.danger,borderWidth:NR},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}}:{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:LR},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}i(QR,"tierPaint");function _p({surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o}){let s=N(),a=react.useMemo(()=>tS(s),[s]),l=te(),u=e.tier,d=e.source;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Bi,{visible:e.showBanner&&u!==null,inMs:l.bannerInMs,outMs:l.bannerOutMs,style:a.pinned,children:u!==null&&d!==null?jsxRuntime.jsx(ZR,{tier:u,reason:d.reason,surface:e,petRef:t,renderVetAction:r,onFindVet:n,vet:o,styles:a}):null}),jsxRuntime.jsx(Bi,{visible:e.showCompactIcon,inMs:l.iconInMs,outMs:l.iconOutMs,style:a.indicatorRow,children:jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:g.showLatestVetAlert,hitSlop:jR,onPress:e.expand,children:jsxRuntime.jsx(Xd,{size:zR,color:s.color.text.muted,strokeWidth:2})})})]})}i(_p,"UrgencyBanner");function ZR({tier:e,reason:t,surface:r,petRef:n,renderVetAction:o,onFindVet:s,vet:a,styles:l}){let u=N(),d=QR(u,e),c=jsxRuntime.jsx(eS,{tier:e,paint:d,petRef:n,onFindVet:s,vet:a,styles:l}),p=r.showVetAction?o!==void 0?jsxRuntime.jsx(xt,{render:()=>o(e.level),fallback:c,resetKey:e.level}):c:null,f=d.action!==null?jsxRuntime.jsx(JR,{paint:d.action,styles:l}):null;return jsxRuntime.jsxs(reactNative.View,{accessibilityRole:"alert",style:[l.card,d.card],children:[jsxRuntime.jsx(E,{tier:"control",style:[l.label,{color:d.label}],children:e.label}),t!==null?jsxRuntime.jsx(E,{style:[l.reason,{color:d.reason}],children:t}):null,p!==null||f!==null?jsxRuntime.jsxs(reactNative.View,{style:l.actions,children:[p,f]}):null,r.dismissLabel!==null?jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:r.dismissLabel,hitSlop:HR,containerStyle:l.closeSlot,style:l.closeButton,onPress:r.dismiss,children:jsxRuntime.jsx(Qe,{size:BR,color:d.close,strokeWidth:1.5})}):null]})}i(ZR,"BannerCard");function JR({paint:e,styles:t}){let r=i(()=>{try{reactNative.Linking.openURL(rd).catch(()=>{});}catch{}},"call");return jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:g.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:r,children:jsxRuntime.jsx(E,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:g.poisonControlNative})})}i(JR,"PoisonControl");function eS({tier:e,paint:t,petRef:r,onFindVet:n,vet:o,styles:s}){let a=N(),l=jn(Pp(r,o)),u=l.status==="opening",d=!l.available&&n!==void 0,c=l.available?()=>{l.open();}:n!==void 0?()=>{$(n,e.level);}:null;if(c===null)return null;let p=t.action;if(p!==null){let m=d?g.nearestEmergencyVet:g.findVet,h=Vn(a.slots.vetVisitButton)?.textColor??p.ink;return jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:d?g.nearestEmergencyVet:g.findVetA11y,accessibilityState:{busy:u},hitSlop:0,style:[s.action,{backgroundColor:p.fill,borderColor:p.edge},s.findVetSlotBox,u?s.findVetBusy:null],onPress:c,children:[jsxRuntime.jsx(Ni,{size:xp,color:h,strokeWidth:1.5}),jsxRuntime.jsx(E,{tier:"control",style:[s.actionLabel,{color:h}],children:m})]})}let f=Vn(a.slots.vetVisitButton)?.textColor??e.textColor;return jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:g.findVetA11y,accessibilityState:{busy:u},style:[s.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},s.findVetSlotBox,u?s.findVetBusy:null],onPress:c,children:[jsxRuntime.jsx(Ni,{size:xp,color:f,strokeWidth:1.5}),jsxRuntime.jsx(E,{tier:"control",style:[s.findVetLabel,{color:f}],children:g.findVet})]})}i(eS,"VetAction");function tS(e){let t=Vn(e.slots.vetVisitButton),r=e.space,n=e.type;return reactNative.StyleSheet.create({pinned:{marginTop:0,marginBottom:r.xs,paddingHorizontal:r.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:r.lg+UR,paddingVertical:r.lg,gap:r.sm},label:{...R(e,"bold"),fontSize:n.size.body,paddingRight:Or},reason:{...R(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*VR),paddingRight:Or},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.sm},action:{flexDirection:"row",alignItems:"center",gap:XR,minHeight:KR,paddingHorizontal:qR,borderRadius:e.radius.pill,borderWidth:$R},actionLabel:{...R(e,"bold"),fontSize:YR},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...me(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...R(e,"monoBold"),fontSize:WR,lineHeight:GR},closeSlot:{position:"absolute",top:r.md,right:r.md},closeButton:{width:Or,height:Or,borderRadius:Or/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:r.lg,paddingTop:2,paddingBottom:r.xs}})}i(tS,"makeStyles");function wp(){let e=Un(),{handle:t}=ee(),r=react.useCallback(n=>t.setActivePet(n),[t]);return react.useMemo(()=>({...e,setActivePet:r}),[e,r])}i(wp,"useChatPets");function sS(){try{let e=reactNative.AccessibilityInfo?.announceForAccessibility;typeof e=="function"&&e.call(reactNative.AccessibilityInfo,g.answered);}catch{}}i(sS,"announceAnswered");function Op(e){let t=react.useRef(false),r=react.useRef({send:e.send,id:e.conversationId});react.useEffect(()=>{let n=r.current;if((n.send!==e.send||n.id!==null&&n.id!==e.conversationId)&&(t.current=false),r.current={send:e.send,id:e.conversationId},t.current&&!e.isStreaming){let o=e.messages[e.messages.length-1];o!==void 0&&o.role==="assistant"&&sS();}t.current=e.isStreaming;},[e.isStreaming,e.messages,e.send,e.conversationId]);}i(Op,"useSettleAnnouncement");var Bp=300,Hp=3e3,Mp=120,Lr=44,lS=120,uS="88%",Lp=520,Qn=2,Zn=.5,dS=1.5,cS=1.6,pS=.6,fS=56,Np=1.5,mS=5,yS=5,Dp=36,gS=20,hS=14,Mr=Lr,Jn=4,zp=24,jp=22,bS=.4,Up=Lr,Wp=20,vS=.4,ES=480,CS=12,RS=.72,SS=48,Vp=1,TS=12,PS=18,kS="12%";function ge(){let e=N(),t=react.useMemo(()=>xS(e),[e]);return {theme:e,styles:t}}i(ge,"useChatTheme");function xS(e){let t=e.color,r=e.space,n=e.radius,o=e.type,s=Math.round(o.size.body*dS),a=Math.round(o.size.body*cS),l=Math.round(gS*o.size.body/hS),u=t.borderRingCream,d=e.slots;return reactNative.StyleSheet.create({container:{flex:1,minHeight:Mp,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Mp,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:kS,paddingHorizontal:r.lg,paddingBottom:r.lg,minHeight:ES,gap:r.lg},errorText:{...R(e,"regular"),fontSize:o.size.subtitle,lineHeight:o.size.subtitle*o.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:r.md},retryButton:{minHeight:Lr,minWidth:Lr,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.sm,borderRadius:n.pill,backgroundColor:t.brand,...me(d.primaryButton)},retryLabel:{...R(e,"medium"),color:t.onPrimary,fontSize:o.size.body,...ke(d.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,paddingHorizontal:r.lg,paddingVertical:r.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...R(e,"regular"),color:t.danger,fontSize:o.size.caption,flexShrink:1},turnNotice:{gap:r.xs,padding:r.md,borderRadius:n.lg,backgroundColor:t.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...R(e,"bold"),color:t.text.primary,fontSize:o.size.body},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...R(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal},turnNoticeAction:{minHeight:Lr,justifyContent:"center"},turnNoticeActionLabel:{...R(e,"medium"),color:t.brandInk,fontSize:o.size.body},setupNoticeAction:{...R(e,"medium"),color:t.brandInk,fontSize:o.size.caption},reconnectingCaption:{...R(e,"medium"),color:t.text.secondary,fontSize:o.size.caption,lineHeight:o.size.caption*o.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingLine:{...R(e,"regular"),color:t.text.muted,fontSize:o.size.bodyTight,lineHeight:Math.round(o.size.bodyTight*o.lineHeight.relaxed)},list:{flex:1},listContent:{padding:r.lg,gap:r.xl},rowBlock:{gap:r.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:r.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:uS,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:Lp,paddingVertical:r.md,paddingHorizontal:r.lg+Qn,backgroundColor:t.bubbleUser,borderRadius:n.lg,borderBottomRightRadius:n.xs,...me(d.userBubble,Zn)},bubbleAssistant:d.assistantBubble?.backgroundColor===void 0?{...me(d.assistantBubble,Zn)}:{paddingVertical:r.md,paddingHorizontal:r.lg+Qn,borderRadius:n.lg,...me(d.assistantBubble,Zn)},bubbleVet:{maxWidth:Lp,paddingVertical:r.md,paddingHorizontal:r.lg+Qn,backgroundColor:t.bubbleVet,borderRadius:n.lg,borderTopLeftRadius:n.xs,...me(d.vetBubble,Zn)},bubblePending:{opacity:pS},bubbleTextUser:{...R(e,"regular"),color:t.onPrimary,fontSize:o.size.body,lineHeight:s,...ke(d.userBubble)},bubbleTextAssistant:{...R(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:a,...ke(d.assistantBubble)},bubbleTextVet:{...R(e,"regular"),color:t.onBubbleVet,fontSize:o.size.body,lineHeight:s,...ke(d.vetBubble)},assistantName:{...R(e,"bold"),color:t.brandInk,fontSize:o.size.bodyTight,marginBottom:r.xs},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:r.sm,marginBottom:r.xs},vetSender:{...R(e,"bold"),color:t.text.primary,fontSize:o.size.bodyTight},vetTime:{...R(e,"regular"),color:t.text.muted,fontSize:o.size.caption},bubbleBold:R(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:R(e,"mono"),followUps:{alignSelf:"stretch",marginTop:r.md},followUpsHeading:{...R(e,"monoBold"),color:t.text.muted,fontSize:CS,textTransform:"uppercase",letterSpacing:RS,paddingBottom:r.sm,borderBottomWidth:Vp,borderBottomColor:u},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:Vp,borderTopColor:u},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,minHeight:SS,paddingVertical:r.sm+Qn},followUpText:{...R(e,"bold"),flex:1,color:t.brandInk,fontSize:o.size.bodyTight},composerOuter:{position:"relative"},composer:{marginHorizontal:r.md,marginTop:r.xs,minHeight:fS,justifyContent:"center",paddingLeft:r.sm,paddingRight:mS,paddingVertical:yS,backgroundColor:t.composerFill,borderWidth:Np,borderColor:t.composerBorder,borderRadius:n.pill,...me(d.composerInput,Np)},composerRow:{flexDirection:"row",alignItems:"center",gap:r.xs,minHeight:Dp},attachControl:{width:Up,height:Up,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:vS},input:{flex:1,minHeight:Dp,maxHeight:lS,paddingHorizontal:0,paddingVertical:0,...R(e,"regular"),fontSize:o.size.body,lineHeight:l,color:t.text.primary,...ke(d.composerInput)},sendControl:{minHeight:Mr,minWidth:Mr,alignItems:"center",justifyContent:"center"},sendDisc:{width:Mr,height:Mr,borderRadius:Mr/2,alignItems:"center",justifyContent:"center",...me(d.sendButton)},sendControlDisabled:{opacity:bS},footnote:{...R(e,"regular"),color:t.text.muted,fontSize:TS,lineHeight:PS,textAlign:"center",marginTop:r.sm,marginBottom:r.xs,paddingHorizontal:r.lg},poweredBy:{...R(e,"regular"),color:t.text.muted,fontSize:o.size.micro,textAlign:"center",paddingBottom:r.xs}})}i(xS,"makeStyles");var _S=Object.freeze({kind:"live"}),wS=Object.freeze({kind:"folded"});function gs(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=Io(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(gs,"askOf");function Kp(e){let t=new Map,r=new Map;for(let o of e){let s=gs(o);if(s===null)continue;let a=r.get(s.caseId);(a===void 0||s.dueDay>=a.dueDay)&&r.set(s.caseId,{messageId:o.id,dueDay:s.dueDay});}if(r.size===0)return t;let n=null;for(let o of e){let s=gs(o);if(s===null){n=null;continue}if(r.get(s.caseId)?.messageId===o.id){t.set(o.id,_S),n=null;continue}if(n!==null&&n.caseId===s.caseId){n.days.push(s.dueDay),t.set(o.id,wS);continue}let a=[s.dueDay];n={id:o.id,caseId:s.caseId,days:a},t.set(o.id,{kind:"past",runDueDays:a});}return t}i(Kp,"placeCheckins");var Gp=864e5,IS=365;function eo(e,t){if(typeof e!="string"||typeof t!="string")return null;let r=Date.parse(e),n=Date.parse(t);if(Number.isNaN(r)||Number.isNaN(n))return null;let o=Math.floor(n/Gp)-Math.floor(r/Gp);return o<1||o>IS?null:o}i(eo,"checkinDayNumber");function qp(e){return gs(e)?.dueDay||null}i(qp,"checkinDueDay");function to(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(to,"formatMessageTime");var xe=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" \xB7 ",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),$p=Object.freeze(en.map(e=>Object.freeze({answer:e,label:xe.answers[e]})));function Yp(e,t){let[r,n]=react.useState(null),[o,s]=react.useState(null),[a,l]=react.useState(null),u=react.useCallback(c=>{t!==null&&(n(c),s(null),t(e.caseId,c).then(p=>{n(null),p.ok?l(c):s(p.error);}));},[t,e.caseId]),d=a??e.answer;return {answer:d,answerable:!Ua(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(Yp,"useCheckinCard");var Zp=44,FS=.6;function ef({message:e,checkin:t,onAnswer:r,petRef:n,onFindVet:o,vet:s,onLayout:a}){let l=N(),u=react.useMemo(()=>MS(l),[l]),d=Yp(t,r),c=d.answer!==null||d.pending!==null,p=r!==null&&d.answerable,f=eo(t.openedAt,qp(e));return jsxRuntime.jsxs(reactNative.View,{style:u.card,accessibilityLabel:xe.eyebrow,onLayout:a,children:[jsxRuntime.jsxs(reactNative.View,{style:u.head,children:[jsxRuntime.jsx(E,{tier:"compact",style:u.eyebrow,children:xe.eyebrow}),f!==null?jsxRuntime.jsx(E,{tier:"compact",style:u.headDay,children:K(xe.day,{day:f})}):null]}),jsxRuntime.jsx(E,{style:u.question,accessibilityRole:"text",children:e.text}),p?jsxRuntime.jsx(reactNative.View,{style:[u.row,d.pending?u.rowPending:null],children:$p.map(({answer:m,label:h})=>{let T=(d.pending??d.answer)===m;return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>d.choose(m),disabled:c,accessibilityRole:"button",accessibilityLabel:h,accessibilityState:{selected:T,disabled:c,busy:d.pending===m},style:[u.pill,T?u.pillSelected:null],children:jsxRuntime.jsx(E,{tier:"control",style:[u.pillLabel,T?u.pillLabelSelected:null],children:h})},m)})}):null,d.answer!==null?jsxRuntime.jsx(E,{style:u.logged,children:xe.logged}):null,d.escalated?o!==void 0?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:xe.findVet,style:u.findVet,children:jsxRuntime.jsx(E,{tier:"control",style:u.findVetLabel,children:xe.findVet})}):n?jsxRuntime.jsx(Zt,{entry:"chat",petRef:n,label:xe.findVet,...s?.returnTo!==void 0?{returnTo:s.returnTo}:{},...s?.usState!==void 0?{usState:s.usState}:{},...s?.prefer!==void 0?{prefer:s.prefer}:{},style:u.findVet,labelStyle:u.findVetLabel}):null:null,t.resolutionText?jsxRuntime.jsx(E,{style:u.resolution,children:t.resolutionText}):null,d.error?jsxRuntime.jsx(E,{style:u.error,accessibilityRole:"alert",children:d.error.displayMessage}):null]})}i(ef,"CheckinCard");function MS(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return reactNative.StyleSheet.create({card:{maxWidth:"92%",padding:r.md,gap:r.sm,borderRadius:n.lg,backgroundColor:t.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},eyebrow:{...R(e,"regular"),color:t.text.secondary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},headDay:{...R(e,"bold"),color:t.text.primary,fontSize:o.size.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...R(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},row:{flexDirection:"row",gap:r.sm,marginTop:r.xs},rowPending:{opacity:FS},pill:{flex:1,minHeight:Zp,alignItems:"center",justifyContent:"center",paddingHorizontal:r.md,borderRadius:n.pill,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...R(e,"regular"),color:t.text.primary,fontSize:o.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...R(e,"regular"),color:t.text.secondary,fontSize:o.size.caption},resolution:{...R(e,"regular"),color:t.text.primary,fontSize:o.size.body,lineHeight:o.size.body*o.lineHeight.normal},error:{...R(e,"regular"),color:t.danger,fontSize:o.size.caption},findVet:{alignSelf:"stretch",minHeight:Zp,alignItems:"center",justifyContent:"center",borderRadius:n.pill,borderWidth:1.5,borderColor:t.brandBorder,backgroundColor:t.surface},findVetLabel:{...R(e,"bold"),color:t.brandInk,fontSize:o.size.body}})}i(MS,"makeStyles");var DS=1.5,US=3;function rf({text:e,runDueDays:t,openedAt:r,onLayout:n}){let o=N(),s=react.useMemo(()=>VS(o),[o]),a=t.map(u=>eo(r,u)).filter(u=>u!==null),l=t.length>1;return l&&a.length===0?null:jsxRuntime.jsxs(reactNative.View,{style:s.row,onLayout:n,children:[jsxRuntime.jsx(reactNative.View,{style:s.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),jsxRuntime.jsxs(reactNative.View,{style:s.body,children:[a.length>0?jsxRuntime.jsx(E,{tier:"compact",style:s.days,children:a.map(u=>K(xe.day,{day:u})).join(xe.daySeparator)}):null,l?null:jsxRuntime.jsx(E,{style:s.question,accessibilityRole:"text",children:e})]})]})}i(rf,"CheckinPastAsk");function VS(e){let t=e.color,r=e.space,n=e.type;return reactNative.StyleSheet.create({row:{flexDirection:"row",paddingVertical:r.xs},rule:{width:DS,borderRadius:1,backgroundColor:t.borderHairlineGreen,marginRight:r.md},body:{flex:1,gap:US},days:{...R(e,"monoMedium"),fontSize:n.size.nano,letterSpacing:n.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},question:{...R(e,"regular"),fontSize:n.size.bodyTight,lineHeight:n.size.bodyTight*n.lineHeight.normal,color:t.text.muted}})}i(VS,"makeStyles");var BS=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),nf="#C8BEB4";function HS(e){return e?BS[e.toUpperCase()]??nf:nf}i(HS,"tierColor");function zS(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(zS,"tierLabel");function We(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(We,"text");function jS(e){let t=We(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(jS,"httpsUrl");function WS(e,t){let r=We(e.source_name)??We(e.sourceName),n=We(e.section),o=We(e.authority_tier)??We(e.authorityTier),s=zS(o),a=r??We(e.title)??`Source ${t+1}`,l=We(e.monograph_chunk_id)??We(e.chunkId),u=[n,s].filter(d=>d!==null).join(" \xB7 ");return Object.freeze({title:a,sourceName:r,section:n,authorityTier:o,tierLabel:s,meta:u.length===0?null:u,url:jS(e.url),excerpt:We(e.excerpt),tierColor:HS(o),key:`${a}-${l??"none"}-${t}`})}i(WS,"toCitationCard");function of(e){return e===void 0||e.length===0?GS:Object.freeze(e.map((t,r)=>WS(t,r)))}i(of,"toCitationCards");var GS=Object.freeze([]);function Cs(e){return e===1?`1 ${g.sourceSingular}`:`${e} ${g.sourcePlural}`}i(Cs,"sourcesLabel");function sf(e,t){return `${t?g.hideSources:g.showSources} ${Cs(e)}`}i(sf,"sourcesToggleLabel");function af(e){return [e.url!==null?`${g.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(af,"citationA11yLabel");var XS=244,uf=8,df=13,QS=14,ZS=.3,JS=-0.24,eT=22,tT=10,rT=15;function cf({citations:e,onOpenUrl:t}){let r=N(),n=react.useMemo(()=>iT(r),[r]),o=react.useMemo(()=>of(e),[e]),[s,a]=react.useState(false);if(o.length===0)return null;let l=o.length;return jsxRuntime.jsxs(reactNative.View,{style:n.block,children:[jsxRuntime.jsxs(z,{accessibilityRole:"button",accessibilityLabel:sf(l,s),accessibilityState:{expanded:s},containerStyle:n.toggleSlot,style:n.togglePill,onPress:()=>a(u=>!u),children:[jsxRuntime.jsx(qd,{size:df,color:r.color.brandInk,strokeWidth:1.5}),jsxRuntime.jsx(E,{tier:"compact",style:n.toggleLabel,children:Cs(l)}),jsxRuntime.jsx(Kd,{size:df,color:r.color.brandInk,strokeWidth:1.5,direction:s?"up":"down"})]}),s?jsxRuntime.jsx(nT,{cards:o,styles:n,open:t}):null]})}i(cf,"CitationCards");function nT({cards:e,styles:t,open:r}){let n=te(),o=Yt(n.citationsInMs,{risePx:n.citationsRisePx});return jsxRuntime.jsx(reactNative.Animated.View,{style:o,children:jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(s=>jsxRuntime.jsx(oT,{card:s,styles:t,open:r},s.key))})})}i(nT,"Deck");function oT({card:e,styles:t,open:r}){let n=N(),o=e.url!==null&&r!==void 0,s=af(o?e:{...e,url:null}),a=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(reactNative.View,{style:t.cardHeader,children:[jsxRuntime.jsx(reactNative.View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),jsxRuntime.jsx(E,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?jsxRuntime.jsx($d,{size:QS,color:n.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?jsxRuntime.jsx(E,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?jsxRuntime.jsx(E,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&r!==void 0){let l=e.url;return jsxRuntime.jsx(z,{accessibilityRole:"link",accessibilityLabel:s,style:t.card,onPress:()=>r(l),children:a})}return jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}i(oT,"Card");function iT(e){let t=e.color,r=e.space,n=e.radius,o=e.type.size;return reactNative.StyleSheet.create({block:{gap:r.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:n.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:r.xs+2,paddingHorizontal:r.md,paddingVertical:r.xs+2,borderRadius:n.pill,backgroundColor:t.brandSoft},toggleLabel:{...R(e,"monoBold"),fontSize:o.micro,lineHeight:o.micro,letterSpacing:ZS,color:t.brandInk,textTransform:"uppercase"},row:{gap:r.sm,paddingRight:r.xl,paddingTop:r.xs},card:{width:XS,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.md,gap:r.xs+2},cardHeader:{flexDirection:"row",alignItems:"center",gap:r.sm},tierDot:{width:uf,height:uf,borderRadius:n.pill},cardTitle:{...R(e,"bold"),flex:1,fontSize:o.bodyTight,lineHeight:eT,color:t.text.primary,letterSpacing:JS},cardTitleLink:{color:t.linkInk},cardMeta:{...R(e,"monoMedium"),fontSize:o.nano,lineHeight:tT,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase"},cardExcerpt:{...R(e,"regular"),fontSize:o.tiny,lineHeight:rT,color:t.text.muted}})}i(iT,"makeStyles");var Nr=15,cT=15,pT=6,fT=Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function gf({message:e,onCopy:t,sentiment:r=null,onSentiment:n,thanks:o=false}){let s=N(),a=react.useMemo(()=>mT(s),[s]),l=te(),u=e.role==="user",d=react.useMemo(()=>to(e.createdAt),[e.createdAt]),c=t!==void 0&&e.role!=="vet"&&e.text.length>0,p=e.role==="assistant"&&n!==void 0&&e.responseId!==void 0,[f,m]=react.useState(false),h=react.useRef(null);react.useEffect(()=>()=>{h.current&&clearTimeout(h.current);},[]);let T=i(()=>{t!==void 0&&(qt(t,e.text),m(true),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{m(false),h.current=null;},l.copiedMs));},"copy");return d===null&&!c&&!p?null:jsxRuntime.jsxs(reactNative.View,{style:a.wrap,children:[jsxRuntime.jsxs(reactNative.View,{style:[a.row,u?a.rowUser:a.rowAssistant],children:[d!==null?jsxRuntime.jsx(E,{tier:"compact",style:a.timestamp,children:d}):null,c?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:f?g.copied:u?g.copyUserMessage:g.copyAssistantMessage,hitSlop:cT,onPress:T,style:a.iconHit,children:f?jsxRuntime.jsx(pt,{size:Nr,color:s.color.success,strokeWidth:2}):jsxRuntime.jsx(Yd,{size:Nr,color:s.color.text.timestamp,strokeWidth:1.5})}):null,p?nd.map(({sentiment:b,label:S})=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:S,accessibilityState:{selected:r===b},hitSlop:pT,onPress:()=>n?.(b),style:a.iconHit,children:jsxRuntime.jsx(An,{size:Nr,color:s.color.sentiment[b],active:r===b,rotate:fT[b],strokeWidth:1.5})},b)):null]}),o?jsxRuntime.jsx(E,{style:a.thanks,accessibilityLiveRegion:"polite",children:g.feedbackThanks}):null]})}i(gf,"MessageFooter");function mT(e){let t=e.type;return reactNative.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...R(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:Nr,height:Nr,alignItems:"center",justifyContent:"center"},thanks:{...R(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary}})}i(mT,"makeStyles");var hf="#10462E";var bf="#000000",yT="#83E0B4",gT=Object.freeze([Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:yT,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:hf,brandEdge:true,borderWidth:1}),Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}\u2019s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]),hT=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function bT(e){return e==null?e:e.replace(hT,"").trim()}i(bT,"formatBreedForPrompt");var vT=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 ET(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return vT.has(t)}i(ET,"isUninformativeBreed");function CT(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(CT,"unspecifiedBreedLabel");function RT(e,t){return ET(e)?CT(t):String(e).replace(/\s+/gu," ").trim()}i(RT,"resolveBreedLabel");function vf(e){let t=e?.name?.trim()||g.emptyTitlePetFallback;return K(g.emptyTitle,{petName:t})}i(vf,"emptyStateTitle");function Ef(e,t=hf){let r=ts(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,s=o||n,a=RT(bT(e?.breed),r)||null,l=rs(e?.ageYears),u=l===null?null:String(l);return Object.freeze(gT.map(d=>{let c=d.label.includes("{breed}"),p=d.label.includes("{ageYears}"),m=d.fallbackLabel!==void 0&&(c&&!a||p&&!u)&&d.fallbackLabel?d.fallbackLabel:d.label,h=K(m,{petName:s,breed:a??n,species:r,ageYears:u??""}),T=!o&&m.startsWith("{petName}")?h.charAt(0).toUpperCase()+h.slice(1):h;return Object.freeze({id:d.id,intent:d.intent,label:T,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(Ef,"resolveQuickPrompts");var TT=44,Sf=0,PT=1,kT=.28,xT=2,_T=2,wT=1.3,IT=-0.015;function Tf({pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o}){let s=N(),a=react.useMemo(()=>OT(s),[s]),l=react.useMemo(()=>Ef(e,s.color.brandInk),[e,s.color.brandInk]),u=vf(e);return jsxRuntime.jsxs(reactNative.View,{style:a.block,children:[jsxRuntime.jsx(E,{tier:"heading",style:a.title,accessibilityRole:"header",children:u}),jsxRuntime.jsx(reactNative.View,{style:a.list,accessibilityLabel:g.suggestions,children:l.map((d,c)=>jsxRuntime.jsx(AT,{prompt:d,index:c,petRef:t,onSend:r,onVetPrep:n,vet:o,pet:e,styles:a},d.id))})]})}i(Tf,"QuickPrompts");function AT({prompt:e,index:t,pet:r,petRef:n,onSend:o,onVetPrep:s,vet:a,styles:l}){let u=te(),d=Yt(u.followUpInMs,{delayMs:Fn(u,t),risePx:u.promptRisePx}),c={backgroundColor:e.background};return e.intent==="vet_report"?s!==void 0?jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:Sf,style:[l.chip,l.chipEdge,c],onPress:()=>{$(s,r);},children:jsxRuntime.jsx(E,{tier:"compact",style:l.chipLabel,children:e.label})})}):n===null?null:jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(Zt,{entry:"chat",petRef:n,label:e.label,...a?.returnTo!==void 0?{returnTo:a.returnTo}:{},...a?.usState!==void 0?{usState:a.usState}:{},...a?.prefer!==void 0?{prefer:a.prefer}:{},style:[l.chip,l.chipEdge,c],labelStyle:l.chipLabel})}):jsxRuntime.jsx(reactNative.Animated.View,{style:d,children:jsxRuntime.jsx(z,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:Sf,style:[l.chip,l.chipEdge,c],onPress:()=>o(e.label),children:jsxRuntime.jsx(E,{tier:"compact",style:l.chipLabel,children:e.label})})})}i(AT,"Chip");function OT(e){let t=e.color,r=e.space,n=e.type;return reactNative.StyleSheet.create({block:{gap:r.lg,alignItems:"stretch",width:"100%"},title:{...R(e,"medium"),fontSize:n.size.heading,lineHeight:Math.round(n.size.heading*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.size.heading*IT,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:r.sm+xT},chip:{borderRadius:e.radius.pill,paddingHorizontal:r.lg+_T,paddingVertical:r.sm,minHeight:TT,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:PT,borderColor:ut(t.brandInk,kT)??t.borderRingCream},chipLabel:{...R(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*wT),color:bf,textAlign:"left"}})}i(OT,"makeStyles");var Ss=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function Pf(e){return e.includes("*")||e.includes("`")}i(Pf,"hasInlineMarkup");function kf(e){let t=[],r=0;Ss.lastIndex=0;for(let n=Ss.exec(e);n!==null;n=Ss.exec(e)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});let o=n[1],s=n[2],a=n[3];o!==void 0?t.push({kind:"bold",text:o}):s!==void 0?t.push({kind:"italic",text:s}):a!==void 0&&t.push({kind:"code",text:a}),r=n.index+n[0].length;}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}i(kf,"tokenizeInlineMarkdown");function xf(e,t){return Pf(e)?kf(e).map((r,n)=>{switch(r.kind){case "bold":return jsxRuntime.jsx(E,{style:t.bold,children:r.text},n);case "italic":return t.italic?jsxRuntime.jsx(E,{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsxRuntime.jsx(E,{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(xf,"renderInlineMarkdown");function _f({petName:e=null}){let{styles:t}=ge(),r=Tn(g.reading,e);return jsxRuntime.jsx(E,{tier:"compact",style:t.readingLine,accessibilityRole:"text",accessibilityLabel:r,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:r})}i(_f,"TypingIndicator");function wf(e,t,r){let n=e-r,o=t!=null?Math.min(n,t):n;return Math.max(0,o)}i(wf,"resolveTurnScrollTarget");function If(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return {assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}i(If,"latestTurn");function Af(e,t,r){let n=Math.max(0,r),o=e===null?n:Math.min(Math.max(0,e),n);return o>t+1?o:null}i(Af,"nextFollowOffset");function Of(e,t){let r=react.useRef(null),n=react.useRef(true),o=react.useRef(t),s=react.useRef(0),a=react.useRef(0),l=react.useRef(0),u=react.useRef(new Map),d=If(e),c=d===null?null:e[d.assistantIndex]?.id??null,p=d===null||d.userIndex===null?null:e[d.userIndex]?.id??null,f=react.useCallback(()=>{let k=r.current;if(k===null||!n.current||a.current===0)return;let x=null;if(c!==null){let _=u.current.get(c);if(_===void 0)return;let A=p===null?null:u.current.get(p)??null;x=wf(_,A,96);}let y=Af(x,s.current,l.current-a.current);y!==null&&(s.current=y,k.scrollTo({y,animated:false}));},[c,p]);react.useEffect(()=>{t&&!o.current&&(n.current=true),o.current=t,f();},[e,t,f]);let m=react.useCallback(k=>{a.current=k.nativeEvent.layout.height,f();},[f]),h=react.useCallback((k,x)=>{l.current=x,a.current>0&&(s.current=Math.min(s.current,Math.max(0,x-a.current))),f();},[f]),T=react.useCallback(k=>{s.current=k.nativeEvent.contentOffset.y;},[]),b=react.useCallback(()=>{n.current=false;},[]),S=react.useCallback(k=>{let{contentOffset:x,contentSize:y,layoutMeasurement:_}=k.nativeEvent;s.current=x.y,n.current=y.height-x.y-_.height<=24;},[]),P=react.useCallback(k=>x=>{u.current.set(k,x.nativeEvent.layout.y),(k===c||k===p)&&f();},[c,p,f]);return {ref:r,onLayout:m,onContentSizeChange:h,onScroll:T,onScrollBeginDrag:b,onScrollEnd:S,rowLayout:P}}i(Of,"useThreadFollow");function Df(e,t,r){switch(e){case "loading":return r.renderPending?jsxRuntime.jsx(xt,{render:r.renderPending,fallback:jsxRuntime.jsx(Mf,{})}):jsxRuntime.jsx(Mf,{});case "empty":return jsxRuntime.jsx(zT,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet});case "error":return jsxRuntime.jsx(GT,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case "populated":return jsxRuntime.jsx(KT,{messages:t.messages,prompts:Hd(t),onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,thanksFor:r.thanksFor,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl,petName:r.shownPet?.name??null});default:return at(e)}}i(Df,"renderView");function Mf(){let{theme:e,styles:t}=ge(),[r,n]=react.useState(false);return react.useEffect(()=>{let o=setTimeout(()=>n(true),Bp);return ()=>clearTimeout(o)},[]),jsxRuntime.jsx(reactNative.View,{style:t.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:g.loading,children:r?jsxRuntime.jsx(reactNative.ActivityIndicator,{color:e.color.brandInk}):null})}i(Mf,"LoadingState");function zT({pet:e,petRef:t,onSelectPrompt:r,onVetPrep:n,vet:o}){let{styles:s}=ge();return jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:s.emptyContent,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,accessibilityLabel:g.empty,children:jsxRuntime.jsx(Tf,{pet:e,petRef:t,onSend:r,onVetPrep:n,vet:o})})}i(zT,"EmptyState");function jT({prompts:e,onSelectPrompt:t}){let{styles:r}=ge();return e.length===0?null:jsxRuntime.jsxs(reactNative.View,{style:r.followUps,children:[jsxRuntime.jsx(E,{tier:"compact",style:r.followUpsHeading,accessibilityRole:"header",children:g.followUpsHeadingNative}),e.map((n,o)=>jsxRuntime.jsx(WT,{prompt:n,index:o,onSelectPrompt:t},n))]})}i(jT,"FollowUps");function WT({prompt:e,index:t,onSelectPrompt:r}){let{theme:n,styles:o}=ge(),s=te(),a=Yt(s.followUpInMs,{delayMs:Fn(s,t)});return jsxRuntime.jsx(reactNative.Animated.View,{style:a,children:jsxRuntime.jsxs(z,{onPress:()=>r(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[o.followUpSlot,t>0?o.followUpSlotRuled:null],style:o.followUpRow,children:[jsxRuntime.jsx(E,{tier:"control",style:o.followUpText,children:e}),jsxRuntime.jsx(In,{size:XT,color:n.color.text.muted,strokeWidth:1.75})]})})}i(WT,"FollowUpRow");function GT({error:e,onRetry:t,onAddPet:r}){let{styles:n}=ge(),o=pd(e)?Ed(r):void 0;return jsxRuntime.jsxs(reactNative.View,{style:n.centered,accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(E,{style:n.errorText,children:e.displayMessage}),o!==void 0?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:g.addPet,style:n.retryButton,children:jsxRuntime.jsx(E,{tier:"control",style:n.retryLabel,children:g.addPet})}):null,e.retryable?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:g.retry,style:n.retryButton,children:jsxRuntime.jsx(E,{tier:"control",style:n.retryLabel,children:g.retry})}):null]})}i(GT,"ErrorState");function KT({messages:e,prompts:t,onSelectPrompt:r,isStreaming:n,onAnswerCheckin:o,onCopy:s,sentimentByMessage:a,onSentiment:l,thanksFor:u,imagesByMessage:d,onPreview:c,notice:p,reconnecting:f,onRetry:m,onStartNew:h,petRef:T,onFindVet:b,vet:S,onOpenUrl:P,petName:k}){let{styles:x}=ge(),y=te();Pr(e.length,y);let _=react.useMemo(()=>Kp(e),[e]),A=Bd(e,n),O=e[e.length-1],F=react.useMemo(()=>e.filter(I=>!(I.checkin&&_.get(I.id)?.kind==="folded")),[e,_]),C=Of(F,n),w=pc(F);return jsxRuntime.jsxs(reactNative.ScrollView,{ref:C.ref,style:x.list,contentContainerStyle:x.listContent,accessibilityLabel:g.transcript,keyboardShouldPersistTaps:"handled",nestedScrollEnabled:true,onLayout:C.onLayout,onContentSizeChange:C.onContentSizeChange,onScroll:C.onScroll,scrollEventThrottle:YT,onScrollBeginDrag:C.onScrollBeginDrag,onScrollEndDrag:C.onScrollEnd,onMomentumScrollEnd:C.onScrollEnd,children:[e.map(I=>{let H=I.checkin?_.get(I.id):void 0;return H?.kind==="folded"?null:H?.kind==="past"?jsxRuntime.jsx(rf,{text:I.text,runDueDays:H.runDueDays,openedAt:I.checkin?.openedAt,onLayout:C.rowLayout(I.id)},I.id):I.checkin&&H!==void 0?jsxRuntime.jsx(ef,{message:I,checkin:I.checkin,onAnswer:o,petRef:T,onFindVet:b,vet:S,onLayout:C.rowLayout(I.id)},I.id):jsxRuntime.jsx(QT,{onLayout:C.rowLayout(I.id),message:I,revealing:n&&I===O&&I.role==="assistant",onCopy:s,sentiment:I.responseId===void 0?null:a[String(I.responseId)]??null,onSentiment:l,thanks:u!==null&&I.responseId!==void 0&&String(I.responseId)===u,images:d[I.id]??$T,onPreview:c,onOpenUrl:P,entering:w(I.id)},I.id)}),f?jsxRuntime.jsx(E,{tier:"compact",style:x.reconnectingCaption,accessibilityRole:"text",children:g.reconnecting}):null,A?jsxRuntime.jsx(_f,{petName:k}):null,p!==null?jsxRuntime.jsx(qT,{notice:p,onRetry:m,onStartNew:h}):null,jsxRuntime.jsx(jT,{prompts:t,onSelectPrompt:r})]})}i(KT,"PopulatedState");function qT({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=ge(),o=e.tone==="error";return jsxRuntime.jsxs(reactNative.View,{style:[n.turnNotice,o?n.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(E,{tier:"control",style:[n.turnNoticeTitle,o?n.turnNoticeTitleError:null],children:e.title}),jsxRuntime.jsx(E,{tier:"compact",style:n.turnNoticeBody,children:e.body}),jsxRuntime.jsx(reactNative.Pressable,{onPress:e.action==="startNew"?r:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Jn,style:n.turnNoticeAction,children:jsxRuntime.jsx(E,{tier:"control",style:n.turnNoticeActionLabel,children:e.actionLabel})})]})}i(qT,"TurnNoticeCard");var $T=Object.freeze([]),YT=16,XT=18;function QT({message:e,revealing:t,onCopy:r,sentiment:n,onSentiment:o,thanks:s,images:a,onPreview:l,onOpenUrl:u,onLayout:d,entering:c}){let{theme:p,styles:f}=ge(),m=te(),h=cc(c,m),T=fc(e.text,t,m),b=e.role==="user",S=e.role==="vet",P=e.role==="assistant",k=P&&!p.meta.hidePoweredBy,x=b?g.senderUser:S?zd(e):k?g.assistantName:g.senderAssistant,y=S?to(e.createdAt):null,_=react.useCallback(O=>o(e,O),[o,e]),A=e.pending!==true;return jsxRuntime.jsxs(reactNative.View,{style:[f.rowBlock,b?f.rowBlockUser:f.rowBlockAssistant],onLayout:d,children:[jsxRuntime.jsx(reactNative.View,{style:[f.row,b?f.rowUser:f.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${x}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:jsxRuntime.jsxs(reactNative.Animated.View,{style:[f.bubble,b?f.bubbleSideUser:null,h],children:[k?jsxRuntime.jsx(E,{tier:"control",style:f.assistantName,children:g.assistantName}):null,S?jsxRuntime.jsxs(reactNative.View,{style:f.vetHeader,children:[jsxRuntime.jsx(E,{tier:"control",style:f.vetSender,children:x}),y!==null?jsxRuntime.jsx(E,{tier:"compact",style:f.vetTime,children:y}):null]}):null,jsxRuntime.jsxs(reactNative.View,{style:[b?f.bubbleUser:S?f.bubbleVet:f.bubbleAssistant,e.pending?f.bubblePending:null],children:[b&&a.length>0?jsxRuntime.jsx(Ic,{images:a,onPreview:O=>l({uri:O.uri,label:O.filename})}):null,jsxRuntime.jsx(E,{style:b?f.bubbleTextUser:S?f.bubbleTextVet:f.bubbleTextAssistant,children:P?xf(T,{bold:f.bubbleBold,italic:f.bubbleItalic,code:f.bubbleCode}):e.text})]})]})}),P&&!t?jsxRuntime.jsx(cf,{citations:e.citations,onOpenUrl:u}):null,A?jsxRuntime.jsx(gf,{message:e,onCopy:r,sentiment:n,onSentiment:e.responseId===void 0?void 0:_,thanks:s}):null]})}i(QT,"MessageRow");var rP=Object.freeze(["photo"]),nP=1;function Vf(e){let{style:t,renderPending:r}=e;return jsxRuntime.jsx(Si,{capability:"chat",style:t,...r?{renderPending:r}:{},children:jsxRuntime.jsx(oP,{...e})})}i(Vf,"EverfurChat");function oP({petRef:e,conversationId:t,style:r,renderPending:n,onCopy:o,onPetChange:s,onVetPrep:a,onFindVet:l,renderVetAction:u,attachments:d,pet:c,onAddPet:p,checkinTarget:f,initialAsk:m,composerSeed:h,lifecycle:T,draftStore:b,vetReturnTo:S,vetUsState:P,vetPrefer:k,onOpenUrl:x,keyboardVerticalOffset:y}){let{theme:_,styles:A}=ge(),O=te(),F=react.useMemo(()=>jd(e,t),[e,t]),C=Rr(F),w=Ud(C),I=wp(),H=Fd(C),Q=reactNativeSafeAreaContext.useSafeAreaInsets(),oe=Vd(C),Y=react.useMemo(()=>l===void 0?void 0:()=>{$(l,"emergency");},[l]),we=react.useMemo(()=>S===void 0&&P===void 0&&k===void 0?void 0:{returnTo:S,usState:P,prefer:k},[S,P,k]),it=ds(I.pets,C.petRef),he=react.useMemo(()=>Nd(C.messages,it?.name??null),[C.messages,it?.name]),st=Dd(he);Op(C),Pr(st.showBanner,O),Td(C.openCheckin,f),hd(C.askEverfur,C.isBootstrapping,m);let Vr=react.useMemo(()=>Ai(h),[h]);Rd(T,{conversationId:C.conversationId===null?null:String(C.conversationId),isTurnInFlight:C.isStreaming,refresh:C.refreshActiveThread});let Br=(C.hasUnreadThreads??false)||H.rows.some(Se=>Se.unreadCount!==null&&Se.unreadCount>0)||(C.unreadCount??0)>0,Lt=yd(C.messages),[Jt,io]=react.useState(null),Hf=react.useCallback(()=>io(null),[]),[er,so]=react.useState(null),[zf,xs]=react.useState(null),Nt=react.useRef(null);react.useEffect(()=>()=>{Nt.current&&clearTimeout(Nt.current);},[]);let _s=react.useCallback(Se=>{xs(String(Se)),Nt.current&&clearTimeout(Nt.current),Nt.current=setTimeout(()=>{xs(null),Nt.current=null;},Hp);},[]),jf=react.useCallback((Se,zr)=>{let tr=Se.responseId;if(tr===void 0)return;let Yf=C.sentimentByMessage[String(tr)];C.feedback(tr,zr),zr==="down"&&Yf!=="down"&&so(tr);},[C]),Wf=react.useCallback(async(Se,zr)=>er===null||!(await C.feedback(er,"down",Se??"other",zr)).ok?false:(so(null),_s(er),true),[C,er,_s]),Gf=react.useCallback(()=>so(null),[]),Kf=react.useCallback(Se=>{C.send(Se);},[C.send]),qf=react.useMemo(()=>x===void 0?void 0:Se=>{$(x,Se,"citation");},[x]),ws=reactNative.Platform.OS==="ios"?"padding":void 0,Hr=Sp(y,ws!==void 0),$f=Hr.topInWindow===null?Q.top:Math.max(0,Q.top-Hr.topInWindow),Is={send:C.send,stop:C.stop,isStreaming:C.isStreaming,conversationId:C.conversationId,seed:Vr,draftStore:b,onStage:Lt.stage,onPreview:io,petName:it?.name??null};return jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:[A.container,{paddingTop:$f},r],behavior:ws,...Hr.avoidingProps,children:[jsxRuntime.jsx(Tp,{probeRef:Hr.probeRef}),jsxRuntime.jsx(mp,{pets:I,petRef:C.petRef,historyUnread:Br,onOpenHistory:H.show,onPetChange:s,onAddPet:p,vet:we}),c!==void 0?jsxRuntime.jsx(iP,{petRef:e??null,pet:c,onRegistered:I.refresh}):null,jsxRuntime.jsx(_p,{surface:st,petRef:C.petRef,renderVetAction:u,onFindVet:l,vet:we}),jsxRuntime.jsx(reactNative.View,{style:A.body,children:Df(w,C,{notice:oe,vet:we,onCheckinFindVet:Y,onSelectPrompt:Kf,renderPending:n,shownPet:it,onVetPrep:a,onCopy:o,onSentiment:jf,thanksFor:zf,imagesByMessage:Lt.byMessage,onPreview:io,onAddPet:p,onOpenUrl:qf})}),d!==void 0?jsxRuntime.jsx(sP,{...Is,attachments:d}):jsxRuntime.jsx(Bf,{...Is,attachments:null}),jsxRuntime.jsx(E,{tier:"compact",style:A.footnote,accessibilityRole:"text",children:g.footnoteNative}),_.meta.hidePoweredBy?null:jsxRuntime.jsx(E,{tier:"compact",style:A.poweredBy,accessibilityRole:"text",accessibilityLabel:g.poweredBy,children:g.poweredBy}),jsxRuntime.jsx(Rp,{chat:C,history:H}),jsxRuntime.jsx(Ep,{visible:er!==null,onSubmit:Wf,onSkip:Gf}),jsxRuntime.jsx(mc,{uri:Jt?.uri??null,label:Jt?.label??"",onClose:Hf}),jsxRuntime.jsx(xr,{})]})}i(oP,"ChatBody");function iP({petRef:e,pet:t,onRegistered:r}){let{styles:n}=ge(),o=fd(e,t,r);return o.status!=="failed"||o.error===null?null:jsxRuntime.jsxs(reactNative.View,{style:n.setupNotice,accessible:true,accessibilityRole:"alert",children:[jsxRuntime.jsx(E,{tier:"compact",style:n.setupNoticeText,children:o.error.displayMessage}),jsxRuntime.jsx(reactNative.Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:g.retry,hitSlop:Jn,children:jsxRuntime.jsx(E,{tier:"control",style:n.setupNoticeAction,children:g.retry})})]})}i(iP,"PetSetupNotice");function sP({attachments:e,...t}){let r=react.useMemo(()=>Oc(),[]),n=Pn({maxPerMessage:e.maxPerMessage??nP,transport:r}),o=react.useMemo(()=>({state:n,sources:e.sources??rP,pick:e.pick}),[n,e.sources,e.pick]);return jsxRuntime.jsx(Bf,{...t,attachments:o})}i(sP,"ComposerWithAttachments");function Bf({send:e,stop:t,isStreaming:r,conversationId:n,attachments:o,seed:s,draftStore:a,onStage:l,onPreview:u,petName:d}){let{theme:c,styles:p}=ge(),f=te(),[m,h]=xd(e,n,s);_d(a,n===null?null:String(n),m,h);let[T,b]=react.useState(false),[S,P]=react.useState(false);react.useEffect(()=>{P(false);},[n]);let k=c.meta.placeholder??Tn(g.placeholder,d),x=o?.state.uploading??false,y=o?.state.failed??false,_=x||y,A=o?.state.attachments??aP;Pr(A.length,f);let O=react.useCallback(()=>{if(m.trim().length===0||_||[...m].length>Ht)return;let oe=o?.state.s3Keys??lP;o!==null&&oe.length>0?(l(o.state.attachments.filter(Y=>Y.status==="uploaded").map(Y=>({uri:Y.previewUri,filename:Y.filename}))),e(m,{imageS3Keys:oe}),o.state.clear()):e(m),h(""),P(false);},[m,e,_,o,l]),F=react.useCallback(()=>{t();},[t]),C=react.useCallback(oe=>{b(false),o!==null&&(P(false),o.state.dismissRejected(),qt(o.pick,oe).then(Y=>{if(!Y.ok){P(true);return}Y.value!==null&&o.state.add(Y.value);}));},[o]),I=react.useMemo(()=>[...m].length>Ht,[m])||_,H=o!==null&&A.length>=o.state.maxPerMessage,Q=c.slots.sendButton?.textColor??c.color.brandInk;return jsxRuntime.jsxs(reactNative.View,{style:p.composerOuter,children:[o!==null&&T?jsxRuntime.jsx(hc,{sources:o.sources,full:H,onPick:C,onClose:()=>b(false)}):null,jsxRuntime.jsxs(reactNative.View,{style:p.composer,children:[o!==null?jsxRuntime.jsx(wc,{attachments:A,rejected:S?uP:o.state.rejected,uploadFailed:y,onRetry:o.state.retry,onRemove:o.state.remove,onPreview:oe=>u({uri:oe.previewUri,label:oe.filename})}):null,jsxRuntime.jsxs(reactNative.View,{style:p.composerRow,children:[o!==null?jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:H?ud(A.length,o.state.maxPerMessage):g.attachPhotoOrFileNative,accessibilityState:{disabled:H,expanded:T},disabled:H,style:[p.attachControl,H?p.attachControlDisabled:null],onPress:()=>b(oe=>!oe),children:jsxRuntime.jsx(Qd,{size:Wp,color:H?c.color.text.muted:c.color.brandInk,strokeWidth:1.75})}):null,jsxRuntime.jsx(Gt,{style:p.input,value:m,onChangeText:h,placeholder:k,placeholderTextColor:c.slots.composerInput?.textColor??c.color.text.placeholder,accessibilityLabel:g.composerLabel,onSubmitEditing:O,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),r?jsxRuntime.jsx(reactNative.Pressable,{onPress:F,accessibilityRole:"button",accessibilityLabel:g.stop,style:p.sendControl,children:jsxRuntime.jsx(reactNative.View,{style:p.sendDisc,testID:"everfur-stop-disc",children:jsxRuntime.jsx(rc,{size:jp,color:Q,testID:"everfur-stop-glyph"})})}):jsxRuntime.jsx(reactNative.Pressable,{onPress:O,disabled:I,accessibilityRole:"button",accessibilityLabel:g.send,accessibilityState:{disabled:I,busy:x},style:[p.sendControl,I?p.sendControlDisabled:null],children:jsxRuntime.jsx(reactNative.View,{style:p.sendDisc,testID:"everfur-send-disc",children:jsxRuntime.jsx(tc,{size:zp,color:Q,testID:"everfur-send-glyph"})})})]})]})]})}i(Bf,"Composer");var aP=Object.freeze([]),lP=Object.freeze([]),uP=Object.freeze({code:"unknown",retryable:true,filename:""});function mP(e){let{runtime:t,userRef:r,scopeEpoch:n}=ee(),o=react.useMemo(()=>lt(t.registry.services.authFor(r)),[t,r,n]),s=react.useMemo(()=>({repository:o,petRef:e}),[o,e]),[a,l]=react.useState({key:s,profile:null,loading:e!==null,error:null}),u=a.key===s?a:{profile:null,loading:e!==null,error:null},d=react.useRef(0),c=react.useCallback(async()=>{let p=++d.current;if(s.petRef===null){l({key:s,profile:null,loading:false,error:null});return}l(m=>({key:s,profile:m.key===s?m.profile:null,loading:true,error:null}));let f=await s.repository.getPetProfile(s.petRef);p===d.current&&l(f.ok?{key:s,profile:f.value,loading:false,error:null}:{key:s,profile:null,loading:false,error:f.error});},[s]);return react.useEffect(()=>(c(),()=>{d.current+=1;}),[c]),react.useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:c}),[u.profile,u.loading,u.error,c])}i(mP,"useEverfurPetProfile");function gP(e){return react.createElement(Cn,{clientTheme:e.clientTheme??null,seams:Sn,children:e.children})}i(gP,"EverfurThemeProvider");exports.APPEARANCE_PRESETS=tu;exports.APPEARANCE_PRESET_NAMES=eu;exports.APPEARANCE_SIZE_RANGES=br;exports.CapabilityGate=Si;exports.EverfurChat=Vf;exports.EverfurConfigError=re;exports.EverfurProvider=Fb;exports.EverfurThemeProvider=gP;exports.EverfurThrownError=jr;exports.THEME_SLOT_KEYS=kg;exports.THEME_SLOT_NAMES=$e;exports.canonicalPetSpecies=pr;exports.categoryFor=lo;exports.conversationId=nm;exports.createRnRecordsUploadTransport=Cm;exports.expandAppearance=ii;exports.face=R;exports.isErr=Zf;exports.isOk=Qf;exports.isRetryableCode=uo;exports.petRef=tm;exports.previewTheme=Ih;exports.unwrap=Jf;exports.useCapability=Wt;exports.useChatAttachments=Pn;exports.useEverfur=Fu;exports.useEverfurChat=Rr;exports.useEverfurPetProfile=mP;exports.useEverfurPets=Un;exports.useEverfurTheme=N;exports.userFacingError=Dt;exports.userRef=rm;
|
|
1
|
+
"use strict";var zod=require("zod"),react=require("react"),reactNativeSafeAreaContext=require("react-native-safe-area-context"),EventSource=require("react-native-sse"),reactNative=require("react-native"),jsxRuntime=require("react/jsx-runtime");function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var EventSource__default=/*#__PURE__*/_interopDefault(EventSource);function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}function ok(value,warning){/* @__PURE__ */
|
|
2
|
+
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
3
|
+
return Object.freeze({ok:false,error:error})}function isOk(r){return r.ok}function isErr(r){return!r.ok}var EverfurThrownError=class _EverfurThrownError extends Error{constructor(error){super(`${error.code}: ${error.displayMessage}`),this.name="EverfurThrownError",this.error=error,this.code=error.code,this.category=error.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(r){if(r.ok)return r.value;throw new EverfurThrownError(r.error)}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var MAX_USER_REF_LEN=128,MAX_PET_REF_LEN=128,CONTROL_CHAR=/[\u0000-\u001F\u007F]/,UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_PET_REF_LEN)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${MAX_PET_REF_LEN} characters`);if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","petRef must be printable (no control characters)");return v}function userRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_USER_REF_LEN)throw new EverfurConfigError("invalid-argument",`userRef must be 1..${MAX_USER_REF_LEN} characters`);if(v.includes("@"))throw new EverfurConfigError("invalid-argument","userRef must not contain '@'");if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","userRef must be printable (no control characters)");return v}function conversationId(raw){if(!UUID_RE.test(raw))throw new EverfurConfigError("invalid-argument","conversationId must be a UUID");return raw}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
4
|
+
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
5
|
+
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
6
|
+
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
7
|
+
/* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
8
|
+
/* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
9
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
10
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
11
|
+
/* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
12
|
+
/* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
|
|
13
|
+
/* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
|
|
14
|
+
/* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
|
|
15
|
+
/* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
16
|
+
/* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
17
|
+
/* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
18
|
+
/* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
19
|
+
/* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
20
|
+
/* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
21
|
+
/* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
22
|
+
/* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
23
|
+
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
24
|
+
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
25
|
+
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
26
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
27
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
28
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
29
|
+
/* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
30
|
+
/* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
31
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
32
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
33
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
34
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
35
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
36
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
37
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
38
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
39
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
40
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
41
|
+
/* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
42
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
43
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
|
|
44
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
45
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
46
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
47
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
48
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
49
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
50
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
51
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
52
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
53
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
54
|
+
/* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
55
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
56
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
57
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
58
|
+
/* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
|
|
59
|
+
/* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
60
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
61
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
62
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
63
|
+
/* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
64
|
+
/* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
65
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
66
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
67
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
68
|
+
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
69
|
+
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
70
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
72
|
+
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
73
|
+
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
74
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
75
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
76
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
77
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
78
|
+
/* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
79
|
+
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
80
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
81
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
82
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
84
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
85
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
86
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
87
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
88
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
89
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
90
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}function shouldRetry(code,frameRetryable=false){return frameRetryable||isAutoRetryable(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}function canRecreateOnNotFound(code){return code==="conversationNotFound"}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var FILENAMES=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function recordsUploadFilename(type){return isAcceptedUploadType(type,RECORDS_PHOTO_CONTENT_TYPES)?FILENAMES[type]:FILENAMES["application/pdf"]}var FILE_FIELD="file",NOT_SENT="multipart upload failed";function postRnMultipart(post){let form;try{form=new FormData;for(let[name,value]of Object.entries(post.fields))form.append(name,value);form.append(FILE_FIELD,post.file)}catch{return Promise.reject(new Error(NOT_SENT))}return post.fetch!==void 0?postWithFetch(post.fetch,post.url,form,post.signal):postWithXhr(post.url,form,post.signal)}function stored(status){return status>=200&&status<300}function postWithXhr(url,form,signal){return new Promise((resolve,reject)=>{let Xhr=globalThis.XMLHttpRequest;if(typeof Xhr!="function"||signal?.aborted===true){reject(new Error(NOT_SENT));return}let onAbort=null,release=()=>{onAbort!==null&&signal?.removeEventListener("abort",onAbort)},fail=()=>{release(),reject(new Error(NOT_SENT))};try{let xhr=new Xhr;xhr.open("POST",url),xhr.withCredentials=!1,xhr.onload=()=>{release(),resolve(stored(xhr.status))},xhr.onerror=fail,xhr.ontimeout=fail,xhr.onabort=fail,signal!==void 0&&(onAbort=()=>{try{xhr.abort()}finally{fail()}},signal.addEventListener("abort",onAbort,{once:!0})),xhr.send(form)}catch{fail()}})}function postWithFetch(send,url,form,signal){return Promise.resolve().then(()=>send(url,{method:"POST",body:form,credentials:"omit",...signal?{signal:signal}:{}})).then(res=>res.ok)}var NO_URI="records upload: the file handle has no uri",FAILED="records upload failed";function createRnRecordsUploadTransport(options={}){/* @__PURE__ */
|
|
91
|
+
return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:{uri:file.uri,name:recordsUploadFilename(file.mimeType),type:partType(file.mimeType)},signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}function partType(mimeType){return isAcceptedUploadType(mimeType,RECORDS_PHOTO_CONTENT_TYPES)?mimeType:"application/pdf"}var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var defaultErrorPolicy=/* @__PURE__ */Object.freeze({shouldRetry(code,attempt){return isAutoRetryable(code)&&attempt<MAX_RETRY_ATTEMPTS},maxAttempts(){return MAX_RETRY_ATTEMPTS}});var unavailableCamera=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function acceptedFrame(streamId,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
92
|
+
return Object.freeze({kind:"accepted",streamId:streamId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function heartbeatFrame(lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
93
|
+
return Object.freeze({kind:"heartbeat",lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function deltaFrame(delta,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
94
|
+
return Object.freeze({kind:"delta",delta:delta,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function doneFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
95
|
+
return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversationId,messageId:fields.messageId,title:fields.title,followUpQuestions:/* @__PURE__ */Object.freeze([...fields.followUpQuestions]),citations:/* @__PURE__ */Object.freeze([...fields.citations]),citationStatus:fields.citationStatus,urgencyLevel:fields.urgencyLevel,urgencyReason:fields.urgencyReason,urgencyProvided:fields.urgencyProvided??fields.urgencyLevel!==null,resultId:fields.resultId,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function errorFrame(fields){/* @__PURE__ */
|
|
96
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
97
|
+
return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
98
|
+
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
99
|
+
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function createIdentityProvider(userRef2,getToken,onMinted){let cached=null,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.9.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
100
|
+
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{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(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
|
|
101
|
+
return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
|
|
102
|
+
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
|
|
103
|
+
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line of data.split(`\n`))block+=`data: ${line}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline2=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline2.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline2.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline2,caller){if(!caller)return deadline2;let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline2=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline2.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline2.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
104
|
+
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null})}}/* @__PURE__ */
|
|
105
|
+
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline2,caller){let noop=()=>{};if(!caller)return{signal:deadline2,dispose:noop};let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline2.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}var CHECKIN_ANSWERS=/* @__PURE__ */Object.freeze(["better","same","worse"]),CASE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function invalid(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}function petPath(petRef2){return typeof petRef2!="string"||petRef2.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):hasLoneSurrogate(petRef2)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(petRef2)}/cases`}var str=v=>typeof v=="string"?v:null,count=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function caseFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,caseId=str(o.case_id),status=str(o.status);if(caseId===null||status===null)return null;let last=str(o.last_response);/* @__PURE__ */
|
|
106
|
+
return Object.freeze({caseId:caseId,status:status,bodyLocation:str(o.body_location),lastResponse:last!==null&&CHECKIN_ANSWERS.includes(last)?last:null,checkInDueAt:str(o.check_in_due_at),openedAt:str(o.opened_at),resolvedAt:str(o.resolved_at),resolutionText:str(o.resolution_text),checkinAskCount:count(o.checkin_ask_count),checkinAnswerCount:count(o.checkin_answer_count)})}function createCasesRepositoryOver(funnel){return{async list(petRef2,opts){let path=petPath(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("cases.list",{method:"GET",path:path,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let rows=typeof res.value=="object"&&res.value!==null?res.value.cases:null;if(!Array.isArray(rows))return malformed();let cases=rows.map(caseFromWire);return cases.every(c=>c!==null)?ok(/* @__PURE__ */Object.freeze(cases)):malformed()},async checkin(petRef2,caseId,answer,opts){let path=petPath(petRef2);if(typeof path!="string")return err(path);if(typeof caseId!="string"||!CASE_ID_PATTERN.test(caseId))return invalid("case_id must be a UUID");if(!CHECKIN_ANSWERS.includes(answer))return invalid("response must be one of better, same, worse");let res=await funnel.send("cases.checkin",{method:"POST",path:`${path}/${caseId}/checkin`,body:{response:answer},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let o=typeof res.value=="object"&&res.value!==null?res.value:{},watchCase=caseFromWire(o.case);return watchCase===null?malformed():ok(/* @__PURE__ */Object.freeze({case:watchCase,ctaDeepLink:str(o.cta_deep_link)}))}}}var unavailableUpload=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}function mergeSignals2(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}var MediaStore=class{constructor(initial){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...initial})}subscribe(listener){return this.listeners.add(listener),()=>{this.listeners.delete(listener)}}getSnapshot(){return this.snapshot}patch(partial){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...partial});for(let listener of this.listeners)listener()}beginOperation(external){this.inFlight?.abort();let ctrl=new AbortController;this.inFlight=ctrl;let epoch=this.epoch;return{signal:external?mergeSignals2(ctrl.signal,external):ctrl.signal,epoch:epoch,settle:()=>{this.inFlight===ctrl&&(this.inFlight=null)}}}alive(epoch){return epoch===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear()}};function makeUser(id,text3,createdAt){/* @__PURE__ */
|
|
107
|
+
return Object.freeze({id:id,role:"user",text:text3,createdAt:createdAt,pending:true})}function makeAssistant(id,text3,createdAt){/* @__PURE__ */
|
|
108
|
+
return Object.freeze({id:id,role:"assistant",text:text3,createdAt:createdAt})}function stripPending(m){/* @__PURE__ */
|
|
109
|
+
return Object.freeze({id:m.id,role:m.role,text:m.text,createdAt:m.createdAt})}function appendText(m,text3){let next={id:m.id,role:m.role,text:m.text+text3,createdAt:m.createdAt};return m.citations&&(next.citations=m.citations),m.responseId&&(next.responseId=m.responseId),/* @__PURE__ */Object.freeze(next)}function finalizeAssistant(m,done){let next={id:done.messageId?done.messageId:m.id,role:"assistant",text:m.text,createdAt:m.createdAt};return done.citations.length>0&&(next.citations=done.citations),done.messageId&&(next.responseId=done.messageId),next.urgencyLevel=done.urgencyLevel,next.urgencyReason=done.urgencyReason,next.urgencyProvided=done.urgencyProvided,/* @__PURE__ */Object.freeze(next)}function freezeSnapshot(s){/* @__PURE__ */
|
|
110
|
+
return Object.freeze({status:s.status,messages:/* @__PURE__ */Object.freeze([...s.messages]),conversationId:s.conversationId,error:s.error,isStreaming:s.isStreaming,isBootstrapping:s.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...s.suggestedPrompts]),unreadCount:s.unreadCount})}function makeError(code,retryable,wireMessage){return makeEverfurError(code,{retryable:retryable,...wireMessage?{wireMessage:wireMessage}:{}})}function errorFromFrame(frame){let code=fromWire(frame.code);return makeEverfurError(code,{retryable:frame.retryable||shouldRetry(code),wireCode:frame.code,wireEnvelope:"sse_frame",...frame.serverRequestId?{requestId:frame.serverRequestId}:{},...frame.wireMessage?{wireMessage:frame.wireMessage}:{},raw:frame})}function synthErrorFrame(error){return errorFrame({code:canonicalWireCode(error.code),retryable:error.retryable,wireMessage:error.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:error.requestId??null})}function canonicalWireCode(code){switch(code){case"authExpired":return"AUTH_EXPIRED";case"authRejected":return"AuthorizationException";case"sessionRequired":return"session_required";case"accessDenied":return"ACCESS_DENIED";case"paymentRequired":return"TIER_UPGRADE_REQUIRED";case"quotaExceeded":return"QUOTA_EXCEEDED";case"rateLimited":return"RATE_LIMITED";case"validationFailed":return"ValidationException";case"sdkUpdateRequired":return"invalidRequest";case"conflict":return"ConflictException";case"idempotencyConflict":return"IDEMPOTENCY_CONFLICT";case"idempotencyInFlight":return"IDEMPOTENCY_KEY_IN_FLIGHT";case"conversationNotFound":return"CONVERSATION_NOT_FOUND";case"petNotFound":return"PET_NOT_FOUND";case"resourceNotFound":return"ResourceNotFoundException";case"streamTimeout":return"STREAM_TIMEOUT";case"mediaUploadFailed":return"MEDIA_UPLOAD_FAILED";case"moderationBlocked":return"MODERATION_BLOCKED";case"upstreamLlmTimeout":return"UPSTREAM_LLM_TIMEOUT";case"internalError":return"INTERNAL_ERROR";case"notImplemented":return"NotImplementedException";case"serviceUnavailable":return"ServiceUnavailableException";case"streamIncomplete":return"STREAM_INCOMPLETE";case"identitySignatureRequired":return"identitySignatureRequired";case"unknown":return"UNKNOWN";default:return assertNever(code)}}function parsePromptCategories(raw){let list=Array.isArray(raw)?raw:isPlainObject2(raw)&&Array.isArray(raw.categories)?raw.categories:[],out=[];for(let entry of list){if(!isPlainObject2(entry))continue;let category=asStr(entry.category)??asStr(entry.title)??"",prompts=asPromptTextList(entry.prompts??entry.questions);category.length===0&&prompts.length===0||out.push(/* @__PURE__ */Object.freeze({category:category,prompts:/* @__PURE__ */Object.freeze(prompts)}))}/* @__PURE__ */
|
|
111
|
+
return Object.freeze(out)}function flattenPrompts(categories){let seen=/* @__PURE__ */new Set,out=[];for(let category of categories)for(let prompt of category.prompts){let trimmed=prompt.trim();trimmed.length===0||seen.has(trimmed)||(seen.add(trimmed),out.push(trimmed))}return out}function isPlainObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asStr(v){return typeof v=="string"?v:null}function asPromptTextList(v){if(!Array.isArray(v))return[];let out=[];for(let entry of v)if(typeof entry=="string")out.push(entry);else if(isPlainObject2(entry)){let text3=asStr(entry.text)??asStr(entry.prompt)??asStr(entry.title);text3!==null&&out.push(text3)}return out}function defaultIdFactory(){let counter=0;return()=>`m-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function defaultIdempotencyFactory(){let counter=0;return()=>`chat-send-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var defaultTimers2={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()};async function*withWatchdog(source,budget,signal,timers){let it=source[Symbol.asyncIterator](),overall=deadline(budget.overallMs,timers),idle=deadline(budget.idleMs,timers),abort=abortPromise(signal);try{for(;;){if(signal.aborted)return;let nextTagged=it.next().then(value=>({tag:"next",value:value}),()=>({tag:"streamError"})),outcome=await Promise.race([nextTagged,idle.promise.then(()=>({tag:"idle"})),overall.promise.then(()=>({tag:"overall"})),abort.then(()=>({tag:"abort"}))]);if(outcome.tag==="abort")return;if(outcome.tag==="streamError"){if(signal.aborted)return;yield synthStreamErrorFrame();return}if(outcome.tag==="idle"||outcome.tag==="overall"){yield synthTimeoutFrame();return}let result=outcome.value;if(result.done||(idle.reset(budget.idleMs),yield result.value,result.value.terminal))return}}finally{idle.cancel(),overall.cancel(),Promise.resolve(it.return?.(void 0)).catch(()=>{})}}function synthTimeoutFrame(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function synthStreamErrorFrame(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function deadline(ms,timers){let resolveFn=()=>{},promise=new Promise(resolve=>{resolveFn=resolve}),handle=timers.setTimeout(()=>resolveFn(),ms);return{promise:promise,reset(next){timers.clearTimeout(handle),handle=timers.setTimeout(()=>resolveFn(),next)},cancel(){timers.clearTimeout(handle)}}}function abortPromise(signal){return new Promise(resolve=>{if(signal.aborted){resolve();return}signal.addEventListener("abort",()=>resolve(),{once:true})})}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function isLiveAskAnswered(counts){let{askCount:askCount,answerCount:answerCount}=counts;return typeof askCount!="number"||!Number.isFinite(askCount)||typeof answerCount!="number"||!Number.isFinite(answerCount)||askCount<=0?true:answerCount>=askCount}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}function parseCheckinOriginRef(ref){return parseCheckinOrigin(ref)?.caseId??null}function historyQuery(opts,max){if(opts?.limit!==void 0&&(!Number.isInteger(opts.limit)||opts.limit<1||opts.limit>max))return err(makeEverfurError("validationFailed"));let query=[];for(let[key,value]of[["cursor",opts?.cursor],["pet_ref",opts?.petRef]])if(value!==void 0){if(typeof value!="string"||value.length===0||hasLoneSurrogate(value))return err(makeEverfurError("validationFailed"));query.push(`${key}=${encodeURIComponent(value)}`)}return opts?.limit!==void 0&&query.push(`limit=${opts.limit}`),ok(query.length?`?${query.join("&")}`:"")}function validConversationId(id){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)}function object(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function cursor(value){return value==null||typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}function mapConversationPage(value){let page=object(value);if(!page||!Array.isArray(page.conversations)||!cursor(page.next_cursor))return malformed2();let conversations=[];for(let raw of page.conversations){let row=object(raw);if(!row||typeof row.conversation_id!="string"||!validConversationId(row.conversation_id)||!(row.title==null||typeof row.title=="string")||typeof row.created_at!="string"||typeof row.updated_at!="string")return malformed2();let unread=row.unread_message_count;if(!(unread==null||Number.isInteger(unread)&&unread>=0))return malformed2();conversations.push(/* @__PURE__ */Object.freeze({id:row.conversation_id,title:row.title??null,createdAt:row.created_at,updatedAt:row.updated_at,unreadCount:unread??null}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(conversations),nextCursor:page.next_cursor??null}))}function mapMessagePage(value){let page=object(value);if(!page||!Array.isArray(page.messages)||!cursor(page.next_cursor))return malformed2();let messages=[],seen=/* @__PURE__ */new Set;for(let raw of page.messages){let row=object(raw);if(!row||typeof row.message_id!="string"||!validConversationId(row.message_id)||typeof row.role!="string"||typeof row.content!="string"||typeof row.created_at!="string")return malformed2();if(row.role!=="user"&&row.role!=="assistant"&&row.role!=="vet"||seen.has(row.message_id))continue;if(seen.add(row.message_id),row.role==="vet"){messages.push(vetMessage(row,row.message_id,row.content,row.created_at));continue}let origin=typeof row.proactive_origin_ref=="string"?row.proactive_origin_ref:null,caseId=row.role==="assistant"?parseCheckinOriginRef(origin):null;messages.push(/* @__PURE__ */Object.freeze({id:row.message_id,role:row.role,text:row.content,createdAt:row.created_at,...row.role==="assistant"?{responseId:row.message_id}:{},...row.urgency_level!==void 0?{urgencyLevel:normalizeUrgency(row.urgency_level)}:{},...Array.isArray(row.citations)?{citations:historyCitations(row.citations)}:{},...origin!==null?{proactiveOriginRef:origin}:{},...caseId!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:caseId,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(messages),nextCursor:page.next_cursor??null}))}function vetMessage(row,id,text3,createdAt){let sender=object(row.sender),displayName=trimmedText(sender?.display_name)??trimmedText(row.sender_display_name),specialty=trimmedText(sender?.specialty);/* @__PURE__ */
|
|
112
|
+
return Object.freeze({id:id,role:"vet",text:text3,createdAt:createdAt,sender:/* @__PURE__ */Object.freeze({displayName:displayName,specialty:specialty})})}function trimmedText(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&!hasLoneSurrogate(trimmed)?trimmed:null}function normalizeUrgency(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}function historyCitations(values){let keys=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
|
|
113
|
+
return Object.freeze(values.flatMap(value=>{let row=object(value);if(!row||typeof row.source_name!="string"||typeof row.authority_tier!="string")return[];let citation={};for(let key of keys){let item=row[key];(typeof item=="string"||item===null)&&(citation[key]=item)}return[/* @__PURE__ */Object.freeze(citation)]}))}var CHAT_FEEDBACK_TYPES=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;function validateImageKeys(keys){return keys===void 0?null:!Array.isArray(keys)||keys.length>5?{reason:"too_many_images",error:makeError("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:keys.some(key=>typeof key!="string"||key.trim().length===0)?{reason:"bad_image_key",error:makeError("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function validateMessageText(text3){let raw=typeof text3=="string"?text3:"";if(raw.trim().length===0)return{reason:"empty",error:makeError("validationFailed",false,"message is empty or whitespace-only")};let codePoints=[...raw].length;return codePoints>MESSAGE_MAX_CHARS?{reason:"too_long",error:makeError("validationFailed",false,`message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`)}:null}function urgencyTier(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}async function*singleFrameStream(frame){yield frame}async function*emptyStream(){}var DEFAULT_IDLE_MS=6e4,DEFAULT_OVERALL_MS=18e4,DELTA_FLUSH_MS=24,DELTA_FLUSH_CHARS=512,SEND_IS_SERVER_DEDUPED=false;function createChatController(deps){return new ChatControllerImpl(deps)}var ChatControllerImpl=class extends MediaStore{constructor(deps){super(freezeSnapshot({status:"idle",messages:[],conversationId:deps.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.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingDelta="";this.flushHandle=null;this.auth=deps.auth,this.funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),this.petRef=deps.petRef??null,this.cases=createCasesRepositoryOver(this.funnel),this.telemetry=deps.telemetry??noopTelemetry,this.errorPolicy=deps.errorPolicy??defaultErrorPolicy,this.timers=deps.timers??defaultTimers2,this.rng=deps.rng??Math.random,this.newId=deps.newId??defaultIdFactory(),this.makeIdempotencyKey=deps.makeIdempotencyKey??defaultIdempotencyFactory(),this.budget={idleMs:deps.budget?.idleMs??DEFAULT_IDLE_MS,overallMs:deps.budget?.overallMs??DEFAULT_OVERALL_MS}}patch(partial){if(partial.messages!==void 0){let frozen=/* @__PURE__ */Object.freeze([...partial.messages]);super.patch({...partial,messages:frozen});return}super.patch(partial)}send(text3,opts,handlers){let options=opts??{};if(this.disposed||this.snapshot.isBootstrapping){let error=makeError(this.disposed?"accessDenied":"internalError",!this.disposed);return handlers?(handlers.onError(error),()=>{}):singleFrameStream(synthErrorFrame(error))}let invalid4=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid4!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),this.patch({status:"error",isStreaming:false,error:invalid4.error}),handlers?(handlers.onError(invalid4.error),()=>{}):singleFrameStream(synthErrorFrame(invalid4.error));if(handlers)return this.driveWithHandlers(text3,options,handlers);let turn=this.beginTurn(text3,options);return this.runTurn(turn,options.signal)}askEverfur(prompt,opts){if(this.disposed)return singleFrameStream(synthErrorFrame(makeError("accessDenied",false)));let invalid4=validateMessageText(prompt);return invalid4!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),singleFrameStream(synthErrorFrame(invalid4.error))):(this.resetThread(),this.send(prompt,opts??{}))}retryLast(){let turn=this.lastTurn;if(turn===null){let id=this.snapshot.conversationId;return id!==null&&this.snapshot.status==="error"?this.retryHistory(id):emptyStream()}turn.assistantMessageId=null,turn.sawDelta=false,turn.conversationIdOverride=null,this.discardPendingDelta();let messages=this.snapshot.messages.some(m=>m.id===turn.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,makeUser(turn.userMessageId,turn.text,this.stamp())];return this.patch({error:null,stopped:false,messages:messages}),this.runTurn(turn,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let stopped=this.snapshot.messages.some(m=>m.role==="user"&&m.pending===true),messages=stopped?this.snapshot.messages.map(m=>m.pending===true?stripPending(m):m):this.snapshot.messages;(this.snapshot.status==="streaming"||stopped)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...stopped?{messages:messages,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot()}resetThread(prompts=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=prompts,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:prompts,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false})}newConversation(){this.disposed||this.resetThread(this.scopePrompts)}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let teardown of this.handlerTeardowns)teardown();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(id){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==id&&this.patch({conversationId:id}))}adoptPrompts(categories){if(this.disposed)return;let prompts=/* @__PURE__ */Object.freeze(flattenPrompts(categories));this.bootstrapPrompts=prompts,this.scopePrompts=prompts,this.replyPrompts===null&&(prompts.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:prompts}))}async listConversations(opts){return this.listConversationsWith(opts)}async listConversationsWith(opts,funnelOpts){let query=historyQuery(opts,100);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},opts?.signal,funnelOpts);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let page=mapConversationPage(result.value);if(page.ok){for(let conversation of page.value.conversations)conversation.unreadCount!==null&&this.unreadByConversation.set(conversation.id,conversation.unreadCount);let active=this.snapshot.conversationId,count2=active===null?void 0:this.unreadByConversation.get(active);count2!==void 0&&count2!==this.snapshot.unreadCount&&this.patch({unreadCount:count2}),this.reflectUnreadDot()}return page}reflectUnreadDot(){let unread=false;for(let count2 of this.unreadByConversation.values())if(count2>0){unread=true;break}unread!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:unread})}async openCheckin(target){if(this.disposed)return err(makeError("accessDenied",false));let named=target?.conversationId??null;if(named!==null){let opened2=await this.resumeConversation(named);return opened2.ok?ok(named):err(opened2.error)}let petRef2=target?.petRef??this.petRef,listed=await this.listConversations({...petRef2===null?{}:{petRef:petRef2},limit:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0)return ok(null);let opened=await this.resumeConversation(head.id);return opened.ok?ok(head.id):err(opened.error)}async markRead(opts){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null)return ok(void 0);let epoch=this.epoch,result=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${id}/read`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?(this.unreadByConversation.set(id,0),this.snapshot.conversationId===id&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),ok(void 0)):err(result.error)}async submitFeedback(responseId,feedbackType,notes,opts){if(this.disposed)return err(makeError("accessDenied",false));if(typeof responseId!="string"||responseId.trim().length===0||hasLoneSurrogate(responseId))return err(makeError("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!CHAT_FEEDBACK_TYPES.includes(feedbackType))return err(makeError("validationFailed",false,`feedback_type must be one of ${CHAT_FEEDBACK_TYPES.join(", ")}`));let note=typeof notes=="string"?notes.trim():"";if([...note].length>FEEDBACK_NOTES_MAX_CHARS)return err(makeError("validationFailed",false,`notes is over ${FEEDBACK_NOTES_MAX_CHARS} characters`));let body={feedback_type:feedbackType};note.length>0&&(body.notes=note);let epoch=this.epoch,result=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(responseId)}/feedback`,body:body},opts?.signal);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let feedbackId=result.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof feedbackId=="string"?feedbackId:""}))}async answerCheckin(caseId,answer,opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??this.petRef;if(petRef2===null)return err(makeError("validationFailed",false,"a check-in needs the pet the case belongs to"));let epoch=this.epoch,result=await this.cases.checkin(petRef2,caseId,answer,opts?.signal?{signal:opts.signal}:{});if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let openedAt=result.value.case.openedAt,checkin=/* @__PURE__ */Object.freeze({caseId:caseId,answer:answer,resolutionText:result.value.case.resolutionText,status:result.value.case.status??null,...openedAt!==null?{openedAt:openedAt}:{}}),carries=m=>m.checkin?.caseId===caseId;return this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,checkin:checkin}):m)}),result}async getMessages(id,opts){if(!validConversationId(id))return err(makeError("validationFailed",false));let query=historyQuery(opts,200);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${id}/messages${query.value}`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?mapMessagePage(result.value):result}async resumeConversation(id){if(this.disposed)return err(makeError("accessDenied",false));if(!validConversationId(id))return err(makeError("validationFailed",false));this.resetThread();let generation=this.historyGeneration;this.patch({conversationId:id,isBootstrapping:true,isLoadingHistory:true});let result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return this.patch({status:"error",error:result.error,isBootstrapping:false,isLoadingHistory:false}),result;let unread=this.unreadByConversation.get(id)??null;return this.patch({messages:result.value.messages,historyCursor:result.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:unread}),this.stampCheckinStatuses(generation),unread!==null&&unread>0&&this.markRead(),ok(void 0)}async stampCheckinStatuses(generation){let petRef2=this.petRef;if(petRef2===null||!this.snapshot.messages.some(m=>m.checkin!==void 0&&m.checkin.status===null))return;let result=await this.cases.list(petRef2);if(!result.ok||generation!==this.historyGeneration||this.disposed)return;let open=new Set(result.value.filter(row=>row.status===CHECKIN_ANSWERABLE_STATUS).map(row=>row.caseId)),byCase=new Map(result.value.map(row=>[row.caseId,row])),changed=false,messages=this.snapshot.messages.map(message=>{let checkin=message.checkin;if(checkin===void 0||checkin.status!==null)return message;changed=true;let row=byCase.get(checkin.caseId),openedAt=checkin.openedAt??row?.openedAt??null,watching=open.has(checkin.caseId),answerOnRecord=row!==void 0&&(!watching||isLiveAskAnswered({askCount:row.checkinAskCount,answerCount:row.checkinAnswerCount}))?row.lastResponse:null;/* @__PURE__ */
|
|
114
|
+
return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null||this.snapshot.isStreaming)return ok(void 0);let generation=this.historyGeneration,result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async primeBounded(petRef2){let head=await this.headThreadWithUnread(petRef2);return head.ok?head.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(head.value)).ok?ok(head.value):ok(this.snapshot.conversationId):head.error.code==="accessDenied"||head.error.httpStatus===403?ok(null):err(head.error)}async headThreadWithUnread(petRef2){let listed=await this.listConversationsWith({...petRef2===null?{}:{petRef:petRef2},limit:1},{maxAttempts:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];return head===void 0||head.unreadCount===null||head.unreadCount<=0?ok(null):ok(head.id)}async createConversation(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef2,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef2?{pet_ref:petRef2}:{}},res=await this.authedUnary("chat.createConversation",req,signal,{maxAttempts:1});if(!res.ok)return err(res.error);let raw=res.value?.conversation_id??res.value?.id;return typeof raw!="string"||raw.length===0?err(makeError("internalError",true)):ok(raw)}async getPrompts(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null;if(petRef2!==null&&hasLoneSurrogate(petRef2))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef2!==null?`?pet_ref=${encodeURIComponent(petRef2)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending=needsConversation?this.unadoptedCreate:null;if(pending!==null&&(turn.petRef===null||turn.petRef===pending.petRef)){let primed=await pending.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&this.adoptConversation(primed.value)}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk):m);this.patch({messages:messages})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(done,turn){this.flushPendingDelta(turn),this.lastResponseIdValue=done.messageId?done.messageId:null;let nextConv=done.conversationId?done.conversationId:this.snapshot.conversationId,messages;if(turn.assistantMessageId!==null)messages=this.snapshot.messages.map(m=>m.id===turn.assistantMessageId?finalizeAssistant(m,done):m);else{let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true,messages=[...this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m),finalizeAssistant(makeAssistant(assistantId,"",this.stamp()),done)]}let followUps=flattenPrompts([{category:"",prompts:done.followUpQuestions}]);this.replyPrompts=followUps.length>0?/* @__PURE__ */Object.freeze(followUps):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:nextConv,messages:messages,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!done.urgencyProvided&&nextConv!==null&&this.classifyTurn(nextConv,this.lastResponseIdValue)}async classifyTurn(conversationId2,responseId){if(responseId===null||this.disposed)return;let messageId=String(responseId);if(this.classifiedMessageIds.has(messageId))return;this.classifiedMessageIds.add(messageId);let epoch=this.epoch,generation=this.historyGeneration,result=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId2}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId2)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return makeError("authRejected",false)}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef2=input.petRef??null,resume=input.resumeConversationId??null,candidateConversationIds=[],sawForbidden=false,sawUnauthorized=false,sawConversationInitFailure=false,authBlock=null,initFailure=null,conversationPromise=resume?controller.resumeConversation(resume).then(result=>result.ok?ok(resume):err(result.error)):controller.primeConversation(petRef2?{petRef:petRef2}:void 0),promptsPromise=controller.getPrompts(petRef2!==null?{petRef:petRef2}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId2=null;if(conversationRes.ok)conversationId2=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
|
|
115
|
+
return Object.freeze({conversationId:conversationId2,petRef:petRef2,suggestedPrompts:suggestedPrompts,error:error,warning:error===null&&conversationId2===null&&sawConversationInitFailure?CONVERSATION_NOT_PRIMED_WARNING:null,cause:authBlock??initFailure,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...candidateConversationIds]),sawForbidden:sawForbidden,sawUnauthorized:sawUnauthorized,sawConversationInitFailure:sawConversationInitFailure})})}var CONVERSATION_NOT_PRIMED_WARNING="Chat is ready. Your first message will start the conversation.";function isUnauthorized(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function isForbidden(e){return e.httpStatus===403||e.code==="accessDenied"}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var MAX_ATTACHMENT_BYTES=10*1024*1024,MAX_ATTACHMENTS_PER_MESSAGE=5,MAX_FILENAME_LENGTH=120,ATTACHMENT_INITIATE_PATH="/widget/v1/uploads/initiate";function isAttachmentMime(mime){return typeof mime=="string"&&ATTACHMENT_MIME_TYPES.includes(mime.trim().toLowerCase())}function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
|
|
116
|
+
return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str4=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str4(o.upload_id),uploadUrl=str4(o.upload_url),s3Key=str4(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
|
|
117
|
+
return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str4(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight3=/* @__PURE__ */new Set,listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed=false,publish2=()=>{snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners2)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed&&inFlight3.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight3.add(id),run(row).finally(()=>{inFlight3.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot:()=>snapshot,get uploading(){return snapshot.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners2.clear(),snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str2=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str2(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(o.ref),name:name,dose:str2(o.dose),frequency:str2(o.frequency),startDate:str2(o.start_date),endDate:str2(o.end_date),notes:str2(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
118
|
+
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str2(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str2(o.food_brand),foodType:str2(o.food_type),microchipId:str2(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str2(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str2(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str2(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),conditionName:conditionName,diagnosedDate:str2(row.diagnosed_date),notes:str2(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid2(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid2(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid2(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef2,profile){if(typeof petRef2!="string")return invalid2("pet_ref must be a string");if(petRef2.trim().length===0)return invalid2("pet_ref must not be blank");if(hasLoneSurrogate(petRef2))return invalid2("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid2("profile must be an object");let checks=[checkString("pet_ref",petRef2,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid2(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid2("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid2("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str3=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef2){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
|
|
119
|
+
return Object.freeze({petRef:str3(o.pet_ref)??petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef2=str3(o.pet_ref);return petRef2===null||petRef2.length===0?null:/* @__PURE__ */Object.freeze({petId:str3(o.pet_id),petRef:petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str3(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
|
|
120
|
+
return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal2=(req,signal)=>signal?{...req,signal:signal}:req,petPath2=petRef2=>validate(petRef2,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef2)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal2({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef2,profile,opts){let invalid4=validate(petRef2,profile);if(invalid4!==null)return err(invalid4);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef2)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async updatePet(petRef2,patch,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal2({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async getPetProfile(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal2({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal2({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal2({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function deniedDecisionsFor(level,reason){let disabled=/* @__PURE__ */Object.freeze({reason:reason,level:level,recoverable:false}),rows=[],seen=/* @__PURE__ */new Set;for(let name of Object.keys(REQUIRES))for(let resource of REQUIRES[name])seen.has(resource)||(seen.add(resource),rows.push(/* @__PURE__ */Object.freeze({resource:resource,granted:false,disabled:disabled}))/* @__PURE__ */);return Object.freeze(rows)}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
121
|
+
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
122
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef2,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef2}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending=inFlight2.get(scope);if(pending!==void 0)return pending;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel2){return channel2<=.03928?channel2/12.92:Math.pow((channel2+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function rgbToHsl(r,g,b){let rn=r/255,gn=g/255,bn=b/255,mx=Math.max(rn,gn,bn),mn=Math.min(rn,gn,bn),l=(mx+mn)/2;if(mx===mn)return{h:0,s:0,l:l};let d=mx-mn,s=d/(1-Math.abs(2*l-1)),h;return mx===rn?(h=(gn-bn)/d*60,h<0&&(h=h+360)):mx===gn?h=((bn-rn)/d+2)*60:h=((rn-gn)/d+4)*60,{h:h,s:s,l:l}}function hslToRgb(hsl){let{h:h,s:s,l:l}=hsl,c=(1-Math.abs(2*l-1))*s,hp=h/60,x=c*(1-Math.abs(hp%2-1)),m=l-c/2,sector=Math.floor(hp)%6,rgb1=[[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]],[r1,g1,b1]=rgb1[sector];return{r:channel(r1+m),g:channel(g1+m),b:channel(b1+m)}}function channel(v){return Math.min(255,Math.max(0,Math.floor(v*255+.5)))}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog"]),THEME_SLOT_KEYS=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),SLOT_MIN_CONTRAST=4.5,EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let text3=typeof value=="string"&&value.length<=16?value.trim().replace(/ ?px$/i,""):null,n=typeof value=="number"?value:text3!==null&&text3.length>0?Number(text3):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let slot=parseSlot(raw);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function pick2(raw,snake,camel){return raw[snake]!==void 0?raw[snake]:raw[camel]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base,over){return over===null||Object.keys(over).length===0?base??EMPTY:base===null||Object.keys(base).length===0?over:/* @__PURE__ */Object.freeze({...base,...over})}function isOpaque(color){let rgba=toRgba(color);return rgba!==null&&rgba.a>=1}var SLOT_MIN_BORDER_CONTRAST=3;function boundaryFor(fill,surrounds,seats=[]){if(surrounds.length===0)return null;let shown=surrounds.map(ground=>flattenOnto(fill,ground)??fill);if(surrounds.every((ground,index)=>contrastRatio(shown[index],ground)>=SLOT_MIN_BORDER_CONTRAST))return null;let against=[...surrounds,...shown,...seats];return pushToContrast(shown[0],against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST)}function seatsOf(background,defaults){return background===void 0?defaults:defaults.length===0?[background]:defaults.map(ground=>flattenOnto(background,ground)??ground)}function someInkReads(seats,target){let pole=poleForGrounds(seats);return seats.every(seat=>contrastRatio(pole,seat)>=target)}function collapseUnsatisfiableFill(background,defaults){let ground=defaults[0];return ground===void 0?null:flattenOnto(background,ground)}function inkFor(seats){let pick5=legibleOn(seats[0],SLOT_MIN_CONTRAST);return seats.every(seat=>contrastRatio(pick5,seat)>=SLOT_MIN_CONTRAST)?pick5:poleForGrounds(seats)}function guardSlotContrast(slots,grounds2,surrounds){let changed=false,out={};for(let name of THEME_SLOT_NAMES){let slot=slots[name];if(slot===void 0)continue;let bg=slot.backgroundColor,defaults=grounds2?.[name]??[],seats=seatsOf(bg,defaults),next={...slot},fixed=false;if(bg!==void 0&&seats.length>1&&!someInkReads(seats,SLOT_MIN_CONTRAST)){let opaque=collapseUnsatisfiableFill(bg,defaults);opaque!==null&&(next.backgroundColor=opaque,seats=[opaque],fixed=true)}let around=surrounds?.[name],fill=next.backgroundColor,melts=around!==void 0&&fill!==void 0&&isOpaque(fill)&&boundaryFor(fill,around,seats)!==null;if(seats.length>0){let ink=slot.textColor;if(bg!==void 0)(ink===void 0||seats.some(seat=>contrastRatio(ink,seat)<SLOT_MIN_CONTRAST))&&(next.textColor=inkFor(seats),fixed=true);else if(ink!==void 0){let legible=pushToContrast(ink,seats,poleForGrounds(seats),SLOT_MIN_CONTRAST);legible!==ink&&(next.textColor=legible,fixed=true)}if(slot.borderColor!==void 0){let against=melts?[...seats,...around??[]]:seats,edge=pushToContrast(slot.borderColor,against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST);edge!==slot.borderColor&&(next.borderColor=edge,fixed=true)}}if(melts&&fill!==void 0&&around!==void 0&&next.borderColor===void 0){let edge=boundaryFor(fill,around,seats);edge!==null&&(next.borderColor=edge,fixed=true)}out[name]=fixed?/* @__PURE__ */Object.freeze(next):slot,changed=changed||fixed}return changed?/* @__PURE__ */Object.freeze(out):slots}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});function textGrounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function controlGrounds(c){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill]}function brandReadsOnControls(c){return controlGrounds(c).every(ground=>contrastRatio(c.brand,ground)>=SLOT_MIN_BORDER_CONTRAST)}function linkGrounds(c){return[c.chatGround,c.surface,c.surfaceCream]}function statusGrounds(c,wash2){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill,...washGrounds(c,wash2)]}function washGrounds(c,wash2){return[flattenOnto(wash2,c.surface)??c.surface,flattenOnto(wash2,c.surfaceCream)??c.surfaceCream]}function composerGrounds(c){return[c.composerFill,c.chatGround]}var AUTHORED_AS_IS=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function onCompiledGrounds(c,compiled){let own=new Set(textGrounds(compiled));return textGrounds(c).every(ground=>own.has(ground))}function guardInks(theme){let c=theme.color,compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,other=(theme.brightness==="dark"?EVERFUR_LIGHT:EVERFUR_DARK).color,grounds2=textGrounds(c),flipped=poleForGrounds(grounds2)!==poleForGrounds(textGrounds(compiled)),keepCompiled=onCompiledGrounds(c,compiled),dangerIsCompiled=c.danger===compiled.danger&&c.badgeBgCritical===compiled.badgeBgCritical,ink=(name,value,authored,twin,on,target)=>{let untouched=value===authored&&(name!=="errorRed"||dangerIsCompiled);return untouched&&keepCompiled&&AUTHORED_AS_IS.has(name)?value:pushToContrast(untouched&&flipped?twin:value,on,poleForGrounds(on),target)},text3=(key,on,target)=>ink(`text.${key}`,c.text[key],compiled.text[key],other.text[key],on,target),token=(key,value,on,target)=>ink(key,value,compiled[key],other[key],on,target),tint=key=>flipped&&c[key]===compiled[key]?other[key]:c[key],primary=c.primary,onPrimary=legibleOn(primary,SLOT_MIN_CONTRAST),danger=token("danger",c.danger,[...grounds2,...washGrounds(c,c.badgeBgCritical)],SLOT_MIN_CONTRAST),guarded={...c,onPrimary:onPrimary,onAccent:legibleOn(c.accent,SLOT_MIN_CONTRAST),onDanger:contrastRatio(onPrimary,danger)>=SLOT_MIN_CONTRAST?onPrimary:legibleOn(danger,SLOT_MIN_CONTRAST),brandSoft:tint("brandSoft"),brandSofter:tint("brandSofter"),brandBorder:tint("brandBorder"),borderHairlineGreen:tint("borderHairlineGreen"),brandInk:token("brandInk",c.brandInk,grounds2,SLOT_MIN_CONTRAST),linkInk:token("linkInk",theme.slots.link?.textColor??c.accent,linkGrounds(c),SLOT_MIN_CONTRAST),text:{...c.text,primary:text3("primary",grounds2,SLOT_MIN_CONTRAST),secondary:text3("secondary",grounds2,SLOT_MIN_CONTRAST),muted:text3("muted",grounds2,SLOT_MIN_CONTRAST),metaCool:text3("metaCool",grounds2,SLOT_MIN_CONTRAST),timestamp:text3("timestamp",grounds2,SLOT_MIN_CONTRAST),placeholder:text3("placeholder",controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},danger:danger,errorRed:token("errorRed",c.errorRed,statusGrounds(c,c.badgeBgCritical),SLOT_MIN_CONTRAST),warningStrong:token("warningStrong",c.warningStrong,statusGrounds(c,c.badgeBgCaution),SLOT_MIN_CONTRAST),composerBorder:token("composerBorder",c.composerBorder,composerGrounds(c),SLOT_MIN_BORDER_CONTRAST),brandBorderStrong:token("brandBorderStrong",c.brandBorderStrong,controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},accented={...guarded,...accentFamily(guarded,compiled,keepCompiled)};return{...accented,...statusInks(c,accented,compiled)}}function statusInks(merged,g,compiled){let out={},push=(value,on,target)=>pushToContrast(value,on,poleForGrounds(on),target);if((!same(merged.success,compiled.success)||!same(merged.badgeBgPositive,compiled.badgeBgPositive))&&(out.success=push(merged.success,statusGrounds(g,merged.badgeBgPositive),SLOT_MIN_CONTRAST)),(!same(merged.cautionAccent,compiled.cautionAccent)||!same(merged.badgeBgCaution,compiled.badgeBgCaution))&&(out.cautionAccent=push(merged.cautionAccent,statusGrounds(g,merged.badgeBgCaution),SLOT_MIN_CONTRAST)),isPartnerInfo(merged,compiled)){out.info=push(merged.info,statusGrounds(g,merged.badgeBgInfo),SLOT_MIN_CONTRAST);let edgeGrounds=[g.surface,g.chatGround,...washGrounds(g,merged.badgeBgInfo)];out.infoEdge=push(merged.infoEdge,edgeGrounds,SLOT_MIN_BORDER_CONTRAST)}else out.info=g.brandInk,out.badgeBgInfo=g.brandSoft,out.infoEdge=g.structureEdge;return out}function isPartnerInfo(c,compiled){return!same(c.info,compiled.info)||!same(c.badgeBgInfo,compiled.badgeBgInfo)}var HIGHLIGHT_LIGHT_TINT=.24,HIGHLIGHT_DARK_TINT=.3;function same(a,b){return parseColor(a)===parseColor(b)}function partnerHue(c,compiled){return same(c.accent,compiled.accent)?same(c.brand,compiled.brand)?null:c.brand:c.accent}function tintOver(hue,surface,tint){let wash2=withAlpha(hue,tint);return(wash2===null?null:flattenOnto(wash2,surface))??surface}function accentFamily(c,compiled,keepCompiled){let hue=partnerHue(c,compiled),controls=controlGrounds(c),controlPole=poleForGrounds(controls),darkGround=poleForGrounds([c.surface])===WHITE,everfurMarks=hue===null&&keepCompiled,highlight;everfurMarks?highlight=compiled.highlight:hue===null?highlight=darkGround?tintOver(EVERFUR_LIGHT.color.highlight,c.surface,HIGHLIGHT_DARK_TINT):EVERFUR_LIGHT.color.highlight:highlight=tintOver(hue,c.surface,darkGround?HIGHLIGHT_DARK_TINT:HIGHLIGHT_LIGHT_TINT);let onHighlight=everfurMarks?compiled.onHighlight:pushToContrast(c.text.primary,[highlight],poleForGrounds([highlight]),SLOT_MIN_CONTRAST),mark=hue===null?compiled.mark:pushToContrast(hue,controls,controlPole,SLOT_MIN_BORDER_CONTRAST),toward=brandReadsOnControls(c)?c.brand:controlPole,edge=(value,authored,compiledEdge)=>keepCompiled&&same(value,authored)?compiledEdge:pushToContrast(value,controls,toward,SLOT_MIN_BORDER_CONTRAST),primaryGrounds=[c.chatGround,c.composerFill,c.surface,c.surfaceCream],primaryEdge=primaryGrounds.every(ground=>contrastRatio(c.primary,ground)>=SLOT_MIN_BORDER_CONTRAST)?c.primary:pushToContrast(c.primary,primaryGrounds,poleForGrounds(primaryGrounds),SLOT_MIN_BORDER_CONTRAST);return{highlight:highlight,onHighlight:onHighlight,mark:mark,controlEdge:edge(c.brandBorder,compiled.brandBorder,compiled.controlEdge),structureEdge:edge(c.borderHairlineGreen,compiled.borderHairlineGreen,compiled.structureEdge),primaryEdge:primaryEdge}}var same2=(a,b)=>a!==void 0&&b!==void 0&&parseColor(a)===parseColor(b);function diffThemeAdjustments(merged,resolved){let compiled=(merged.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,m=merged.color,r=resolved.color,out=[],add=(field,role,requested,painted)=>{out.push(/* @__PURE__ */Object.freeze({field:field,role:role,requested:requested,painted:painted}))},own=(value,compiledValue)=>!same2(value,compiledValue);own(m.text.primary,compiled.text.primary)&&!same2(r.text.primary,m.text.primary)&&add("text_color","body text",m.text.primary,r.text.primary),own(m.brand,compiled.brand)&&(same2(r.brandInk,m.brand)||add("primary_color","brand text and icons",m.brand,r.brandInk),same2(r.primaryEdge,m.primary)||add("primary_color","edge of a filled control",m.primary,r.primaryEdge),!same2(r.controlEdge,m.brandBorder)&&!brandReadsOnControls({...r,brand:m.brand})&&add("primary_color","control outline",m.brand,r.controlEdge)),own(m.accent,compiled.accent)&&merged.slots.link?.textColor===void 0&&!same2(r.linkInk,m.accent)&&add("accent_color","link text",m.accent,r.linkInk),own(m.danger,compiled.danger)&&!same2(r.danger,m.danger)&&add("danger_color","error text",m.danger,r.danger),own(m.success,compiled.success)&&!same2(r.success,m.success)&&add("success_color","positive status",m.success,r.success),own(m.warningStrong,compiled.warningStrong)&&!same2(r.warningStrong,m.warningStrong)&&add("warning_color","caution text",m.warningStrong,r.warningStrong),own(m.cautionAccent,compiled.cautionAccent)&&!same2(r.cautionAccent,m.cautionAccent)&&add("warning_color","caution accent",m.cautionAccent,r.cautionAccent),(own(m.info,compiled.info)||own(m.badgeBgInfo,compiled.badgeBgInfo))&&(same2(r.info,m.info)||add("info_color","information text",m.info,r.info),same2(r.infoEdge,m.infoEdge)||add("info_color","information outline",m.infoEdge,r.infoEdge));for(let name of THEME_SLOT_NAMES){let before=merged.slots[name],after=resolved.slots[name];before===void 0||after===void 0||before===after||(after.backgroundColor!==void 0&&!same2(after.backgroundColor,before.backgroundColor)&&add(`slots.${name}.background_color`,"fill",before.backgroundColor??null,after.backgroundColor),before.textColor!==void 0&&after.textColor!==void 0&&!same2(after.textColor,before.textColor)&&add(`slots.${name}.text_color`,"text",before.textColor??null,after.textColor),after.borderColor!==void 0&&!same2(after.borderColor,before.borderColor)&&add(`slots.${name}.border_color`,"outline",before.borderColor??null,after.borderColor))}/* @__PURE__ */
|
|
123
|
+
return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAdjustments(adjustments){if(adjustments.length===0)return;let message=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${adjustments.map(a=>` ${a.field} (${a.role}): ${a.requested??"not set"} -> ${a.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(warned.has(message))return;warned.add(message);let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var DARK_VARIANT_GROUND="#23272C",DARK_VARIANT_TARGET_RATIO=4.5,DARK_VARIANT_LIGHTNESS_FLOOR=.6,DARK_VARIANT_LIGHTNESS_CEILING=.9,DARK_VARIANT_LIGHTNESS_STEP=.02,WHITE_INK="#FFFFFF",NEAR_BLACK_INK="#111111";function readsOnDark(candidate){return contrastRatio(candidate,DARK_VARIANT_GROUND)>=DARK_VARIANT_TARGET_RATIO&&Math.max(contrastRatio(candidate,WHITE_INK),contrastRatio(candidate,NEAR_BLACK_INK))>=DARK_VARIANT_TARGET_RATIO}function deriveDarkVariant(color){let rgba=toRgba(color);if(rgba===null)return null;let{h:h,s:s,l:l}=rgbToHsl(rgba.r,rgba.g,rgba.b),lDark=Math.min(Math.max(l,DARK_VARIANT_LIGHTNESS_FLOOR),DARK_VARIANT_LIGHTNESS_CEILING);for(let i=0;;i+=1){let li=lDark+i*DARK_VARIANT_LIGHTNESS_STEP;if(li>DARK_VARIANT_LIGHTNESS_CEILING)break;let rgb=hslToRgb({h:h,s:s,l:li}),candidate=rgbToHex(rgb.r,rgb.g,rgb.b);if(readsOnDark(candidate))return candidate}let ceiling=hslToRgb({h:h,s:s,l:DARK_VARIANT_LIGHTNESS_CEILING});return rgbToHex(ceiling.r,ceiling.g,ceiling.b)}var HIGH_CONTRAST_TARGET_RATIO=7,PUSH_STEP2=.05,BLACK2="#000000",WHITE2="#FFFFFF";function pushContrast(color,ground,pole,target){let flat=flattenOnto(color,ground);if(flat===null)return pole;if(contrastRatio(flat,ground)>=target)return flat;let from=toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP2;step+=1){let t=step*PUSH_STEP2,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(contrastRatio(candidate,ground)>=target)return candidate}return pole}function hardestGround(color,dark){let grounds2=textGrounds(color),pick5=grounds2[0],pickLum=luminanceOf(pick5);for(let ground of grounds2){let lum=luminanceOf(ground);(dark?lum>pickLum:lum<pickLum)&&(pick5=ground,pickLum=lum)}return pick5}function luminanceOf(color){let rgba=toRgba(color);return rgba===null?0:relativeLuminance(rgba)}function solid(wash2,surface){return flattenOnto(wash2,surface)??parseColor(wash2)??surface}function deriveHighContrast(theme){let c=theme.color,lightInk=poleForGrounds(textGrounds(c))===WHITE2,pole=lightInk?WHITE2:BLACK2,ground=hardestGround(c,lightInk),text3=color2=>pushContrast(color2,ground,pole,HIGH_CONTRAST_TARGET_RATIO),color={...c,brandSoft:solid(c.brandSoft,c.surface),brandSofter:solid(c.brandSofter,c.surface),brandBorder:text3(c.brandBorder),borderHairlineGreen:text3(c.borderHairlineGreen),brandBorderStrong:text3(c.brandBorderStrong),controlEdge:text3(c.controlEdge),structureEdge:text3(c.structureEdge),brandInk:text3(c.brandInk),linkInk:text3(c.linkInk),borderRingCream:text3(c.borderRingCream),composerBorder:text3(c.composerBorder),text:{primary:text3(c.text.primary),secondary:text3(c.text.secondary),muted:text3(c.text.muted),placeholder:text3(c.text.placeholder),onBrand:c.text.onBrand,metaCool:text3(c.text.metaCool),timestamp:text3(c.text.timestamp)},badgeBgPositive:solid(c.badgeBgPositive,c.surface),badgeBgCaution:solid(c.badgeBgCaution,c.surface),badgeBgCritical:solid(c.badgeBgCritical,c.surface),badgeBgNeutral:solid(c.badgeBgNeutral,c.surface),checkupCardLowRiskBg:solid(c.checkupCardLowRiskBg,c.surface),checkupCardConcernBg:solid(c.checkupCardConcernBg,c.surface),info:text3(c.info),infoEdge:text3(c.infoEdge),badgeBgInfo:solid(c.badgeBgInfo,c.surface)};return deepFreeze({...theme,highContrast:true,color:color})}var BACKGROUND_STEPS=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),CREAM_STEP=BACKGROUND_STEPS.cream,SUBTLE_STEP=BACKGROUND_STEPS.subtle,RING_STEP=BACKGROUND_STEPS.ring,MIN_DERIVED_TYPE_SIZE=10;function mix(color,toward,t){let from=toRgba(color),to=toRgba(toward);if(from===null||to===null)return null;let at=(a,b)=>Math.round(a+(b-a)*t);return rgbToHex(at(from.r,to.r),at(from.g,to.g),at(from.b,to.b))}function surfaceFamily(background){if(background===null)return{};let pole=poleForGrounds([background]),cream=mix(background,pole,CREAM_STEP),subtle=mix(background,pole,SUBTLE_STEP),ring=mix(background,pole,RING_STEP);return cream===null||subtle===null||ring===null?{}:{surface:background,background:background,chatGround:background,bubbleAssistant:background,surfaceCream:cream,composerFill:cream,surfaceSubtle:subtle,skeleton:subtle,borderRingCream:ring}}function dangerFamily(danger){if(danger===null)return{};let rgba=toRgba(danger);return rgba===null?{}:{danger:danger,errorRed:danger,badgeBgCritical:`rgba(${rgba.r},${rgba.g},${rgba.b},0.12)`}}function typeSizesFor(base,current,compiled){if(base===null)return current;let factor=base/compiled.type.size.body;if(factor===1)return compiled.type.size;let out={};for(let[key,value]of Object.entries(compiled.type.size))out[key]=Math.max(MIN_DERIVED_TYPE_SIZE,Math.round(value*factor*10)/10);return out}function spaceFor(unit,current,compiled){if(unit===null)return current;let factor=unit/compiled.space.xs,s=n=>Math.round(n*factor),c=compiled.space;return{xs:s(c.xs),sm:s(c.sm),md:s(c.md),lg:s(c.lg),xl:s(c.xl),xxl:s(c.xxl)}}function radiiFor(base,compiled){let factor=base/compiled.radius.md,s=n=>Math.round(n*factor),r=compiled.radius;return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var STATUS_WASH=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function wash(color,alpha){let rgba=toRgba(color);return rgba===null?null:`rgba(${rgba.r},${rgba.g},${rgba.b},${alpha})`}function successFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.success.dark:STATUS_WASH.success.light),card=wash(color,dark?STATUS_WASH.successCard.dark:STATUS_WASH.successCard.light);return badge===null||card===null?{}:{success:color,badgeBgPositive:badge,checkupCardLowRiskBg:card}}function warningFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.warning.dark:STATUS_WASH.warning.light);return badge===null?{}:{warningStrong:color,cautionAccent:color,badgeBgCaution:badge}}function infoFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.info.dark:STATUS_WASH.info.light);return badge===null?{}:{info:color,infoEdge:color,badgeBgInfo:badge}}function lineHeightsFor(lineHeight,current,compiled){if(lineHeight===null)return current;let c=compiled.type.lineHeight,factor=lineHeight/c.normal;if(factor===1)return c;let s=n=>Math.round(n*factor*100)/100;return{tight:s(c.tight),snug:s(c.snug),normal:s(c.normal),relaxed:s(c.relaxed)}}function slotGrounds(c){return{composerInput:[c.composerFill],sendButton:[c.composerFill],userBubble:[c.bubbleUser],assistantBubble:[c.chatGround,c.surfaceCream],vetBubble:[c.bubbleVet],recordCard:[c.surface],vetVisitButton:[c.primary],primaryButton:[c.brand],link:linkGrounds(c),header:[c.surface,c.background,c.chatGround],banner:[flattenOnto(c.badgeBgInfo,c.surface)??c.surface,flattenOnto(c.badgeBgCaution,c.surface)??c.surface,c.surface],chip:[c.chatGround,c.surface,c.background,c.surfaceCream],card:[c.surface],input:[c.surface,c.composerFill,c.surfaceCream,c.surfaceSubtle],tab:[c.surface,c.background],bookingStep:[c.surface,c.background],dialog:[c.surface]}}function slotSurrounds(c){return{userBubble:[c.chatGround],assistantBubble:[c.chatGround],vetBubble:[c.chatGround],sendButton:[c.composerFill],vetVisitButton:[c.surfaceCream,c.surface,c.chatGround],primaryButton:[c.surface,c.surfaceCream]}}var APPEARANCE_PRESET_NAMES=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),APPEARANCE_PRESETS=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),APPEARANCE_SIZE_RANGES=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function isRecord2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPreset(value){return typeof value=="string"&&APPEARANCE_PRESET_NAMES.includes(value.trim().toLowerCase())}function present(vars,key){let value=vars[key];return value??void 0}var PX_MAX_LENGTH=16;function parsePx(value){if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value!="string"||value.length>PX_MAX_LENGTH)return;let match=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(value.trim());return match===null?void 0:Number(match[1])}var COLOR_VARIABLES=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],STATUS_VARIABLES=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],PASSTHROUGH_VARIABLES=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],STRING_VARIABLES=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],SIZE_VARIABLES=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(appearance){if(!isRecord2(appearance))return null;let preset=isPreset(appearance.theme)?APPEARANCE_PRESETS[appearance.theme.trim().toLowerCase()]:{},own=isRecord2(appearance.variables)?appearance.variables:{},vars={...preset};for(let[key,value]of Object.entries(own))value!=null&&(vars[key]=value);let out={},scheme=present(vars,"colorScheme"),schemeName=typeof scheme=="string"?scheme.trim().toLowerCase():null;(schemeName==="light"||schemeName==="dark"||schemeName==="auto")&&(out.color_scheme=schemeName);let suffix=schemeName==="dark"?"_dark":"";for(let[variable,field]of COLOR_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STATUS_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STRING_VARIABLES){let value=present(vars,variable);typeof value=="string"&&value.trim().length>0&&(out[field]=value.trim())}for(let[variable,field]of SIZE_VARIABLES){let px=parsePx(present(vars,variable));px!==void 0&&(out[field]=px)}for(let[variable,field]of PASSTHROUGH_VARIABLES){let value=present(vars,variable);(typeof value=="number"||typeof value=="string")&&(out[field]=value)}let fonts=appearance.fonts;Array.isArray(fonts)&&fonts.length>0&&(out.font_sources=fonts);let rules=appearance.rules;if(isRecord2(rules)){let slots={};for(let name of THEME_SLOT_NAMES){let paint=rules[name];isRecord2(paint)&&(slots[name]=paint)}Object.keys(slots).length>0&&(out.slots=slots)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var LINE_HEIGHT_RANGE=/* @__PURE__ */Object.freeze({min:1,max:2}),FAMILY_MAX_LENGTH=100,URL_MAX_LENGTH=2048,WEIGHTS=["100","200","300","400","500","600","700","800","900"];function finiteNumber(value){if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value!="string"||value.trim().length===0||value.length>16)return null;let n=Number(value.trim());return Number.isFinite(n)?n:null}function parseFontWeight(value){let n=finiteNumber(value);if(n===null)return null;let name=String(n);return WEIGHTS.includes(name)?name:null}function parseLineHeight(value){let n=finiteNumber(value);return n===null?null:Math.min(LINE_HEIGHT_RANGE.max,Math.max(LINE_HEIGHT_RANGE.min,n))}function fontSourceUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>URL_MAX_LENGTH?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(trimmed)?trimmed:null}function familyName(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>FAMILY_MAX_LENGTH||/[\u0000-\u001F\u007F]/.test(trimmed)?null:trimmed}function isRecord3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function pick3(raw,...keys){for(let key of keys)if(raw[key]!==void 0&&raw[key]!==null)return raw[key]}function parseFontSource(raw){if(!isRecord3(raw))return null;let family=familyName(raw.family);if(family===null)return null;let srcRaw=pick3(raw,"src"),cssRaw=pick3(raw,"cssSrc","css_src");if(srcRaw===void 0==(cssRaw===void 0))return null;if(cssRaw!==void 0){let cssSrc=fontSourceUrl(cssRaw);return cssSrc===null?null:/* @__PURE__ */Object.freeze({family:family,cssSrc:cssSrc})}let src=fontSourceUrl(srcRaw);if(src===null)return null;let out={family:family,src:src},weight=parseFontWeight(raw.weight);weight!==null&&(out.weight=weight);let style=typeof raw.style=="string"?raw.style.trim().toLowerCase():null;return(style==="normal"||style==="italic")&&(out.style=style),/* @__PURE__ */Object.freeze(out)}function parseFontSources(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(out.length>=4)break;let source=parseFontSource(entry);source!==null&&out.push(source)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var LOCKABLE_THEME_FIELDS=/* @__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"]),SLOT_LOCK_PREFIX="slots.",THEME_SCHEMA_VERSIONS=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(b){return Object.keys(b).every(key=>key==="schemaVersion"||(b[key]??null)===null)}function isKnownBrandingSchema(b){let version=b?.schemaVersion??null;return version===null||THEME_SCHEMA_VERSIONS.includes(version)}function lockedFieldsOf(b){/* @__PURE__ */
|
|
124
|
+
return new Set(["hide_powered_by",...b?.lockedFields??[]])}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)?true:name.startsWith(SLOT_LOCK_PREFIX)&&THEME_SLOT_NAMES.includes(name.slice(SLOT_LOCK_PREFIX.length))}function parseClientBranding(json){if(json===null||typeof json!="object")return null;let raw=json,flat=parseFlat(raw),expanded=expandAppearance(pick4(raw,"appearance")),branding=expanded===null?flat:overlayFlat(parseFlat(expanded),flat);return isEmptyBranding(branding)?null:/* @__PURE__ */Object.freeze(branding)}function overlayFlat(base,over){let out={...base};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base.slots??null,over.slots??null);return out.slots=Object.keys(slots).length===0?null:slots,out}function parseFlat(raw){return{displayName:parseNonEmptyString(pick4(raw,"display_name","displayName")),logoUrl:parseNonEmptyString(pick4(raw,"logo_url","logoUrl")),primaryColor:parseColor(pick4(raw,"primary_color","primaryColor")),accentColor:parseColor(pick4(raw,"accent_color","accentColor")),brightness:parseBrightness(pick4(raw,"brightness","color_scheme","colorScheme")),fontFamily:parseNonEmptyString(pick4(raw,"font_family","fontFamily")),fontUrl:parseNonEmptyString(pick4(raw,"font_url","fontUrl")),fonts:parseFaceMap(pick4(raw,"fonts")),fontUrls:parseFaceMap(pick4(raw,"font_urls","fontUrls")),placeholder:parseNonEmptyString(pick4(raw,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:parseBool(pick4(raw,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pick4(raw,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pick4(raw,"accent_color_dark","accentColorDark")),surfaceStyle:parseEnum(pick4(raw,"surface_style","surfaceStyle"),SURFACE_STYLES),radiusScale:parseEnum(pick4(raw,"radius_scale","radiusScale"),RADIUS_SCALES),logoUrlDark:parseNonEmptyString(pick4(raw,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pick4(raw,"slots")),accessibilityMaxFontScale:parseMaxFontScale(pick4(raw,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:parseLockedFields(pick4(raw,"locked_fields","lockedFields")),schemaVersion:parseSchemaVersion(pick4(raw,"schema_version","schemaVersion")),backgroundColor:parseColor(pick4(raw,"background_color","backgroundColor")),backgroundColorDark:parseColor(pick4(raw,"background_color_dark","backgroundColorDark")),textColor:parseColor(pick4(raw,"text_color","textColor")),textColorDark:parseColor(pick4(raw,"text_color_dark","textColorDark")),dangerColor:parseColor(pick4(raw,"danger_color","dangerColor")),dangerColorDark:parseColor(pick4(raw,"danger_color_dark","dangerColorDark")),fontSizeBase:parseClamped(pick4(raw,"font_size_base","fontSizeBase"),APPEARANCE_SIZE_RANGES.fontSizeBase),borderRadius:parseClamped(pick4(raw,"border_radius","borderRadius"),APPEARANCE_SIZE_RANGES.borderRadius),spacingUnit:parseClamped(pick4(raw,"spacing_unit","spacingUnit"),APPEARANCE_SIZE_RANGES.spacingUnit),successColor:parseColor(pick4(raw,"success_color","successColor")),successColorDark:parseColor(pick4(raw,"success_color_dark","successColorDark")),warningColor:parseColor(pick4(raw,"warning_color","warningColor")),warningColorDark:parseColor(pick4(raw,"warning_color_dark","warningColorDark")),infoColor:parseColor(pick4(raw,"info_color","infoColor")),infoColorDark:parseColor(pick4(raw,"info_color_dark","infoColorDark")),headingFontFamily:parseNonEmptyString(pick4(raw,"heading_font_family","headingFontFamily")),fontWeightBody:parseFontWeight(pick4(raw,"font_weight_body","fontWeightBody")),fontWeightHeading:parseFontWeight(pick4(raw,"font_weight_heading","fontWeightHeading")),lineHeight:parseLineHeight(pick4(raw,"line_height","lineHeight")),fontSources:parseFontSources(pick4(raw,"font_sources","fontSources")),assistantAvatarUrl:parseNonEmptyString(pick4(raw,"assistant_avatar_url","assistantAvatarUrl"))}}function parseClamped(value,range){let n=parseNumber(typeof value=="string"?value.trim().replace(/px$/i,""):value);return n===null?null:Math.min(range.max,Math.max(range.min,n))}function parseBool(value){if(typeof value=="boolean")return value;if(typeof value=="string"){let lower=value.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false}return null}function pick4(raw,...keys){for(let key of keys)if(Object.prototype.hasOwnProperty.call(raw,key)){let value=raw[key];if(value!==void 0)return value}}function parseNonEmptyString(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}var FONT_FACE_KEYS=["regular","medium","bold","mono","monoMedium","monoBold"];function parseFaceMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;let raw=value,out={};for(let key of FONT_FACE_KEYS){let entry=parseNonEmptyString(pick4(raw,key));entry!==null&&(out[key]=entry)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var SURFACE_STYLES=["white","cream","subtle"],RADIUS_SCALES=["sharp","default","round"];function parseEnum(value,allowed){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return allowed.includes(lower)?lower:null}function parseBrightness(value){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return lower==="light"||lower==="dark"||lower==="auto"?lower:null}function parseNumber(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)&&(typeof value!="string"||value.trim().length>0)?n:null}var MAX_FONT_SCALE_FLOOR=1,MAX_FONT_SCALE_CEILING=3.1;function parseMaxFontScale(value){let n=parseNumber(value);return n===null?null:n<=0?0:Math.min(MAX_FONT_SCALE_CEILING,Math.max(MAX_FONT_SCALE_FLOOR,n))}function parseSchemaVersion(value){if(value==null)return null;let n=parseNumber(value);return n!==null&&Number.isInteger(n)&&n>=1?n:0}function toWireName(name){let trimmed=name.trim();return trimmed.startsWith(SLOT_LOCK_PREFIX)?trimmed:trimmed.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function parseLockedFields(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(typeof entry!="string")continue;let name=toWireName(entry);isThemeLockName(name)&&!out.includes(name)&&out.push(name)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}var BRAND_ASSET_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/brand\/[0-9a-f]{16}\.(png|jpg|webp)$/;function hardenBrandAssetUrl(url){let https=hardenHttpsUrl(url);return https!==null&&BRAND_ASSET_URL.test(https)?https:null}function withServerBranding(base,b){if(b===null||isEmptyBranding(b))return base;let palette=(b.brightness==="light"||b.brightness==="dark")&&b.brightness!==base.brightness?b.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT:base,compiled=palette.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,dark=palette.brightness==="dark",primaryIn=dark?b.primaryColorDark??darkVariantOf(b.primaryColor):b.primaryColor,accentIn=dark?b.accentColorDark??darkVariantOf(b.accentColor):b.accentColor,primaryRaw=primaryIn??palette.color.primary,accent=accentIn??palette.color.accent,keepsCompiled=primaryIn!==null&&isCompiledPrimary(b,primaryRaw,compiled,dark),primary=keepsCompiled?compiled.color.primary:primaryRaw,pr=primaryIn!==null&&!keepsCompiled?toRgba(primary):null,lift=c=>Math.round(c+(255-c)*.4),brandFamily=pr!==null?{brand:primary,bubbleUser:primary,brandInk:primary,text:{...palette.color.text,secondary:primary},brandSoft:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,brandSofter:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,brandBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,borderHairlineGreen:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,brandBorderStrong:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.55)`,composerBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.75)`,accentEdge:`rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`}:keepsCompiled?compiledBrandFamily(compiled,palette.color.text):{},background=(dark?b.backgroundColorDark:b.backgroundColor)??null,grounds2=surfaceFamily(background),groundFamily={...palette.color,...grounds2},bodyInk=(dark?b.textColorDark:b.textColor)??null,status=(light,darkTwin)=>(dark?darkTwin??darkVariantOf(light??null):light)??null,next={brightness:palette.brightness,highContrast:palette.highContrast,meta:{displayName:b.displayName??palette.meta.displayName,logoUrl:(dark?b.logoUrlDark??b.logoUrl:b.logoUrl)??palette.meta.logoUrl,placeholder:b.placeholder??palette.meta.placeholder,hidePoweredBy:b.hidePoweredBy??palette.meta.hidePoweredBy,assistantAvatarUrl:b.assistantAvatarUrl??palette.meta.assistantAvatarUrl},color:{...palette.color,...brandFamily,...grounds2,...dangerFamily(status(b.dangerColor,b.dangerColorDark)),...successFamily(status(b.successColor,b.successColorDark),dark),...warningFamily(status(b.warningColor,b.warningColorDark),dark),...infoFamily(status(b.infoColor,b.infoColorDark),dark),...bodyInk!==null?{text:{...brandFamily.text??palette.color.text,primary:bodyInk}}:{},...surfaceOf(b.surfaceStyle??null,groundFamily),primary:primary,accent:accent,onPrimary:palette.color.onPrimary,onAccent:palette.color.onAccent},space:spaceFor(b.spacingUnit??null,palette.space,compiled),radius:b.borderRadius!=null?radiiFor(b.borderRadius,compiled):radiusOf(b.radiusScale??null,palette.radius,compiled),type:{...palette.type,...mergeFaces(palette.type,b),size:typeSizesFor(b.fontSizeBase??null,palette.type.size,compiled),maxScale:b.accessibilityMaxFontScale??palette.type.maxScale,lineHeight:lineHeightsFor(b.lineHeight??null,palette.type.lineHeight,compiled),weight:b.fontWeightBody==null?palette.type.weight:{...palette.type.weight,regular:b.fontWeightBody},headingFamily:b.headingFontFamily??palette.type.headingFamily,headingWeight:b.fontWeightHeading??palette.type.headingWeight,fontSources:b.fontSources??palette.type.fontSources},motion:palette.motion,slots:mergeThemeSlots(palette.slots,b.slots??null)};return deepFreeze(next)}var FACE_CHAIN={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},FACE_GROUPS=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function isMonoFace(face2){return face2==="mono"||face2==="monoMedium"||face2==="monoBold"}function mergeFaces(base,b){let fonts=b.fonts??{},urls=b.fontUrls??{},families={...base.families},namedFaces={...base.namedFaces},fontUrls={...base.fontUrls};for(let face2 of FONT_FACE_KEYS){let named=FACE_CHAIN[face2].map(key=>fonts[key]).find(name=>name!==void 0),legacy=isMonoFace(face2)?null:b.fontFamily;named!==void 0?(families[face2]=named,namedFaces[face2]=true):legacy!==null&&(families[face2]=legacy,namedFaces[face2]=false);let url=urls[face2]??(face2==="regular"?b.fontUrl:null)??null;url!==null?fontUrls[face2]=url:named!==void 0&&delete fontUrls[face2]}for(let group of FACE_GROUPS)for(let face2 of group)namedFaces[face2]&&group.some(other=>other!==face2&&families[other]===families[face2])&&(namedFaces[face2]=false);return{family:families.regular,mono:families.mono,fontUrl:fontUrls.regular??null,families:families,namedFaces:namedFaces,fontUrls:fontUrls}}function darkVariantOf(color){return color===null?null:deriveDarkVariant(color)}function surfaceOf(style,family){if(style===null)return{};let c=family;return{chatGround:style==="white"?c.surface:style==="subtle"?c.surfaceSubtle:c.surfaceCream}}function sameColor(a,b){return a==null?false:parseColor(a)===parseColor(b)}function isCompiledPrimary(b,primary,compiled,dark){return sameColor(primary,compiled.color.primary)?true:dark&&(b.primaryColorDark??null)===null&&sameColor(b.primaryColor,EVERFUR_LIGHT.color.primary)}function compiledBrandFamily(compiled,text3){let c=compiled.color;return{text:{...text3,secondary:c.text.secondary},brand:c.brand,bubbleUser:c.bubbleUser,brandInk:c.brandInk,brandSoft:c.brandSoft,brandSofter:c.brandSofter,brandBorder:c.brandBorder,borderHairlineGreen:c.borderHairlineGreen,brandBorderStrong:c.brandBorderStrong,composerBorder:c.composerBorder,accentEdge:c.accentEdge}}var RADIUS_FACTOR={sharp:.5,default:1,round:1.5};function radiusOf(scale,base,compiled){if(scale===null)return base;let f=RADIUS_FACTOR[scale],r=compiled.radius,s=n=>Math.round(n*f);return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var DEFAULT_DISPLAY_NAME="Everfur",TEXT_SCALE_FLOOR=.5;function resolveTheme(input){return finalize(mergeLayers(input),input)}function themeAdjustments(input){let merged=mergeLayers(input);return diffThemeAdjustments(merged,finalize(merged,{...input,highContrast:false}))}function mergeLayers(input){let candidate=input?.branding??null,server=isKnownBrandingSchema(candidate)?candidate:null,client=withoutFields(input?.clientOverride??null,lockedFieldsOf(server)),device=input?.colorScheme==="dark"?"dark":"light",chosen=client?.brightness??server?.brightness??"light",withServer=withServerBranding((chosen==="auto"?device:chosen)==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,withoutBrightness(server));return withServerBranding(withServer,withoutBrightness(client))}function previewTheme(input,hints,options){return resolveTheme({...options,branding:parseClientBranding(hints),clientOverride:parseClientBranding(input)})}function wireNameOf(key){return key==="placeholder"?"chat_placeholder":toWireName(key)}var LOCK_ALIASES={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 isLocked(key,locked){return locked.has(wireNameOf(key))?true:(LOCK_ALIASES[key]??[]).some(name=>locked.has(name))}function withoutFields(b,locked){if(b===null)return null;let changed=false,out={...b};for(let key of Object.keys(b))(b[key]??null)!==null&&(isLocked(key,locked)||key==="lockedFields")&&(out[key]=null,changed=true);let slots=out.slots??null;if(slots!==null){let kept={},dropped=false;for(let name of THEME_SLOT_NAMES){let slot=slots[name];slot!==void 0&&(locked.has(`${SLOT_LOCK_PREFIX}${name}`)?dropped=true:kept[name]=slot)}dropped&&(out.slots=Object.keys(kept).length===0?null:/* @__PURE__ */Object.freeze(kept),changed=true)}if(!changed)return b;let stripped=/* @__PURE__ */Object.freeze(out);return isEmptyBranding(stripped)?null:stripped}function withoutBrightness(b){return b===null||b.brightness===null?b:/* @__PURE__ */Object.freeze({...b,brightness:null})}function scaledSizes(size,scale){if(scale===1)return size;let out={};for(let[key,value]of Object.entries(size))out[key]=Math.round(value*scale*10)/10;return out}function effectiveScale(textScale){return textScale===void 0||!Number.isFinite(textScale)?1:Math.max(TEXT_SCALE_FLOOR,textScale)}var SCALE_TIERS=["content","heading","control","compact","badge"];function tierCaps(maxScale){if(!(maxScale>0))return TEXT_SCALE_TIER_CAPS;let out={};for(let tier of SCALE_TIERS){let cap=TEXT_SCALE_TIER_CAPS[tier];out[tier]=cap===0?0:Math.min(cap,maxScale)}return out}function capped(scale,cap){return cap>0?Math.min(scale,cap):scale}function sizesByTier(size,scale,caps,scaleSizes){let out={};for(let tier of SCALE_TIERS)out[tier]=scaleSizes?scaledSizes(size,capped(scale,caps[tier])):size;return out}function registration(isFontRegistered,family){try{let answer=isFontRegistered(family);return answer===!0||answer===!1?answer:null}catch{return null}}function platformFaces(type,input){let isFontRegistered=input?.isFontRegistered,platformMono=input?.platformMonoFamily?.trim()||null;if(isFontRegistered===void 0&&platformMono===null)return{family:type.family,mono:type.mono,families:type.families,namedFaces:type.namedFaces,headingFamily:type.headingFamily};let headingFamily=type.headingFamily!==null&&isFontRegistered!==void 0&®istration(isFontRegistered,type.headingFamily)===false?null:type.headingFamily,families={...type.families},namedFaces={...type.namedFaces};for(let key of FONT_FACE_KEYS)!(families[key]===SYSTEM_FONT_FAMILY||families[key]===SYSTEM_MONO_FAMILY)&&isFontRegistered!==void 0&®istration(isFontRegistered,families[key])===false&&(families[key]=isMonoFace(key)?SYSTEM_MONO_FAMILY:SYSTEM_FONT_FAMILY,namedFaces[key]=false),platformMono!==null&&isMonoFace(key)&&families[key]===SYSTEM_MONO_FAMILY&&(families[key]=platformMono);return{family:families.regular,mono:families.mono,families:families,namedFaces:namedFaces,headingFamily:headingFamily}}function finalize(theme,input){let displayName=theme.meta.displayName.trim().length===0?DEFAULT_DISPLAY_NAME:theme.meta.displayName,logoUrl=hardenBrandAssetUrl(theme.meta.logoUrl),fontUrls={};for(let face2 of FONT_FACE_KEYS){let url=theme.type.fontUrls[face2];url!==void 0&&(fontUrls[face2]=hardenHttpsUrl(url))}let fontUrl=fontUrls.regular??null,motion=input?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:theme.motion.easing,reducedMotion:true}:theme.motion,maxScale=Number.isFinite(theme.type.maxScale)?theme.type.maxScale:DEFAULT_MAX_FONT_SCALE,scale=effectiveScale(input?.textScale),scaleCaps=tierCaps(maxScale),tierSizes=sizesByTier(theme.type.size,scale,scaleCaps,input?.scaleTypeSizes===true),color=guardInks(theme),finalized={brightness:theme.brightness,highContrast:false,meta:{displayName:displayName,logoUrl:logoUrl,placeholder:theme.meta.placeholder,hidePoweredBy:theme.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(theme.meta.assistantAvatarUrl)},color:color,space:theme.space,radius:theme.radius,type:{...theme.type,...platformFaces(theme.type,input),fontUrl:fontUrl,fontUrls:fontUrls,size:tierSizes.content,tierSizes:tierSizes,scale:scale,maxScale:maxScale,scaleCaps:scaleCaps},motion:motion,slots:guardSlotContrast(theme.slots,slotGrounds(color),slotSurrounds(color))};return input?.highContrast===true?deriveHighContrast(deepFreeze(finalized)):deepFreeze(finalized)}var ENTITLEMENTS_PATH="/widget/v1/entitlements",HTTP_NOT_MODIFIED=304,NOT_MODIFIED=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(auth,args={},funnel=createRequestFunnel({auth:auth})){let result=await funnel.send("entitlements.fetch",buildRequest(args));return result.ok?parseUpdated(result.value):result.error.httpStatus===HTTP_NOT_MODIFIED?NOT_MODIFIED:{kind:"failed",error:result.error}}var REGION_MAX=64;function buildRequest(args){let headers={};return isFiniteNumber(args.cachedRevision)&&(headers["if-none-match"]=`"${args.cachedRevision}"`),args.region&&args.region.length<=REGION_MAX?{method:"GET",path:ENTITLEMENTS_PATH,headers:headers,query:{region:args.region}}:{method:"GET",path:ENTITLEMENTS_PATH,headers:headers}}function parseUpdated(body){if(body===null||typeof body!="object"||!isFiniteNumber(body.revision))return malformed3();let region=typeof body.region=="string"?body.region:"",ttlSeconds=isFiniteNumber(body.ttl_seconds)?body.ttl_seconds:0;/* @__PURE__ */
|
|
125
|
+
return Object.freeze({kind:"updated",revision:body.revision,region:region,ttlSeconds:ttlSeconds,decisions:mapCapabilities(body.capabilities),branding:parseBranding(body),livemode:body.livemode!==false})}function parseBranding(body){let direct=parseClientBranding(body.branding);if(direct!==null)return direct;let hints=body.render_hints;if(hints!==null&&typeof hints=="object"){let nested=parseClientBranding(hints.branding);return nested!==null?nested:parseClientBranding(hints)}return null}function mapCapabilities(capabilities){if(capabilities===null||typeof capabilities!="object")/* @__PURE__ */return Object.freeze([]);let out=[];for(let[resource,value]of Object.entries(capabilities))isEnabled(value)&&out.push(/* @__PURE__ */Object.freeze({resource:resource,granted:true}));/* @__PURE__ */
|
|
126
|
+
return Object.freeze(out)}function isEnabled(value){return typeof value=="object"&&value!==null&&value.enabled===true}function malformed3(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}var MIN_POLL_INTERVAL_SECONDS=30;function createEntitlementPoller(deps){let scheduler=deps.scheduler??defaultScheduler,resolve=deps.resolve??fetchEntitlements,floorSeconds=Math.max(1,deps.floorSeconds??MIN_POLL_INTERVAL_SECONDS),rng=deps.rng??Math.random,jitteredFloorSeconds=()=>floorSeconds+rng()*floorSeconds,started=false,stopped=false,timer=null,cachedRevision=null,lastCadenceSeconds=floorSeconds,generation=0,clearTimer=()=>{timer!==null&&(scheduler.clear(timer),timer=null)},schedule=seconds=>{stopped||!started||(lastCadenceSeconds=Math.max(floorSeconds,seconds),timer=scheduler.set(()=>{timer=null,run()},lastCadenceSeconds*1e3))},inFlight3=null,tick=async()=>{if(stopped)return null;let myGen=generation;deps.onFetch?.();let args=deps.region?{cachedRevision:cachedRevision,region:deps.region}:{cachedRevision:cachedRevision},resolution;try{resolution=await resolve(deps.authFor(),args)}catch(cause){return deps.telemetry?.track("sdk.entitlements.poll_error",{reason:describe(cause)}),!stopped&&myGen===generation&&(deps.onSettled?.(),schedule(jitteredFloorSeconds())),null}if(stopped||myGen!==generation)return null;switch(resolution.kind){case"updated":cachedRevision=resolution.revision,deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false),schedule(resolution.ttlSeconds);break;case"notModified":schedule(lastCadenceSeconds);break;case"failed":deps.telemetry?.track("sdk.entitlements.poll_failed",{code:resolution.error.code}),schedule(jitteredFloorSeconds());break;default:schedule(jitteredFloorSeconds())}return deps.onSettled?.(),resolution},run=()=>{let current=tick().finally(()=>{inFlight3===current&&(inFlight3=null)});return inFlight3=current,current};return{start(){started||stopped||(started=true,run())},prime(){return stopped?Promise.resolve(null):inFlight3??run()},stop(){stopped||(stopped=true,generation++,clearTimer())},refresh(){stopped||!started||(generation++,cachedRevision=null,clearTimer(),run())}}}var defaultScheduler={set(callback,ms){let handle=setTimeout(callback,ms);return handle.unref?.(),handle},clear(handle){clearTimeout(handle)}};function describe(cause){return cause instanceof Error?cause.message:"poll failed"}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3,PER_USER_KV_KEYS=/* @__PURE__ */Object.freeze([NOTIFICATIONS_DEVICE_KV_KEY]);function startBeforeLogoutHooks(deps){let{leaving:leaving,identity:identity,hooks:hooks,telemetry:telemetry}=deps;if(leaving===null||identity===null||hooks.size===0)return null;let context=/* @__PURE__ */Object.freeze({userRef:leaving.userRef,auth:deps.graceAuth()}),runs=[...hooks].map(hook=>{try{return Promise.resolve(hook(context))}catch(cause){return Promise.reject(cause)}}),report=(reason,count2)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count2,totalCount:runs.length})}catch{}},settled=Promise.allSettled(runs).then(outcomes=>{let failed=outcomes.filter(outcome=>outcome.status==="rejected").length;failed>0&&report("failed",failed)});return new Promise(resolve=>{let done=false,finish=()=>{done||(done=true,clearTimeout(timer),resolve())},timer=setTimeout(()=>{done||report("timeout",runs.length),finish()},LOGOUT_HOOK_BUDGET_MS);settled.then(finish,finish)})}function graceAuth(deps){let{leaving:leaving,identity:identity,transport:transport,sessionId:sessionId}=deps,token=identity.currentToken();token.catch(()=>{});let frozen={userRef:leaving.userRef,currentToken:()=>token,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:transport,identity:frozen,userRef:leaving.userRef,sessionId:sessionId}}async function sweepPerUserKv(kv,telemetry){if(PER_USER_KV_KEYS.length===0)return;let results=await Promise.allSettled(PER_USER_KV_KEYS.map(key=>kv.removeItem(key))),failedCount=results.filter(result=>result.status==="rejected").length;failedCount>0&&telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:failedCount,totalCount:results.length})}function compiledDefaultDecisions(){/* @__PURE__ */
|
|
127
|
+
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners2)listener()};return{subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot(){return snapshot},set(next){snapshot=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{}}),emit()},reset(){snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit()},setPending(pending){snapshot.isPending!==pending&&(snapshot=/* @__PURE__ */Object.freeze({...snapshot,isPending:pending}),emit())}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
|
|
128
|
+
return Object.freeze({track(event,props){try{port.track(event,props)}catch{}},trackExpectedFailure(code,props){try{port.trackExpectedFailure(code,props)}catch{}}})}var ENV_HINT=/* @__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 ${ENV_API_BASE_URL} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function reportConfigFailure(failure2,telemetry,platform=SDK_PLATFORM){try{telemetry.trackExpectedFailure("sdk.config.invalid",{reason:failure2.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${failure2.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+ENV_HINT[platform])}function refusingTransport(failure2){/* @__PURE__ */
|
|
129
|
+
return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}function createInMemoryKv(){let map=/* @__PURE__ */new Map;return{async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}}}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("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=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&reportConfigFailure(failure2,this.telemetry,opts?.platform),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store;let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs));return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,branding,livemode)=>this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{}}),onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){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:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&¬ifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&¤t.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),()=>err(makeEverfurError("authRejected",{retryable:false}))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}/* @__PURE__ */
|
|
130
|
+
return Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll())}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=react.useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot.branding??null,theme=react.useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment2=props.seams.isDevelopment;return react.useEffect(()=>{isDevelopment2===void 0||!safeDevelopment(isDevelopment2)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment2,serverBranding,clientOverride,scheme]),react.createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment2){try{return isDevelopment2()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=react.useRef(null),supersededRef=react.useRef(null),[renderTick,scheduleRender]=react.useReducer(n=>n+1,0),imperativeUserRef=react.useRef(null),lastPropUserRef=react.useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=react.useRef(null),lastPropPetRef=react.useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:seams.withDefaults?seams.withDefaults(config):config,user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=react.useRef(null);react.useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),react.useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;react.useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),react.useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]),react.useEffect(()=>()=>runtime.dispose(),[runtime]),react.useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=react.useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=react.useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=react.createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return react.createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}var HEADERS_RECEIVED=2;function readEventSourceResponseHeader(instance,name){let xhr=instance?._xhr;if(!xhr||typeof xhr.getResponseHeader!="function"||typeof xhr.readyState=="number"&&xhr.readyState<HEADERS_RECEIVED)return null;let value;try{value=xhr.getResponseHeader(name)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function createRnEventSourceFactory(){let Ctor=EventSource__default.default;return(url,init)=>{let instance=new Ctor(url,{method:init.method,headers:init.headers,pollingInterval:init.pollingInterval??0,...init.body!==void 0?{body:init.body}:{}});return Object.assign(instance,{getResponseHeader:name=>readEventSourceResponseHeader(instance,name)})}}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe=reactNative.Dimensions?.addEventListener;if(typeof subscribe!="function")return()=>{};let subscription=subscribe.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe=="function"?subscribe.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", 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 rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,isDevelopment:isDevelopment});function wrapInSafeArea(children){return react.createElement(reactNativeSafeAreaContext.SafeAreaProvider,null,children)}var rnSeams=/* @__PURE__ */Object.freeze({platform:"react-native",eventSourceFactory:createRnEventSourceFactory(),wrap:wrapInSafeArea,theme:rnThemeSeams});function EverfurProvider(props){return react.createElement(EverfurProviderCore,{...props,seams:rnSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
131
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles2.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
132
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles2.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
|
|
133
|
+
/* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
134
|
+
/* @__PURE__ */Object.freeze({key:"outdated",label:CHAT_COPY.feedbackReasonOutdated,feedbackType:"outdated"}),
|
|
135
|
+
/* @__PURE__ */Object.freeze({key:"unsafe",label:CHAT_COPY.feedbackReasonUnsafe,feedbackType:"dangerous"}),
|
|
136
|
+
/* @__PURE__ */Object.freeze({key:"unclear",label:CHAT_COPY.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
137
|
+
/* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
|
|
138
|
+
/* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
|
|
139
|
+
/* @__PURE__ */Object.freeze({sentiment:"neutral",label:CHAT_COPY.feedbackNeutral}),
|
|
140
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,scope=react.useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch]),[binding,setBinding]=react.useState(null),controller=binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=react.useRef(null);react.useEffect(()=>{let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,scope]);let subscribe=react.useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=react.useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot=react.useSyncExternalStore(subscribe,getSnapshot,getSnapshot),send=react.useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=react.useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=react.useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=react.useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=react.useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=react.useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=react.useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=react.useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return react.useMemo(()=>({status:snapshot.status,messages:snapshot.messages,conversationId:snapshot.conversationId,petRef:petRef2,error:snapshot.error,isStreaming:snapshot.isStreaming,isBootstrapping:snapshot.isBootstrapping,historyCursor:snapshot.historyCursor??null,isLoadingHistory:snapshot.isLoadingHistory??false,stopped:snapshot.stopped??false,reconnecting:snapshot.reconnecting??false,...history,suggestedPrompts:snapshot.suggestedPrompts,unreadCount:snapshot.unreadCount,hasUnreadThreads:snapshot.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot=controller.getSnapshot();return snapshot.status==="error"&&snapshot.error!==null?err(snapshot.error):ok(lastAssistantResponseId(snapshot.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return err(makeEverfurError("internalError",{retryable:true}))}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=react.useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef2),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef2,scopeEpoch,maxPerMessage,options.transport]),scoped=react.useMemo(()=>options.queue??build(),[options.queue,build]),disposed=react.useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=react.useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;react.useEffect(()=>{if(queue!==options.queue){if(disposed.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot=react.useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=react.useState(null),add=react.useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=react.useCallback(id=>queue.retry(id),[queue]),remove=react.useCallback(id=>queue.remove(id),[queue]),clear=react.useCallback(()=>queue.clear(),[queue]),dismissRejected=react.useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot.attachments.some(row=>row.status==="uploading"),failed=snapshot.attachments.some(row=>row.status==="failed");return react.useMemo(()=>({available:queue.available,attachments:snapshot.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=react.useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=react.useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=react.useState({key:null,status:"idle",error:null,registered:null}),generation=react.useRef(0),onRegisteredRef=react.useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=react.useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);react.useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=react.useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return react.useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var NONE=/* @__PURE__ */Object.freeze({});function useSentImages(messages){let[byMessage,setByMessage]=react.useState(NONE),pending=react.useRef(null),knownIds=react.useRef([]);knownIds.current=messages.map(message=>message.id),react.useEffect(()=>{if(messages.length===0){pending.current=null,setByMessage(current=>current===NONE?current:NONE);return}let staged=pending.current;if(staged===null)return;let bubble=messages.find(message=>message.role==="user"&&!staged.known.has(message.id));bubble!==void 0&&(pending.current=null,setByMessage(current=>({...current,[bubble.id]:staged.images})))},[messages]);let stage=react.useCallback(images=>{pending.current=images.length===0?null:{images:images,known:new Set(knownIds.current)}},[]);return react.useMemo(()=>({byMessage:byMessage,stage:stage}),[byMessage,stage])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt){let clean=sanitizeSeedPrompt(prompt),latest=react.useRef(askEverfur);latest.current=askEverfur;let asked=react.useRef(null);react.useEffect(()=>{if(clean===null||isBootstrapping||asked.current===clean)return;let ask=latest.current;ask!==void 0&&(asked.current=clean,Promise.resolve(ask(clean)).catch(()=>{}))},[clean,isBootstrapping])}function isCoalesced(trigger,conversationId2,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId2=state.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable2(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=react.useRef(target);latest.current=target;let lastRefresh=react.useRef(null),deferred=react.useRef(null),isOffline=lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,run=react.useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:isOffline,lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},react.useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),react.useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=react.useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=react.useRef(null);react.useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}function useChatDraft(send,conversationId2,seed){let[state,setState]=react.useState({send:send,conversationId:conversationId2,text:seed??"",seeded:seed??null}),belongs=state.send===send&&(state.conversationId===null||state.conversationId===conversationId2);react.useEffect(()=>{setState(previous=>{let kept=previous.send===send&&(previous.conversationId===null||previous.conversationId===conversationId2),text3=kept?previous.text:"",seeded=kept?previous.seeded:null,fresh2=seed!=null&&seed!==seeded&&text3.length===0;return{send:send,conversationId:conversationId2,text:fresh2?seed:text3,seeded:fresh2?seed:seeded}})},[send,conversationId2,seed]);let setDraft=react.useCallback(text3=>setState(previous=>({send:send,conversationId:conversationId2,text:text3,seeded:previous.seeded})),[send,conversationId2]);return[belongs?state.text:"",setDraft]}function usePersistedDraft(store,conversationId2,draft,setDraft){let latest=react.useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=react.useRef(null),[settled,setSettled]=react.useState(null);react.useEffect(()=>{if(store===void 0)return;let key=`${conversationId2??""}`;if(asked.current===key)return;asked.current=key;let live=true;return(async()=>{let outcome=await callHostAsync(()=>store.read(conversationId2));if(!live)return;let stored2=outcome.ok&&typeof outcome.value=="string"?outcome.value:"";stored2.length>0&&latest.current.draft.length===0&&latest.current.setDraft(stored2),setSettled(key)})(),()=>{live=false}},[store,conversationId2]),react.useEffect(()=>{store===void 0||settled!==`${conversationId2??""}`||callHost(()=>store.write(conversationId2,draft))},[store,conversationId2,draft,settled])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=react.useState(false),[query,setQuery]=react.useState(""),scope=chat.listConversations,generation=react.useRef(0),[state,setState]=react.useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);react.useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=react.useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=react.useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:petName?.trim()||CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason(petName)}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=react.useState(null),[expanded,setExpanded]=react.useState(false);react.useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=react.useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=react.useCallback(()=>setExpanded(true),[]);return react.useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView2(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
|
|
141
|
+
return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef2,conversationId2){let opts={};return petRef2!==void 0&&(opts.petRef=petRef2),conversationId2!==void 0&&(opts.conversationId=conversationId2),opts}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
|
|
142
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
|
|
143
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar}),
|
|
144
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar}),
|
|
145
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar})]})}function Cross({size:size,color:color,strokeWidth:strokeWidth,rotate:rotate}){let w=stroke(size,strokeWidth),length=size*.78;/* @__PURE__ */
|
|
146
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{transform:[{rotate:rotate}]}],...HIDDEN,children:[
|
|
147
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:length,height:w,borderRadius:w,backgroundColor:color}}),
|
|
148
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:w,height:length,borderRadius:w,backgroundColor:color}})]})}function PlusGlyph(props){/* @__PURE__ */
|
|
149
|
+
return jsxRuntime.jsx(Cross,{...props,rotate:"0deg"})}function CloseGlyph(props){/* @__PURE__ */
|
|
150
|
+
return jsxRuntime.jsx(Cross,{...props,rotate:"45deg"})}function CheckGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
151
|
+
return jsxRuntime.jsx(reactNative.View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:size*.36,height:size*.66,marginTop:-size*.14,borderBottomWidth:w,borderRightWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})})}var CHEVRON_POSE={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:size,color:color,strokeWidth:strokeWidth,direction:direction}){let w=stroke(size,strokeWidth),side=size*.46,pose=CHEVRON_POSE[direction];/* @__PURE__ */
|
|
152
|
+
return jsxRuntime.jsx(reactNative.View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:side,height:side,borderRightWidth:w,borderBottomWidth:w,borderColor:color,marginTop:side*pose.marginTop,marginLeft:side*pose.marginLeft,transform:[{rotate:pose.rotate}]}})})}function BookGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),page={width:size*.42,height:size*.7,borderWidth:w,borderColor:color,borderRadius:w};/* @__PURE__ */
|
|
153
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{flexDirection:"row",gap:1}],...HIDDEN,children:[
|
|
154
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[page,{borderTopLeftRadius:size*.2}]}),
|
|
155
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[page,{borderTopRightRadius:size*.2}]})]})}function ArrowUpRightGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),head=size*.5;/* @__PURE__ */
|
|
156
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
157
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",width:size*.78,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"-45deg"}]}}),
|
|
158
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.16,right:size*.16,width:head,height:head,borderTopWidth:w,borderRightWidth:w,borderColor:color}})]})}function CopyGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),side=size*.6,square={position:"absolute",width:side,height:side,borderWidth:w,borderColor:color,borderRadius:size*.14};/* @__PURE__ */
|
|
159
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
160
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[square,{top:0,left:0}]}),
|
|
161
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[square,{bottom:0,right:0}]})]})}function ThumbGlyph({size:size,color:color,strokeWidth:strokeWidth,active:active,rotate:rotate}){let w=stroke(size,strokeWidth),fill=active?color:"transparent";/* @__PURE__ */
|
|
162
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{transform:[{rotate:rotate}]}],...HIDDEN,children:[
|
|
163
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:size*.08,left:size*.12,width:size*.62,height:size*.5,borderWidth:w,borderColor:color,backgroundColor:fill,borderRadius:size*.12,borderTopLeftRadius:size*.04}}),
|
|
164
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.04,left:size*.4,width:size*.3,height:size*.5,borderWidth:w,borderColor:color,backgroundColor:fill,borderRadius:size*.15,transform:[{rotate:"-20deg"}]}}),
|
|
165
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:size*.08,left:0,width:size*.2,height:size*.5,borderWidth:w,borderColor:color,backgroundColor:fill,borderRadius:size*.05}})]})}function InfoGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
166
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{borderRadius:size/2,borderWidth:w,borderColor:color}],...HIDDEN,children:[
|
|
167
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:w,height:w,borderRadius:w,backgroundColor:color,marginBottom:size*.1}}),
|
|
168
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:w,height:size*.34,borderRadius:w,backgroundColor:color}})]})}function UploadGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),head=size*.34;/* @__PURE__ */
|
|
169
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
170
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.06,width:head,height:head,borderTopWidth:w,borderLeftWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}}),
|
|
171
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.1,width:w,height:size*.56,borderRadius:w,backgroundColor:color}}),
|
|
172
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:0,width:size*.84,height:size*.3,borderBottomWidth:w,borderLeftWidth:w,borderRightWidth:w,borderColor:color,borderBottomLeftRadius:w,borderBottomRightRadius:w}})]})}function PhotoGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
173
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{borderWidth:w,borderColor:color,borderRadius:size*.14,overflow:"hidden"}],...HIDDEN,children:[
|
|
174
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.16,left:size*.18,width:size*.16,height:size*.16,borderRadius:size,backgroundColor:color}}),
|
|
175
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:-size*.3,right:-size*.1,width:size*.7,height:size*.7,borderTopWidth:w,borderLeftWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
176
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
177
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.08,width:size*.34,height:size*.2,borderTopWidth:w,borderLeftWidth:w,borderRightWidth:w,borderColor:color,borderTopLeftRadius:w,borderTopRightRadius:w}}),
|
|
178
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.22,width:size*.92,height:size*.66,borderWidth:w,borderColor:color,borderRadius:size*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:size*.3,height:size*.3,borderRadius:size,borderWidth:w,borderColor:color}})})]})}function SearchGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),unit=size/24,outer=16*unit+w,ringAt=11*unit-outer/2,start=11+8/Math.SQRT2,length=(21-start)*Math.SQRT2*unit,middle=(start+21)/2*unit;/* @__PURE__ */
|
|
179
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
180
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:ringAt,left:ringAt,width:outer,height:outer,borderRadius:outer,borderWidth:w,borderColor:color}}),
|
|
181
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:middle-w/2,left:middle-(length+w)/2,width:length+w,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"45deg"}]}})]})}function MapPinGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),ring=size*.62;/* @__PURE__ */
|
|
182
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
183
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,width:ring,height:ring,borderRadius:ring,borderWidth:w,borderColor:color,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:w*1.4,height:w*1.4,borderRadius:w,backgroundColor:color}})}),
|
|
184
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:size*.04,width:ring*.5,height:ring*.5,borderRightWidth:w,borderBottomWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:size,color:color,testID:testID}){let half=size*.36;/* @__PURE__ */
|
|
185
|
+
return jsxRuntime.jsx(reactNative.View,{style:box(size),testID:testID,...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:0,height:0,marginLeft:size*.12,borderLeftWidth:size*.78,borderTopWidth:half,borderBottomWidth:half,borderLeftColor:color,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:size,color:color,testID:testID}){/* @__PURE__ */
|
|
186
|
+
return jsxRuntime.jsx(reactNative.View,{style:box(size),testID:testID,...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:size*.5,height:size*.5,backgroundColor:color}})})}function Ring({size:size,strokeWidth:strokeWidth,color:color,children:children}){/* @__PURE__ */
|
|
187
|
+
return jsxRuntime.jsx(reactNative.View,{style:[box(size),{borderRadius:size/2,borderWidth:strokeWidth??reactNative.StyleSheet.hairlineWidth,borderColor:color}],children:children})}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var CHAT_MOTION=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return chatMotion(theme)}var NEWTON_ITERATIONS=8;function bezierComponent(t,a1,a2){return((1-3*a2+3*a1)*t+(3*a2-6*a1))*t*t+3*a1*t}function bezierSlope(t,a1,a2){return 3*(1-3*a2+3*a1)*t*t+2*(3*a2-6*a1)*t+3*a1}function bezierEasing(curve){let[x1,y1,x2,y2]=curve;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<NEWTON_ITERATIONS;i+=1){let slope=bezierSlope(t,x1,x2);if(slope===0)break;t-=(bezierComponent(t,x1,x2)-x)/slope}return bezierComponent(Math.min(1,Math.max(0,t)),y1,y2)}}var STANDARD=bezierEasing(CHAT_EASING.standard),OUT_QUAD=bezierEasing(CHAT_EASING.outQuad),OUT=bezierEasing(CHAT_EASING.out);function useAnimatedValue(initial){let ref=react.useRef(null);return ref.current===null&&(ref.current=new reactNative.Animated.Value(initial)),ref.current}function useFadeIn(durationMs,options={}){let risePx=options.risePx??0,delayMs=options.delayMs??0,value=useAnimatedValue(durationMs>0?0:1);return react.useEffect(()=>{if(durationMs<=0)return;let timing=reactNative.Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT_QUAD,useNativeDriver:true}),animation=delayMs>0?reactNative.Animated.sequence([reactNative.Animated.delay(delayMs),timing]):timing;return animation.start(),()=>animation.stop()},[value,durationMs,delayMs]),react.useMemo(()=>({opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})}]}),[value,risePx])}function FadePresence({visible:visible,inMs:inMs,outMs:outMs,style:style,children:children}){let[mounted,setMounted]=react.useState(visible),opacity=useAnimatedValue(visible&&inMs<=0?1:0);return react.useEffect(()=>{if(visible){setMounted(true);let animation2=reactNative.Animated.timing(opacity,{toValue:1,duration:Math.max(0,inMs),easing:STANDARD,useNativeDriver:true});return animation2.start(),()=>animation2.stop()}if(!mounted)return;if(outMs<=0){setMounted(false);return}let animation=reactNative.Animated.timing(opacity,{toValue:0,duration:outMs,easing:STANDARD,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&setMounted(false)}),()=>animation.stop()},[visible,mounted,inMs,outMs,opacity]),!mounted&&!visible?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[style,{opacity:opacity}],children:children})}var AT_REST=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function useBubbleEnter(animate,motion){let[durationMs]=react.useState(()=>animate?motion.bubbleInMs:0),run=durationMs>0,value=useAnimatedValue(run?0:1);react.useEffect(()=>{if(durationMs<=0)return;let animation=reactNative.Animated.timing(value,{toValue:1,duration:durationMs,easing:OUT,useNativeDriver:true});return animation.start(),()=>animation.stop()},[durationMs,value]);let fromScale=motion.bubbleFromScale,risePx=motion.bubbleRisePx;return react.useMemo(()=>run?{opacity:value,transform:[{translateY:value.interpolate({inputRange:[0,1],outputRange:[risePx,0]})},{scale:value.interpolate({inputRange:[0,1],outputRange:[fromScale,1]})}]}:AT_REST,[run,value,risePx,fromScale])}function useEnteringRows(rows){let verdicts=react.useRef(null),head=react.useRef(null),first=rows[0]?.id??null;if(verdicts.current===null||head.current!==first){let opened=verdicts.current===null;verdicts.current=new Map(rows.map(row=>[row.id,opened&&row.pending===true])),head.current=first}let map=verdicts.current;for(let row of rows)map.has(row.id)||map.set(row.id,true);return react.useCallback(id=>map.get(id)===true,[map])}var PRESS_SCALE_HIT_SLOP=12;function PressScale({style:style,containerStyle:containerStyle,children:children,onPressIn:onPressIn,onPressOut:onPressOut,hitSlop:hitSlop,...pressable}){let motion=useChatMotion(),scale=useAnimatedValue(1),animate=react.useCallback(toValue=>{motion.pressMs<=0||motion.pressScale===1||reactNative.Animated.timing(scale,{toValue:toValue,duration:motion.pressMs,easing:STANDARD,useNativeDriver:true}).start()},[scale,motion.pressMs,motion.pressScale]);/* @__PURE__ */
|
|
188
|
+
return jsxRuntime.jsx(reactNative.Pressable,{...pressable,hitSlop:hitSlop??PRESS_SCALE_HIT_SLOP,style:containerStyle,onPressIn:event=>{animate(motion.pressScale),onPressIn?.(event)},onPressOut:event=>{animate(1),onPressOut?.(event)},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[style,{transform:[{scale:scale}]}],children:children})})}function useRevealedText(text3,revealing,motion){let ticking=revealing&&motion.revealTickMs>0,[visible,setVisible]=react.useState(0),latest=react.useRef(text3);return latest.current=text3,react.useEffect(()=>{if(!ticking)return;let id=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.length))},motion.revealTickMs);return()=>clearInterval(id)},[ticking,motion]),ticking?text3.slice(0,Math.min(visible,text3.length)):text3}var layoutAnimationEnabled=false;function animateLayout(motion){motion.layoutMs<=0||(layoutAnimationEnabled||(layoutAnimationEnabled=true,reactNative.Platform.OS==="android"&&typeof reactNative.UIManager.setLayoutAnimationEnabledExperimental=="function"&&reactNative.UIManager.setLayoutAnimationEnabledExperimental(true)),reactNative.LayoutAnimation.configureNext({duration:motion.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function useAnimateLayoutOn(key,motion){let previous=react.useRef(key);previous.current!==key&&(previous.current=key,animateLayout(motion))}var CLOSE_SIZE=36,CLOSE_GLYPH=22,CLOSE_HIT_SLOP=12,CLOSE_TOP_OFFSET=12,CLOSE_RIGHT=16,BACKDROP="#000",CLOSE_BG="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:uri,label:label,onClose:onClose}){let theme=useEverfurTheme(),insets=reactNativeSafeAreaContext.useSafeAreaInsets();return uri===null?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Modal,{visible:true,animationType:theme.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:onClose,children:[
|
|
189
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,style:styles.backdrop,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:uri},style:styles.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:label,accessibilityIgnoresInvertColors:true})}),
|
|
190
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{pointerEvents:"box-none",style:[styles.closeWrap,{top:insets.top+CLOSE_TOP_OFFSET}],children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closePreview,hitSlop:CLOSE_HIT_SLOP,style:styles.closeButton,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH,color:theme.color.surface,strokeWidth:2})})})]})}var styles=reactNative.StyleSheet.create({backdrop:{flex:1,backgroundColor:BACKDROP,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:CLOSE_RIGHT},closeButton:{width:CLOSE_SIZE,height:CLOSE_SIZE,borderRadius:CLOSE_SIZE/2,backgroundColor:CLOSE_BG,alignItems:"center",justifyContent:"center"}});var TAIL_SIZE=12,TILE_MIN_WIDTH=80,TILE_ICON_SIZE=44,TILE_GLYPH=22,BUBBLE_SHADOW_OPACITY=.14,BUBBLE_SHADOW_RADIUS=18,BUBBLE_SHADOW_OFFSET_Y=8,TILE_LABEL=/* @__PURE__ */Object.freeze({photo:CHAT_COPY.attachmentPhoto,camera:CHAT_COPY.attachmentCamera});function AttachmentPickerPopover({sources:sources,full:full,onPick:onPick,onClose:onClose}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles2(theme),[theme]);/* @__PURE__ */
|
|
191
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles2.anchor,pointerEvents:"box-none",children:[
|
|
192
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:styles2.dismissLayer,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.closeAttachmentPicker,onPress:onClose}),
|
|
193
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.bubble,children:[
|
|
194
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.tilesRow,children:sources.map(source=>/* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:TILE_LABEL[source],accessibilityState:{disabled:full},disabled:full,containerStyle:styles2.tile,style:styles2.tileInner,onPress:()=>onPick(source),children:[
|
|
195
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.tileIconWrap,children:source==="photo"?/* @__PURE__ */jsxRuntime.jsx(PhotoGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */jsxRuntime.jsx(CameraGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5})}),
|
|
196
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.tileLabel,children:TILE_LABEL[source]})]},source))}),
|
|
197
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.tail}),
|
|
198
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.tailFill})]})]})}function makeStyles2(theme){let c=theme.color,r=theme.radius;return reactNative.StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:c.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:c.shadow,shadowOpacity:BUBBLE_SHADOW_OPACITY,shadowRadius:BUBBLE_SHADOW_RADIUS,shadowOffset:{width:0,height:BUBBLE_SHADOW_OFFSET_Y},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:TILE_MIN_WIDTH,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:TILE_ICON_SIZE,height:TILE_ICON_SIZE,borderRadius:TILE_ICON_SIZE/2,backgroundColor:c.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(theme,"medium"),fontSize:12,lineHeight:14,color:c.text.primary},tail:{position:"absolute",left:24,bottom:-TAIL_SIZE/2,width:TAIL_SIZE,height:TAIL_SIZE,backgroundColor:c.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:c.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:TAIL_SIZE+4,height:2,backgroundColor:c.surfaceCream}})}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var THUMB_SIZE=56,CARD_RADIUS=12,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_RADIUS=10,UPLOADING_ALPHA=.45,SUCCESS_OVERLAY="rgba(7,193,104,0.55)",FAILED_OVERLAY="rgba(185,28,28,0.55)",SUCCESS_FLASH_FADE_IN_MS=200,SUCCESS_FLASH_FADE_OUT_MS=300,SUCCESS_GLYPH=20,REMOVE_SIZE=22,REMOVE_GLYPH=12,REMOVE_BG="rgba(0,0,0,0.78)",SINGLE_IMAGE=220,GRID_IMAGE=100,IMAGE_ON_BRAND="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:attachments,rejected:rejected,uploadFailed:uploadFailed=false,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles3(theme),[theme]);return attachments.length===0&&rejected===null?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.strip,children:[attachments.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.cards,children:attachments.map(row=>/* @__PURE__ */jsxRuntime.jsx(PreviewCard,{row:row,styles:styles2,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview},row.id))}):null,uploadFailed?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.rejected,accessibilityRole:"alert",children:CHAT_COPY.attachmentsFailedBlocked}):null,rejected!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.rejected,accessibilityRole:"alert",children:attachmentErrorMessage(rejected)}):null]})}function PreviewCard({row:row,styles:styles2,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),uploading=row.status==="uploading",failed=row.status==="failed",uploaded=row.status==="uploaded",previous=react.useRef(row.status),[flash,setFlash]=react.useState(false);return react.useEffect(()=>{let before=previous.current;previous.current=row.status,row.status==="uploaded"&&before==="uploading"&&setFlash(true)},[row.status]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.card,children:[
|
|
199
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:uploaded?"button":"image",accessibilityLabel:uploaded?fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}):row.filename,accessibilityState:{busy:uploading,disabled:!uploaded},disabled:!uploaded,style:styles2.thumbHit,onPress:()=>onPreview(row),children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.thumb,children:[
|
|
200
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:row.previewUri},style:styles2.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),uploading?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.uploadingOverlay,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:theme.color.surface})}):null,flash?/* @__PURE__ */jsxRuntime.jsx(SuccessFlash,{styles:styles2,onDone:()=>setFlash(false)}):null]})}),failed?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.retryUpload,{filename:row.filename}),style:styles2.failedOverlay,onPress:()=>onRetry(row.id),children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.failedInner,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}):null,
|
|
201
|
+
/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.removeAttachment,{filename:row.filename}),hitSlop:6,containerStyle:styles2.removeSlot,style:styles2.removeButton,onPress:()=>onRemove(row.id),children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:REMOVE_GLYPH,color:theme.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:styles2,onDone:onDone}){let theme=useEverfurTheme(),motion=useChatMotion(),opacity=react.useRef(null);opacity.current===null&&(opacity.current=new reactNative.Animated.Value(0));let value=opacity.current;return react.useEffect(()=>{let animation=reactNative.Animated.sequence([reactNative.Animated.timing(value,{toValue:1,duration:SUCCESS_FLASH_FADE_IN_MS,useNativeDriver:true}),reactNative.Animated.delay(motion.uploadFlashMs),reactNative.Animated.timing(value,{toValue:0,duration:SUCCESS_FLASH_FADE_OUT_MS,useNativeDriver:true})]);return animation.start(({finished:finished})=>{finished&&onDone()}),()=>animation.stop()},[value,motion.uploadFlashMs,onDone]),/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{pointerEvents:"none",style:[styles2.successOverlay,{opacity:value}],children:/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}function SentImages({images:images,onPreview:onPreview}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles3(theme),[theme]);if(images.length===0)return null;let single=images.length===1;/* @__PURE__ */
|
|
202
|
+
return jsxRuntime.jsx(reactNative.View,{style:single?styles2.sentSingle:styles2.sentGrid,children:images.map((image,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.attachedImage,{filename:image.filename}),onPress:()=>onPreview(image),children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:image.uri},style:single?styles2.singleImage:styles2.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${image.uri}-${index}`))})}function makeStyles3(theme){let c=theme.color,t=theme.type;return reactNative.StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:THUMB_SIZE,height:THUMB_SIZE,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:CARD_RADIUS,overflow:"hidden",backgroundColor:c.composerFill,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center",backgroundColor:withAlpha(theme.color.brandInk,UPLOADING_ALPHA)??theme.color.brandSofter},successOverlay:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center",backgroundColor:SUCCESS_OVERLAY},failedOverlay:{...ABSOLUTE_FILL,borderRadius:CARD_RADIUS,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:FAILED_OVERLAY},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:REMOVE_SIZE,height:REMOVE_SIZE,borderRadius:REMOVE_SIZE/2,backgroundColor:REMOVE_BG,borderWidth:1.5,borderColor:c.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:SINGLE_IMAGE,height:SINGLE_IMAGE,borderRadius:SINGLE_IMAGE_RADIUS,backgroundColor:IMAGE_ON_BRAND},gridImage:{width:GRID_IMAGE,height:GRID_IMAGE,borderRadius:GRID_IMAGE_RADIUS,backgroundColor:IMAGE_ON_BRAND}})}var NO_URI2="chat attachment upload: the file handle has no uri",FAILED2="chat attachment upload failed";function filePartOf(file){return{uri:file.uri,name:sanitizeFilename(file.name),type:file.mimeType}}function createRnChatAttachmentTransport(options={}){/* @__PURE__ */
|
|
203
|
+
return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI2));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED2));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:filePartOf(file),signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function ownGroundSlot(slot){return slot===void 0||slot.backgroundColor!==void 0?slot:slot.borderRadius===void 0?void 0:{borderRadius:slot.borderRadius}}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function useEverfurPets(){let{runtime:runtime,userRef:userRef2,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),[state,setState]=react.useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=react.useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return react.useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present2=televetGlobal().presenter;if(present2===null)return"absent";try{return present2(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}var warned2=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned2||(warned2=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=react.useState(null);react.useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot=react.useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot.activeHost===id?snapshot.request:null,[module,setModule]=react.useState(null),wanted=request!==null&&module===null;return react.useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>import("@everfur/sdk/televet/booking"));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}={}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetModal:EverfurTelevetModal}=host.module;/* @__PURE__ */
|
|
204
|
+
return jsxRuntime.jsx(EverfurTelevetModal,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef2,options){let body={};petRef2!==void 0&&(body.pet_ref=petRef2);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef2===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef2,options){let pet;if(petRef2!=null){let length=typeof petRef2=="string"?[...petRef2].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef2}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=react.useState(null);if(react.useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef2!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=react.useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef2),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef2,scopeEpoch,opts.controller]),preflightController=react.useRef(controller);preflightController.current=controller;let scope=react.useMemo(()=>({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}),[runtime,userRef2,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=react.useState(IDLE2),inFlight3=react.useRef(null),scopeRef=react.useRef({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch};let controllerRef=react.useRef(controller);controllerRef.current=controller;let availableRef=react.useRef(available);availableRef.current=available;let start=react.useCallback((petRef2,visit)=>{if(inFlight3.current)return inFlight3.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef2===void 0?defaultPet:petRef2;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight3.current===tracked&&(inFlight3.current=null)});return inFlight3.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=react.useCallback((petRef2,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef2===void 0?defaultPet:petRef2,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=react.useCallback(petRef2=>redirect?start(petRef2,null):openInApp(petRef2,null),[redirect,start,openInApp]),openVisit=react.useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit}}var defaultOpenUrl=url=>reactNative.Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=react.useMemo(()=>{let openImpl=openUrl??defaultOpenUrl;return{prepare:()=>({ok:true,value:null}),async finish(_prepared,handoff){try{return await openImpl(handoff.url),null}catch{return"openFailed"}},abandon:()=>{}}},[openUrl]);return useVetVisitWith(opener,rest)}var MIN_TOUCH_TARGET=44,BUSY_OPACITY=.6;function VetVisitButton(props){let{petRef:petRef2,label:label,openUrl:openUrl,onOpened:onOpened,onError:onError,style:style,labelStyle:labelStyle,controller:controller,returnTo:returnTo,usState:usState,entry:entry,visitRef:visitRef,intent:intent,onStartInApp:onStartInApp,prefer:prefer}=props,redirecting=prefer==="redirect",visit=useVetVisit({...returnTo!==void 0?{returnTo:returnTo}:{},...usState!==void 0?{usState:usState}:{},...entry!==void 0?{entry:entry}:{},...petRef2!==void 0?{petRef:petRef2}:{},...openUrl!==void 0?{openUrl:openUrl}:{},...controller!==void 0?{controller:controller}:{},prefer:redirecting?"redirect":"in-app"}),theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles4(theme),[theme]),settling=react.useRef(false);if(!visit.available)/* @__PURE__ */
|
|
205
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[null,
|
|
206
|
+
/* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})]});let busy=visit.status==="opening",text3=label??TELEVET_COPY.visitButton;/* @__PURE__ */
|
|
207
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
208
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{if(!(busy||settling.current)){if(!redirecting){let request={...petRef2!==void 0?{petRef:petRef2}:{},...usState!==void 0?{usState:usState}:{},...visitRef!=null?{visitRef:visitRef,intent:intent??null}:{}};openVetVisitInApp(request,onStartInApp)===null&&callHost(onError,"unavailable",null);return}settling.current=true,(visitRef==null?visit.open():visit.openVisit(visitRef,intent??null)).then(result=>{result.opened?callHost(onOpened,result.flowId??null):result.reason!=="cancelled"&&callHost(onError,result.reason,result.error)}).finally(()=>{settling.current=false})}},accessibilityRole:"button",accessibilityLabel:text3,accessibilityState:{busy:busy,disabled:busy},style:[styles2.button,busy?styles2.busy:null,style],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.label,labelStyle],children:text3})}),
|
|
209
|
+
/* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})]})}function makeStyles4(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({button:{minHeight:MIN_TOUCH_TARGET,minWidth:MIN_TOUCH_TARGET,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.sm,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.vetVisitButton)},busy:{opacity:BUSY_OPACITY},label:{...face(theme,"medium"),color:color.onPrimary,fontSize:type.size.body,lineHeight:type.size.body*type.lineHeight.snug,...slotText(slots.vetVisitButton)}})}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandImage({uri:uri,label:label,decorative:decorative=false,style:style,resizeMode:resizeMode="contain",fallback:fallback=null,onError:onError,testID:testID}){let image=useBrandImage(uri);if(uri===null||!image.shown)return fallback;let a11y=decorative?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...label===void 0?{}:{accessibilityLabel:label}};/* @__PURE__ */
|
|
210
|
+
return jsxRuntime.jsx(reactNative.Image,{source:{uri:uri},style:style,resizeMode:resizeMode,...a11y,onError:()=>{image.onError(),onError?.()},...testID===void 0?{}:{testID:testID}})}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}function grounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function isEverfurLightLook(theme){if(theme.brightness!=="light")return false;let compiled=EVERFUR_LIGHT.color,c=theme.color,same3=(a,b)=>parseColor(a)===parseColor(b),own=new Set(grounds(compiled));return same3(c.brand,compiled.brand)&&same3(c.accent,compiled.accent)&&grounds(c).every(ground=>own.has(ground))}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same3=(a,b)=>parseColor(a)===parseColor(b);return{success:!same3(c.success,compiled.success),warning:!same3(c.warningStrong,compiled.warningStrong)||!same3(c.cautionAccent,compiled.cautionAccent),info:!(same3(c.info,c.brandInk)&&same3(c.badgeBgInfo,c.brandSoft)&&same3(c.infoEdge,c.structureEdge))}}function speciesOf(species){return canonicalPetSpecies(species)==="cat"?"cat":"dog"}function petAgeYears(ageYears){return typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<0?null:Math.floor(ageYears)}function formatPetMeta(pet){let ageYears=petAgeYears(pet.ageYears),speciesLabel=speciesOf(pet.species)==="cat"?"Cat":"Dog";if(ageYears==null)return speciesLabel;let ageLabel=ageYears===1?"1 yr":`${ageYears} yrs`;return`${speciesLabel} · ${ageLabel}`}var INITIALS_PALETTE=/* @__PURE__ */Object.freeze([
|
|
211
|
+
/* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
|
|
212
|
+
/* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
|
|
213
|
+
/* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
|
|
214
|
+
/* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
|
|
215
|
+
/* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
|
|
216
|
+
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function pickInitialsPalette(key){let hash=0;for(let i=0;i<key.length;i+=1)hash=hash*31+key.charCodeAt(i)>>>0;return INITIALS_PALETTE[hash%INITIALS_PALETTE.length]}function getInitial(name){let trimmed=(name??"").trim();return(Array.from(trimmed)[0]??"?").toUpperCase()}function petInitials(pet){return{...pickInitialsPalette(pet.petRef),initial:getInitial(pet.name)}}function petDiscPaint(pet,everfurLook,highlight){let initials=petInitials(pet);return everfurLook?initials:{background:highlight.fill,foreground:highlight.ink,initial:initials.initial}}function letterSize(size){return Math.max(12,Math.round(size*.42))}function PetDisc({pet:pet,size:size,ringStroke:ringStroke}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles5(theme),[theme]),inner=size-ringStroke*2,palette=pet===null?null:petDiscPaint(pet,isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),fontSize=letterSize(inner);/* @__PURE__ */
|
|
217
|
+
return jsxRuntime.jsx(Ring,{size:size,strokeWidth:ringStroke,color:theme.color.mark,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.disc,{width:inner,height:inner,borderRadius:inner/2},palette===null?styles2.discEmpty:{backgroundColor:palette.background}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:[styles2.letter,{fontSize:fontSize,lineHeight:Math.round(fontSize*1.2),color:palette===null?theme.color.text.muted:palette.foreground}],children:palette===null?getInitial(null):palette.initial})})})}function makeStyles5(theme){return reactNative.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:theme.color.brandSoft},letter:{...face(theme,"bold"),textAlign:"center",includeFontPadding:false}})}function sheetSlotBox(slot,borderWidth){let{borderRadius:borderRadius,...box2}=slotBox(slot,borderWidth);return borderRadius===void 0?box2:{...box2,borderTopLeftRadius:borderRadius,borderTopRightRadius:borderRadius}}function drawerSlotBox(slot,borderWidth){let{backgroundColor:backgroundColor,borderColor:borderColor,borderWidth:width,borderRadius:borderRadius}=slotBox(slot,borderWidth);return{...backgroundColor===void 0?{}:{backgroundColor:backgroundColor},...borderColor===void 0?{}:{borderRightColor:borderColor,borderRightWidth:width??1},...borderRadius===void 0?{}:{borderTopRightRadius:borderRadius,borderBottomRightRadius:borderRadius}}}var ROW_RING_SIZE=48,ROW_RING_STROKE=2,LIST_MAX_HEIGHT=320,PANEL_MAX_HEIGHT="80%",BACKDROP2="rgba(17,17,17,0.45)",CHECK_SIZE=18,PANEL_RADIUS=22,CLOSE_RADIUS=12,META_TRACKING=.4,MIN_TOUCH_TARGET2=44;function petDisplayName(pet){return pet?.name?.trim()||CHAT_COPY.yourPet}function PetSwitcherSheet({visible:visible,pets:pets,activePetRef:activePetRef,onSelect:onSelect,onAddPet:onAddPet=null,onClose:onClose}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles6(theme),[theme]);return visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"fade",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.root,children:[
|
|
218
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,onPress:onClose,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.close,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.backdrop})}),
|
|
219
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.panel,accessibilityViewIsModal:true,children:[
|
|
220
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:CHAT_COPY.yourPets}),
|
|
221
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{style:styles2.list,contentContainerStyle:styles2.listContent,showsVerticalScrollIndicator:true,children:pets.map(pet=>{let isActive=pet.petRef===activePetRef,name=petDisplayName(pet),meta=formatPetMeta(pet);/* @__PURE__ */
|
|
222
|
+
return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(isActive?CHAT_COPY.petCurrentlyActive:CHAT_COPY.switchToPet,{name:name}),accessibilityState:{selected:isActive},style:[styles2.row,isActive?styles2.rowActive:null],onPress:()=>onSelect(pet.petRef),children:[
|
|
223
|
+
/* @__PURE__ */jsxRuntime.jsx(PetDisc,{pet:pet,size:ROW_RING_SIZE,ringStroke:ROW_RING_STROKE}),
|
|
224
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.copy,children:[
|
|
225
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.name,numberOfLines:1,children:name}),
|
|
226
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.meta,numberOfLines:1,children:isActive?`${CHAT_COPY.activePrefix}${meta}`:meta})]}),isActive?/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:CHECK_SIZE,color:theme.color.brandInk}):null]},pet.petRef)})}),onAddPet!==null?/* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addAnotherPet,style:styles2.addRow,onPress:onAddPet,children:[
|
|
227
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.addDisc,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.addPlus,children:"+"})}),
|
|
228
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.addLabel,children:CHAT_COPY.addAnotherPet})]}):null,
|
|
229
|
+
/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.close,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:onClose,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.closeText,children:CHAT_COPY.close})})]})]})}):null}function makeStyles6(theme){let c=theme.color,r=theme.radius,dialogText=slotText(theme.slots.dialog);return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:BACKDROP2},panel:{backgroundColor:c.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:PANEL_RADIUS,borderTopRightRadius:PANEL_RADIUS,gap:14,maxHeight:PANEL_MAX_HEIGHT,...sheetSlotBox(theme.slots.dialog)},title:{...headingFace(theme,"bold"),fontSize:18,lineHeight:22,color:c.brandInk,...dialogText},list:{maxHeight:LIST_MAX_HEIGHT,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:MIN_TOUCH_TARGET2,paddingHorizontal:8},addDisc:{width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,alignItems:"center",justifyContent:"center",borderWidth:ROW_RING_STROKE,borderStyle:"dashed",borderColor:c.brandBorder,backgroundColor:c.surfaceCream},addPlus:{...face(theme,"bold"),fontSize:20,lineHeight:22,color:c.brandInk},addLabel:{...face(theme,"bold"),fontSize:15,lineHeight:20,color:c.text.primary,...dialogText},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface},rowActive:{borderColor:c.brandInk,backgroundColor:c.brandSoft},copy:{flex:1,gap:2},name:{...face(theme,"bold"),fontSize:15,lineHeight:18,color:c.text.primary},meta:{...face(theme,"monoBold"),fontSize:11,lineHeight:13,color:c.text.muted,textTransform:"uppercase",letterSpacing:META_TRACKING},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:CLOSE_RADIUS,backgroundColor:c.brandSoft},closeText:{...face(theme,"bold"),color:c.brandInk,fontSize:13,lineHeight:16,letterSpacing:META_TRACKING}})}var MIN_TOUCH_TARGET3=44,ICON_BUTTON_SIZE=36,MENU_GLYPH_SIZE=22,UNREAD_DOT_SIZE=9,UNREAD_DOT_RING=1.5,UNREAD_DOT_INSET=6,HEADER_AVATAR_SIZE=35,HEADER_RING_STROKE=1.75,ADD_BADGE_SIZE=12.4,ADD_BADGE_BORDER=.5,ADD_BADGE_GLYPH=8,LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160;function headerPet(pets,petRef2){return headerPetOf(pets,petRef2)}function ChatHeader({pets:pets,petRef:petRef2,historyUnread:historyUnread,onOpenHistory:onOpenHistory,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles7(theme),[theme]),[switcherOpen,setSwitcherOpen]=react.useState(false),shown=headerPet(pets.pets,petRef2),canSwitch=pets.pets.length>=2,shownPetRef=petRef2??shown?.petRef??null,name=petDisplayName(shown),select=next=>{setSwitcherOpen(false),pets.setActivePet(next),callHost(onPetChange,next)},addPet=onAddPet===void 0?null:()=>{setSwitcherOpen(false),callHost(onAddPet)};/* @__PURE__ */
|
|
230
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles2.row,children:[
|
|
231
|
+
/* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:historyUnread?`${CHAT_COPY.openHistoryNative}${CHAT_COPY.newReplySuffix}`:CHAT_COPY.openHistoryNative,containerStyle:styles2.iconSlot,style:styles2.iconButton,onPress:onOpenHistory,children:[
|
|
232
|
+
/* @__PURE__ */jsxRuntime.jsx(MenuGlyph,{size:MENU_GLYPH_SIZE,color:theme.slots.header?.textColor??theme.color.text.primary,strokeWidth:2}),historyUnread?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.unreadDot,pointerEvents:"none"}):null]}),
|
|
233
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.center,pointerEvents:"box-none",children:/* @__PURE__ */jsxRuntime.jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,barStyle:styles2.logoBar,logoStyle:styles2.logo})}),shownPetRef===null?null:/* @__PURE__ */jsxRuntime.jsx(VetVisitButton,{entry:"chat",petRef:shownPetRef,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles2.vetEntry,labelStyle:styles2.vetEntryLabel}),
|
|
234
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.right,children:canSwitch?/* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.switchActivePet,{name:name}),containerStyle:styles2.avatarSlot,style:styles2.avatarWrap,onPress:()=>setSwitcherOpen(true),children:[
|
|
235
|
+
/* @__PURE__ */jsxRuntime.jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE}),
|
|
236
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsxRuntime.jsx(PlusGlyph,{size:ADD_BADGE_GLYPH,color:theme.color.brandInk,strokeWidth:2})})]}):pets.loading&&shown===null?
|
|
237
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.avatarWrap,accessible:true,accessibilityLabel:CHAT_COPY.yourPet,children:/* @__PURE__ */jsxRuntime.jsx(Ring,{size:HEADER_AVATAR_SIZE,strokeWidth:HEADER_RING_STROKE,color:theme.color.mark,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.placeholderDisc})})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:shown===null?CHAT_COPY.yourPet:name,children:/* @__PURE__ */jsxRuntime.jsx(PetDisc,{pet:shown,size:HEADER_AVATAR_SIZE,ringStroke:HEADER_RING_STROKE})})}),
|
|
238
|
+
/* @__PURE__ */jsxRuntime.jsx(PetSwitcherSheet,{visible:switcherOpen,pets:pets.pets,activePetRef:shown?.petRef??null,onSelect:select,onAddPet:addPet,onClose:()=>setSwitcherOpen(false)})]})}function makeStyles7(theme){let c=theme.color,placeholderInner=HEADER_AVATAR_SIZE-HEADER_RING_STROKE*2,header=theme.slots.header;return reactNative.StyleSheet.create({vetEntry:{minHeight:MIN_TOUCH_TARGET3,justifyContent:"center",paddingHorizontal:12,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.controlEdge},vetEntryLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:theme.type.size.caption},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:16,paddingVertical:10,backgroundColor:c.surface,...slotBox(header)},iconSlot:{borderRadius:ICON_BUTTON_SIZE/2},iconButton:{width:ICON_BUTTON_SIZE,height:ICON_BUTTON_SIZE,borderRadius:ICON_BUTTON_SIZE/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:UNREAD_DOT_INSET,right:UNREAD_DOT_INSET,width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:UNREAD_DOT_SIZE,backgroundColor:c.danger,borderWidth:UNREAD_DOT_RING,borderColor:header?.backgroundColor??c.surface},center:{...ABSOLUTE_FILL,alignItems:"center",justifyContent:"center"},logoBar:{alignItems:"center",paddingHorizontal:theme.space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:HEADER_AVATAR_SIZE/2},avatarWrap:{width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,position:"relative"},placeholderDisc:{width:placeholderInner,height:placeholderInner,borderRadius:placeholderInner/2,backgroundColor:c.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:ADD_BADGE_SIZE/2,borderWidth:ADD_BADGE_BORDER,borderColor:c.mark,backgroundColor:c.surface,alignItems:"center",justifyContent:"center"}})}var MIN_TOUCH_TARGET4=44,SCRIM="rgba(17,17,17,0.55)",SHEET_RADIUS=26,HANDLE_WIDTH=36,HANDLE_HEIGHT=4,RADIO_SIZE=20,BADGE_SIZE=38,BADGE_GLYPH=18,RADIO_CHECK=12;function FeedbackReasons({visible:visible,onSubmit:onSubmit,onSkip:onSkip}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles8(theme),[theme]),[reason,setReason]=react.useState(null),[note,setNote]=react.useState(""),[pending,setPending]=react.useState(false),[failed,setFailed]=react.useState(false),reset=()=>{setReason(null),setNote(""),setPending(false),setFailed(false)},skip=()=>{pending||(reset(),onSkip())},submit=async()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=note.trim();await onSubmit(reason,trimmed.length>0?trimmed:null)?reset():(setPending(false),setFailed(true))};if(!visible)return null;let overLimit=[...note].length>FEEDBACK_NOTES_MAX_CHARS;/* @__PURE__ */
|
|
239
|
+
return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:theme.motion.reducedMotion?"none":"slide",onRequestClose:skip,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:reactNative.Platform.OS==="ios"?"padding":void 0,style:styles2.root,children:[
|
|
240
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:styles2.scrim,onPress:skip,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y}),
|
|
241
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.sheet,accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
|
|
242
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.handle}),
|
|
243
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.header,children:[
|
|
244
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.iconBadge,children:/* @__PURE__ */jsxRuntime.jsx(ThumbGlyph,{size:BADGE_GLYPH,color:theme.color.brandInk,active:false,rotate:"180deg"})}),
|
|
245
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.headerText,children:[
|
|
246
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:CHAT_COPY.feedbackTitle}),
|
|
247
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.subtitle,children:CHAT_COPY.feedbackSubtitle})]})]}),
|
|
248
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.options,children:FEEDBACK_REASONS.map(option=>{let selected=reason===option.key;/* @__PURE__ */
|
|
249
|
+
return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:option.label,accessibilityState:{selected:selected},style:[styles2.option,selected?styles2.optionSelected:null],onPress:()=>setReason(current=>current===option.key?null:option.key),children:[
|
|
250
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.optionLabel,selected?styles2.optionLabelSelected:null],children:option.label}),
|
|
251
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.radio,selected?styles2.radioSelected:null],children:selected?/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:RADIO_CHECK,color:theme.color.surface,strokeWidth:2}):null})]},option.key)})}),
|
|
252
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.inputWrap,children:[
|
|
253
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{style:styles2.input,placeholder:CHAT_COPY.feedbackNotesPlaceholder,placeholderTextColor:theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.feedbackNotesPlaceholder,value:note,onChangeText:setNote,multiline:true,editable:!pending}),note.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:[styles2.counter,overLimit?styles2.counterOver:null],children:`${[...note].length}/${FEEDBACK_NOTES_MAX_CHARS}`}):null]}),failed?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.failed,accessibilityRole:"alert",children:CHAT_COPY.feedbackFailed}):null,
|
|
254
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.actions,children:[
|
|
255
|
+
/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSubmit,accessibilityState:{busy:pending,disabled:pending||overLimit},disabled:pending||overLimit,style:[styles2.submit,pending||overLimit?styles2.submitDisabled:null],onPress:()=>{submit()},children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.submitLabel,children:CHAT_COPY.feedbackSubmit})}),
|
|
256
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.feedbackSkipA11y,hitSlop:8,onPress:skip,style:styles2.skip,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.skipLabel,children:CHAT_COPY.feedbackSkip})})]})]})]})})}function makeStyles8(theme){let c=theme.color,t=theme.type,r=theme.radius,slots=theme.slots,dialogText=slotText(slots.dialog);return reactNative.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...ABSOLUTE_FILL,backgroundColor:SCRIM},sheet:{backgroundColor:c.surface,borderTopLeftRadius:SHEET_RADIUS,borderTopRightRadius:SHEET_RADIUS,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:HANDLE_WIDTH,height:HANDLE_HEIGHT,borderRadius:HANDLE_HEIGHT/2,backgroundColor:c.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:BADGE_SIZE,height:BADGE_SIZE,borderRadius:BADGE_SIZE/2,alignItems:"center",justifyContent:"center",backgroundColor:c.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(theme,"bold"),fontSize:20,lineHeight:28,color:c.text.primary,letterSpacing:t.letterSpacing.tight,...dialogText},subtitle:{...face(theme,"regular"),fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.relaxed,color:c.text.muted,...dialogText},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:r.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.controlEdge,backgroundColor:c.surface,...slotBox(slots.chip,reactNative.StyleSheet.hairlineWidth)},optionSelected:{borderColor:c.brandInk,backgroundColor:c.brandSoft},optionLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.primary,...slotText(slots.chip)},optionLabelSelected:{color:c.brandInk},radio:{width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:RADIO_SIZE/2,borderWidth:2,borderColor:c.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:c.brandInk,backgroundColor:c.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(theme,"regular"),fontSize:t.size.body,color:c.text.primary,textAlignVertical:"top",...slotBox(slots.input,1),...slotText(slots.input)},counter:{...face(theme,"mono"),alignSelf:"flex-end",fontSize:t.size.caption,letterSpacing:.3,color:c.text.placeholder},counterOver:{color:c.danger},failed:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:c.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET4,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.xl,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.onPrimary,...slotText(slots.primaryButton)},skip:{minHeight:MIN_TOUCH_TARGET4,alignItems:"center",justifyContent:"center",paddingHorizontal:theme.space.lg},skipLabel:{...face(theme,"medium"),fontSize:t.size.body,color:c.text.muted}})}var PANEL_WIDTH_FRACTION=.88,PANEL_MAX_WIDTH=420,PANEL_PADDING_TOP=58,BACKDROP3="rgba(17,17,17,0.28)",ACTIVE_ROW_ALPHA=.15,ACTION_SIZE=14,LABEL_SIZE=12,CONTROL_SIZE=44,CLOSE_GLYPH2=16,CARD_RADIUS2=14,ERROR_RADIUS=12,SEARCH_GLYPH=14,UNREAD_DOT=8,HALF_STEP=2,END_REACHED_THRESHOLD=.5,STANDARD2=bezierEasing(CHAT_EASING.standard);function drawerPanelWidth(windowWidth){return Math.min(Math.round(windowWidth*PANEL_WIDTH_FRACTION),PANEL_MAX_WIDTH)}function HistoryDrawer({chat:chat,history:history}){let[mounted,setMounted]=react.useState(history.open),onHidden=react.useCallback(()=>setMounted(false),[]);return history.open&&!mounted&&setMounted(true),mounted?/* @__PURE__ */jsxRuntime.jsx(DrawerModal,{chat:chat,history:history,onHidden:onHidden}):null}function DrawerModal({chat:chat,history:history,onHidden:onHidden}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles9(theme),[theme]),motion=useChatMotion(),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),{width:width}=reactNative.useWindowDimensions(),panelWidth=drawerPanelWidth(width),open=history.open,progress=react.useRef(null);progress.current===null&&(progress.current=new reactNative.Animated.Value(motion.drawerMs<=0&&open?1:0));let value=progress.current;react.useEffect(()=>{if(!open&&motion.drawerMs<=0){onHidden();return}let animation=reactNative.Animated.timing(value,{toValue:open?1:0,duration:motion.drawerMs,easing:STANDARD2,useNativeDriver:true});return animation.start(({finished:finished})=>{finished&&!open&&onHidden()}),()=>animation.stop()},[open,value,motion.drawerMs,onHidden]);let translateX=value.interpolate({inputRange:[0,1],outputRange:[-panelWidth,0]}),rows=history.filtered,hasNoConversations=history.rows.length===0,complete=history.cursor===null&&!history.loading&&history.error===null,empty=hasNoConversations&&history.loading?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.emptyCard,accessibilityLabel:HISTORY_COPY.loading,accessibilityState:{busy:true},children:[
|
|
257
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:styles2.emptyTitle.color}),
|
|
258
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.emptyBody,children:HISTORY_COPY.loading})]}):hasNoConversations&&history.error!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.emptyCard,children:[
|
|
259
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.emptyTitle,accessibilityRole:"alert",children:HISTORY_COPY.loadFailed}),
|
|
260
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.emptyBody,children:history.error}),
|
|
261
|
+
/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.retry,containerStyle:styles2.retrySlot,style:styles2.retryButton,onPress:()=>{history.load()},children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.retryText,children:HISTORY_COPY.retry})})]}):history.emptyKind==="empty"?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.emptyCard,children:[
|
|
262
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.emptyTitle,children:HISTORY_COPY.empty}),
|
|
263
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.emptyBody,children:HISTORY_COPY.emptyBody})]}):
|
|
264
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.noMatch,children:HISTORY_COPY.noMatch}),footer=!history.searching&&history.loadingMore?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.loadMoreFooter,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.loadMoreLabel,children:HISTORY_COPY.loadingMore})}):null;/* @__PURE__ */
|
|
265
|
+
return jsxRuntime.jsx(reactNative.Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:history.close,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.root,children:[
|
|
266
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,onPress:history.close,accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.closeA11y,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[styles2.backdrop,{opacity:value}]})}),
|
|
267
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[styles2.panel,{width:panelWidth,paddingTop:Math.max(PANEL_PADDING_TOP,insets.top+theme.space.md),transform:[{translateX:translateX}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:styles2.keyboardAvoider,behavior:reactNative.Platform.OS==="ios"?"padding":"height",children:[
|
|
268
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.header,children:[
|
|
269
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles2.heading,accessibilityRole:"header",children:HISTORY_COPY.heading}),
|
|
270
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.newChat,style:styles2.newChat,onPress:history.newConversation,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.newChatLabel,children:HISTORY_COPY.newChat})}),
|
|
271
|
+
/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:HISTORY_COPY.close,hitSlop:0,style:styles2.closeButton,onPress:history.close,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH2,color:theme.color.text.muted,strokeWidth:1.75})})]}),
|
|
272
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.searchPill,children:[
|
|
273
|
+
/* @__PURE__ */jsxRuntime.jsx(SearchGlyph,{size:SEARCH_GLYPH,color:theme.color.text.muted,strokeWidth:1.5}),
|
|
274
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{value:history.query,onChangeText:next=>history.setQuery(next.replace(/^\s+/,"")),style:styles2.searchInput,placeholder:HISTORY_COPY.searchPlaceholder,placeholderTextColor:theme.color.text.placeholder,accessibilityLabel:HISTORY_COPY.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
|
|
275
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.countLabel,children:historyCountLabel(history.rows.length,complete)}),history.error!==null&&!hasNoConversations?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.errorCard,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.errorText,accessibilityRole:"alert",children:history.error})}):null,
|
|
276
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.FlatList,{data:rows,keyExtractor:row=>row.id,renderItem:({item:item})=>/* @__PURE__ */jsxRuntime.jsx(Row,{row:item,active:item.id===chat.conversationId,disabled:history.loading,styles:styles2,onPress:()=>{history.resume(item.id)}}),contentContainerStyle:rows.length===0?styles2.listEmpty:styles2.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:empty,ListFooterComponent:footer,onEndReached:history.loadMore,onEndReachedThreshold:END_REACHED_THRESHOLD})]})})]})})}function Row({row:row,active:active,disabled:disabled,styles:styles2,onPress:onPress}){let unread=row.unreadCount!==null&&row.unreadCount>0,meta=conversationMeta(row);/* @__PURE__ */
|
|
277
|
+
return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:openConversationLabel(row),accessibilityState:{selected:active,disabled:disabled},disabled:disabled,style:[styles2.item,active?styles2.itemActive:null],onPress:onPress,children:[
|
|
278
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.itemRow,children:[
|
|
279
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.itemTitle,numberOfLines:1,children:conversationTitle(row.title)}),unread?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.unreadDot}):null]}),meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.itemMeta,numberOfLines:1,children:meta}):null]})}function makeStyles9(theme){let c=theme.color,s=theme.space,t=theme.type,slots=theme.slots,ink=c.text.primary,cardText=slotText(slots.card);return reactNative.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:BACKDROP3},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:c.surface,paddingHorizontal:s.lg,borderRightWidth:reactNative.StyleSheet.hairlineWidth,borderRightColor:c.borderRingCream,gap:s.md,...drawerSlotBox(slots.dialog,reactNative.StyleSheet.hairlineWidth)},keyboardAvoider:{flex:1,gap:s.md},header:{flexDirection:"row",alignItems:"center",gap:s.sm},heading:{...headingFace(theme,"bold"),flex:1,fontSize:t.size.subtitle,color:ink,...slotText(slots.dialog)},newChat:{minHeight:CONTROL_SIZE,justifyContent:"center",paddingHorizontal:s.xs},newChatLabel:{...face(theme,"bold"),fontSize:ACTION_SIZE,color:c.brandInk},closeButton:{width:CONTROL_SIZE,height:CONTROL_SIZE,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:s.sm,borderRadius:theme.radius.pill,backgroundColor:c.surfaceSubtle,paddingHorizontal:s.md+HALF_STEP,paddingVertical:s.sm+HALF_STEP,borderWidth:1,borderColor:c.borderRingCream,...slotBox(slots.input,1)},searchInput:{...face(theme,"regular"),flex:1,fontSize:t.size.bodyTight,color:c.text.primary,padding:0,...slotText(slots.input)},countLabel:{...face(theme,"mono"),fontSize:LABEL_SIZE,color:c.text.muted},list:{gap:s.xs,paddingBottom:s.xl},listEmpty:{flexGrow:1},item:{paddingVertical:s.sm+HALF_STEP,paddingHorizontal:s.sm,borderRadius:theme.radius.md,gap:HALF_STEP},itemActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??c.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:s.sm},itemTitle:{...face(theme,"bold"),flex:1,fontSize:t.size.bodyTight,color:ink},itemMeta:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted},unreadDot:{width:UNREAD_DOT,height:UNREAD_DOT,borderRadius:UNREAD_DOT/2,backgroundColor:c.danger},errorCard:{borderRadius:ERROR_RADIUS,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.danger,backgroundColor:c.surface,padding:s.md},errorText:{...face(theme,"regular"),fontSize:t.size.caption,color:c.danger},emptyCard:{borderRadius:CARD_RADIUS2,padding:s.md+HALF_STEP,gap:s.xs+HALF_STEP,backgroundColor:c.surfaceSubtle,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.borderRingCream,...slotBox(slots.card,reactNative.StyleSheet.hairlineWidth)},emptyTitle:{...headingFace(theme,"bold"),fontSize:t.size.bodyTight,color:ink,...cardText},emptyBody:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.secondary,...cardText},noMatch:{...face(theme,"regular"),fontSize:t.size.bodyTight,color:c.text.muted,paddingVertical:s.sm},retrySlot:{marginTop:s.sm,alignSelf:"flex-start"},retryButton:{borderRadius:theme.radius.pill,paddingHorizontal:s.md+HALF_STEP,paddingVertical:s.sm,borderWidth:1,borderColor:c.brandInk,...slotBox(slots.primaryButton)},retryText:{...face(theme,"bold"),fontSize:t.size.caption,color:c.brandInk,...slotText(slots.primaryButton)},loadMoreFooter:{paddingVertical:s.md+HALF_STEP,alignItems:"center"},loadMoreLabel:{...face(theme,"regular"),fontSize:t.size.caption,color:c.text.muted}})}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number"&&Number.isFinite(hostOffset),probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset}:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:hostGiven?{keyboardVerticalOffset:hostOffset,onLayout:onLayout}:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function useKeyboardOpen(){let[open,setOpen]=react.useState(false);return react.useEffect(()=>{let keyboard=reactNative.Keyboard;if(typeof keyboard?.addListener!="function")return;let ios=reactNative.Platform.OS==="ios",shown=keyboard.addListener(ios?"keyboardWillShow":"keyboardDidShow",()=>setOpen(true)),hidden=keyboard.addListener(ios?"keyboardWillHide":"keyboardDidHide",()=>setOpen(false));return()=>{shown.remove(),hidden.remove()}},[]),open}function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency")return tier;let caution=tier.level==="schedule_soon",branded=brandedStatus(theme),statusSet=caution?branded.warning:branded.info,painted=isEverfurLightLook(theme)&&!statusSet?tier:tokenPaint(tier,theme,caution);return withBannerSlot(painted,theme.slots.banner)}function tokenPaint(tier,theme,caution){let c=theme.color,fill=flattenOnto(caution?c.badgeBgCaution:c.badgeBgInfo,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.infoEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.info,[fill,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
|
|
280
|
+
return Object.freeze({...tier,borderColor:borderColor,backgroundColor:fill,textColor:textColor,reasonColor:readOn(c.text.primary,[fill],SLOT_MIN_CONTRAST),pillColor:c.surface})}function withBannerSlot(tier,slot){if(slot===void 0)return tier;let next={...tier};return slot.backgroundColor!==void 0&&(next.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(next.borderColor=slot.borderColor),slot.textColor!==void 0&&(next.textColor=slot.textColor,next.reasonColor=slot.textColor),/* @__PURE__ */Object.freeze(next)}function chatVetVisitOptions(petRef2,vet){let options={entry:"chat",petRef:petRef2};return vet?.returnTo!==void 0&&(options.returnTo=vet.returnTo),vet?.usState!==void 0&&(options.usState=vet.usState),vet?.prefer!==void 0&&(options.prefer=vet.prefer),options}var CARD_EDGE=.75,EMERGENCY_EDGE=1.5,EMERGENCY_EDGE_ALPHA=.4,CARD_PAD_X_EXTRA=4,REASON_LEAD=1.5,CLOSE_SIZE2=22,CLOSE_GLYPH3=14,CLOSE_HIT_SLOP2=8,INFO_GLYPH=20,INFO_HIT_SLOP=10,PIN_GLYPH=13,PILL_LABEL_SIZE=12,PILL_LABEL_LINE=15,ACTION_MIN_HEIGHT=44,ACTION_PAD_X=14,ACTION_EDGE=1.25,ACTION_LABEL_SIZE=14,ACTION_GLYPH_GAP=6,COMPACT_REASON_LINES=2;function tierPaint(theme,tier){let c=theme.color;if(tier.level==="emergency")return{card:{backgroundColor:c.badgeBgCritical,borderColor:withAlpha(c.danger,EMERGENCY_EDGE_ALPHA)??c.danger,borderWidth:EMERGENCY_EDGE},label:c.danger,reason:c.text.primary,close:c.danger,action:{fill:c.surface,edge:c.danger,ink:c.danger}};let radius=theme.slots.banner?.borderRadius;return{card:{backgroundColor:tier.backgroundColor,borderColor:tier.borderColor,borderWidth:CARD_EDGE,...radius===void 0?{}:{borderRadius:radius}},label:tier.textColor,reason:tier.reasonColor,close:tier.textColor,action:null}}function UrgencyBanner({surface:surface,petRef:petRef2,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:compact=false}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles10(theme),[theme]),motion=useChatMotion(),tier=surface.tier===null?null:themedUrgencyTier(surface.tier,theme),source=surface.source;/* @__PURE__ */
|
|
281
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
282
|
+
/* @__PURE__ */jsxRuntime.jsx(FadePresence,{visible:surface.showBanner&&tier!==null,inMs:motion.bannerInMs,outMs:motion.bannerOutMs,style:styles2.pinned,children:tier!==null&&source!==null?/* @__PURE__ */jsxRuntime.jsx(BannerCard,{tier:tier,reason:source.reason,surface:surface,petRef:petRef2,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,styles:styles2,compact:compact}):null}),
|
|
283
|
+
/* @__PURE__ */jsxRuntime.jsx(FadePresence,{visible:surface.showCompactIcon,inMs:motion.iconInMs,outMs:motion.iconOutMs,style:styles2.indicatorRow,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.showLatestVetAlert,hitSlop:INFO_HIT_SLOP,onPress:surface.expand,children:/* @__PURE__ */jsxRuntime.jsx(InfoGlyph,{size:INFO_GLYPH,color:theme.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:tier,reason:reason,surface:surface,petRef:petRef2,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,styles:styles2,compact:compact}){let theme=useEverfurTheme(),paint=tierPaint(theme,tier),builtIn=/* @__PURE__ */jsxRuntime.jsx(VetAction,{tier:tier,paint:paint,petRef:petRef2,onFindVet:onFindVet,vet:vet,styles:styles2}),vetAction=surface.showVetAction?renderVetAction!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderVetAction(tier.level),fallback:builtIn,resetKey:tier.level}):builtIn:null,poison=paint.action!==null?/* @__PURE__ */jsxRuntime.jsx(PoisonControl,{paint:paint.action,styles:styles2}):null;/* @__PURE__ */
|
|
284
|
+
return jsxRuntime.jsxs(reactNative.View,{accessibilityRole:"alert",style:[styles2.card,paint.card,compact?styles2.cardCompact:null],testID:compact?"chat-urgency-compact":void 0,children:[
|
|
285
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.label,{color:paint.label}],children:tier.label}),reason!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.reason,{color:paint.reason}],numberOfLines:compact?COMPACT_REASON_LINES:void 0,accessibilityLabel:compact?reason:void 0,children:reason}):null,vetAction!==null||poison!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.actions,children:[vetAction,poison]}):null,surface.dismissLabel!==null?/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:surface.dismissLabel,hitSlop:CLOSE_HIT_SLOP2,containerStyle:styles2.closeSlot,style:styles2.closeButton,onPress:surface.dismiss,children:/* @__PURE__ */jsxRuntime.jsx(CloseGlyph,{size:CLOSE_GLYPH3,color:paint.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:paint,styles:styles2}){let call=()=>{try{reactNative.Linking.openURL(POISON_CONTROL_TEL).catch(()=>{})}catch{}};/* @__PURE__ */
|
|
286
|
+
return jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.poisonControlNative,hitSlop:0,style:[styles2.action,{backgroundColor:paint.fill,borderColor:paint.edge}],onPress:call,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.actionLabel,{color:paint.ink}],children:CHAT_COPY.poisonControlNative})})}function VetAction({tier:tier,paint:paint,petRef:petRef2,onFindVet:onFindVet,vet:vet,styles:styles2}){let theme=useEverfurTheme(),visit=useVetVisit(chatVetVisitOptions(petRef2,vet)),busy=visit.status==="opening",hostFinder=!visit.available&&onFindVet!==void 0,onPress=visit.available?()=>{visit.open()}:onFindVet!==void 0?()=>{callHost(onFindVet,tier.level)}:null;if(onPress===null)return null;let action=paint.action;if(action!==null){let label=hostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVet,ink2=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??action.ink;/* @__PURE__ */
|
|
287
|
+
return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:hostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},hitSlop:0,style:[styles2.action,{backgroundColor:action.fill,borderColor:action.edge},styles2.findVetSlotBox,busy?styles2.findVetBusy:null],onPress:onPress,children:[
|
|
288
|
+
/* @__PURE__ */jsxRuntime.jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink2,strokeWidth:1.5}),
|
|
289
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.actionLabel,{color:ink2}],children:label})]})}let ink=ownGroundSlot(theme.slots.vetVisitButton)?.textColor??tier.textColor;/* @__PURE__ */
|
|
290
|
+
return jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:CHAT_COPY.findVetA11y,accessibilityState:{busy:busy},style:[styles2.findVetButton,{borderColor:tier.borderColor,backgroundColor:tier.pillColor},styles2.findVetSlotBox,busy?styles2.findVetBusy:null],onPress:onPress,children:[
|
|
291
|
+
/* @__PURE__ */jsxRuntime.jsx(MapPinGlyph,{size:PIN_GLYPH,color:ink,strokeWidth:1.5}),
|
|
292
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.findVetLabel,{color:ink}],children:CHAT_COPY.findVet})]})}function makeStyles10(theme){let pill=ownGroundSlot(theme.slots.vetVisitButton),s=theme.space,t=theme.type;return reactNative.StyleSheet.create({pinned:{marginTop:0,marginBottom:s.xs,paddingHorizontal:s.lg},card:{borderRadius:theme.radius.lg,paddingHorizontal:s.lg+CARD_PAD_X_EXTRA,paddingVertical:s.lg,gap:s.sm},cardCompact:{paddingVertical:s.md,gap:s.xs},label:{...face(theme,"bold"),fontSize:t.size.body,paddingRight:CLOSE_SIZE2},reason:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*REASON_LEAD),paddingRight:CLOSE_SIZE2},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:s.sm},action:{flexDirection:"row",alignItems:"center",gap:ACTION_GLYPH_GAP,minHeight:ACTION_MIN_HEIGHT,paddingHorizontal:ACTION_PAD_X,borderRadius:theme.radius.pill,borderWidth:ACTION_EDGE},actionLabel:{...face(theme,"bold"),fontSize:ACTION_LABEL_SIZE},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:theme.radius.pill,borderWidth:1},findVetSlotBox:{...slotBox(pill,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(theme,"monoBold"),fontSize:PILL_LABEL_SIZE,lineHeight:PILL_LABEL_LINE},closeSlot:{position:"absolute",top:s.md,right:s.md},closeButton:{width:CLOSE_SIZE2,height:CLOSE_SIZE2,borderRadius:CLOSE_SIZE2/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:s.lg,paddingTop:2,paddingBottom:s.xs}})}function useChatPets(){let pets=useEverfurPets(),{handle:handle}=useEverfurContext(),setActivePet=react.useCallback(petRef2=>handle.setActivePet(petRef2),[handle]);return react.useMemo(()=>({...pets,setActivePet:setActivePet}),[pets,setActivePet])}function announceAnswered(){try{let announce=reactNative.AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(reactNative.AccessibilityInfo,CHAT_COPY.answered)}catch{}}function useSettleAnnouncement(chat){let wasStreaming=react.useRef(false),scope=react.useRef({send:chat.send,id:chat.conversationId});react.useEffect(()=>{let previous=scope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),scope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];last!==void 0&&last.role==="assistant"&&announceAnswered()}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId])}var SPINNER_DELAY_MS=300,THANKS_VISIBLE_MS=3e3,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET5=44,INPUT_MAX_HEIGHT=120,BUBBLE_MAX_WIDTH="88%",BUBBLE_MAX_WIDTH_CAP=520,HALF_STEP2=2,BUBBLE_EDGE_WIDTH=.5,BUBBLE_LEAD_USER=1.5,BUBBLE_LEAD_ASSISTANT=1.6,PENDING_OPACITY=.6,COMPOSER_MIN_HEIGHT=56,COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_RIGHT=5,COMPOSER_PADDING_VERTICAL=5,INPUT_MIN_HEIGHT=36,INPUT_LINE_HEIGHT=20,APP_BODY_SIZE=14,SEND_CONTROL_SIZE=MIN_TOUCH_TARGET5,TEXT_ACTION_HIT_SLOP=4,SEND_GLYPH_SIZE=24,STOP_GLYPH_SIZE=22,SEND_DISABLED_OPACITY=.4,ATTACH_CONTROL_SIZE=MIN_TOUCH_TARGET5,ATTACH_GLYPH_SIZE=20,ATTACH_DISABLED_OPACITY=.4,EMPTY_MIN_HEIGHT=480,FOLLOW_UP_HEADING_SIZE=12,FOLLOW_UP_HEADING_TRACKING=.72,FOLLOW_UP_ROW_MIN_HEIGHT=48,RULE_WIDTH=1,FOOTNOTE_SIZE=12,FOOTNOTE_LINE=18,EMPTY_PADDING_TOP="12%",ASSISTANT_AVATAR_SIZE=20;function useChatTheme(){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles11(theme),[theme]);return{theme:theme,styles:styles2}}function makeStyles11(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,userLine=Math.round(t.size.body*BUBBLE_LEAD_USER),assistantLine=Math.round(t.size.body*BUBBLE_LEAD_ASSISTANT),inputLine=Math.round(INPUT_LINE_HEIGHT*t.size.body/APP_BODY_SIZE),rule=c.borderRingCream,slots=theme.slots;return reactNative.StyleSheet.create({container:{flex:1,minHeight:MIN_SURFACE_HEIGHT,backgroundColor:c.chatGround},body:{flex:1},centered:{minHeight:MIN_SURFACE_HEIGHT,flexGrow:1,alignItems:"center",justifyContent:"center",padding:s.xl},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:EMPTY_PADDING_TOP,paddingHorizontal:s.lg,paddingBottom:s.lg,minHeight:EMPTY_MIN_HEIGHT,gap:s.lg},errorText:{...face(theme,"regular"),fontSize:t.size.subtitle,lineHeight:t.size.subtitle*t.lineHeight.snug,color:c.danger,textAlign:"center",marginBottom:s.md},retryButton:{minHeight:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,alignItems:"center",justifyContent:"center",paddingHorizontal:s.xl,paddingVertical:s.sm,borderRadius:r.pill,backgroundColor:c.brand,...slotBox(slots.primaryButton)},retryLabel:{...face(theme,"medium"),color:c.onPrimary,fontSize:t.size.body,...slotText(slots.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,paddingHorizontal:s.lg,paddingVertical:s.sm,backgroundColor:c.surfaceCream},setupNoticeText:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption,flexShrink:1},turnNotice:{gap:s.xs,padding:s.md,borderRadius:r.lg,backgroundColor:c.surfaceCream,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder,alignItems:"flex-start",...slotBox(slots.card,reactNative.StyleSheet.hairlineWidth)},turnNoticeError:{borderColor:c.danger},turnNoticeTitle:{...headingFace(theme,"bold"),color:c.text.primary,fontSize:t.size.body,...slotText(slots.card)},turnNoticeTitleError:{color:c.danger},turnNoticeBody:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,...slotText(slots.card)},turnNoticeAction:{minHeight:MIN_TOUCH_TARGET5,justifyContent:"center"},turnNoticeActionLabel:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.body},setupNoticeAction:{...face(theme,"medium"),color:c.brandInk,fontSize:t.size.caption},reconnectingCaption:{...face(theme,"medium"),color:c.text.secondary,fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingLine:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*t.lineHeight.relaxed)},list:{flex:1},listContent:{padding:s.lg,gap:s.xl},rowBlock:{gap:s.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:s.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:BUBBLE_MAX_WIDTH,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,backgroundColor:c.bubbleUser,...c.primaryEdge!==c.primary&&c.bubbleUser===c.primary?{borderWidth:BUBBLE_EDGE_WIDTH,borderColor:c.primaryEdge}:{},borderRadius:r.lg,borderBottomRightRadius:r.xs,...slotBox(slots.userBubble,BUBBLE_EDGE_WIDTH)},bubbleAssistant:slots.assistantBubble?.backgroundColor===void 0?{...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)}:{paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,borderRadius:r.lg,...slotBox(slots.assistantBubble,BUBBLE_EDGE_WIDTH)},bubbleVet:{maxWidth:BUBBLE_MAX_WIDTH_CAP,paddingVertical:s.md,paddingHorizontal:s.lg+HALF_STEP2,backgroundColor:c.bubbleVet,borderRadius:r.lg,borderTopLeftRadius:r.xs,...slotBox(slots.vetBubble,BUBBLE_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{...face(theme,"regular"),color:c.onPrimary,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.userBubble)},bubbleTextAssistant:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:assistantLine,...slotText(slots.assistantBubble)},bubbleTextVet:{...face(theme,"regular"),color:c.onBubbleVet,fontSize:t.size.body,lineHeight:userLine,...slotText(slots.vetBubble)},assistantName:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,marginBottom:s.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:s.sm,marginBottom:s.xs},assistantAvatar:{width:ASSISTANT_AVATAR_SIZE,height:ASSISTANT_AVATAR_SIZE,borderRadius:ASSISTANT_AVATAR_SIZE/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:s.sm,marginBottom:s.xs},vetSender:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight},vetTime:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.caption},bubbleBold:face(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(theme,"mono"),followUps:{alignSelf:"stretch",marginTop:s.md},followUpsHeading:{...face(theme,"monoBold"),color:c.text.muted,fontSize:FOLLOW_UP_HEADING_SIZE,textTransform:"uppercase",letterSpacing:FOLLOW_UP_HEADING_TRACKING,paddingBottom:s.sm,borderBottomWidth:RULE_WIDTH,borderBottomColor:rule},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:RULE_WIDTH,borderTopColor:rule},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.md,minHeight:FOLLOW_UP_ROW_MIN_HEIGHT,paddingVertical:s.sm+HALF_STEP2,...slots.chip?.backgroundColor!==void 0||slots.chip?.borderColor!==void 0?{paddingHorizontal:s.md}:{},...slotBox(slots.chip)},followUpText:{...face(theme,"bold"),flex:1,color:c.brandInk,fontSize:t.size.bodyTight,...slotText(slots.chip)},composerOuter:{position:"relative"},composer:{marginHorizontal:s.md,marginTop:s.xs,minHeight:COMPOSER_MIN_HEIGHT,justifyContent:"center",paddingLeft:s.sm,paddingRight:COMPOSER_PADDING_RIGHT,paddingVertical:COMPOSER_PADDING_VERTICAL,backgroundColor:c.composerFill,borderWidth:COMPOSER_BORDER_WIDTH,borderColor:c.composerBorder,borderRadius:r.pill,...slotBox(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerRow:{flexDirection:"row",alignItems:"center",gap:s.xs,minHeight:INPUT_MIN_HEIGHT},attachControl:{width:ATTACH_CONTROL_SIZE,height:ATTACH_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:ATTACH_DISABLED_OPACITY},input:{flex:1,minHeight:INPUT_MIN_HEIGHT,maxHeight:INPUT_MAX_HEIGHT,paddingHorizontal:0,paddingVertical:0,...face(theme,"regular"),fontSize:t.size.body,lineHeight:inputLine,color:c.text.primary,...slotText(slots.composerInput)},sendControl:{minHeight:SEND_CONTROL_SIZE,minWidth:SEND_CONTROL_SIZE,alignItems:"center",justifyContent:"center"},sendDisc:{width:SEND_CONTROL_SIZE,height:SEND_CONTROL_SIZE,borderRadius:SEND_CONTROL_SIZE/2,alignItems:"center",justifyContent:"center",...slotBox(slots.sendButton)},sendControlDisabled:{opacity:SEND_DISABLED_OPACITY},footnote:{...face(theme,"regular"),color:c.text.muted,fontSize:FOOTNOTE_SIZE,lineHeight:FOOTNOTE_LINE,textAlign:"center",marginTop:s.sm,marginBottom:s.xs,paddingHorizontal:s.lg},poweredBy:{...face(theme,"regular"),color:c.text.muted,fontSize:t.size.micro,textAlign:"center",paddingBottom:s.xs}})}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}var MS_PER_DAY=864e5,MAX_WATCH_DAY=365;function checkinDayNumber(openedAtIso,dueDay){if(typeof openedAtIso!="string"||typeof dueDay!="string")return null;let opened=Date.parse(openedAtIso),due=Date.parse(dueDay);if(Number.isNaN(opened)||Number.isNaN(due))return null;let elapsed=Math.floor(due/MS_PER_DAY)-Math.floor(opened/MS_PER_DAY);return elapsed<1||elapsed>MAX_WATCH_DAY?null:elapsed}function checkinDueDay(message){return askOf(message)?.dueDay||null}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:avatarUrl,named:named,styles:styles2}){let image=useBrandImage(avatarUrl);return image.shown?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.assistantSender,testID:"everfur-assistant-sender",children:[
|
|
293
|
+
/* @__PURE__ */jsxRuntime.jsx(BrandImage,{uri:avatarUrl,decorative:true,style:styles2.assistantAvatar,resizeMode:"cover",onError:image.onError,testID:"everfur-assistant-avatar"}),named?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.assistantName,styles2.assistantNameInRow],children:CHAT_COPY.assistantName}):null]}):named?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.assistantName,children:CHAT_COPY.assistantName}):null}var CHECKIN_COPY=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),CHECKIN_OPTIONS=/* @__PURE__ */Object.freeze(CHECKIN_ANSWERS.map(answer=>/* @__PURE__ */Object.freeze({answer:answer,label:CHECKIN_COPY.answers[answer]})));function useCheckinCard(checkin,answerCheckin){let[pending,setPending]=react.useState(null),[error,setError]=react.useState(null),[tapped,setTapped]=react.useState(null),choose=react.useCallback(answer2=>{answerCheckin!==null&&(setPending(answer2),setError(null),answerCheckin(checkin.caseId,answer2).then(result=>{setPending(null),result.ok?setTapped(answer2):setError(result.error)}))},[answerCheckin,checkin.caseId]),answer=tapped??checkin.answer;return{answer:answer,answerable:!isCheckinSettled(checkin),escalated:answer==="worse",pending:pending,error:error,choose:choose}}var MIN_TOUCH_TARGET6=44,PENDING_OPACITY2=.6;function CheckinCard({message:message,checkin:checkin,onAnswer:onAnswer,petRef:petRef2,onFindVet:onFindVet,vet:vet,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles12(theme),[theme]),state=useCheckinCard(checkin,onAnswer),settled=state.answer!==null||state.pending!==null,answerable=onAnswer!==null&&state.answerable,day=checkinDayNumber(checkin.openedAt,checkinDueDay(message));/* @__PURE__ */
|
|
294
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles2.card,accessibilityLabel:CHECKIN_COPY.eyebrow,onLayout:onLayout,children:[
|
|
295
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.head,children:[
|
|
296
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.eyebrow,children:CHECKIN_COPY.eyebrow}),day!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.headDay,children:fillCopy(CHECKIN_COPY.day,{day:day})}):null]}),
|
|
297
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.question,accessibilityRole:"text",children:message.text}),answerable?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.row,state.pending?styles2.rowPending:null],children:CHECKIN_OPTIONS.map(({answer:answer,label:label})=>{let selected=(state.pending??state.answer)===answer;/* @__PURE__ */
|
|
298
|
+
return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>state.choose(answer),disabled:settled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected,disabled:settled,busy:state.pending===answer},style:[styles2.pill,selected?styles2.pillSelected:null],children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.pillLabel,selected?styles2.pillLabelSelected:null],children:label})},answer)})}):null,state.answer!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.logged,children:CHECKIN_COPY.logged}):null,state.escalated?onFindVet!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onFindVet,accessibilityRole:"button",accessibilityLabel:CHECKIN_COPY.findVet,style:styles2.findVet,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.findVetLabel,children:CHECKIN_COPY.findVet})}):petRef2?/* @__PURE__ */jsxRuntime.jsx(VetVisitButton,{entry:"chat",petRef:petRef2,label:CHECKIN_COPY.findVet,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:styles2.findVet,labelStyle:styles2.findVetLabel}):null:null,checkin.resolutionText?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.resolution,children:checkin.resolutionText}):null,state.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.error,accessibilityRole:"alert",children:state.error.displayMessage}):null]})}function makeStyles12(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,card=ownGroundSlot(theme.slots.card),cardText=slotText(card);return reactNative.StyleSheet.create({card:{maxWidth:"92%",padding:s.md,gap:s.sm,borderRadius:r.lg,backgroundColor:c.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:c.brandBorder,...slotBox(card,reactNative.StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm},eyebrow:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},headDay:{...face(theme,"bold"),color:c.text.primary,fontSize:t.size.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},question:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},row:{flexDirection:"row",gap:s.sm,marginTop:s.xs},rowPending:{opacity:PENDING_OPACITY2},pill:{flex:1,minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",paddingHorizontal:s.md,borderRadius:r.pill,borderWidth:1,borderColor:c.controlEdge,backgroundColor:c.surface},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk},pillLabel:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body},pillLabelSelected:{color:c.onPrimary},logged:{...face(theme,"regular"),color:c.text.secondary,fontSize:t.size.caption,...cardText},resolution:{...face(theme,"regular"),color:c.text.primary,fontSize:t.size.body,lineHeight:t.size.body*t.lineHeight.normal,...cardText},error:{...face(theme,"regular"),color:c.danger,fontSize:t.size.caption},findVet:{alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET6,alignItems:"center",justifyContent:"center",borderRadius:r.pill,borderWidth:1.5,borderColor:c.controlEdge,backgroundColor:c.surface},findVetLabel:{...face(theme,"bold"),color:c.brandInk,fontSize:t.size.body}})}var RULE_WIDTH2=1.5,BODY_GAP=3;function CheckinPastAsk({text:text3,runDueDays:runDueDays,openedAt:openedAt,onLayout:onLayout}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles13(theme),[theme]),days=runDueDays.map(dueDay=>checkinDayNumber(openedAt,dueDay)).filter(day=>day!==null),collapsed=runDueDays.length>1;return collapsed&&days.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.row,onLayout:onLayout,children:[
|
|
299
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.rule,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}),
|
|
300
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.body,children:[days.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.days,children:days.map(day=>fillCopy(CHECKIN_COPY.day,{day:day})).join(CHECKIN_COPY.daySeparator)}):null,collapsed?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.question,accessibilityRole:"text",children:text3})]})]})}function makeStyles13(theme){let c=theme.color,s=theme.space,t=theme.type;return reactNative.StyleSheet.create({row:{flexDirection:"row",paddingVertical:s.xs},rule:{width:RULE_WIDTH2,borderRadius:1,backgroundColor:c.borderHairlineGreen,marginRight:s.md},body:{flex:1,gap:BODY_GAP},days:{...face(theme,"monoMedium"),fontSize:t.size.nano,letterSpacing:t.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase"},question:{...face(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:t.size.bodyTight*t.lineHeight.normal,color:c.text.muted}})}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
|
|
301
|
+
return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count2){return count2===1?`1 ${CHAT_COPY.sourceSingular}`:`${count2} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count2,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count2)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}var CARD_WIDTH=244,TIER_DOT=8,PILL_GLYPH=13,LINK_GLYPH=14,TOGGLE_TRACKING=.3,TITLE_TRACKING=-.24,TITLE_LINE=22,META_LINE=10,EXCERPT_LINE=15;function CitationCards({citations:citations,onOpenUrl:onOpenUrl}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles14(theme),[theme]),cards=react.useMemo(()=>toCitationCards(citations),[citations]),[expanded,setExpanded]=react.useState(false);if(cards.length===0)return null;let count2=cards.length;/* @__PURE__ */
|
|
302
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles2.block,children:[
|
|
303
|
+
/* @__PURE__ */jsxRuntime.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:sourcesToggleLabel(count2,expanded),accessibilityState:{expanded:expanded},containerStyle:styles2.toggleSlot,style:styles2.togglePill,onPress:()=>setExpanded(current=>!current),children:[
|
|
304
|
+
/* @__PURE__ */jsxRuntime.jsx(BookGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}),
|
|
305
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.toggleLabel,children:sourcesLabel(count2)}),
|
|
306
|
+
/* @__PURE__ */jsxRuntime.jsx(ChevronGlyph,{size:PILL_GLYPH,color:theme.color.brandInk,strokeWidth:1.5,direction:expanded?"up":"down"})]}),expanded?/* @__PURE__ */jsxRuntime.jsx(Deck,{cards:cards,styles:styles2,open:onOpenUrl}):null]})}function Deck({cards:cards,styles:styles2,open:open}){let motion=useChatMotion(),fade=useFadeIn(motion.citationsInMs,{risePx:motion.citationsRisePx});/* @__PURE__ */
|
|
307
|
+
return jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:styles2.row,children:cards.map(card=>/* @__PURE__ */jsxRuntime.jsx(Card,{card:card,styles:styles2,open:open},card.key))})})}function Card({card:card,styles:styles2,open:open}){let theme=useEverfurTheme(),linked=card.url!==null&&open!==void 0,label=citationA11yLabel(linked?card:{...card,url:null}),inner=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
308
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.cardHeader,children:[
|
|
309
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.tierDot,{backgroundColor:card.tierColor}]}),
|
|
310
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles2.cardTitle,linked?styles2.cardTitleLink:null],numberOfLines:2,children:card.title}),linked?/* @__PURE__ */jsxRuntime.jsx(ArrowUpRightGlyph,{size:LINK_GLYPH,color:theme.color.linkInk,strokeWidth:1.5}):null]}),card.meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.cardMeta,numberOfLines:1,children:card.meta}):null,card.excerpt!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.cardExcerpt,numberOfLines:3,children:card.excerpt}):null]});if(card.url!==null&&open!==void 0){let url=card.url;/* @__PURE__ */
|
|
311
|
+
return jsxRuntime.jsx(PressScale,{accessibilityRole:"link",accessibilityLabel:label,style:styles2.card,onPress:()=>open(url),children:inner})}/* @__PURE__ */
|
|
312
|
+
return jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:label,style:styles2.card,children:inner})}function makeStyles14(theme){let c=theme.color,s=theme.space,r=theme.radius,size=theme.type.size,cardText=slotText(theme.slots.card);return reactNative.StyleSheet.create({block:{gap:s.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:r.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:s.xs+2,paddingHorizontal:s.md,paddingVertical:s.xs+2,borderRadius:r.pill,backgroundColor:c.brandSoft},toggleLabel:{...face(theme,"monoBold"),fontSize:size.micro,lineHeight:size.micro,letterSpacing:TOGGLE_TRACKING,color:c.brandInk,textTransform:"uppercase"},row:{gap:s.sm,paddingRight:s.xl,paddingTop:s.xs},card:{width:CARD_WIDTH,borderRadius:r.md,borderWidth:1,borderColor:c.brandBorder,backgroundColor:c.surface,padding:s.md,gap:s.xs+2,...slotBox(theme.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:s.sm},tierDot:{width:TIER_DOT,height:TIER_DOT,borderRadius:r.pill},cardTitle:{...headingFace(theme,"bold"),flex:1,fontSize:size.bodyTight,lineHeight:TITLE_LINE,color:c.text.primary,letterSpacing:TITLE_TRACKING,...cardText},cardTitleLink:{color:c.linkInk},cardMeta:{...face(theme,"monoMedium"),fontSize:size.nano,lineHeight:META_LINE,letterSpacing:theme.type.letterSpacing.monoWide,color:c.text.metaCool,textTransform:"uppercase",...cardText},cardExcerpt:{...face(theme,"regular"),fontSize:size.tiny,lineHeight:EXCERPT_LINE,color:c.text.muted,...cardText}})}var ICON_SIZE=15,ICON_HIT_SLOP=15,THUMB_HIT_SLOP=6,SENTIMENT_ROTATE=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:message,onCopy:onCopy,sentiment:sentiment=null,onSentiment:onSentiment,thanks:thanks=false}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles15(theme),[theme]),motion=useChatMotion(),isUser=message.role==="user",timeLabel=react.useMemo(()=>formatMessageTime(message.createdAt),[message.createdAt]),canCopy=onCopy!==void 0&&message.role!=="vet"&&message.text.length>0,thumbs=message.role==="assistant"&&onSentiment!==void 0&&message.responseId!==void 0,[justCopied,setJustCopied]=react.useState(false),resetTimer=react.useRef(null);react.useEffect(()=>()=>{resetTimer.current&&clearTimeout(resetTimer.current)},[]);let copy=()=>{onCopy!==void 0&&(callHostAsync(onCopy,message.text),setJustCopied(true),resetTimer.current&&clearTimeout(resetTimer.current),resetTimer.current=setTimeout(()=>{setJustCopied(false),resetTimer.current=null},motion.copiedMs))};return timeLabel===null&&!canCopy&&!thumbs?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.wrap,children:[
|
|
313
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],children:[timeLabel!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.timestamp,children:timeLabel}):null,canCopy?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:justCopied?CHAT_COPY.copied:isUser?CHAT_COPY.copyUserMessage:CHAT_COPY.copyAssistantMessage,hitSlop:ICON_HIT_SLOP,onPress:copy,style:styles2.iconHit,children:justCopied?/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:ICON_SIZE,color:theme.color.success,strokeWidth:2}):/* @__PURE__ */jsxRuntime.jsx(CopyGlyph,{size:ICON_SIZE,color:theme.color.text.timestamp,strokeWidth:1.5})}):null,thumbs?SENTIMENT_OPTIONS.map(({sentiment:kind,label:label})=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:sentiment===kind},hitSlop:THUMB_HIT_SLOP,onPress:()=>onSentiment?.(kind),style:styles2.iconHit,children:/* @__PURE__ */jsxRuntime.jsx(ThumbGlyph,{size:ICON_SIZE,color:theme.color.sentiment[kind],active:sentiment===kind,rotate:SENTIMENT_ROTATE[kind],strokeWidth:1.5})},kind)):null]}),thanks?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.thanks,accessibilityLiveRegion:"polite",children:CHAT_COPY.feedbackThanks}):null]})}function makeStyles15(theme){let t=theme.type;return reactNative.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(theme,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:theme.color.text.timestamp,textAlign:"center"},iconHit:{width:ICON_SIZE,height:ICON_SIZE,alignItems:"center",justifyContent:"center"},thanks:{...face(theme,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:theme.color.text.secondary}})}var QUICK_PROMPT_BRAND_EDGE="#10462E";var QUICK_PROMPT_TEXT_COLOR="#000000",PILL_ACTIVITY_ON_WHITE="#83E0B4",PROMPTS=/* @__PURE__ */Object.freeze([
|
|
314
|
+
/* @__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}),
|
|
315
|
+
/* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:PILL_ACTIVITY_ON_WHITE,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
316
|
+
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:QUICK_PROMPT_BRAND_EDGE,brandEdge:true,borderWidth:1}),
|
|
317
|
+
/* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function quickPromptThemePaint(everfurLook,highlight){return everfurLook?null:{fill:highlight.fill,ink:highlight.ink}}var TRAILING_SIZE_SUFFIX_RE=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function formatBreedForPrompt(breed){return breed==null?breed:breed.replace(TRAILING_SIZE_SUFFIX_RE,"").trim()}var UNINFORMATIVE_BREEDS=/* @__PURE__ */new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function isUninformativeBreed(breed){let key=String(breed??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return UNINFORMATIVE_BREEDS.has(key)}function unspecifiedBreedLabel(species){return species==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function resolveBreedLabel(breed,species){return isUninformativeBreed(breed)?unspecifiedBreedLabel(species):String(breed).replace(/\s+/gu," ").trim()}function emptyStateTitle(pet){let petName=pet?.name?.trim()||CHAT_COPY.emptyTitlePetFallback;return fillCopy(CHAT_COPY.emptyTitle,{petName:petName})}function resolveQuickPrompts(pet,brandEdge=QUICK_PROMPT_BRAND_EDGE){let species=speciesOf(pet?.species),speciesFallback=species==="cat"?"my cat":"my dog",trimmedPetName=pet?.name?.trim()||null,petToken=trimmedPetName||speciesFallback,breedToken=resolveBreedLabel(formatBreedForPrompt(pet?.breed),species)||null,age=petAgeYears(pet?.ageYears),ageToken=age===null?null:String(age);/* @__PURE__ */
|
|
318
|
+
return Object.freeze(PROMPTS.map(template=>{let usesBreed=template.label.includes("{breed}"),usesAge=template.label.includes("{ageYears}"),baseLabel=template.fallbackLabel!==void 0&&(usesBreed&&!breedToken||usesAge&&!ageToken)&&template.fallbackLabel?template.fallbackLabel:template.label,resolvedLabel=fillCopy(baseLabel,{petName:petToken,breed:breedToken??speciesFallback,species:species,ageYears:ageToken??""}),label=!trimmedPetName&&baseLabel.startsWith("{petName}")?resolvedLabel.charAt(0).toUpperCase()+resolvedLabel.slice(1):resolvedLabel;/* @__PURE__ */
|
|
319
|
+
return Object.freeze({id:template.id,intent:template.intent,label:label,background:template.background,borderColor:template.brandEdge===true?brandEdge:template.borderColor,borderWidth:template.borderWidth})}))}var CHIP_MIN_HEIGHT=44,CHIP_HIT_SLOP=0,CHIP_EDGE_WIDTH=1,CHIP_EDGE_ALPHA=.28,CHIP_GAP_EXTRA=2,CHIP_PAD_X_EXTRA=2,CHIP_LEAD=1.3,TITLE_TRACKING_EM=-.015;function QuickPrompts({pet:pet,petRef:petRef2,onSend:onSend,onVetPrep:onVetPrep,vet:vet}){let theme=useEverfurTheme(),styles2=react.useMemo(()=>makeStyles16(theme),[theme]),prompts=react.useMemo(()=>resolveQuickPrompts(pet,theme.color.brandInk),[pet,theme.color.brandInk]),themed=react.useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]),title=emptyStateTitle(pet);/* @__PURE__ */
|
|
320
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles2.block,children:[
|
|
321
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles2.title,accessibilityRole:"header",children:title}),
|
|
322
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.list,accessibilityLabel:CHAT_COPY.suggestions,children:prompts.map((prompt,index)=>/* @__PURE__ */jsxRuntime.jsx(Chip,{prompt:prompt,themed:themed,index:index,petRef:petRef2,onSend:onSend,onVetPrep:onVetPrep,vet:vet,pet:pet,styles:styles2},prompt.id))})]})}function Chip({prompt:prompt,themed:themed,index:index,pet:pet,petRef:petRef2,onSend:onSend,onVetPrep:onVetPrep,vet:vet,styles:styles2}){let motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index),risePx:motion.promptRisePx}),paint=styles2.chipSlot===null?{backgroundColor:themed?.fill??prompt.background}:{backgroundColor:themed?.fill??prompt.background,...styles2.chipSlot},label=themed===null?styles2.chipSlotLabel===null?styles2.chipLabel:[styles2.chipLabel,styles2.chipSlotLabel]:[styles2.chipLabel,{color:themed.ink},...styles2.chipSlotLabel===null?[]:[styles2.chipSlotLabel]];return prompt.intent==="vet_report"?onVetPrep!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,styles2.chipEdge,paint],onPress:()=>{callHost(onVetPrep,pet)},children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:label,children:prompt.label})})}):petRef2===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(VetVisitButton,{entry:"chat",petRef:petRef2,label:prompt.label,...vet?.returnTo!==void 0?{returnTo:vet.returnTo}:{},...vet?.usState!==void 0?{usState:vet.usState}:{},...vet?.prefer!==void 0?{prefer:vet.prefer}:{},style:[styles2.chip,styles2.chipEdge,paint],labelStyle:label})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:prompt.label,hitSlop:CHIP_HIT_SLOP,style:[styles2.chip,styles2.chipEdge,paint],onPress:()=>onSend(prompt.label),children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:label,children:prompt.label})})})}function makeStyles16(theme){let chip=ownGroundSlot(theme.slots.chip),chipText=slotText(chip);return{chipSlot:chip===void 0?null:slotBox(chip,CHIP_EDGE_WIDTH),chipSlotLabel:chipText.color===void 0?null:chipText,...makeSheet(theme)}}function makeSheet(theme){let c=theme.color,s=theme.space,t=theme.type;return reactNative.StyleSheet.create({block:{gap:s.lg,alignItems:"stretch",width:"100%"},title:{...headingFace(theme,"medium"),fontSize:t.size.heading,lineHeight:Math.round(t.size.heading*t.lineHeight.snug),color:c.brandInk,letterSpacing:t.size.heading*TITLE_TRACKING_EM,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:s.sm+CHIP_GAP_EXTRA},chip:{borderRadius:theme.radius.pill,paddingHorizontal:s.lg+CHIP_PAD_X_EXTRA,paddingVertical:s.sm,minHeight:CHIP_MIN_HEIGHT,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:CHIP_EDGE_WIDTH,borderColor:withAlpha(c.brandInk,CHIP_EDGE_ALPHA)??c.borderRingCream},chipLabel:{...face(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:Math.round(t.size.bodyTight*CHIP_LEAD),color:QUICK_PROMPT_TEXT_COLOR,textAlign:"left"}})}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor2=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor2&&runs.push({kind:"text",text:text3.slice(cursor2,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor2=match.index+match[0].length}return cursor2<text3.length&&runs.push({kind:"text",text:text3.slice(cursor2)}),runs}function renderInlineMarkdown(text3,styles2){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
|
|
323
|
+
return jsxRuntime.jsx(Text,{style:styles2.bold,children:run.text},key);case"italic":return styles2.italic?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.italic,children:run.text},key):run.text;case"code":return styles2.code?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.code,children:run.text},key):run.text;default:return run.text}}):text3}function TypingIndicator({petName:petName=null}){let{styles:styles2}=useChatTheme(),line=forPet(CHAT_COPY.reading,petName);/* @__PURE__ */
|
|
324
|
+
return jsxRuntime.jsx(Text,{tier:"compact",style:styles2.readingLine,accessibilityRole:"text",accessibilityLabel:line,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:line})}function resolveTurnScrollTarget(assistantTop,userTop,inset){let replyTarget=assistantTop-inset,target=userTop!=null?Math.min(replyTarget,userTop):replyTarget;return Math.max(0,target)}function latestTurn(messages){let assistantIndex=messages.length-1,last=messages[assistantIndex];if(last===void 0||last.role!=="assistant")return null;let above=messages[assistantIndex-1];return{assistantIndex:assistantIndex,userIndex:above!==void 0&&above.role==="user"?assistantIndex-1:null}}function nextFollowOffset(anchor,current,maxOffset){let end=Math.max(0,maxOffset),target=anchor===null?end:Math.min(Math.max(0,anchor),end);return target>current+1?target:null}function useThreadFollow(rows,isStreaming){let ref=react.useRef(null),following=react.useRef(true),wasStreaming=react.useRef(isStreaming),offset=react.useRef(0),viewport=react.useRef(0),content=react.useRef(0),tops=react.useRef(/* @__PURE__ */new Map),turn=latestTurn(rows),assistantId=turn===null?null:rows[turn.assistantIndex]?.id??null,userId=turn===null||turn.userIndex===null?null:rows[turn.userIndex]?.id??null,follow=react.useCallback(()=>{let view=ref.current;if(view===null||!following.current||viewport.current===0)return;let anchor=null;if(assistantId!==null){let assistantTop=tops.current.get(assistantId);if(assistantTop===void 0)return;let userTop=userId===null?null:tops.current.get(userId)??null;anchor=resolveTurnScrollTarget(assistantTop,userTop,96)}let next=nextFollowOffset(anchor,offset.current,content.current-viewport.current);next!==null&&(offset.current=next,view.scrollTo({y:next,animated:false}))},[assistantId,userId]);react.useEffect(()=>{isStreaming&&!wasStreaming.current&&(following.current=true),wasStreaming.current=isStreaming,follow()},[rows,isStreaming,follow]);let onLayout=react.useCallback(event=>{viewport.current=event.nativeEvent.layout.height,follow()},[follow]),onContentSizeChange=react.useCallback((_width,height)=>{content.current=height,viewport.current>0&&(offset.current=Math.min(offset.current,Math.max(0,height-viewport.current))),follow()},[follow]),onScroll=react.useCallback(event=>{offset.current=event.nativeEvent.contentOffset.y},[]),onScrollBeginDrag=react.useCallback(()=>{following.current=false},[]),onScrollEnd=react.useCallback(event=>{let{contentOffset:contentOffset,contentSize:contentSize,layoutMeasurement:layoutMeasurement}=event.nativeEvent;offset.current=contentOffset.y,following.current=contentSize.height-contentOffset.y-layoutMeasurement.height<=24},[]),rowLayout=react.useCallback(id=>event=>{tops.current.set(id,event.nativeEvent.layout.y),(id===assistantId||id===userId)&&follow()},[assistantId,userId,follow]);return{ref:ref,onLayout:onLayout,onContentSizeChange:onContentSizeChange,onScroll:onScroll,onScrollBeginDrag:onScrollBeginDrag,onScrollEnd:onScrollEnd,rowLayout:rowLayout}}function renderView(view,chat,extras){switch(view){case"loading":return extras.renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:extras.renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(LoadingState,{})}):/* @__PURE__ */jsxRuntime.jsx(LoadingState,{});case"empty":/* @__PURE__ */
|
|
325
|
+
return jsxRuntime.jsx(EmptyState,{pet:extras.shownPet,petRef:chat.petRef,onSelectPrompt:extras.onSelectPrompt,onVetPrep:extras.onVetPrep,vet:extras.vet});case"error":/* @__PURE__ */
|
|
326
|
+
return jsxRuntime.jsx(ErrorState,{error:chat.error,onRetry:chat.retryLast,onAddPet:extras.onAddPet});case"populated":/* @__PURE__ */
|
|
327
|
+
return jsxRuntime.jsx(PopulatedState,{messages:chat.messages,prompts:visibleFollowUps(chat),onSelectPrompt:extras.onSelectPrompt,isStreaming:chat.isStreaming,onAnswerCheckin:chat.petRef?chat.answerCheckin:null,onCopy:extras.onCopy,sentimentByMessage:chat.sentimentByMessage,onSentiment:extras.onSentiment,thanksFor:extras.thanksFor,imagesByMessage:extras.imagesByMessage,onPreview:extras.onPreview,notice:extras.notice,reconnecting:chat.reconnecting===true,onRetry:chat.retryLast,onStartNew:chat.newConversation,petRef:chat.petRef,onFindVet:extras.onCheckinFindVet,vet:extras.vet,onOpenUrl:extras.onOpenUrl,petName:extras.shownPet?.name??null});default:return assertNever(view)}}function LoadingState(){let{theme:theme,styles:styles2}=useChatTheme(),[visible,setVisible]=react.useState(false);return react.useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:CHAT_COPY.loading,children:visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:theme.color.brandInk}):null})}function EmptyState({pet:pet,petRef:petRef2,onSelectPrompt:onSelectPrompt,onVetPrep:onVetPrep,vet:vet}){let{styles:styles2}=useChatTheme();
|
|
328
|
+
/* @__PURE__ */
|
|
329
|
+
return jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:styles2.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,accessibilityLabel:CHAT_COPY.empty,children:/* @__PURE__ */jsxRuntime.jsx(QuickPrompts,{pet:pet,petRef:petRef2,onSend:onSelectPrompt,onVetPrep:onVetPrep,vet:vet})})}function FollowUps({prompts:prompts,onSelectPrompt:onSelectPrompt}){let{styles:styles2}=useChatTheme();return prompts.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.followUps,children:[
|
|
330
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.followUpsHeading,accessibilityRole:"header",children:CHAT_COPY.followUpsHeadingNative}),prompts.map((prompt,index)=>/* @__PURE__ */jsxRuntime.jsx(FollowUpRow,{prompt:prompt,index:index,onSelectPrompt:onSelectPrompt},prompt))]})}function FollowUpRow({prompt:prompt,index:index,onSelectPrompt:onSelectPrompt}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),fade=useFadeIn(motion.followUpInMs,{delayMs:followUpDelayMs(motion,index)});/* @__PURE__ */
|
|
331
|
+
return jsxRuntime.jsx(reactNative.Animated.View,{style:fade,children:/* @__PURE__ */jsxRuntime.jsxs(PressScale,{onPress:()=>onSelectPrompt(prompt),accessibilityRole:"button",accessibilityLabel:prompt,containerStyle:[styles2.followUpSlot,index>0?styles2.followUpSlotRuled:null],style:styles2.followUpRow,children:[
|
|
332
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.followUpText,children:prompt}),
|
|
333
|
+
/* @__PURE__ */jsxRuntime.jsx(PlusGlyph,{size:FOLLOW_UP_PLUS,color:theme.slots.chip?.textColor??theme.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:error,onRetry:onRetry,onAddPet:onAddPet}){let{styles:styles2}=useChatTheme(),addPet=isPetNotRegistered(error)?guardHost(onAddPet):void 0;/* @__PURE__ */
|
|
334
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles2.centered,accessible:true,accessibilityRole:"alert",children:[
|
|
335
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles2.errorText,children:error.displayMessage}),addPet!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:addPet,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.addPet,style:styles2.retryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.addPet})}):null,error.retryable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onRetry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,style:styles2.retryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.retryLabel,children:CHAT_COPY.retry})}):null]})}function PopulatedState({messages:messages,prompts:prompts,onSelectPrompt:onSelectPrompt,isStreaming:isStreaming,onAnswerCheckin:onAnswerCheckin,onCopy:onCopy,sentimentByMessage:sentimentByMessage,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:imagesByMessage,onPreview:onPreview,notice:notice,reconnecting:reconnecting,onRetry:onRetry,onStartNew:onStartNew,petRef:petRef2,onFindVet:onFindVet,vet:vet,onOpenUrl:onOpenUrl,petName:petName}){let{styles:styles2}=useChatTheme(),motion=useChatMotion();useAnimateLayoutOn(messages.length,motion);let checkins=react.useMemo(()=>placeCheckins(messages),[messages]),awaiting=awaitingAssistant(messages,isStreaming),last=messages[messages.length-1],rows=react.useMemo(()=>messages.filter(message=>!(message.checkin&&checkins.get(message.id)?.kind==="folded")),[messages,checkins]),follow=useThreadFollow(rows,isStreaming),isEntering=useEnteringRows(rows);/* @__PURE__ */
|
|
336
|
+
return jsxRuntime.jsxs(reactNative.ScrollView,{ref:follow.ref,style:styles2.list,contentContainerStyle:styles2.listContent,accessibilityLabel:CHAT_COPY.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:KEYBOARD_DISMISS_MODE,nestedScrollEnabled:true,onLayout:follow.onLayout,onContentSizeChange:follow.onContentSizeChange,onScroll:follow.onScroll,scrollEventThrottle:SCROLL_EVENT_THROTTLE_MS,onScrollBeginDrag:follow.onScrollBeginDrag,onScrollEndDrag:follow.onScrollEnd,onMomentumScrollEnd:follow.onScrollEnd,children:[messages.map(message=>{let placement=message.checkin?checkins.get(message.id):void 0;return placement?.kind==="folded"?null:placement?.kind==="past"?/* @__PURE__ */jsxRuntime.jsx(CheckinPastAsk,{text:message.text,runDueDays:placement.runDueDays,openedAt:message.checkin?.openedAt,onLayout:follow.rowLayout(message.id)},message.id):message.checkin&&placement!==void 0?/* @__PURE__ */jsxRuntime.jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,petRef:petRef2,onFindVet:onFindVet,vet:vet,onLayout:follow.rowLayout(message.id)},message.id):/* @__PURE__ */jsxRuntime.jsx(MessageRow,{onLayout:follow.rowLayout(message.id),message:message,revealing:isStreaming&&message===last&&message.role==="assistant",onCopy:onCopy,sentiment:message.responseId===void 0?null:sentimentByMessage[String(message.responseId)]??null,onSentiment:onSentiment,thanks:thanksFor!==null&&message.responseId!==void 0&&String(message.responseId)===thanksFor,images:imagesByMessage[message.id]??NO_IMAGES,onPreview:onPreview,onOpenUrl:onOpenUrl,entering:isEntering(message.id)},message.id)}),reconnecting?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.reconnectingCaption,accessibilityRole:"text",children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsxRuntime.jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsxRuntime.jsx(TurnNoticeCard,{notice:notice,onRetry:onRetry,onStartNew:onStartNew}):null,
|
|
337
|
+
/* @__PURE__ */jsxRuntime.jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt})]})}function TurnNoticeCard({notice:notice,onRetry:onRetry,onStartNew:onStartNew}){let{styles:styles2}=useChatTheme(),error=notice.tone==="error";/* @__PURE__ */
|
|
338
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles2.turnNotice,error?styles2.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
|
|
339
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[styles2.turnNoticeTitle,error?styles2.turnNoticeTitleError:null],children:notice.title}),
|
|
340
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.turnNoticeBody,children:notice.body}),
|
|
341
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:notice.action==="startNew"?onStartNew:onRetry,accessibilityRole:"button",accessibilityLabel:notice.actionLabel,hitSlop:TEXT_ACTION_HIT_SLOP,style:styles2.turnNoticeAction,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.turnNoticeActionLabel,children:notice.actionLabel})})]})}var NO_IMAGES=/* @__PURE__ */Object.freeze([]),SCROLL_EVENT_THROTTLE_MS=16,KEYBOARD_DISMISS_MODE=reactNative.Platform.OS==="ios"?"interactive":"on-drag",FOLLOW_UP_PLUS=18;function MessageRow({message:message,revealing:revealing,onCopy:onCopy,sentiment:sentiment,onSentiment:onSentiment,thanks:thanks,images:images,onPreview:onPreview,onOpenUrl:onOpenUrl,onLayout:onLayout,entering:entering}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),enter=useBubbleEnter(entering,motion),shown=useRevealedText(message.text,revealing,motion),isUser=message.role==="user",isVet=message.role==="vet",isAssistant=message.role==="assistant",namesAssistant=isAssistant&&!theme.meta.hidePoweredBy,sender=isUser?CHAT_COPY.senderUser:isVet?vetSenderLabel(message):namesAssistant?CHAT_COPY.assistantName:CHAT_COPY.senderAssistant,vetTime=isVet?formatMessageTime(message.createdAt):null,rate=react.useCallback(kind=>onSentiment(message,kind),[onSentiment,message]),settled=message.pending!==true;/* @__PURE__ */
|
|
342
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles2.rowBlock,isUser?styles2.rowBlockUser:styles2.rowBlockAssistant],onLayout:onLayout,children:[
|
|
343
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles2.row,isUser?styles2.rowUser:styles2.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${sender}: ${message.text}`,accessibilityState:message.pending===true?{busy:true}:void 0,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Animated.View,{style:[styles2.bubble,isUser?styles2.bubbleSideUser:null,enter],children:[isAssistant&&theme.meta.assistantAvatarUrl!==null?/* @__PURE__ */jsxRuntime.jsx(AssistantSender,{avatarUrl:theme.meta.assistantAvatarUrl,named:namesAssistant,styles:styles2}):namesAssistant?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.assistantName,children:CHAT_COPY.assistantName}):null,isVet?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.vetHeader,children:[
|
|
344
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.vetSender,children:sender}),vetTime!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.vetTime,children:vetTime}):null]}):null,
|
|
345
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[isUser?styles2.bubbleUser:isVet?styles2.bubbleVet:styles2.bubbleAssistant,message.pending?styles2.bubblePending:null],children:[isUser&&images.length>0?/* @__PURE__ */jsxRuntime.jsx(SentImages,{images:images,onPreview:image=>onPreview({uri:image.uri,label:image.filename})}):null,
|
|
346
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:isUser?styles2.bubbleTextUser:isVet?styles2.bubbleTextVet:styles2.bubbleTextAssistant,children:isAssistant?renderInlineMarkdown(shown,{bold:styles2.bubbleBold,italic:styles2.bubbleItalic,code:styles2.bubbleCode}):message.text})]})]})}),isAssistant&&!revealing?/* @__PURE__ */jsxRuntime.jsx(CitationCards,{citations:message.citations,onOpenUrl:onOpenUrl}):null,settled?/* @__PURE__ */jsxRuntime.jsx(MessageFooter,{message:message,onCopy:onCopy,sentiment:sentiment,onSentiment:message.responseId===void 0?void 0:rate,thanks:thanks}):null]})}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),DEFAULT_MAX_PER_MESSAGE=1;function EverfurChat(props){let{style:style,renderPending:renderPending}=props;/* @__PURE__ */
|
|
347
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsxRuntime.jsx(ChatBody,{...props})})}function ChatBody({petRef:petRef2,conversationId:conversationId2,style:style,renderPending:renderPending,onCopy:onCopy,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,attachments:attachments,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),chatOpts=react.useMemo(()=>buildChatOpts(petRef2,conversationId2),[petRef2,conversationId2]),chat=useEverfurChat(chatOpts),view=selectView2(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),notice=turnNotice(chat),onCheckinFindVet=react.useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=react.useMemo(()=>vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer},[vetReturnTo,vetUsState,vetPrefer]),shownPet=headerPet(pets.pets,chat.petRef),urgencySource=react.useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion),useCheckinTarget(chat.openCheckin,checkinTarget),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk);let seed=react.useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]);useChatLifecycle(lifecycle,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refresh:chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=react.useState(null),closePreview=react.useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=react.useState(null),[thanksFor,setThanksFor]=react.useState(null),thanksTimer=react.useRef(null);react.useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showThanks=react.useCallback(responseId=>{setThanksFor(String(responseId)),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=setTimeout(()=>{setThanksFor(null),thanksTimer.current=null},THANKS_VISIBLE_MS)},[]),onSentiment=react.useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];chat.feedback(responseId,sentiment),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat]),submitReasons=react.useCallback(async(reason,notes)=>feedbackTarget===null||!(await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showThanks(feedbackTarget),true),[chat,feedbackTarget,showThanks]),skipReasons=react.useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=react.useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=react.useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=reactNative.Platform.OS==="ios"?"padding":void 0,keyboard=useChatKeyboardOffset(keyboardVerticalOffset,avoidBehavior!==void 0),topInset=keyboard.topInWindow===null?insets.top:Math.max(0,insets.top-keyboard.topInWindow),keyboardOpen=useKeyboardOpen(),composerProps={send:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,onStage:sentImages.stage,onPreview:setPreview,petName:shownPet?.name??null};
|
|
348
|
+
/* @__PURE__ */
|
|
349
|
+
return jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{style:[styles2.container,{paddingTop:topInset},style],behavior:avoidBehavior,...keyboard.avoidingProps,children:[
|
|
350
|
+
/* @__PURE__ */jsxRuntime.jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),
|
|
351
|
+
/* @__PURE__ */jsxRuntime.jsx(ChatHeader,{pets:pets,petRef:chat.petRef,historyUnread:historyUnread,onOpenHistory:history.show,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet}),pet!==void 0?/* @__PURE__ */jsxRuntime.jsx(PetSetupNotice,{petRef:petRef2??null,pet:pet,onRegistered:pets.refresh}):null,
|
|
352
|
+
/* @__PURE__ */jsxRuntime.jsx(UrgencyBanner,{surface:urgency,petRef:chat.petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:keyboardOpen}),
|
|
353
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,thanksFor:thanksFor,imagesByMessage:sentImages.byMessage,onPreview:setPreview,onAddPet:onAddPet,onOpenUrl:openCitation})}),attachments!==void 0?/* @__PURE__ */jsxRuntime.jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsxRuntime.jsx(Composer,{...composerProps,attachments:null}),
|
|
354
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.footnote,accessibilityRole:"text",children:CHAT_COPY.footnoteNative}),theme.meta.hidePoweredBy?null:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),
|
|
355
|
+
/* @__PURE__ */jsxRuntime.jsx(HistoryDrawer,{chat:chat,history:history}),
|
|
356
|
+
/* @__PURE__ */jsxRuntime.jsx(FeedbackReasons,{visible:feedbackTarget!==null,onSubmit:submitReasons,onSkip:skipReasons}),
|
|
357
|
+
/* @__PURE__ */jsxRuntime.jsx(AttachmentImageLightbox,{uri:preview?.uri??null,label:preview?.label??"",onClose:closePreview}),
|
|
358
|
+
/* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})]})}function PetSetupNotice({petRef:petRef2,pet:pet,onRegistered:onRegistered}){let{styles:styles2}=useChatTheme(),setup=useChatPetRegistration(petRef2,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.setupNotice,accessible:true,accessibilityRole:"alert",children:[
|
|
359
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:styles2.setupNoticeText,children:setup.error.displayMessage}),
|
|
360
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:setup.retry,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.retry,hitSlop:TEXT_ACTION_HIT_SLOP,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:styles2.setupNoticeAction,children:CHAT_COPY.retry})})]})}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=react.useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??DEFAULT_MAX_PER_MESSAGE,transport:transport}),bound=react.useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
|
|
361
|
+
return jsxRuntime.jsx(Composer,{...rest,attachments:bound})}function Composer({send:send,stop:stop,isStreaming:isStreaming,conversationId:conversationId2,attachments:attachments,seed:seed,draftStore:draftStore,onStage:onStage,onPreview:onPreview,petName:petName}){let{theme:theme,styles:styles2}=useChatTheme(),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId2,seed);usePersistedDraft(draftStore,conversationId2===null?null:String(conversationId2),draft,setDraft);let[pickerOpen,setPickerOpen]=react.useState(false),[pickFailed,setPickFailed]=react.useState(false);react.useEffect(()=>{setPickFailed(false)},[conversationId2]);let placeholder=theme.meta.placeholder??forPet(CHAT_COPY.placeholder,petName),uploading=attachments?.state.uploading??false,uploadFailed=attachments?.state.failed??false,sendBlocked=uploading||uploadFailed,rows=attachments?.state.attachments??NO_ROWS;useAnimateLayoutOn(rows.length,motion);let onSend=react.useCallback(()=>{if(draft.trim().length===0||sendBlocked||[...draft].length>MESSAGE_MAX_CHARS)return;let keys=attachments?.state.s3Keys??NO_KEYS;attachments!==null&&keys.length>0?(onStage(attachments.state.attachments.filter(row=>row.status==="uploaded").map(row=>({uri:row.previewUri,filename:row.filename}))),send(draft,{imageS3Keys:keys}),attachments.state.clear()):send(draft),setDraft(""),setPickFailed(false)},[draft,send,sendBlocked,attachments,onStage]),onStop=react.useCallback(()=>{stop()},[stop]),pickFrom=react.useCallback(source=>{setPickerOpen(false),attachments!==null&&(setPickFailed(false),attachments.state.dismissRejected(),callHostAsync(attachments.pick,source).then(outcome=>{if(!outcome.ok){setPickFailed(true);return}outcome.value!==null&&attachments.state.add(outcome.value)}))},[attachments]),sendDisabled=react.useMemo(()=>[...draft].length>MESSAGE_MAX_CHARS,[draft])||sendBlocked,slotsFull=attachments!==null&&rows.length>=attachments.state.maxPerMessage,sendInk=theme.slots.sendButton?.textColor??theme.color.brandInk;/* @__PURE__ */
|
|
362
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles2.composerOuter,children:[attachments!==null&&pickerOpen?/* @__PURE__ */jsxRuntime.jsx(AttachmentPickerPopover,{sources:attachments.sources,full:slotsFull,onPick:pickFrom,onClose:()=>setPickerOpen(false)}):null,
|
|
363
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.composer,children:[attachments!==null?/* @__PURE__ */jsxRuntime.jsx(AttachmentStrip,{attachments:rows,rejected:pickFailed?PICK_FAILED:attachments.state.rejected,uploadFailed:uploadFailed,onRetry:attachments.state.retry,onRemove:attachments.state.remove,onPreview:row=>onPreview({uri:row.previewUri,label:row.filename})}):null,
|
|
364
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles2.composerRow,children:[attachments!==null?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:slotsFull?attachControlLabel(rows.length,attachments.state.maxPerMessage):CHAT_COPY.attachPhotoOrFileNative,accessibilityState:{disabled:slotsFull,expanded:pickerOpen},disabled:slotsFull,style:[styles2.attachControl,slotsFull?styles2.attachControlDisabled:null],onPress:()=>setPickerOpen(open=>!open),children:/* @__PURE__ */jsxRuntime.jsx(UploadGlyph,{size:ATTACH_GLYPH_SIZE,color:slotsFull?theme.color.text.muted:theme.color.brandInk,strokeWidth:1.75})}):null,
|
|
365
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{style:styles2.input,value:draft,onChangeText:setDraft,placeholder:placeholder,placeholderTextColor:theme.slots.composerInput?.textColor??theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.composerLabel,onSubmitEditing:onSend,returnKeyType:"send",blurOnSubmit:false,multiline:true,editable:true}),isStreaming?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles2.sendControl,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsxRuntime.jsx(StopGlyph,{size:STOP_GLYPH_SIZE,color:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles2.sendControl,sendDisabled?styles2.sendControlDisabled:null],children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles2.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */jsxRuntime.jsx(SendGlyph,{size:SEND_GLYPH_SIZE,color:sendInk,testID:"everfur-send-glyph"})})})]})]})]})}var NO_ROWS=/* @__PURE__ */Object.freeze([]),NO_KEYS=/* @__PURE__ */Object.freeze([]),PICK_FAILED=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=react.useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state,setState]=react.useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state.key===key?state:{profile:null,loading:petRef2!==null,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;if(key.petRef===null){setState({key:key,profile:null,loading:false,error:null});return}setState(previous=>({key:key,profile:previous.key===key?previous.profile:null,loading:true,error:null}));let result=await key.repository.getPetProfile(key.petRef);request===generation.current&&setState(result.ok?{key:key,profile:result.value,loading:false,error:null}:{key:key,profile:null,loading:false,error:result.error})},[key]);return react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return react.createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:rnThemeSeams,children:props.children})}exports.APPEARANCE_PRESETS=APPEARANCE_PRESETS;exports.APPEARANCE_PRESET_NAMES=APPEARANCE_PRESET_NAMES;exports.APPEARANCE_SIZE_RANGES=APPEARANCE_SIZE_RANGES;exports.CapabilityGate=CapabilityGate;exports.EverfurChat=EverfurChat;exports.EverfurConfigError=EverfurConfigError;exports.EverfurProvider=EverfurProvider;exports.EverfurThemeProvider=EverfurThemeProvider;exports.EverfurThrownError=EverfurThrownError;exports.THEME_SLOT_KEYS=THEME_SLOT_KEYS;exports.THEME_SLOT_NAMES=THEME_SLOT_NAMES;exports.canonicalPetSpecies=canonicalPetSpecies;exports.categoryFor=categoryFor;exports.conversationId=conversationId;exports.createRnRecordsUploadTransport=createRnRecordsUploadTransport;exports.expandAppearance=expandAppearance;exports.face=face;exports.headingFace=headingFace;exports.isErr=isErr;exports.isOk=isOk;exports.isRetryableCode=isRetryableCode;exports.petRef=petRef;exports.previewTheme=previewTheme;exports.themeAdjustments=themeAdjustments;exports.unwrap=unwrap;exports.useCapability=useCapability;exports.useChatAttachments=useChatAttachments;exports.useEverfur=useEverfur;exports.useEverfurChat=useEverfurChat;exports.useEverfurPetProfile=useEverfurPetProfile;exports.useEverfurPets=useEverfurPets;exports.useEverfurTheme=useEverfurTheme;exports.userFacingError=userFacingError;exports.userRef=userRef;
|