@everfur/sdk 0.18.2 → 0.19.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 +124 -0
- package/README.md +6 -5
- package/dist/{Chat.d-BkLu9G00.d.ts → Chat.d-BHovj6Ku.d.ts} +1 -1
- package/dist/{Chat.d-B7iUVGmB.d.cts → Chat.d-BO-XtVYe.d.cts} +1 -1
- package/dist/{DepthViews.d-BiS-GTEf.d.cts → DepthViews.d-BwIkdmWZ.d.cts} +1 -1
- package/dist/{DepthViews.d-C-zs_BnZ.d.cts → DepthViews.d-Bx85LeiP.d.cts} +1 -1
- package/dist/{DepthViews.d-hXV6Ef0y.d.ts → DepthViews.d-CBUunxP1.d.ts} +1 -1
- package/dist/{DepthViews.d-C0DVqywN.d.ts → DepthViews.d-DKoZgF8l.d.ts} +1 -1
- package/dist/{IntakeMedia.d-4a89XrP7.d.ts → IntakeMedia.d-B_ZVDxh3.d.ts} +1 -1
- package/dist/{IntakeMedia.d-JJCUvQu7.d.cts → IntakeMedia.d-CnGzpllr.d.cts} +1 -1
- package/dist/{IntakeMedia.d-DGxrhgIW.d.ts → IntakeMedia.d-DNUAks9E.d.ts} +1 -1
- package/dist/{IntakeMedia.d-DUPR4lVM.d.cts → IntakeMedia.d-Dqc5V_YH.d.cts} +1 -1
- package/dist/{RecordsPage.d-BG_RDR1V.d.ts → RecordsPage.d-CsvBhU0f.d.ts} +1 -1
- package/dist/{RecordsPage.d-5rHMTDyY.d.cts → RecordsPage.d-DRFp2LXH.d.cts} +1 -1
- package/dist/animations/index.cjs +1 -94
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/animations/index.js +1 -94
- package/dist/{attachments.d-_mgNU-ur.d.ts → attachments.d-DOZjCdkb.d.ts} +2 -2
- package/dist/{attachments.d-DFbXLAYK.d.cts → attachments.d-DWUsHPf9.d.cts} +2 -2
- package/dist/{bookingCopy.d-RU8lNYJ4.d.ts → bookingCopy.d-BlMWlvgv.d.ts} +10 -3
- package/dist/{bookingCopy.d-0K1trjxx.d.cts → bookingCopy.d-tvO7y6MK.d.cts} +10 -3
- package/dist/{casesRepository.d-D2SQFL27.d.ts → casesRepository.d-C7qbrOL-.d.ts} +1 -1
- package/dist/{casesRepository.d-D7vIZ9oX.d.cts → casesRepository.d-sSo6oakf.d.cts} +1 -1
- package/dist/chat/index.cjs +29 -119
- package/dist/chat/index.d.cts +11 -10
- package/dist/chat/index.d.ts +11 -10
- package/dist/chat/index.js +30 -120
- package/dist/chat/lite/index.cjs +29 -119
- package/dist/chat/lite/index.d.cts +11 -10
- package/dist/chat/lite/index.d.ts +11 -10
- package/dist/chat/lite/index.js +30 -120
- package/dist/{attachments.d-D7f7OfPE.d.ts → chatHandoffToken.d-C4tEyuCT.d.ts} +33 -9
- package/dist/{attachments.d-HmRqizDG.d.cts → chatHandoffToken.d-D6GUoBvs.d.cts} +33 -9
- package/dist/{ports.d-RKc2C07X.d.ts → chatTypes.d-BI4vidgu.d.ts} +41 -52
- package/dist/{ports.d-CB9YZT2L.d.cts → chatTypes.d-CSyw9em_.d.cts} +41 -52
- package/dist/client/index.cjs +2 -95
- package/dist/client/index.d.cts +7 -7
- package/dist/client/index.d.ts +7 -7
- package/dist/client/index.js +2 -95
- package/dist/{clinicBatch.d-BN1jfVGo.d.cts → clinicBatch.d-BxA_uGBb.d.cts} +2 -2
- package/dist/{clinicBatch.d-BhaCdstU.d.ts → clinicBatch.d-T5oSAhY-.d.ts} +2 -2
- package/dist/{config.d-D_k_rNZZ.d.ts → config.d-N5Xzy53V.d.ts} +1 -1
- package/dist/{config.d-BFTqU7ft.d.cts → config.d-jCmrhM4a.d.cts} +1 -1
- package/dist/consent/index.cjs +1 -94
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/consent/index.js +1 -94
- package/dist/{context.d-B4LODPF1.d.ts → context.d-BJEpEERH.d.ts} +7 -6
- package/dist/{context.d-D2fhrjAM.d.cts → context.d-l4HkFJI8.d.cts} +7 -6
- package/dist/{copy.d-Bn9eIgkW.d.ts → copy.d-hFRaovog.d.ts} +2 -2
- package/dist/{copy.d-DjYhMxxS.d.cts → copy.d-hS49oJ4w.d.cts} +2 -2
- package/dist/core/index.cjs +6 -99
- package/dist/core/index.d.cts +14 -13
- package/dist/core/index.d.ts +14 -13
- package/dist/core/index.js +6 -99
- package/dist/{depth.d-CsKZkLNi.d.cts → depth.d-BYwddMNU.d.cts} +2 -2
- package/dist/{depth.d-DlaIV8TV.d.ts → depth.d-C99_xup2.d.ts} +2 -2
- package/dist/{entitlementRepository.d-CpIRpfzy.d.cts → entitlementRepository.d-CiU_QIPL.d.cts} +2 -2
- package/dist/{entitlementRepository.d-C5d_6QMi.d.ts → entitlementRepository.d-qZAlET7C.d.ts} +2 -2
- package/dist/{focus.d-DOlAaNIU.d.ts → focus.d-CG6KhDBK.d.ts} +2 -2
- package/dist/{focus.d-DdBbwzjP.d.cts → focus.d-RJMXplJc.d.cts} +2 -2
- package/dist/health-plan/index.cjs +1 -94
- package/dist/health-plan/index.d.cts +9 -9
- package/dist/health-plan/index.d.ts +9 -9
- package/dist/health-plan/index.js +1 -94
- package/dist/{idempotency.d-CmQc1OUv.d.ts → idempotency.d-D-ZWpO9p.d.ts} +1 -1
- package/dist/{idempotency.d-P4O5lNBq.d.cts → idempotency.d-DJyOZDPb.d.cts} +1 -1
- package/dist/{identity.d-BmbAwQYx.d.cts → identity.d-CA7mW59I.d.cts} +1 -1
- package/dist/{identity.d-BZXPu9Hi.d.ts → identity.d-DIOnFzXL.d.ts} +1 -1
- package/dist/index.cjs +30 -120
- package/dist/index.d.cts +14 -13
- package/dist/index.d.ts +14 -13
- package/dist/index.js +31 -121
- package/dist/{introEvents.d-Bqw2Hcpt.d.cts → introEvents.d-7wNDMhEF.d.cts} +1 -1
- package/dist/{introEvents.d-Cy8yxOoe.d.ts → introEvents.d-BjqfFgE1.d.ts} +1 -1
- package/dist/notifications/inbox/index.cjs +44 -0
- package/dist/notifications/inbox/index.d.cts +50 -0
- package/dist/notifications/inbox/index.d.ts +50 -0
- package/dist/notifications/inbox/index.js +44 -0
- package/dist/notifications/index.cjs +18 -98
- package/dist/notifications/index.d.cts +12 -6
- package/dist/notifications/index.d.ts +12 -6
- package/dist/notifications/index.js +18 -98
- package/dist/{optInView.d-wGSNOB86.d.ts → optInView.d-B5v4cDDW.d.ts} +2 -2
- package/dist/{optInView.d-DXj2w4KU.d.cts → optInView.d-BQhHPleh.d.cts} +2 -2
- package/dist/parse.d-DYsx1Q2V.d.cts +168 -0
- package/dist/parse.d-Do0sdAgm.d.ts +168 -0
- package/dist/{pets.d-CP13kAFa.d.cts → pets.d-DRqMaP8A.d.cts} +1 -1
- package/dist/{pets.d-tqGZP3Co.d.ts → pets.d-DVrOb-Bj.d.ts} +1 -1
- package/dist/{petsRepository.d-CLyzuoo4.d.ts → petsRepository.d-CpYWRWFq.d.ts} +1 -1
- package/dist/{petsRepository.d-CyerzD5G.d.cts → petsRepository.d-tZADfKA1.d.cts} +1 -1
- package/dist/photo/index.cjs +1 -94
- package/dist/photo/index.js +1 -94
- package/dist/records/depth/index.cjs +1 -94
- package/dist/records/depth/index.d.cts +9 -9
- package/dist/records/depth/index.d.ts +9 -9
- package/dist/records/depth/index.js +1 -94
- package/dist/records/index.cjs +2 -95
- package/dist/records/index.d.cts +10 -10
- package/dist/records/index.d.ts +10 -10
- package/dist/records/index.js +2 -95
- package/dist/{requestFunnel.d-BPWf5SQf.d.ts → requestFunnel.d-B8OVGh0p.d.ts} +2 -2
- package/dist/{requestFunnel.d-DocT7FXR.d.cts → requestFunnel.d-C4abgvt9.d.cts} +2 -2
- package/dist/{parse.d-MQST1RP3.d.ts → route.d-BAZqGLfl.d.ts} +90 -53
- package/dist/{parse.d-C9_UMXfA.d.cts → route.d-CTf8h9vS.d.cts} +90 -53
- package/dist/{runtimeTypes.d-CkwEMpy8.d.cts → runtimeTypes.d-DbaQKGLv.d.cts} +39 -5
- package/dist/{runtimeTypes.d-D4Cjjf_C.d.ts → runtimeTypes.d-DrIz5e6L.d.ts} +39 -5
- package/dist/{screenProps.d-DNTTp7hU.d.ts → screenProps.d-BP8LAZWn.d.ts} +1 -1
- package/dist/{screenProps.d-Byla6nJL.d.cts → screenProps.d-Di3wYGCn.d.cts} +1 -1
- package/dist/server/events/index.cjs +2 -95
- package/dist/server/events/index.d.cts +122 -4
- package/dist/server/events/index.d.ts +122 -4
- package/dist/server/events/index.js +2 -95
- package/dist/server/index.cjs +2 -95
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +2 -95
- package/dist/shop/index.d.cts +3 -3
- package/dist/shop/index.d.ts +3 -3
- package/dist/tabs/index.cjs +3 -96
- package/dist/tabs/index.d.cts +6 -6
- package/dist/tabs/index.d.ts +6 -6
- package/dist/tabs/index.js +3 -96
- package/dist/televet/booking/index.cjs +11 -103
- package/dist/televet/booking/index.d.cts +13 -11
- package/dist/televet/booking/index.d.ts +13 -11
- package/dist/televet/booking/index.js +11 -103
- package/dist/televet/index.cjs +1 -94
- package/dist/televet/index.d.cts +3 -3
- package/dist/televet/index.d.ts +3 -3
- package/dist/televet/index.js +1 -94
- package/dist/{televetGlobal.d-CC-DrqkQ.d.ts → televetGlobal.d-B0_jbCtC.d.ts} +7 -0
- package/dist/{televetGlobal.d-CKwDCbmN.d.cts → televetGlobal.d-BWYJR391.d.cts} +7 -0
- package/dist/testing/index.cjs +1 -94
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -94
- package/dist/testing/rn/index.cjs +1 -94
- package/dist/testing/rn/index.d.cts +8 -7
- package/dist/testing/rn/index.d.ts +8 -7
- package/dist/testing/rn/index.js +1 -94
- package/dist/testing/web/index.cjs +1 -94
- package/dist/testing/web/index.d.cts +8 -7
- package/dist/testing/web/index.d.ts +8 -7
- package/dist/testing/web/index.js +1 -94
- package/dist/texting/index.cjs +1 -94
- package/dist/texting/index.d.cts +5 -5
- package/dist/texting/index.d.ts +5 -5
- package/dist/texting/index.js +1 -94
- package/dist/{threadOptions.d-jgk_sHrj.d.ts → threadOptions.d-Cwmyu8pc.d.ts} +2 -2
- package/dist/{threadOptions.d-CIrevUL8.d.cts → threadOptions.d-REwBuXAY.d.cts} +2 -2
- package/dist/{timelineRows.d-BST14weg.d.ts → timelineRows.d-CTlGQTB0.d.ts} +1 -1
- package/dist/{timelineRows.d-BEjiHpkP.d.cts → timelineRows.d-CongJG58.d.cts} +1 -1
- package/dist/unreadStore.d-gCsleb6l.d.ts +74 -0
- package/dist/unreadStore.d-w5x6lEpR.d.cts +74 -0
- package/dist/{useHealthPlanSubscription.d-C9kh4mvk.d.ts → useHealthPlanSubscription.d-BSo5kFT9.d.ts} +2 -2
- package/dist/{useHealthPlanSubscription.d-CYJi9ZNE.d.cts → useHealthPlanSubscription.d-Br7GKHTt.d.cts} +2 -2
- package/dist/useInboxUnread.d-Blxu00eY.d.ts +206 -0
- package/dist/useInboxUnread.d-pi6FNnK-.d.cts +206 -0
- package/dist/{usePresentation.d-COEh8Xa1.d.cts → usePresentation.d-C6ci1s3j.d.cts} +1 -1
- package/dist/{usePresentation.d-WA3sfMpz.d.ts → usePresentation.d-yd9Gh4GB.d.ts} +1 -1
- package/dist/{useRecordsDepth.d-DZfdRdIU.d.cts → useRecordsDepth.d-BIDVPfx7.d.cts} +1 -1
- package/dist/{useRecordsDepth.d-CAYnVYl1.d.ts → useRecordsDepth.d-C5snbNxR.d.ts} +1 -1
- package/dist/{appStateLifecycle.d-_TM06yEk.d.cts → useUnread.d-CORommFJ.d.cts} +49 -14
- package/dist/{appStateLifecycle.d-7H_2a9it.d.ts → useUnread.d-w0dKMnx7.d.ts} +49 -14
- package/dist/video/index.cjs +1 -94
- package/dist/video/index.js +1 -94
- package/dist/{view.d-D8soknYh.d.ts → view.d-CK2UN4qn.d.ts} +3 -3
- package/dist/{view.d-eM315KIZ.d.cts → view.d-DUhKppyl.d.cts} +3 -3
- package/dist/web/consent/index.cjs +1 -94
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/consent/index.js +1 -94
- package/dist/web/health-plan/index.cjs +1 -94
- package/dist/web/health-plan/index.d.cts +11 -11
- package/dist/web/health-plan/index.d.ts +11 -11
- package/dist/web/health-plan/index.js +1 -94
- package/dist/web/inbox/index.cjs +49 -0
- package/dist/web/inbox/index.d.cts +191 -0
- package/dist/web/inbox/index.d.ts +191 -0
- package/dist/web/inbox/index.js +49 -0
- package/dist/web/index.cjs +28 -118
- package/dist/web/index.d.cts +76 -36
- package/dist/web/index.d.ts +76 -36
- package/dist/web/index.js +28 -118
- package/dist/web/intro/index.cjs +3 -96
- package/dist/web/intro/index.d.cts +6 -6
- package/dist/web/intro/index.d.ts +6 -6
- package/dist/web/intro/index.js +3 -96
- package/dist/web/notifications/index.cjs +16 -96
- package/dist/web/notifications/index.d.cts +8 -3
- package/dist/web/notifications/index.d.ts +8 -3
- package/dist/web/notifications/index.js +16 -96
- package/dist/web/records/depth/index.cjs +1 -94
- package/dist/web/records/depth/index.d.cts +9 -9
- package/dist/web/records/depth/index.d.ts +9 -9
- package/dist/web/records/depth/index.js +1 -94
- package/dist/web/records/index.cjs +1 -94
- package/dist/web/records/index.d.cts +11 -11
- package/dist/web/records/index.d.ts +11 -11
- package/dist/web/records/index.js +1 -94
- package/dist/web/records-sheet/index.cjs +2 -95
- package/dist/web/records-sheet/index.js +2 -95
- package/dist/web/shop/index.d.cts +3 -3
- package/dist/web/shop/index.d.ts +3 -3
- package/dist/web/televet/booking/index.cjs +9 -102
- package/dist/web/televet/booking/index.d.cts +18 -11
- package/dist/web/televet/booking/index.d.ts +18 -11
- package/dist/web/televet/booking/index.js +9 -102
- package/dist/web/televet/index.cjs +1 -94
- package/dist/web/televet/index.d.cts +3 -3
- package/dist/web/televet/index.d.ts +3 -3
- package/dist/web/televet/index.js +1 -94
- package/dist/web/texting/index.cjs +1 -94
- package/dist/web/texting/index.d.cts +5 -5
- package/dist/web/texting/index.d.ts +5 -5
- package/dist/web/texting/index.js +1 -94
- package/notifications/inbox/package.json +8 -0
- package/package.json +29 -1
- package/web/inbox/native-blocked.cjs +12 -0
- package/web/inbox/package.json +8 -0
package/dist/web/index.js
CHANGED
|
@@ -2,100 +2,7 @@
|
|
|
2
2
|
"use client";
|
|
3
3
|
import{createContext,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useLayoutEffect,Suspense,useReducer,useId,Fragment as Fragment$1,lazy,Component}from"react";import{z}from"zod";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import{createPortal}from"react-dom";function ok(value,warning){/* @__PURE__ */
|
|
4
4
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
5
|
-
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 noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
6
|
-
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
7
|
-
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
8
|
-
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
9
|
-
/* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
10
|
-
/* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
11
|
-
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
12
|
-
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
13
|
-
/* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
14
|
-
/* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
|
|
15
|
-
/* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
|
|
16
|
-
/* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
|
|
17
|
-
/* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
18
|
-
/* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
19
|
-
/* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
20
|
-
/* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
21
|
-
/* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
22
|
-
/* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
23
|
-
/* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
24
|
-
/* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
25
|
-
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
26
|
-
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
27
|
-
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
28
|
-
/* @__PURE__ */Object.freeze({wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
29
|
-
/* @__PURE__ */Object.freeze({wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
30
|
-
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
31
|
-
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
32
|
-
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
33
|
-
/* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
34
|
-
/* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
35
|
-
/* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
36
|
-
/* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
37
|
-
/* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
38
|
-
/* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
39
|
-
/* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
40
|
-
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
41
|
-
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
42
|
-
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
43
|
-
/* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
44
|
-
/* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
45
|
-
/* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
46
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
47
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
|
|
48
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
49
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
50
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
51
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
52
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
53
|
-
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
54
|
-
/* @__PURE__ */Object.freeze({wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
55
|
-
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
56
|
-
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
57
|
-
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
58
|
-
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
59
|
-
/* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
60
|
-
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
61
|
-
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
62
|
-
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
63
|
-
/* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
|
|
64
|
-
/* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
65
|
-
/* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
66
|
-
/* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
67
|
-
/* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
68
|
-
/* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
69
|
-
/* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
70
|
-
/* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
71
|
-
/* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
72
|
-
/* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
73
|
-
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
74
|
-
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
75
|
-
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
76
|
-
/* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
77
|
-
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
78
|
-
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
79
|
-
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
80
|
-
/* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
81
|
-
/* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
82
|
-
/* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
83
|
-
/* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
84
|
-
/* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
85
|
-
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
86
|
-
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
87
|
-
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
88
|
-
/* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
89
|
-
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
90
|
-
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
91
|
-
/* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
92
|
-
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
93
|
-
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
94
|
-
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
95
|
-
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
96
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
97
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
98
|
-
/* @__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",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),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",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(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"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(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 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__ */
|
|
5
|
+
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 noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var RETRYABILITY_ROWS=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze(RETRYABILITY_ROWS.map(row=>/* @__PURE__ */Object.freeze(row)));/* @__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",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable"}),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",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(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"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(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 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__ */
|
|
99
6
|
return Object.freeze({kind:"accepted",streamId:streamId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function heartbeatFrame(lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
100
7
|
return Object.freeze({kind:"heartbeat",lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function deltaFrame(delta,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
101
8
|
return Object.freeze({kind:"delta",delta:delta,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function doneFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
@@ -103,11 +10,11 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
|
|
|
103
10
|
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__ */
|
|
104
11
|
return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
105
12
|
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__ */
|
|
106
|
-
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",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:VALIDATION_FAILED_COPY,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,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}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),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};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)}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,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,rejectionReported=!1,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},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}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(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}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(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}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?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending3=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending3.length>0?pending3.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending3=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending3=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */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=createUtf8Decoder(),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 ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var SDK_VERSION="0.18.2",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
13
|
+
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",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:VALIDATION_FAILED_COPY,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,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}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),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};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)}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,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,rejectionReported=!1,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},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}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(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}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(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}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?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending3=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending3.length>0?pending3.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending3=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending3=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */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=createUtf8Decoder(),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 ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host2="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host2.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host2.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}var SDK_VERSION="0.19.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
107
14
|
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__ */
|
|
108
15
|
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__ */
|
|
109
16
|
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}}function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host2){return host2.length===0||host2.includes("@")?false:host2.startsWith("[")&&host2.endsWith("]")?true:!host2.includes(":")}function canEchoOrigin(rawTrimmed,host2){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host2)}function safeOrigin(scheme,host2){return`${scheme}://${host2}`}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(),host2=hostOf(match[2]);if(host2.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host2)?`: ${safeOrigin(scheme,host2)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host2)))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__ */
|
|
110
|
-
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host2=hostname.toLowerCase();return host2==="localhost"||host2==="127.0.0.1"||host2==="[::1]"||host2==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}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))}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 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(base2,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base2}${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?foldDailyQuotaWireCode(code,body):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,base2=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({...base2,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(
|
|
17
|
+
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host2=hostname.toLowerCase();return host2==="localhost"||host2==="127.0.0.1"||host2==="[::1]"||host2==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}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 record2=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record2!==null&&namesAWait(record2)?body:{...record2??{},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))}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 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(base2,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base2}${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?foldDailyQuotaWireCode(code,body):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,base2=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({...base2,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(
|
|
111
18
|
/* @__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__ */
|
|
112
19
|
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 noop2=()=>{};if(!caller)return{signal:deadline2,dispose:noop2};let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop2};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})})}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}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__ */
|
|
113
20
|
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__ */
|
|
@@ -117,8 +24,8 @@ return Object.freeze({id:m.id,role:m.role,text:m.text,createdAt:m.createdAt})}fu
|
|
|
117
24
|
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"runtimeDisposed":return"runtimeDisposed";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__ */
|
|
118
25
|
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 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 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();let preview=typeof row.preview=="string"?row.preview.replace(/\s+/g," ").trim().slice(0,140):"";conversations.push(/* @__PURE__ */Object.freeze({id:row.conversation_id,title:row.title??null,createdAt:row.created_at,updatedAt:row.updated_at,unreadCount:unread??null,...preview.length>0?{preview:preview}:{}}))}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__ */
|
|
119
26
|
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__ */
|
|
120
|
-
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.onConversationStarted=deps.onConversationStarted,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 invalid5=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid5!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),this.patch({status:"error",isStreaming:false,error:invalid5.error}),handlers?(handlers.onError(invalid5.error),()=>{}):singleFrameStream(synthErrorFrame(invalid5.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 invalid5=validateMessageText(prompt);return invalid5!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),singleFrameStream(synthErrorFrame(invalid5.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__ */
|
|
121
|
-
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,pending3={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending3;let result=await pending3.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending3&&(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,pending3={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending3;let result=await pending3.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending3&&(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,pending3=needsConversation?this.unadoptedCreate:null;if(pending3!==null&&(turn.petRef===null||turn.petRef===pending3.petRef)){let primed=await pending3.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(primed.value),this.reportConversationStarted(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),this.reportConversationStarted(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{this.reportSessionRejected();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){this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let e=this.authRejected(terminalError);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}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(id){try{this.onConversationStarted?.(id)}catch{}}authRejected(refusal){return refusal===void 0?makeError("authRejected",false):makeEverfurError("authRejected",{retryable:false,...refusal.code?{wireCode:refusal.code}:{},...refusal.serverRequestId?{requestId:refusal.serverRequestId}:{}})}};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__ */
|
|
27
|
+
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.onConversationStarted=deps.onConversationStarted,this.unread=deps.unread,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 invalid5=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid5!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),this.patch({status:"error",isStreaming:false,error:invalid5.error}),handlers?(handlers.onError(invalid5.error),()=>{}):singleFrameStream(synthErrorFrame(invalid5.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 invalid5=validateMessageText(prompt);return invalid5!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),singleFrameStream(synthErrorFrame(invalid5.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,count3=active===null?void 0:this.unreadByConversation.get(active);count3!==void 0&&count3!==this.snapshot.unreadCount&&this.patch({unreadCount:count3}),this.reflectUnreadDot(),opts?.cursor===void 0&&this.unread?.reportHead(opts?.petRef??null,page.value.conversations[0]??null)}return page}reflectUnreadDot(){let unread=false;for(let count3 of this.unreadByConversation.values())if(count3>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(),this.unread?.reportRead(id),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__ */
|
|
28
|
+
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(options){if(this.disposed)return err(makeError("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let id=this.snapshot.conversationId;if(id===null&&options?.openUnreadHead!==true)return ok(void 0);let generation=this.historyGeneration,listed=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(id===null){if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0||head.unreadCount===null||head.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let opened=await this.resumeConversation(head.id);return opened.ok?ok(void 0):err(opened.error)}let 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]}),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,pending3={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending3;let result=await pending3.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending3&&(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,pending3={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending3;let result=await pending3.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending3&&(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,pending3=needsConversation?this.unadoptedCreate:null;if(pending3!==null&&(turn.petRef===null||turn.petRef===pending3.petRef)){let primed=await pending3.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(primed.value),this.reportConversationStarted(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),this.reportConversationStarted(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{this.reportSessionRejected();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){this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let e=this.authRejected(terminalError);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}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(id){try{this.onConversationStarted?.(id)}catch{}}authRejected(refusal){return refusal===void 0?makeError("authRejected",false):makeEverfurError("authRejected",{retryable:false,...refusal.code?{wireCode:refusal.code}:{},...refusal.serverRequestId?{requestId:refusal.serverRequestId}:{}})}};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__ */
|
|
122
29
|
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"]),ATTACHMENT_ACCEPT="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",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__ */
|
|
123
30
|
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,str6=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str6(o.upload_id),uploadUrl=str6(o.upload_url),s3Key=str6(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__ */
|
|
124
31
|
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:str6(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=[],pending3=[],inFlight3=/* @__PURE__ */new Set,listeners3=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed3=false,publish2=()=>{snapshot2=/* @__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 listeners3)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed3&&inFlight3.size<concurrency&&pending3.length>0;){let id=pending3.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(disposed3||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(disposed3||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(disposed3||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=>{pending3.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},getSnapshot:()=>snapshot2,get uploading(){return snapshot2.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot2.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed3||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||disposed3||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=pending3.indexOf(id);queued>=0&&pending3.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed3=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending3.length=0,listeners3.clear(),snapshot2=/* @__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__ */
|
|
@@ -131,10 +38,10 @@ return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAd
|
|
|
131
38
|
return Object.freeze(out)}var MAX_FONT_SOURCES=4,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 pick3(raw,...keys){for(let key of keys)if(raw[key]!==void 0&&raw[key]!==null)return raw[key]}function parseFontSource(raw){if(!isRecord2(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>=MAX_FONT_SOURCES)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__ */
|
|
132
39
|
return new Set(["hide_powered_by",...b?.lockedFields??[]])}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)||isPresentationLockName(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(base2,over){let out={...base2};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base2.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")),presentation:parsePresentation(pick4(raw,"presentation")),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.startsWith(PRESENTATION_LOCK_PREFIX)?PRESENTATION_LOCK_PREFIX+trimmed.slice(PRESENTATION_LOCK_PREFIX.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():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(base2,b){if(b===null||isEmptyBranding(b))return base2;let palette=(b.brightness==="light"||b.brightness==="dark")&&b.brightness!==base2.brightness?b.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT:base2,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(base2,b){let fonts=b.fonts??{},urls=b.fontUrls??{},families={...base2.families},namedFaces={...base2.namedFaces},fontUrls={...base2.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 sameColor2(a,b){return a==null?false:parseColor(a)===parseColor(b)}function isCompiledPrimary(b,primary,compiled,dark){return sameColor2(primary,compiled.color.primary)?true:dark&&(b.primaryColorDark??null)===null&&sameColor2(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,base2,compiled){if(scale===null)return base2;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__ */
|
|
133
40
|
return Object.freeze({kind:"updated",revision:body.revision,region:region,ttlSeconds:ttlSeconds,decisions:mapCapabilities(body.capabilities),branding:parseBranding(body),livemode:body.livemode!==false,...smsProfileOf(body)})}function smsProfileOf(body){let hints=body.render_hints,raw=body.sms_profile_public??(hints!==null&&typeof hints=="object"?hints.sms_profile_public:void 0);return raw!==null&&typeof raw=="object"?{smsProfilePublic:raw}:{}}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__ */
|
|
134
|
-
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,resolution.smsProfilePublic!==void 0?deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false,resolution.smsProfilePublic):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,
|
|
41
|
+
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,resolution.smsProfilePublic!==void 0?deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false,resolution.smsProfilePublic):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"}function createUnreadStore(deps){let states=/* @__PURE__ */new Map,unknowns=/* @__PURE__ */new Map,unknown=petRef2=>{let key=petRef2??"",state3=unknowns.get(key);return state3===void 0&&(state3=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:petRef2}),unknowns.set(key,state3)),state3},inFlight3=/* @__PURE__ */new Map,listeners3=/* @__PURE__ */new Set,generation=0,set=(petRef2,next)=>{let key=petRef2??"",previous=states.get(key)??unknown(petRef2);if(!(previous.hasUnread===next.hasUnread&&previous.unreadCount===next.unreadCount&&previous.conversationId===next.conversationId)){states.set(key,next);for(let listener of[...listeners3])listener();listeners3.size>0&&next.hasUnread!==null&&next.unreadCount!==null&&deps.emit({type:"unread_changed",petRef:petRef2,conversationId:next.conversationId,unreadCount:next.unreadCount,hasUnread:next.hasUnread})}},reportHead=(petRef2,head)=>{if(head===null){set(petRef2,/* @__PURE__ */Object.freeze({hasUnread:false,unreadCount:0,conversationId:null,petRef:petRef2}));return}if(head.unreadCount===null){set(petRef2,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:head.id,petRef:petRef2}));return}set(petRef2,/* @__PURE__ */Object.freeze({hasUnread:head.unreadCount>0,unreadCount:head.unreadCount,conversationId:head.id,petRef:petRef2}))};return{subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},get(petRef2){return states.get(petRef2??"")??unknown(petRef2)},refresh(petRef2){let key=petRef2??"",running=inFlight3.get(key);if(running!==void 0)return running;let read=deps.read(petRef2);if(read===null)return Promise.resolve();let at=generation,settled=read.then(result=>{at!==generation||!result.ok||reportHead(petRef2,result.value.conversations[0]??null)},()=>{}).finally(()=>{inFlight3.get(key)===settled&&inFlight3.delete(key)});return inFlight3.set(key,settled),settled},reportHead:reportHead,reportRead(conversationId2){for(let state3 of[...states.values()])state3.conversationId!==conversationId2||state3.unreadCount===null||state3.unreadCount===0||set(state3.petRef,/* @__PURE__ */Object.freeze({...state3,hasUnread:false,unreadCount:0}))},reset(){if(generation+=1,inFlight3.clear(),states.size!==0){states.clear();for(let listener of[...listeners3])listener()}}}}function readConversationHead(auth,petRef2,errorPolicy){let query=historyQuery({...petRef2===null?{}:{petRef:petRef2},limit:1},100);return query.ok?createRequestFunnel({auth:auth,...errorPolicy?{errorPolicy:errorPolicy}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},{maxAttempts:1}).then(result=>result.ok?mapConversationPage(result.value):err(result.error)):Promise.resolve(err(query.error))}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,count3)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count3,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__ */
|
|
135
42
|
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners3=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners3)listener()};return{subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},getSnapshot(){return snapshot2},set(next){snapshot2=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{},...next.smsProfilePublic!==void 0&&next.smsProfilePublic!==null?{smsProfilePublic:next.smsProfilePublic}:{}}),emit()},reset(opts){snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:opts?.keepBranding===true?snapshot2.branding??null:null,...opts?.keepBranding===true&&snapshot2.smsProfilePublic!==void 0?{smsProfilePublic:snapshot2.smsProfilePublic}:{}}),emit()},setPending(pending3){snapshot2.isPending!==pending3&&(snapshot2=/* @__PURE__ */Object.freeze({...snapshot2,isPending:pending3}),emit())}}}var BRANDING_CACHE_KEY_PREFIX="everfur.branding.v1.";function utf8Bytes(text3){let out=[];for(let ch of text3){let cp=ch.codePointAt(0);cp<128?out.push(cp):cp<2048?out.push(192|cp>>6,128|cp&63):cp<65536?out.push(224|cp>>12,128|cp>>6&63,128|cp&63):out.push(240|cp>>18,128|cp>>12&63,128|cp>>6&63,128|cp&63)}return out}function fnv1a64Hex(text3){let hi=3421674724,lo=2216829733;for(let byte2 of utf8Bytes(text3)){lo=(lo^byte2)>>>0;let loProduct=lo*435,carry=Math.floor(loProduct/4294967296),nextLo=loProduct>>>0;hi=hi*435+carry+lo*256>>>0,lo=nextLo}return hi.toString(16).padStart(8,"0")+lo.toString(16).padStart(8,"0")}function brandingCacheKey(scope){return`${BRANDING_CACHE_KEY_PREFIX}${fnv1a64Hex(scope)}`}function serializeBranding(branding){return branding?JSON.stringify(branding):null}async function readCachedBranding(kv,scope){try{let raw=await kv.getItem(brandingCacheKey(scope));if(raw===null)return null;let parsed=parseClientBranding(JSON.parse(raw));return parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,logoUrl:hardenBrandAssetUrl(parsed.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(parsed.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(parsed.assistantAvatarUrl??null)})}catch{return null}}async function writeCachedBranding(kv,scope,serialized){try{serialized===null?await kv.removeItem(brandingCacheKey(scope)):await kv.setItem(brandingCacheKey(scope),serialized)}catch{}}function createBrandingCache(kv,scope){let lastWritten;return{restore(apply){readCachedBranding(kv,scope).then(branding=>{branding!==null&&apply(branding)})},persist(branding){let serialized=serializeBranding(branding);serialized!==lastWritten&&(lastWritten=serialized,writeCachedBranding(kv,scope,serialized))}}}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__ */
|
|
136
43
|
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__ */
|
|
137
|
-
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)}}}})}var IN_MEMORY_KVS=/* @__PURE__ */new WeakSet;function createInMemoryKv(){let map=/* @__PURE__ */new Map,kv={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))}};return IN_MEMORY_KVS.add(kv),kv}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.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let 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,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;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))}if(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.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),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,failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}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),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});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?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,fresh4,livemode,smsProfilePublic)=>{this.verdictLanded=true;let painted=this.store.getSnapshot().branding??null,branding=painted!==null&&fresh4!=null&&serializeBranding(painted)===serializeBranding(fresh4)?painted:fresh4;this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{},...smsProfilePublic!==void 0?{smsProfilePublic:smsProfilePublic}:{}}),this.brandingCache?.persist(branding??null)},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,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2})});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 pending3=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending3!==null&&await pending3,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),cause=>(identity.reportRejected?.(),err(mintFailedError(cause)))),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{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */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({keepBranding:true}))}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(opts){this.epoch+=1,this.disposeAllControllers(),this.store.reset(opts),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("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=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=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot2.branding??null,theme=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 isDevelopment=props.seams.isDevelopment;return useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!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=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=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=useRef(null),lastPropPetRef=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:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=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=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
|
|
44
|
+
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)}}}})}var IN_MEMORY_KVS=/* @__PURE__ */new WeakSet;function createInMemoryKv(){let map=/* @__PURE__ */new Map,kv={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))}};return IN_MEMORY_KVS.add(kv),kv}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.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let 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,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;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))}if(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.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),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,this.unread=createUnreadStore({read:petRef2=>this.disposed||this.currentUser===null||this.configFailure!==null?null:readConversationHead(this.buildAuth(this.currentUser.userRef),petRef2,this.errorPolicy),emit:event=>this.emit(event)}),failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}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),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});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?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,fresh4,livemode,smsProfilePublic)=>{this.verdictLanded=true;let painted=this.store.getSnapshot().branding??null,branding=painted!==null&&fresh4!=null&&serializeBranding(painted)===serializeBranding(fresh4)?painted:fresh4;this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{},...smsProfilePublic!==void 0?{smsProfilePublic:smsProfilePublic}:{}}),this.brandingCache?.persist(branding??null)},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,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2}),unread:this.unread});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 pending3=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending3!==null&&await pending3,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),cause=>(identity.reportRejected?.(),err(mintFailedError(cause)))),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{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */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({keepBranding:true}))}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(opts){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(opts),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("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=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=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot2.branding??null,theme=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 isDevelopment=props.seams.isDevelopment;return useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!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=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=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=useRef(null),lastPropPetRef=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:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=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=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
|
|
138
45
|
return Object.freeze(out)}catch{return[]}}}}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 tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}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 base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face2=>(fonts.add(face2),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok3=>(ok3||warnOnce(source,warn),ok3));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face2 of FACES){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){return createElement(EverfurProviderCore,{...props,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state3){return Object.is(props.resetKey,state3.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 createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base2=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base2:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});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,className:className}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
139
46
|
return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
140
47
|
return jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";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",goToNearestEmergencyVet:EMERGENCY_ER_LINE,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([
|
|
@@ -144,8 +51,8 @@ return jsx("div",{className:className,style:{...styles.offstate,...style},childr
|
|
|
144
51
|
/* @__PURE__ */Object.freeze({key:"unclear",label:CHAT_COPY.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
145
52
|
/* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
|
|
146
53
|
/* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
|
|
147
|
-
/* @__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 NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}function useStalePetHold(runtime,userRef2,petRef2,scopeEpoch){let[owner,setOwner]=useState({pet:petRef2,user:userRef2}),adopt=owner.pet!==petRef2||owner.user===null&&userRef2!==null;adopt&&setOwner({pet:petRef2,user:userRef2});let current=adopt?{user:userRef2}:owner,held=petRef2!==null&¤t.user!==null&¤t.user!==userRef2;return useEffect(()=>{if(!held||userRef2===null||petRef2===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef2)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef2)&&setOwner({pet:petRef2,user:userRef2})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef2,petRef2,scopeEpoch]),held}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,held=useStalePetHold(runtime,userRef2,petRef2,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{if(held)return;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,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=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=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=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=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 useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef2,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,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 snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.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 chatNotReadyResult()}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=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=useMemo(()=>options.queue??build(),[options.queue,build]),disposed3=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;useEffect(()=>{if(queue!==options.queue){if(disposed3.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed3.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot2=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=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=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot2.attachments.some(row=>row.status==="uploading"),failed=snapshot2.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot2.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot2.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,snapshot2,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=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=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state3,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=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]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state3.status==="failed"&&run()},[state3.status,run]);return useMemo(()=>scopeKey===null?IDLE:state3.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state3.status,error:state3.error,registered:state3.registered,retry:retry},[scopeKey,state3,retry])}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,key){let clean2=sanitizeSeedPrompt(prompt),id=clean2===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean2}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight3=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean2===null||id===null||isBootstrapping||done.current===id||inFlight3.current===id)return;let ask=latest.current;if(ask===void 0)return;inFlight3.current=id;let settle=result=>{inFlight3.current===id&&(inFlight3.current=null),!isChatNotReadyResult(result)&¤t.current===id&&(done.current=id)};Promise.resolve(ask(clean2)).then(settle,()=>settle(void 0))},[clean2,id,isBootstrapping,askEverfur])}function isCoalesced(trigger,conversationId2,state3){if(trigger==="announced")return false;let last=state3.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state3.now-last.at<15e3}function decideChatRefresh(trigger,state3){let conversationId2=state3.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state3.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state3.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state3)?{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 isThenable(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 isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}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=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:probeOffline(),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(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(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=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);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])}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]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state3,setState]=useState(()=>fresh(scope)),current=state3.scope===scope?state3:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=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=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: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()}: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]=useState(null),[expanded,setExpanded]=useState(false);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=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return 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(state3){return state3.isBootstrapping?"loading":state3.status==="error"&&state3.error&&state3.messages.length===0?"error":state3.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state3,host2="native"){if(state3.messages.length===0)return null;let error=state3.status==="error"?state3.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host2==="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 state3.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(state3){let last=state3.messages[state3.messages.length-1];if(state3.isStreaming||state3.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state3.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__ */
|
|
148
|
-
return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(state3,policy){if(policy===void 0)return visibleFollowUps(state3);let last=state3.messages[state3.messages.length-1];if(state3.isStreaming||state3.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let
|
|
54
|
+
/* @__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 NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}function useStalePetHold(runtime,userRef2,petRef2,scopeEpoch){let[owner,setOwner]=useState({pet:petRef2,user:userRef2}),adopt=owner.pet!==petRef2||owner.user===null&&userRef2!==null;adopt&&setOwner({pet:petRef2,user:userRef2});let current=adopt?{user:userRef2}:owner,held=petRef2!==null&¤t.user!==null&¤t.user!==userRef2;return useEffect(()=>{if(!held||userRef2===null||petRef2===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef2)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef2)&&setOwner({pet:petRef2,user:userRef2})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef2,petRef2,scopeEpoch]),held}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,held=useStalePetHold(runtime,userRef2,petRef2,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{if(held)return;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,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=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=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=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=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:options=>run(current=>current.refreshActiveThread(options)),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef2,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,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 snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.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 chatNotReadyResult()}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=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=useMemo(()=>options.queue??build(),[options.queue,build]),disposed3=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;useEffect(()=>{if(queue!==options.queue){if(disposed3.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed3.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot2=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=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=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot2.attachments.some(row=>row.status==="uploading"),failed=snapshot2.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot2.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot2.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,snapshot2,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=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=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state3,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=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]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state3.status==="failed"&&run()},[state3.status,run]);return useMemo(()=>scopeKey===null?IDLE:state3.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state3.status,error:state3.error,registered:state3.registered,retry:retry},[scopeKey,state3,retry])}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,key){let clean2=sanitizeSeedPrompt(prompt),id=clean2===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean2}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight3=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean2===null||id===null||isBootstrapping||done.current===id||inFlight3.current===id)return;let ask=latest.current;if(ask===void 0)return;inFlight3.current=id;let settle=result=>{inFlight3.current===id&&(inFlight3.current=null),!isChatNotReadyResult(result)&¤t.current===id&&(done.current=id)};Promise.resolve(ask(clean2)).then(settle,()=>settle(void 0))},[clean2,id,isBootstrapping,askEverfur])}function isCoalesced(trigger,conversationId2,state3){if(trigger==="announced")return false;let last=state3.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state3.now-last.at<15e3}function decideChatRefresh(trigger,state3){let conversationId2=state3.activeConversationId===null||state3.activeConversationId.length===0?null:state3.activeConversationId;return conversationId2===null&&state3.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:state3.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state3.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state3)?{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 isThenable(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 isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}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}))}var OPEN_UNREAD_HEAD=/* @__PURE__ */Object.freeze({openUnreadHead:true});function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh,refreshesBlankThread:refreshesBlankThread}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,refreshesBlankThread:refreshesBlankThread===true,isOffline:probeOffline(),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(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}var HANDOFF_TOKEN=/^efch_[A-Za-z0-9_-]{43}$/,FRAGMENT_KEY="efch";function isChatHandoffToken(value){return typeof value=="string"&&HANDOFF_TOKEN.test(value)}function chatHandoffTokenFromUrl(url){if(typeof url!="string")return null;let hash=url.indexOf("#");if(hash<0)return null;for(let pair of url.slice(hash+1).split("&")){if(!pair.startsWith(`${FRAGMENT_KEY}=`))continue;let value=pair.slice(FRAGMENT_KEY.length+1);return isChatHandoffToken(value)?value:null}return null}function withoutChatHandoffToken(url){let hash=url.indexOf("#");if(hash<0)return url;let kept=url.slice(hash+1).split("&").filter(pair=>pair!==FRAGMENT_KEY&&!pair.startsWith(`${FRAGMENT_KEY}=`));return kept.length===0?url.slice(0,hash):`${url.slice(0,hash)}#${kept.join("&")}`}var MAX_PET_REF_LENGTH=128,CONTROL_CHAR2=/[\u0000-\u001f\u007f]/;function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:null}function petRefOf(value){return typeof value!="string"||value.length===0||value.length>MAX_PET_REF_LENGTH||CONTROL_CHAR2.test(value)||value.includes("://")?null:value}function targetOf(body){if(body===null)return null;let conversationId2=body.conversation_id,petRef2=petRefOf(body.pet_ref);return typeof conversationId2!="string"||!validConversationId(conversationId2)||petRef2===null?null:{conversationId:conversationId2,petRef:petRef2}}function redeemChatHandoff(auth,token,errorPolicy){return isChatHandoffToken(token)?createRequestFunnel({auth:auth,...errorPolicy?{errorPolicy:errorPolicy}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:token}},{maxAttempts:1}).then(result=>result.ok?ok(targetOf(record(result.value))):result.error.httpStatus===404?ok(null):err(result.error),()=>err(makeError("internalError",false))):Promise.resolve(ok(null))}function useChatHandoffTarget(token,context){let runtime=context?.runtime??null,userRef2=context?.userRef??null,valid=isChatHandoffToken(token)?token:null,key=valid===null||userRef2===null?null:`${String(userRef2)}|${valid}`,[landed,setLanded]=useState(null);return useEffect(()=>{if(key===null||valid===null||userRef2===null||runtime===null)return;let live=true,services=runtime.registry.services;return redeemChatHandoff(services.authFor(userRef2),valid,services.errorPolicy).then(result=>{!live||!result.ok||result.value===null||setLanded({key:key,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:result.value.conversationId,petRef:result.value.petRef})})}),()=>{live=false}},[key,runtime,valid,userRef2]),landed!==null&&landed.key===key?landed.target:void 0}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,scope){let key=targetKey(target),forChat=target?.kind==="chat",wanted=target?.petRef??null,elsewhere=forChat&&!scope.pinned&&wanted!==null&&scope.petRef!==null&&wanted!==scope.petRef,latest=useRef({openCheckin:openCheckin,target:target,selectPet:scope.selectPet});latest.current={openCheckin:openCheckin,target:target,selectPet:scope.selectPet};let opened=useRef(null),moved=useRef(null),petRef2=scope.petRef;useEffect(()=>{if(key===null||opened.current===key)return;let{openCheckin:open,target:current,selectPet:selectPet}=latest.current;if(elsewhere&&wanted!==null){if(moved.current?.key!==key){moved.current={key:key,from:petRef2},selectPet(wanted);return}petRef2!==moved.current.from&&(opened.current=key);return}forChat&&!scope.ready||(opened.current=key,!(open===void 0||current===void 0)&&Promise.resolve(open(current)).catch(()=>{}))},[key,forChat,elsewhere,wanted,petRef2,scope.ready])}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(count3,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count3}`: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]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state3,setState]=useState(()=>fresh(scope)),current=state3.scope===scope?state3:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=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=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: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()}: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]=useState(null),[expanded,setExpanded]=useState(false);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=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return 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(state3){return state3.isBootstrapping?"loading":state3.status==="error"&&state3.error&&state3.messages.length===0?"error":state3.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state3,host2="native"){if(state3.messages.length===0)return null;let error=state3.status==="error"?state3.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host2==="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 state3.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(state3){let last=state3.messages[state3.messages.length-1];if(state3.isStreaming||state3.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state3.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__ */
|
|
55
|
+
return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(state3,policy){if(policy===void 0)return visibleFollowUps(state3);let last=state3.messages[state3.messages.length-1];if(state3.isStreaming||state3.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let count3=Math.max(1,Math.min(MAX_POLICY_FOLLOW_UPS,Math.floor(policy.count??MAX_VISIBLE_FOLLOW_UPS))),question=null;for(let i=state3.messages.length-1;i>=0;i-=1){let m=state3.messages[i];if(m!==void 0&&m.role==="user"){question=m.text;break}}let norm=t=>t.trim().replace(/\s+/g," ").toLowerCase(),seen=new Set(question===null?[]:[norm(question)]),out=[],take=prompt=>{let text3=prompt.trim(),key=norm(text3);out.length>=count3||key.length===0||seen.has(key)||excluded(policy.exclude,text3)||(seen.add(key),out.push(text3))};for(let prompt of state3.suggestedPrompts)take(prompt);let fill2=[];try{fill2=typeof policy.fill=="function"?policy.fill(question):policy.fill??[]}catch{fill2=[]}for(let prompt of Array.isArray(fill2)?fill2:[])typeof prompt=="string"&&take(prompt);/* @__PURE__ */
|
|
149
56
|
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}function useEverfurPets(){let{runtime:runtime,userRef:userRef2,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),[state3,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state3.repository===repository?state3:{pets:[],loading:true,error:null},generation=useRef(0),load=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]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return 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 VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var FOCUS_RING_WIDTH=2,SELF_FOCUS_RING_ATTRIBUTE="data-ef-focus-ring",FOCUS_VISIBLE_ATTRIBUTE="data-ef-focus-visible",FOCUS_RING_COLOR_ATTRIBUTE="data-ef-focus-ring-color";function focusRingStyle(color){return{outline:`${FOCUS_RING_WIDTH}px solid ${color}`,outlineOffset:FOCUS_RING_WIDTH}}var keyboardDriving=false,bound=0;function onKeyDown(event){event.metaKey||event.ctrlKey||event.altKey||(keyboardDriving=true)}function onPointerDown(){keyboardDriving=false}function bindModality(){return typeof document>"u"?()=>{}:(bound===0&&(document.addEventListener("keydown",onKeyDown,true),document.addEventListener("pointerdown",onPointerDown,true),document.addEventListener("mousedown",onPointerDown,true),document.addEventListener("touchstart",onPointerDown,true)),bound+=1,()=>{bound-=1,!(bound>0)&&(document.removeEventListener("keydown",onKeyDown,true),document.removeEventListener("pointerdown",onPointerDown,true),document.removeEventListener("mousedown",onPointerDown,true),document.removeEventListener("touchstart",onPointerDown,true),keyboardDriving=false)})}var TEXT_INPUT_TYPES=/* @__PURE__ */new Set(["","text","search","email","tel","url","password","number"]);function isTextField(element){return element.tagName==="TEXTAREA"||element.isContentEditable?true:element.tagName!=="INPUT"?false:TEXT_INPUT_TYPES.has((element.getAttribute("type")??"").toLowerCase())}function useKeyboardFocusRing(root,color){useEffect(()=>{let node=root.current;if(node!==null)return bindKeyboardFocusRing(node,color)},[root,color])}function bindKeyboardFocusRing(node,color){let unbind=bindModality(),painted=/* @__PURE__ */new Map,onFocusIn=event=>{let target=event.target;if(!(target instanceof HTMLElement)||painted.has(target)||target.closest(`[${SELF_FOCUS_RING_ATTRIBUTE}="self"]`)!==null||!keyboardDriving&&!isTextField(target))return;painted.set(target,{outline:target.style.outline,outlineOffset:target.style.outlineOffset});let region=target.closest(`[${FOCUS_RING_COLOR_ATTRIBUTE}]`),ring=focusRingStyle(region?.getAttribute(FOCUS_RING_COLOR_ATTRIBUTE)||color);target.style.outline=ring.outline,target.style.outlineOffset=`${ring.outlineOffset}px`,target.setAttribute(FOCUS_VISIBLE_ATTRIBUTE,"")},onFocusOut=event=>{let target=event.target;if(!(target instanceof HTMLElement))return;let before=painted.get(target);before!==void 0&&(painted.delete(target),target.style.outline=before.outline,target.style.outlineOffset=before.outlineOffset,target.removeAttribute(FOCUS_VISIBLE_ATTRIBUTE))};return node.addEventListener("focusin",onFocusIn),node.addEventListener("focusout",onFocusOut),()=>{node.removeEventListener("focusin",onFocusIn),node.removeEventListener("focusout",onFocusOut);for(let[element,before]of painted)element.style.outline=before.outline,element.style.outlineOffset=before.outlineOffset,element.removeAttribute(FOCUS_VISIBLE_ATTRIBUTE);painted.clear(),unbind()}}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 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(host2=>host2!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}function memoizeTelevetLoader(load){let pending3=null;return()=>{if(pending3!==null)return pending3;let started=load();return pending3=started,started.then(void 0,()=>{pending3===started&&(pending3=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=useState(null);useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot2=useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot2.activeHost===id?snapshot2.request:null,[module,setModule]=useState(null),wanted=request!==null&&module===null;return useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded3=>{live&&setModule(()=>loaded3)},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:snapshot2.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>import("@everfur/sdk/web/televet/booking"));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}){let host2=useTelevetExperienceHost(loadExperience);if(host2===null)return null;let{EverfurTelevetDialog:EverfurTelevetDialog}=host2.module;/* @__PURE__ */
|
|
150
57
|
return jsx(EverfurTelevetDialog,{request:host2.request,onClose:host2.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host2.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(state3){if(typeof state3!="string"||state3.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:state3}},{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 host2=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host2);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 warned3=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned3||(warned3=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}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]=useState(null);if(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=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=useRef(controller);preflightController.current=controller;let scope=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]=useState(IDLE2),inFlight3=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=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=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&&"consultId"in visit?{consultId:visit.consultId}:{},...visit!==null&&"visitRef"in visit?{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=useCallback(petRef2=>redirect?start(petRef2,null):openInApp(petRef2,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=useCallback(consultId=>redirect?start(void 0,null):openInApp(void 0,{consultId:consultId.trim()}),[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,joinVisit:joinVisit}}function closeQuietly(tab){try{tab.closed||tab.close()}catch{}}var BROWSER_OPENER=/* @__PURE__ */Object.freeze({prepare(){let tab=null;try{tab=typeof window>"u"?null:window.open("about:blank","_blank")}catch{tab=null}if(tab===null)return{ok:false,reason:"popupBlocked"};try{tab.opener=null}catch{}return{ok:true,value:{tab:tab}}},async finish({tab:tab},handoff){if(tab.closed)return"cancelled";try{return tab.location.replace(handoff.url),null}catch{return closeQuietly(tab),"popupBlocked"}},abandon({tab:tab}){closeQuietly(tab)}});function useVetVisit(opts){return useVetVisitWith(BROWSER_OPENER,opts)}var FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function activeIn(node){if(typeof document>"u")return null;let root=node?.getRootNode();return root&&root!==document&&"activeElement"in root?root.activeElement:document.activeElement}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=useRef(null),wasOpen=useRef(false),opener=useRef(null),trigger=useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||activeIn(target)===target)&&(opener.current=null)},[]);useEffect(()=>{if(!open){restoreFocus();return}let node=dialogRef.current;if(!wasOpen.current){let active=activeIn(node);active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(activeIn(node))||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),useEffect(()=>restoreFocus,[restoreFocus]),useEffect(()=>{let node=dialogRef.current;if(!open||node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&activeIn(dialog)!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown2=useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=activeIn(node);event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown2,onCancel:onCancel}}var PATHS=/* @__PURE__ */Object.freeze({check:/* @__PURE__ */jsx("polyline",{points:"20 6 9 17 4 12"}),copy:/* @__PURE__ */jsxs(Fragment,{children:[
|
|
151
58
|
/* @__PURE__ */jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),
|
|
@@ -217,7 +124,10 @@ return jsxs("header",{style:styles.bar,children:[
|
|
|
217
124
|
/* @__PURE__ */jsx(AvatarRing,{pet:activePet,styles:styles}),
|
|
218
125
|
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.addBadge,children:/* @__PURE__ */jsx("span",{style:styles.addBadgeGlyph,children:"+"})})]}),
|
|
219
126
|
/* @__PURE__ */jsx(PetSwitcherDialog,{open:open,pets:pets,activePetRef:activePet.petRef,returnFocusTo:triggerRef,onClose:()=>setOpen(false),onSelect:petRef2=>{setOpen(false),onSelectPet(petRef2)},onAddPet:onAddPet===null?null:()=>{setOpen(false),onAddPet()}})]})}function AvatarRing({pet:pet,styles:styles}){let theme=useEverfurTheme(),palette=pet===null?null:petDiscPaint(pet,isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight});/* @__PURE__ */
|
|
220
|
-
return jsx("span",{style:styles.ring,children:/* @__PURE__ */jsx("span",{style:{...styles.disc,...palette===null?styles.discEmpty:{backgroundColor:palette.background,color:palette.foreground}},children:palette===null?getInitial(null):palette.initial})})}function headerEntryPillCss(theme){let c=theme.color;return{boxSizing:"border-box",minHeight:44,padding:`0 ${theme.space.md}px`,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,border:`1px solid ${c.controlEdge}`,color:c.brandInk,cursor:"pointer",whiteSpace:"nowrap",...faceCss(theme,"bold"),fontSize:theme.type.size.caption}}function makeStyles4(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,header=theme.slots.header;return{vetEntry:headerEntryPillCss(theme),trailingGroup:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,flexShrink:0},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm+2}px ${s.lg}px`,backgroundColor:c.surfaceCream,...slotCss(header)},menuButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",cursor:"pointer",color:header?.textColor??c.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:MENU_BUTTON_SIZE,height:MENU_BUTTON_SIZE,borderRadius:r.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:r.pill,backgroundColor:c.danger,border:`${UNREAD_DOT_RING}px solid ${header?.backgroundColor??c.surfaceCream}`},leading:{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"flex-start",gap:s.sm,flex:"1 1 0"},trailing:{display:"flex",flexDirection:"row",flexWrap:"wrap-reverse",alignItems:"center",justifyContent:"flex-end",gap:s.sm,flex:"1 1 0"},centre:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:{...LOGO_STYLE,minWidth:0,flexShrink:1},avatarSlot:{position:"relative",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,borderRadius:r.pill,border:`${RING_WIDTH}px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:AVATAR_INNER_SIZE,height:AVATAR_INNER_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(AVATAR_INNER_SIZE*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:c.surfaceSubtle,color:c.text.muted},addBadge:{position:"absolute",bottom:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,right:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,boxSizing:"border-box",width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:r.pill,border:`0.5px solid ${c.mark}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...faceCss(theme,"bold"),fontSize:t.tierSizes.badge.small,lineHeight:1,color:c.brandInk}}}var STATIC=/* @__PURE__ */Object.freeze({kind:"static"}),CitationLinkContext=createContext(STATIC);function useCitationLinks(){return useContext(CitationLinkContext)}function useCitationLinkMode(onOpenUrl){return useMemo(()=>onOpenUrl===void 0?STATIC:/* @__PURE__ */Object.freeze({kind:"host",open:url=>{callHost(onOpenUrl,url,"citation")}}),[onOpenUrl])}function CitationLinksScope({onOpenUrl:onOpenUrl,children:children}){let mode=useCitationLinkMode(onOpenUrl);return createElement(CitationLinkContext.Provider,{value:mode},children)}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level>=6?6:level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var HISTORY_PANEL_WIDTH=320,MIN_THREAD_WIDTH=480,RAIL_MIN_CONTAINER_WIDTH=HISTORY_PANEL_WIDTH+MIN_THREAD_WIDTH,DESKTOP_MIN_CONTAINER_WIDTH=1024,CHAT_COLUMN_MAX_WIDTH=768,ASSISTANT_MEASURE="72ch",NARROW_LAYOUT=/* @__PURE__ */Object.freeze({rail:false,desktop:false}),RAIL_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:false}),DESKTOP_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:true});function layoutFor(width){return width===null||width<RAIL_MIN_CONTAINER_WIDTH?NARROW_LAYOUT:width>=DESKTOP_MIN_CONTAINER_WIDTH?DESKTOP_LAYOUT:RAIL_LAYOUT}var ChatLayoutContext=createContext({layout:NARROW_LAYOUT,report:()=>{},headingLevel:headingLevel(void 0)});function useChatLayout(){return useContext(ChatLayoutContext).layout}function useChatHeadingLevel(){return useContext(ChatLayoutContext).headingLevel}function ChatLayoutScope({children:children,headingLevel:hostLevel}){let[layout,setLayout]=useState(NARROW_LAYOUT),level=headingLevel(hostLevel),value=useMemo(()=>({layout:layout,report:setLayout,headingLevel:level}),[layout,level]);return createElement(ChatLayoutContext.Provider,{value:value},children)}function useMeasuredLayout(root){let{report:report}=useContext(ChatLayoutContext);useEffect(()=>{let node=root.current;if(node===null||typeof ResizeObserver>"u")return;let read=()=>{let width=node.getBoundingClientRect().width;report(layoutFor(width>0?Math.round(width):null))};read();let observer=new ResizeObserver(read);return observer.observe(node),()=>observer.disconnect()},[root,report])}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])}),cubicBezier=cssCubicBezier,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 useMemo(()=>chatMotion(theme),[theme])}function canAnimate(node){return node!==null&&typeof node.animate=="function"}function animateEnter(node,motion){if(!canAnimate(node)||motion.durationMs<=0)return null;let translate=[motion.fromTranslateX!==void 0?`translateX(${motion.fromTranslateX})`:"",motion.fromTranslateY!==void 0&&motion.fromTranslateY!==0?`translateY(${motion.fromTranslateY}px)`:""].filter(part=>part.length>0).join(" "),from={...motion.fromOpacity!==void 0?{opacity:motion.fromOpacity}:{},...translate.length>0?{transform:translate}:{}},to={...motion.fromOpacity!==void 0?{opacity:1}:{},...translate.length>0?{transform:"none"}:{}};try{return node.animate([from,to],{duration:motion.durationMs,delay:motion.delayMs??0,easing:cubicBezier(CHAT_EASING.standard),fill:"backwards"})}catch{return null}}function popIn(node,motion){if(!canAnimate(node)||motion.bubbleInMs<=0)return null;try{return node.animate([{opacity:0,transform:`translateY(${motion.bubbleRisePx}px) scale(${motion.bubbleFromScale})`},{opacity:1,transform:"none"}],{duration:motion.bubbleInMs,easing:cubicBezier(CHAT_EASING.out),fill:"backwards"})}catch{return null}}function animateExit(node,durationMs,toTranslateX){if(!canAnimate(node)||durationMs<=0)return Promise.resolve();try{let animation=node.animate([{opacity:1,transform:"none"},{opacity:0,...toTranslateX!==void 0?{transform:`translateX(${toTranslateX})`}:{}}],{duration:durationMs,easing:cubicBezier(CHAT_EASING.exit),fill:"forwards"});return new Promise(resolve=>{animation.onfinish=()=>resolve(),animation.oncancel=()=>resolve()})}catch{return Promise.resolve()}}function usePresence(show,exitMs){let[present2,setPresent]=useState(show),exiting=present2&&!show;return useEffect(()=>{if(show){setPresent(true);return}if(!present2)return;if(exitMs<=0){setPresent(false);return}let handle=setTimeout(()=>setPresent(false),exitMs);return()=>clearTimeout(handle)},[show,exitMs,present2]),{present:present2,exiting:exiting}}function useRevealedText(text3,active,motion){let[visible,setVisible]=useState(active&&!motion.reduced?0:text3.length),latest=useRef({text:text3,active:active});return latest.current={text:text3,active:active},useEffect(()=>{if(!active||motion.reduced||motion.revealTickMs<=0){setVisible(latest.current.text.length);return}let handle=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.text.length))},motion.revealTickMs);return()=>clearInterval(handle)},[active,motion]),active&&!motion.reduced?text3.slice(0,Math.min(visible,text3.length)):text3}var MIN_TOUCH_TARGET4=44,DRAWER_MAX_WIDTH="85%",DRAWER_SHADOW={y:16,blur:48,alpha:.18},SCRIM_ALPHA=.32,UNREAD_DOT_SIZE2=8,ACTIVE_ROW_ALPHA=.22,SEARCH_EDGE_WIDTH=1.5,LOAD_MORE_MARGIN="50%";function HistoryDrawer({chat:chat,history:history,mode:mode,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles5(theme,mode==="dialog"),[theme,mode]),motion=useChatMotion(),dialog=useModalDialog(mode==="dialog"&&history.open,history.close,returnFocusTo),panelRef=useRef(null),open=history.open,slideMs=motion.drawerMs;if(useEffect(()=>{if(!open||mode!=="dialog")return;let animation=animateEnter(panelRef.current,{durationMs:slideMs,fromOpacity:0,fromTranslateX:"-100%"});return()=>animation?.cancel()},[open,mode,slideMs]),!open)return null;let body=/* @__PURE__ */jsx(PanelBody,{chat:chat,history:history,styles:styles,theme:theme,rail:mode==="rail"});return mode==="rail"?/* @__PURE__ */jsx("aside",{ref:node=>{panelRef.current=node},"aria-label":HISTORY_COPY.heading,style:styles.rail,children:body}):/* @__PURE__ */jsx("div",{style:styles.scrim,onClick:history.close,children:/* @__PURE__ */jsx("div",{ref:node=>{dialog.dialogRef.current=node,panelRef.current=node},role:"dialog","aria-modal":"true","aria-label":HISTORY_COPY.heading,tabIndex:-1,onKeyDown:dialog.onKeyDown,onClick:event=>event.stopPropagation(),style:styles.overlay,children:body})})}function PanelBody({chat:chat,history:history,styles:styles,theme:theme,rail:rail}){let{rows:rows,filtered:filtered,loading:loading,loadingMore:loadingMore,error:error,cursor:cursor2,emptyKind:emptyKind,searching:searching,query:query,setQuery:setQuery}=history,showRows=!loading&&error===null,[searchFocused,setSearchFocused]=useState(false),closeInk=(rail?void 0:theme.slots.dialog?.textColor)??theme.color.brandInk,searchInk=theme.slots.input?.textColor??theme.color.text.muted;/* @__PURE__ */
|
|
127
|
+
return jsx("span",{style:styles.ring,children:/* @__PURE__ */jsx("span",{style:{...styles.disc,...palette===null?styles.discEmpty:{backgroundColor:palette.background,color:palette.foreground}},children:palette===null?getInitial(null):palette.initial})})}function headerEntryPillCss(theme){let c=theme.color;return{boxSizing:"border-box",minHeight:44,padding:`0 ${theme.space.md}px`,borderRadius:theme.radius.pill,backgroundColor:c.surfaceCream,border:`1px solid ${c.controlEdge}`,color:c.brandInk,cursor:"pointer",whiteSpace:"nowrap",...faceCss(theme,"bold"),fontSize:theme.type.size.caption}}function makeStyles4(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,header=theme.slots.header;return{vetEntry:headerEntryPillCss(theme),trailingGroup:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,flexShrink:0},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm+2}px ${s.lg}px`,backgroundColor:c.surfaceCream,...slotCss(header)},menuButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",cursor:"pointer",color:header?.textColor??c.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:MENU_BUTTON_SIZE,height:MENU_BUTTON_SIZE,borderRadius:r.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:r.pill,backgroundColor:c.danger,border:`${UNREAD_DOT_RING}px solid ${header?.backgroundColor??c.surfaceCream}`},leading:{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"flex-start",gap:s.sm,flex:"1 1 0"},trailing:{display:"flex",flexDirection:"row",flexWrap:"wrap-reverse",alignItems:"center",justifyContent:"flex-end",gap:s.sm,flex:"1 1 0"},centre:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:{...LOGO_STYLE,minWidth:0,flexShrink:1},avatarSlot:{position:"relative",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,borderRadius:r.pill,border:`${RING_WIDTH}px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:AVATAR_INNER_SIZE,height:AVATAR_INNER_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(AVATAR_INNER_SIZE*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:c.surfaceSubtle,color:c.text.muted},addBadge:{position:"absolute",bottom:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,right:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,boxSizing:"border-box",width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:r.pill,border:`0.5px solid ${c.mark}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...faceCss(theme,"bold"),fontSize:t.tierSizes.badge.small,lineHeight:1,color:c.brandInk}}}var STATIC=/* @__PURE__ */Object.freeze({kind:"static"}),CitationLinkContext=createContext(STATIC);function useCitationLinks(){return useContext(CitationLinkContext)}function useCitationLinkMode(onOpenUrl){return useMemo(()=>onOpenUrl===void 0?STATIC:/* @__PURE__ */Object.freeze({kind:"host",open:url=>{callHost(onOpenUrl,url,"citation")}}),[onOpenUrl])}function CitationLinksScope({onOpenUrl:onOpenUrl,children:children}){let mode=useCitationLinkMode(onOpenUrl);return createElement(CitationLinkContext.Provider,{value:mode},children)}var EVERFUR_LINK_DOMAIN="everfur.com",MAX_LINK_LENGTH=2048,HOST_ENTRY=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function normalizeLinkHosts(hosts){if(!Array.isArray(hosts))return[];let out=/* @__PURE__ */new Set;for(let entry of hosts){if(typeof entry!="string")continue;let host2=entry.trim().toLowerCase();host2.length<=253&&HOST_ENTRY.test(host2)&&out.add(host2)}/* @__PURE__ */
|
|
128
|
+
return Object.freeze([...out])}function isLinkHost(hostname,hosts){if(hostname===EVERFUR_LINK_DOMAIN||hostname.endsWith(`.${EVERFUR_LINK_DOMAIN}`))return true;for(let entry of hosts)if(entry.startsWith("*.")?hostname.endsWith(entry.slice(1)):hostname===entry)return true;return false}function linkHref(raw,hosts){if(typeof raw!="string"||raw.length===0||raw.length>MAX_LINK_LENGTH||!/^https:\/\//i.test(raw))return null;let url=parseUrl(raw);return url===null||url.protocol!=="https:"||url.username!==""||url.password!==""||url.port!==""?null:isLinkHost(url.hostname,hosts)?url.href:null}function openInNewTab(href){if(!(typeof window>"u"||typeof window.open!="function"))try{window.open(href,"_blank","noopener,noreferrer")}catch{}}var MessageLinksContext=createContext(null),MessageLinkOpenerContext=createContext(null);function useMessageLinks(){return useContext(MessageLinksContext)??void 0}function MessageLinksScope({linkHosts:linkHosts,onOpenUrl:onOpenUrl,children:children}){let frameOpener=useContext(MessageLinkOpenerContext),key=Array.isArray(linkHosts)?linkHosts.join(`\n`):null,value=useMemo(()=>{if(key===null)return null;let hosts=normalizeLinkHosts(key===""?[]:key.split(`\n`));/* @__PURE__ */
|
|
129
|
+
return Object.freeze({hosts:hosts,open:onOpenUrl!==void 0?href=>{callHost(onOpenUrl,href,"message")}:frameOpener??openInNewTab})},[key,onOpenUrl,frameOpener]);return createElement(MessageLinksContext.Provider,{value:value},children)}var LINK_STYLE=/* @__PURE__ */Object.freeze({color:"inherit",textDecoration:"underline",textUnderlineOffset:2,overflowWrap:"anywhere",cursor:"pointer"});function MessageLink({href:href,text:text3,open:open}){/* @__PURE__ */
|
|
130
|
+
return jsx("a",{href:href,target:"_blank",rel:"noopener noreferrer",style:LINK_STYLE,onClick:event=>{event.preventDefault(),open(href)},children:text3})}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level>=6?6:level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var HISTORY_PANEL_WIDTH=320,MIN_THREAD_WIDTH=480,RAIL_MIN_CONTAINER_WIDTH=HISTORY_PANEL_WIDTH+MIN_THREAD_WIDTH,DESKTOP_MIN_CONTAINER_WIDTH=1024,CHAT_COLUMN_MAX_WIDTH=768,ASSISTANT_MEASURE="72ch",NARROW_LAYOUT=/* @__PURE__ */Object.freeze({rail:false,desktop:false}),RAIL_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:false}),DESKTOP_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:true});function layoutFor(width){return width===null||width<RAIL_MIN_CONTAINER_WIDTH?NARROW_LAYOUT:width>=DESKTOP_MIN_CONTAINER_WIDTH?DESKTOP_LAYOUT:RAIL_LAYOUT}var ChatLayoutContext=createContext({layout:NARROW_LAYOUT,report:()=>{},headingLevel:headingLevel(void 0)});function useChatLayout(){return useContext(ChatLayoutContext).layout}function useChatHeadingLevel(){return useContext(ChatLayoutContext).headingLevel}function ChatLayoutScope({children:children,headingLevel:hostLevel}){let[layout,setLayout]=useState(NARROW_LAYOUT),level=headingLevel(hostLevel),value=useMemo(()=>({layout:layout,report:setLayout,headingLevel:level}),[layout,level]);return createElement(ChatLayoutContext.Provider,{value:value},children)}function useMeasuredLayout(root){let{report:report}=useContext(ChatLayoutContext);useEffect(()=>{let node=root.current;if(node===null||typeof ResizeObserver>"u")return;let read=()=>{let width=node.getBoundingClientRect().width;report(layoutFor(width>0?Math.round(width):null))};read();let observer=new ResizeObserver(read);return observer.observe(node),()=>observer.disconnect()},[root,report])}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])}),cubicBezier=cssCubicBezier,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 useMemo(()=>chatMotion(theme),[theme])}function canAnimate(node){return node!==null&&typeof node.animate=="function"}function animateEnter(node,motion){if(!canAnimate(node)||motion.durationMs<=0)return null;let translate=[motion.fromTranslateX!==void 0?`translateX(${motion.fromTranslateX})`:"",motion.fromTranslateY!==void 0&&motion.fromTranslateY!==0?`translateY(${motion.fromTranslateY}px)`:""].filter(part=>part.length>0).join(" "),from={...motion.fromOpacity!==void 0?{opacity:motion.fromOpacity}:{},...translate.length>0?{transform:translate}:{}},to={...motion.fromOpacity!==void 0?{opacity:1}:{},...translate.length>0?{transform:"none"}:{}};try{return node.animate([from,to],{duration:motion.durationMs,delay:motion.delayMs??0,easing:cubicBezier(CHAT_EASING.standard),fill:"backwards"})}catch{return null}}function popIn(node,motion){if(!canAnimate(node)||motion.bubbleInMs<=0)return null;try{return node.animate([{opacity:0,transform:`translateY(${motion.bubbleRisePx}px) scale(${motion.bubbleFromScale})`},{opacity:1,transform:"none"}],{duration:motion.bubbleInMs,easing:cubicBezier(CHAT_EASING.out),fill:"backwards"})}catch{return null}}function animateExit(node,durationMs,toTranslateX){if(!canAnimate(node)||durationMs<=0)return Promise.resolve();try{let animation=node.animate([{opacity:1,transform:"none"},{opacity:0,...toTranslateX!==void 0?{transform:`translateX(${toTranslateX})`}:{}}],{duration:durationMs,easing:cubicBezier(CHAT_EASING.exit),fill:"forwards"});return new Promise(resolve=>{animation.onfinish=()=>resolve(),animation.oncancel=()=>resolve()})}catch{return Promise.resolve()}}function usePresence(show,exitMs){let[present2,setPresent]=useState(show),exiting=present2&&!show;return useEffect(()=>{if(show){setPresent(true);return}if(!present2)return;if(exitMs<=0){setPresent(false);return}let handle=setTimeout(()=>setPresent(false),exitMs);return()=>clearTimeout(handle)},[show,exitMs,present2]),{present:present2,exiting:exiting}}function useRevealedText(text3,active,motion){let[visible,setVisible]=useState(active&&!motion.reduced?0:text3.length),latest=useRef({text:text3,active:active});return latest.current={text:text3,active:active},useEffect(()=>{if(!active||motion.reduced||motion.revealTickMs<=0){setVisible(latest.current.text.length);return}let handle=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.text.length))},motion.revealTickMs);return()=>clearInterval(handle)},[active,motion]),active&&!motion.reduced?text3.slice(0,Math.min(visible,text3.length)):text3}var MIN_TOUCH_TARGET4=44,DRAWER_MAX_WIDTH="85%",DRAWER_SHADOW={y:16,blur:48,alpha:.18},SCRIM_ALPHA=.32,UNREAD_DOT_SIZE2=8,ACTIVE_ROW_ALPHA=.22,SEARCH_EDGE_WIDTH=1.5,LOAD_MORE_MARGIN="50%";function HistoryDrawer({chat:chat,history:history,mode:mode,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles5(theme,mode==="dialog"),[theme,mode]),motion=useChatMotion(),dialog=useModalDialog(mode==="dialog"&&history.open,history.close,returnFocusTo),panelRef=useRef(null),open=history.open,slideMs=motion.drawerMs;if(useEffect(()=>{if(!open||mode!=="dialog")return;let animation=animateEnter(panelRef.current,{durationMs:slideMs,fromOpacity:0,fromTranslateX:"-100%"});return()=>animation?.cancel()},[open,mode,slideMs]),!open)return null;let body=/* @__PURE__ */jsx(PanelBody,{chat:chat,history:history,styles:styles,theme:theme,rail:mode==="rail"});return mode==="rail"?/* @__PURE__ */jsx("aside",{ref:node=>{panelRef.current=node},"aria-label":HISTORY_COPY.heading,style:styles.rail,children:body}):/* @__PURE__ */jsx("div",{style:styles.scrim,onClick:history.close,children:/* @__PURE__ */jsx("div",{ref:node=>{dialog.dialogRef.current=node,panelRef.current=node},role:"dialog","aria-modal":"true","aria-label":HISTORY_COPY.heading,tabIndex:-1,onKeyDown:dialog.onKeyDown,onClick:event=>event.stopPropagation(),style:styles.overlay,children:body})})}function PanelBody({chat:chat,history:history,styles:styles,theme:theme,rail:rail}){let{rows:rows,filtered:filtered,loading:loading,loadingMore:loadingMore,error:error,cursor:cursor2,emptyKind:emptyKind,searching:searching,query:query,setQuery:setQuery}=history,showRows=!loading&&error===null,[searchFocused,setSearchFocused]=useState(false),closeInk=(rail?void 0:theme.slots.dialog?.textColor)??theme.color.brandInk,searchInk=theme.slots.input?.textColor??theme.color.text.muted;/* @__PURE__ */
|
|
221
131
|
return jsxs(Fragment,{children:[
|
|
222
132
|
/* @__PURE__ */jsxs("div",{style:styles.head,children:[
|
|
223
133
|
/* @__PURE__ */jsx("p",{style:styles.heading,children:HISTORY_COPY.heading}),
|
|
@@ -233,9 +143,9 @@ return jsxs(Fragment,{children:[
|
|
|
233
143
|
/* @__PURE__ */jsx("p",{style:styles.state,children:emptyKind==="noMatch"?HISTORY_COPY.noMatch:HISTORY_COPY.empty}),emptyKind==="noMatch"?null:/* @__PURE__ */jsx("p",{style:styles.stateBody,children:HISTORY_COPY.emptyBody})]}):null,showRows&&filtered.length>0?/* @__PURE__ */jsx(RowList,{rows:filtered,activeId:chat.conversationId,onSelect:id=>{history.resume(id)},styles:styles,canLoadMore:cursor2!==null&&!searching&&!loadingMore,onLoadMore:history.loadMore}):null,loadingMore?/* @__PURE__ */jsx("p",{role:"status",style:styles.state,children:HISTORY_COPY.loadingMore}):null]})}function RowList({rows:rows,activeId:activeId,onSelect:onSelect,styles:styles,canLoadMore:canLoadMore,onLoadMore:onLoadMore}){let sentinel=useRef(null),observable=typeof IntersectionObserver=="function",loadMore=useRef(onLoadMore);loadMore.current=onLoadMore;let observe=useCallback(node=>{sentinel.current=node},[]);return useEffect(()=>{let node=sentinel.current;if(!observable||!canLoadMore||node===null)return;let observer=new IntersectionObserver(entries=>{entries.some(entry=>entry.isIntersecting)&&loadMore.current()},{rootMargin:LOAD_MORE_MARGIN});return observer.observe(node),()=>observer.disconnect()},[observable,canLoadMore,rows.length]),/* @__PURE__ */jsxs("ul",{style:styles.list,children:[rows.map(row=>{let unread=row.unreadCount!==null&&row.unreadCount>0,active=row.id===activeId,meta=conversationMeta(row);/* @__PURE__ */
|
|
234
144
|
return jsx("li",{children:/* @__PURE__ */jsxs("button",{type:"button","aria-label":openConversationLabel(row),"aria-current":active?"true":void 0,onClick:()=>onSelect(row.id),style:{...styles.row,...active?styles.rowActive:null},children:[
|
|
235
145
|
/* @__PURE__ */jsxs("span",{style:styles.rowText,children:[
|
|
236
|
-
/* @__PURE__ */jsx("span",{style:styles.rowTitle,children:conversationTitle(row.title)}),meta!==null?/* @__PURE__ */jsx("span",{style:{...styles.rowMeta,...unread?styles.rowMetaUnread:null},children:meta}):null]}),unread?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.unreadDot}):null]})},row.id)}),canLoadMore?/* @__PURE__ */jsx("li",{ref:observe,style:styles.sentinel,children:observable?null:/* @__PURE__ */jsx("button",{type:"button",onClick:onLoadMore,style:styles.textControl,children:HISTORY_COPY.more})}):null]})}function makeStyles5(theme,drawer){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,control=t.tierSizes.control,dialogSlot=drawer?theme.slots.dialog:void 0,panelInk=slotText(dialogSlot),inputSlot=theme.slots.input,ink=c.text.primary,panel={boxSizing:"border-box",display:"flex",flexDirection:"column",gap:s.md,padding:`${s.lg}px ${s.lg}px ${s.lg}px`,backgroundColor:c.surface,color:ink,overflowY:"auto"},textControl={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${dialogSlot?.textColor??c.brandInk}`,background:"transparent",color:dialogSlot?.textColor??c.brandInk,cursor:"pointer",...faceCss(theme,"medium"),fontSize:control.body};return{rail:{...panel,flex:`0 0 ${HISTORY_PANEL_WIDTH}px`,width:HISTORY_PANEL_WIDTH,minHeight:0,borderLeft:`1px solid ${c.borderRingCream}`},scrim:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",zIndex:1,backgroundColor:withAlpha(c.shadow,SCRIM_ALPHA)??"transparent"},overlay:{...panel,position:"absolute",top:0,bottom:0,left:0,margin:0,width:HISTORY_PANEL_WIDTH,maxWidth:DRAWER_MAX_WIDTH,border:0,borderRadius:0,boxShadow:`0 ${DRAWER_SHADOW.y}px ${DRAWER_SHADOW.blur}px ${withAlpha(c.brand,DRAWER_SHADOW.alpha)??"transparent"}`,outline:"none",...slotCss(dialogSlot),...dialogSlot?.borderRadius===void 0?null:{borderRadius:`0 ${dialogSlot.borderRadius}px ${dialogSlot.borderRadius}px 0`}},head:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm},heading:{margin:0,marginRight:"auto",...headingFaceCss(theme,"bold"),fontSize:t.tierSizes.heading.subtitle,lineHeight:`${Math.round(t.tierSizes.heading.subtitle*t.lineHeight.snug)}px`,color:ink,...panelInk},newChat:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",gap:s.xs+2,margin:0,padding:`0 ${s.lg}px`,border:0,borderRadius:r.pill,backgroundColor:c.primary,color:c.onPrimary,cursor:"pointer",...faceCss(theme,"bold"),fontSize:control.bodyTight,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},searchPill:{boxSizing:"border-box",minWidth:0,minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,padding:`0 ${s.md+s.xs/2}px`,borderRadius:r.pill,backgroundColor:c.surface,border:`${SEARCH_EDGE_WIDTH}px solid ${c.brandBorderStrong}`,color:c.text.primary,...slotCss(inputSlot,SEARCH_EDGE_WIDTH)},searchInput:{boxSizing:"border-box",flex:"1 1 auto",minWidth:0,minHeight:MIN_TOUCH_TARGET4-SEARCH_EDGE_WIDTH*2,margin:0,padding:0,border:0,outline:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:Math.max(16,t.size.bodyTight),lineHeight:`${t.size.bodyTight+5}px`,color:c.text.primary,...slotText(inputSlot)},roundControl:{boxSizing:"border-box",flexShrink:0,width:MIN_TOUCH_TARGET4,height:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,minHeight:MIN_TOUCH_TARGET4,margin:0,padding:0,border:0,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",background:"transparent",borderRadius:r.pill},count:{margin:`${s.xs}px 0 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},state:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${t.size.bodyTight+5}px`,color:c.text.muted,...panelInk},stateBody:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+4}px`,color:c.text.muted,...panelInk},stateBlock:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.sm},textControl:textControl,retryControl:{...textControl,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},list:{listStyle:"none",margin:`0 -${s.md}px`,padding:0,display:"flex",flexDirection:"column",gap:2},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`${s.sm+s.xs/2}px ${s.md}px`,border:0,borderRadius:r.md,background:"transparent",color:ink,textAlign:"left",cursor:"pointer",font:"inherit",...panelInk},rowActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??"transparent"},rowText:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:1},rowTitle:{...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*t.lineHeight.snug)}px`,color:c.brandInk,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...panelInk},rowMeta:{...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},rowMetaUnread:{...faceCss(theme,"bold"),color:c.text.primary,...panelInk},unreadDot:{boxSizing:"border-box",flexShrink:0,width:UNREAD_DOT_SIZE2,height:UNREAD_DOT_SIZE2,borderRadius:r.pill,backgroundColor:c.danger},sentinel:{minHeight:1,display:"flex",justifyContent:"center",padding:`${s.xs}px 0`}}}var SPINNER_DELAY_MS=300,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET5=44,INPUT_MAX_HEIGHT=120;var EMPTY_LEAD_RATIO="100 / 12",EMPTY_MIN_HEIGHT=480,EMPTY_GAP=18,BUBBLE_MAX_WIDTH="min(88%, 520px)",BUBBLE_PADDING_Y_TOKEN="md",BUBBLE_PADDING_X_TOKEN="lg",BUBBLE_RADIUS_TOKEN="lg",BUBBLE_TAIL_RADIUS_TOKEN="xs",USER_LINE_HEIGHT=1.5,ASSISTANT_LINE_HEIGHT=1.6;var BUBBLE_SLOT_EDGE_WIDTH=1,PENDING_OPACITY=.6,TURN_GAP_TOKEN="lg",ASSISTANT_INSET_TOKEN="xl",COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_TOKEN="sm",COMPOSER_LEAD_EXTRA_TOKEN="xs",COMPOSER_GAP_TOKEN="xs",COMPOSER_MIN_HEIGHT=60,INPUT_MIN_HEIGHT=44,INPUT_MIN_FONT_SIZE=16,INPUT_LINE_HEIGHT=1.4,SEND_DISC_SIZE=44,SEND_GLYPH_SIZE=22,STOP_GLYPH_SIZE=18,DISABLED_OPACITY=.4,EARLIER_LETTER_SPACING=.5;var SPINNER_SIZE=24,SPINNER_STROKE=3,SPINNER_LOOP_MS=900,ATTACH_GLYPH_SIZE=20,FOLLOW_UP_EDGE_WIDTH=1.5,ASSISTANT_AVATAR_SIZE=20,FOLLOW_UP_LINE_HEIGHT=1.3,FOOTNOTE_LINE_HEIGHT=1.5;function useChatTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles6(theme),[theme]);return{theme:theme,styles:styles}}function columnInset(minimum){return`max(${minimum}px, calc((100% - ${CHAT_COLUMN_MAX_WIDTH}px) / 2))`}function linePx(size,ratio){return`${Math.round(size*ratio)}px`}function makeStyles6(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,slots=theme.slots,family=cssFontFamily(t.family),body=t.size.body,inputSize=Math.max(INPUT_MIN_FONT_SIZE,body),inputLine=Math.round(inputSize*INPUT_LINE_HEIGHT),controlSize=t.tierSizes.control,compactSize=t.tierSizes.compact,bubblePadY=s[BUBBLE_PADDING_Y_TOKEN]+s.xs/2,bubblePadX=s[BUBBLE_PADDING_X_TOKEN]+s.xs/2,control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,border:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:controlSize.body,lineHeight:`${Math.round(controlSize.body*t.lineHeight.normal)}px`},sendSlot=slots.sendButton,discFill=sendSlot?.backgroundColor??(sendSlot?.textColor!==void 0?"transparent":c.primary),primaryOutline=c.primaryEdge!==c.primary?c.primaryEdge:null;return{container:{...SURFACE_ROOT_RESET,boxSizing:"border-box",position:"relative",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:c.chatGround,color:c.text.primary,fontFamily:family},split:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"row"},main:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:s.xl},spinner:{boxSizing:"border-box",width:SPINNER_SIZE,height:SPINNER_SIZE,borderRadius:r.pill,border:`${SPINNER_STROKE}px solid ${c.brandSofter}`,borderTopColor:c.brandInk},emptyScroller:{boxSizing:"border-box",flex:`1 1 ${EMPTY_MIN_HEIGHT}px`,minHeight:0,overflowY:"auto"},emptyContent:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"stretch",justifyContent:"flex-start",height:"100%",paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg),paddingBottom:s.lg,gap:EMPTY_GAP},emptyLead:{flex:"0 1 auto",width:"100%",maxHeight:s.xxl*2,aspectRatio:EMPTY_LEAD_RATIO,minHeight:0,marginBottom:-EMPTY_GAP},errorText:{margin:`0 0 ${s.md}px`,...faceCss(theme,"regular"),fontSize:t.size.subtitle,lineHeight:`${Math.round(t.size.subtitle*t.lineHeight.snug)}px`,color:c.danger,textAlign:"center"},retryButton:{...control,padding:`${s.sm}px ${s.xl}px`,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},setupNotice:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm}px ${s.lg}px`,backgroundColor:c.surfaceCream},setupNoticeText:{...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},setupNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,fontSize:t.size.caption,minHeight:MIN_TOUCH_TARGET5},turnNotice:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.xs,padding:s.md,borderRadius:r.md,backgroundColor:c.surfaceCream,border:`1px solid ${c.borderRingCream}`},turnNoticeError:{border:`1px solid ${c.danger}`},turnNoticeTitle:{...faceCss(theme,"bold"),margin:0,fontSize:t.size.bodyTight,color:c.text.primary},turnNoticeTitleError:{color:c.danger},reconnectingCaption:{...faceCss(theme,"medium"),margin:0,fontSize:t.size.caption,color:c.text.muted,textTransform:"uppercase",letterSpacing:"0.5px"},turnNoticeBody:{...faceCss(theme,"regular"),margin:0,fontSize:t.size.caption,color:c.text.muted},turnNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,minHeight:MIN_TOUCH_TARGET5,...faceCss(theme,"bold"),fontSize:t.size.bodyTight},earlierButton:{...control,alignSelf:"center",padding:`0 ${s.md+s.xs/2}px`,backgroundColor:"transparent",color:c.linkInk,...faceCss(theme,"monoBold"),fontSize:compactSize.tiny,lineHeight:`${Math.round(compactSize.tiny*t.lineHeight.snug)}px`,letterSpacing:EARLIER_LETTER_SPACING,textTransform:"uppercase"},list:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2,paddingTop:s.lg,paddingBottom:s.lg,paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg)},messageList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2},row:{display:"flex",flexDirection:"column"},rowUser:{alignItems:"flex-end"},rowAssistant:{alignItems:"flex-start"},bubble:{boxSizing:"border-box",maxWidth:BUBBLE_MAX_WIDTH,paddingTop:bubblePadY,paddingBottom:bubblePadY,paddingLeft:bubblePadX,paddingRight:bubblePadX,borderRadius:r[BUBBLE_RADIUS_TOKEN],position:"relative"},bubbleUser:{backgroundColor:c.bubbleUser,...primaryOutline!==null&&c.bubbleUser===c.primary?{border:`${BUBBLE_SLOT_EDGE_WIDTH}px solid ${primaryOutline}`}:{},borderBottomRightRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"100% 100%",...slotBoxCss(slots.userBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleAssistant:{...slots.assistantBubble?.backgroundColor===void 0?{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:s[ASSISTANT_INSET_TOKEN],maxWidth:`min(100%, ${ASSISTANT_MEASURE})`}:{},transformOrigin:"0 100%",...slotBoxCss(slots.assistantBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleVet:{backgroundColor:c.bubbleVet,borderTopLeftRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"0 100%",...slotBoxCss(slots.vetBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{margin:0,...faceCss(theme,"regular"),color:c.onPrimary,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.userBubble)},bubbleTextAssistant:{margin:0,...faceCss(theme,"regular"),color:c.text.primary,fontSize:body,lineHeight:linePx(body,ASSISTANT_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.assistantBubble)},bubbleTextVet:{margin:0,...faceCss(theme,"regular"),color:c.onBubbleVet,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.vetBubble)},senderRow:{display:"flex",flexDirection:"row",alignItems:"baseline",flexWrap:"wrap",gap:s.sm,margin:`0 0 ${s.sm}px`},assistantName:{margin:0,...faceCss(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug)},assistantAvatar:{display:"block",flexShrink:0,alignSelf:"center",width:ASSISTANT_AVATAR_SIZE,height:ASSISTANT_AVATAR_SIZE,borderRadius:r.pill,objectFit:"cover"},vetSender:{margin:0,...faceCss(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug),overflowWrap:"anywhere"},bubbleBold:faceCss(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:faceCss(theme,"mono"),followUps:{listStyle:"none",margin:`${s.md}px 0 0`,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm},followUpRow:{...control,justifyContent:"flex-start",textAlign:"left",maxWidth:"100%",padding:`${s.sm}px ${s.lg}px`,borderRadius:r.pill,border:`${FOLLOW_UP_EDGE_WIDTH}px solid ${c.brandInk}`,background:c.chatGround,color:c.brandInk,...faceCss(theme,"bold"),fontSize:controlSize.bodyTight,lineHeight:linePx(controlSize.bodyTight,FOLLOW_UP_LINE_HEIGHT),whiteSpace:"normal",overflowWrap:"anywhere",...slotCss(slots.chip,FOLLOW_UP_EDGE_WIDTH)},composerBlock:{boxSizing:"border-box",display:"flex",flexDirection:"column",width:`calc(100% - ${s.md*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:"0 auto"},composerError:{margin:`${s.xs}px ${s.md}px 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${Math.round(t.size.caption*t.lineHeight.normal)}px`,color:c.danger},composer:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"flex-end",gap:s[COMPOSER_GAP_TOKEN],minHeight:COMPOSER_MIN_HEIGHT,width:"100%",margin:`${s.xs}px 0 0`,paddingTop:s[COMPOSER_PADDING_TOKEN],paddingRight:s[COMPOSER_PADDING_TOKEN],paddingBottom:s[COMPOSER_PADDING_TOKEN],paddingLeft:s.lg+s[COMPOSER_LEAD_EXTRA_TOKEN],backgroundColor:c.chatGround,border:`${COMPOSER_BORDER_WIDTH}px solid ${c.composerBorder}`,borderRadius:r.xl,...slotBoxCss(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerFocused:{border:`${COMPOSER_BORDER_WIDTH}px solid ${slots.composerInput?.borderColor??c.brandInk}`,outline:`${FOCUS_RING_WIDTH}px solid ${c.brandInk}`,outlineOffset:FOCUS_RING_WIDTH},inputWrap:{position:"relative",flex:"1 1 auto",minWidth:0,minHeight:INPUT_MIN_HEIGHT,display:"flex",alignItems:"center"},placeholder:{position:"absolute",top:"50%",left:0,right:0,transform:"translateY(-50%)",pointerEvents:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.placeholder,...slotText(slots.composerInput)},input:{boxSizing:"border-box",flex:"1 1 auto",width:"100%",maxHeight:INPUT_MAX_HEIGHT,margin:0,padding:`${Math.max(0,(INPUT_MIN_HEIGHT-inputLine)/2)}px 0`,border:0,outline:"none",resize:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.primary,...slotText(slots.composerInput)},iconControl:{...control,flexShrink:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",color:c.brandInk},actionButton:{...control,flexShrink:0,padding:0,backgroundColor:"transparent",borderRadius:r.pill},sendDisc:{boxSizing:"border-box",width:SEND_DISC_SIZE,height:SEND_DISC_SIZE,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:SEND_DISC_SIZE/2,backgroundColor:discFill,border:"1px solid transparent",...primaryOutline!==null&&discFill===c.primary?{border:`1.5px solid ${primaryOutline}`}:{},...slotBoxCss(sendSlot)},actionButtonDisabled:{opacity:DISABLED_OPACITY,cursor:"not-allowed"},footnote:{margin:`${s.md}px 0 ${s.sm}px`,padding:`0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:linePx(t.size.caption,FOOTNOTE_LINE_HEIGHT)},poweredBy:{margin:0,padding:`0 0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:compactSize.micro,lineHeight:`${Math.round(compactSize.micro*t.lineHeight.normal)}px`,textAlign:"center"}}}function sendGlyphInk(theme){return theme.slots.sendButton?.textColor??theme.color.onPrimary}var UNREAD_DOT_SIZE3=8;function HistoryBar({bar:bar,history:history,triggerRef:triggerRef,empty:empty,unread:unread=false}){let{theme:theme}=useChatTheme(),cls=bar.classNames,{open:open}=history,count2=history.cursor===null?history.rows.length:0,pill={display:"inline-flex",alignItems:"center",gap:6,minHeight:36,padding:"0 12px",border:"none",borderRadius:999,background:theme.color.surfaceSubtle,color:theme.color.text.primary,font:"inherit",fontSize:theme.type.size.caption,cursor:"pointer"};/* @__PURE__ */
|
|
146
|
+
/* @__PURE__ */jsx("span",{style:styles.rowTitle,children:conversationTitle(row.title)}),meta!==null?/* @__PURE__ */jsx("span",{style:{...styles.rowMeta,...unread?styles.rowMetaUnread:null},children:meta}):null]}),unread?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.unreadDot}):null]})},row.id)}),canLoadMore?/* @__PURE__ */jsx("li",{ref:observe,style:styles.sentinel,children:observable?null:/* @__PURE__ */jsx("button",{type:"button",onClick:onLoadMore,style:styles.textControl,children:HISTORY_COPY.more})}):null]})}function makeStyles5(theme,drawer){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,control=t.tierSizes.control,dialogSlot=drawer?theme.slots.dialog:void 0,panelInk=slotText(dialogSlot),inputSlot=theme.slots.input,ink=c.text.primary,panel={boxSizing:"border-box",display:"flex",flexDirection:"column",gap:s.md,padding:`${s.lg}px ${s.lg}px ${s.lg}px`,backgroundColor:c.surface,color:ink,overflowY:"auto"},textControl={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${dialogSlot?.textColor??c.brandInk}`,background:"transparent",color:dialogSlot?.textColor??c.brandInk,cursor:"pointer",...faceCss(theme,"medium"),fontSize:control.body};return{rail:{...panel,flex:`0 0 ${HISTORY_PANEL_WIDTH}px`,width:HISTORY_PANEL_WIDTH,minHeight:0,borderLeft:`1px solid ${c.borderRingCream}`},scrim:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",zIndex:1,backgroundColor:withAlpha(c.shadow,SCRIM_ALPHA)??"transparent"},overlay:{...panel,position:"absolute",top:0,bottom:0,left:0,margin:0,width:HISTORY_PANEL_WIDTH,maxWidth:DRAWER_MAX_WIDTH,border:0,borderRadius:0,boxShadow:`0 ${DRAWER_SHADOW.y}px ${DRAWER_SHADOW.blur}px ${withAlpha(c.brand,DRAWER_SHADOW.alpha)??"transparent"}`,outline:"none",...slotCss(dialogSlot),...dialogSlot?.borderRadius===void 0?null:{borderRadius:`0 ${dialogSlot.borderRadius}px ${dialogSlot.borderRadius}px 0`}},head:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm},heading:{margin:0,marginRight:"auto",...headingFaceCss(theme,"bold"),fontSize:t.tierSizes.heading.subtitle,lineHeight:`${Math.round(t.tierSizes.heading.subtitle*t.lineHeight.snug)}px`,color:ink,...panelInk},newChat:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",gap:s.xs+2,margin:0,padding:`0 ${s.lg}px`,border:0,borderRadius:r.pill,backgroundColor:c.primary,color:c.onPrimary,cursor:"pointer",...faceCss(theme,"bold"),fontSize:control.bodyTight,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},searchPill:{boxSizing:"border-box",minWidth:0,minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,padding:`0 ${s.md+s.xs/2}px`,borderRadius:r.pill,backgroundColor:c.surface,border:`${SEARCH_EDGE_WIDTH}px solid ${c.brandBorderStrong}`,color:c.text.primary,...slotCss(inputSlot,SEARCH_EDGE_WIDTH)},searchInput:{boxSizing:"border-box",flex:"1 1 auto",minWidth:0,minHeight:MIN_TOUCH_TARGET4-SEARCH_EDGE_WIDTH*2,margin:0,padding:0,border:0,outline:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:Math.max(16,t.size.bodyTight),lineHeight:`${t.size.bodyTight+5}px`,color:c.text.primary,...slotText(inputSlot)},roundControl:{boxSizing:"border-box",flexShrink:0,width:MIN_TOUCH_TARGET4,height:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,minHeight:MIN_TOUCH_TARGET4,margin:0,padding:0,border:0,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",background:"transparent",borderRadius:r.pill},count:{margin:`${s.xs}px 0 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},state:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${t.size.bodyTight+5}px`,color:c.text.muted,...panelInk},stateBody:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+4}px`,color:c.text.muted,...panelInk},stateBlock:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.sm},textControl:textControl,retryControl:{...textControl,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},list:{listStyle:"none",margin:`0 -${s.md}px`,padding:0,display:"flex",flexDirection:"column",gap:2},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`${s.sm+s.xs/2}px ${s.md}px`,border:0,borderRadius:r.md,background:"transparent",color:ink,textAlign:"left",cursor:"pointer",font:"inherit",...panelInk},rowActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??"transparent"},rowText:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:1},rowTitle:{...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*t.lineHeight.snug)}px`,color:c.brandInk,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...panelInk},rowMeta:{...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},rowMetaUnread:{...faceCss(theme,"bold"),color:c.text.primary,...panelInk},unreadDot:{boxSizing:"border-box",flexShrink:0,width:UNREAD_DOT_SIZE2,height:UNREAD_DOT_SIZE2,borderRadius:r.pill,backgroundColor:c.danger},sentinel:{minHeight:1,display:"flex",justifyContent:"center",padding:`${s.xs}px 0`}}}var SPINNER_DELAY_MS=300,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET5=44,INPUT_MAX_HEIGHT=120;var EMPTY_LEAD_RATIO="100 / 12",EMPTY_MIN_HEIGHT=480,EMPTY_GAP=18,BUBBLE_MAX_WIDTH="min(88%, 520px)",BUBBLE_PADDING_Y_TOKEN="md",BUBBLE_PADDING_X_TOKEN="lg",BUBBLE_RADIUS_TOKEN="lg",BUBBLE_TAIL_RADIUS_TOKEN="xs",USER_LINE_HEIGHT=1.5,ASSISTANT_LINE_HEIGHT=1.6;var BUBBLE_SLOT_EDGE_WIDTH=1,PENDING_OPACITY=.6,TURN_GAP_TOKEN="lg",ASSISTANT_INSET_TOKEN="xl",COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_TOKEN="sm",COMPOSER_LEAD_EXTRA_TOKEN="xs",COMPOSER_GAP_TOKEN="xs",COMPOSER_MIN_HEIGHT=60,INPUT_MIN_HEIGHT=44,INPUT_MIN_FONT_SIZE=16,INPUT_LINE_HEIGHT=1.4,SEND_DISC_SIZE=44,SEND_GLYPH_SIZE=22,STOP_GLYPH_SIZE=18,DISABLED_OPACITY=.4,EARLIER_LETTER_SPACING=.5;var SPINNER_SIZE=24,SPINNER_STROKE=3,SPINNER_LOOP_MS=900,ATTACH_GLYPH_SIZE=20,FOLLOW_UP_EDGE_WIDTH=1.5,ASSISTANT_AVATAR_SIZE=20,FOLLOW_UP_LINE_HEIGHT=1.3,FOOTNOTE_LINE_HEIGHT=1.5;function useChatTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles6(theme),[theme]);return{theme:theme,styles:styles}}function columnInset(minimum){return`max(${minimum}px, calc((100% - ${CHAT_COLUMN_MAX_WIDTH}px) / 2))`}function linePx(size,ratio){return`${Math.round(size*ratio)}px`}function makeStyles6(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,slots=theme.slots,family=cssFontFamily(t.family),body=t.size.body,inputSize=Math.max(INPUT_MIN_FONT_SIZE,body),inputLine=Math.round(inputSize*INPUT_LINE_HEIGHT),controlSize=t.tierSizes.control,compactSize=t.tierSizes.compact,bubblePadY=s[BUBBLE_PADDING_Y_TOKEN]+s.xs/2,bubblePadX=s[BUBBLE_PADDING_X_TOKEN]+s.xs/2,control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,border:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:controlSize.body,lineHeight:`${Math.round(controlSize.body*t.lineHeight.normal)}px`},sendSlot=slots.sendButton,discFill=sendSlot?.backgroundColor??(sendSlot?.textColor!==void 0?"transparent":c.primary),primaryOutline=c.primaryEdge!==c.primary?c.primaryEdge:null;return{container:{...SURFACE_ROOT_RESET,boxSizing:"border-box",position:"relative",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:c.chatGround,color:c.text.primary,fontFamily:family},split:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"row"},main:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:s.xl},spinner:{boxSizing:"border-box",width:SPINNER_SIZE,height:SPINNER_SIZE,borderRadius:r.pill,border:`${SPINNER_STROKE}px solid ${c.brandSofter}`,borderTopColor:c.brandInk},emptyScroller:{boxSizing:"border-box",flex:`1 1 ${EMPTY_MIN_HEIGHT}px`,minHeight:0,overflowY:"auto"},emptyContent:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"stretch",justifyContent:"flex-start",height:"100%",paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg),paddingBottom:s.lg,gap:EMPTY_GAP},emptyLead:{flex:"0 1 auto",width:"100%",maxHeight:s.xxl*2,aspectRatio:EMPTY_LEAD_RATIO,minHeight:0,marginBottom:-EMPTY_GAP},errorText:{margin:`0 0 ${s.md}px`,...faceCss(theme,"regular"),fontSize:t.size.subtitle,lineHeight:`${Math.round(t.size.subtitle*t.lineHeight.snug)}px`,color:c.danger,textAlign:"center"},retryButton:{...control,padding:`${s.sm}px ${s.xl}px`,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},setupNotice:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm}px ${s.lg}px`,backgroundColor:c.surfaceCream},setupNoticeText:{...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},setupNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,fontSize:t.size.caption,minHeight:MIN_TOUCH_TARGET5},turnNotice:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.xs,padding:s.md,borderRadius:r.md,backgroundColor:c.surfaceCream,border:`1px solid ${c.borderRingCream}`},turnNoticeError:{border:`1px solid ${c.danger}`},turnNoticeTitle:{...faceCss(theme,"bold"),margin:0,fontSize:t.size.bodyTight,color:c.text.primary},turnNoticeTitleError:{color:c.danger},reconnectingCaption:{...faceCss(theme,"medium"),margin:0,fontSize:t.size.caption,color:c.text.muted,textTransform:"uppercase",letterSpacing:"0.5px"},turnNoticeBody:{...faceCss(theme,"regular"),margin:0,fontSize:t.size.caption,color:c.text.muted},turnNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,minHeight:MIN_TOUCH_TARGET5,...faceCss(theme,"bold"),fontSize:t.size.bodyTight},earlierButton:{...control,alignSelf:"center",padding:`0 ${s.md+s.xs/2}px`,backgroundColor:"transparent",color:c.linkInk,...faceCss(theme,"monoBold"),fontSize:compactSize.tiny,lineHeight:`${Math.round(compactSize.tiny*t.lineHeight.snug)}px`,letterSpacing:EARLIER_LETTER_SPACING,textTransform:"uppercase"},list:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2,paddingTop:s.lg,paddingBottom:s.lg,paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg)},messageList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2},row:{display:"flex",flexDirection:"column"},rowUser:{alignItems:"flex-end"},rowAssistant:{alignItems:"flex-start"},bubble:{boxSizing:"border-box",maxWidth:BUBBLE_MAX_WIDTH,paddingTop:bubblePadY,paddingBottom:bubblePadY,paddingLeft:bubblePadX,paddingRight:bubblePadX,borderRadius:r[BUBBLE_RADIUS_TOKEN],position:"relative"},bubbleUser:{backgroundColor:c.bubbleUser,...primaryOutline!==null&&c.bubbleUser===c.primary?{border:`${BUBBLE_SLOT_EDGE_WIDTH}px solid ${primaryOutline}`}:{},borderBottomRightRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"100% 100%",...slotBoxCss(slots.userBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleAssistant:{...slots.assistantBubble?.backgroundColor===void 0?{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:s[ASSISTANT_INSET_TOKEN],maxWidth:`min(100%, ${ASSISTANT_MEASURE})`}:{},transformOrigin:"0 100%",...slotBoxCss(slots.assistantBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleVet:{backgroundColor:c.bubbleVet,borderTopLeftRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"0 100%",...slotBoxCss(slots.vetBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{margin:0,...faceCss(theme,"regular"),color:c.onPrimary,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.userBubble)},bubbleTextAssistant:{margin:0,...faceCss(theme,"regular"),color:c.text.primary,fontSize:body,lineHeight:linePx(body,ASSISTANT_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.assistantBubble)},bubbleTextVet:{margin:0,...faceCss(theme,"regular"),color:c.onBubbleVet,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.vetBubble)},senderRow:{display:"flex",flexDirection:"row",alignItems:"baseline",flexWrap:"wrap",gap:s.sm,margin:`0 0 ${s.sm}px`},assistantName:{margin:0,...faceCss(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug)},assistantAvatar:{display:"block",flexShrink:0,alignSelf:"center",width:ASSISTANT_AVATAR_SIZE,height:ASSISTANT_AVATAR_SIZE,borderRadius:r.pill,objectFit:"cover"},vetSender:{margin:0,...faceCss(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug),overflowWrap:"anywhere"},bubbleBold:faceCss(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:faceCss(theme,"mono"),followUps:{listStyle:"none",margin:`${s.md}px 0 0`,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm},followUpRow:{...control,justifyContent:"flex-start",textAlign:"left",maxWidth:"100%",padding:`${s.sm}px ${s.lg}px`,borderRadius:r.pill,border:`${FOLLOW_UP_EDGE_WIDTH}px solid ${c.brandInk}`,background:c.chatGround,color:c.brandInk,...faceCss(theme,"bold"),fontSize:controlSize.bodyTight,lineHeight:linePx(controlSize.bodyTight,FOLLOW_UP_LINE_HEIGHT),whiteSpace:"normal",overflowWrap:"anywhere",...slotCss(slots.chip,FOLLOW_UP_EDGE_WIDTH)},composerBlock:{boxSizing:"border-box",display:"flex",flexDirection:"column",width:`calc(100% - ${s.md*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:"0 auto"},composerError:{margin:`${s.xs}px ${s.md}px 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${Math.round(t.size.caption*t.lineHeight.normal)}px`,color:c.danger},composer:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"flex-end",gap:s[COMPOSER_GAP_TOKEN],minHeight:COMPOSER_MIN_HEIGHT,width:"100%",margin:`${s.xs}px 0 0`,paddingTop:s[COMPOSER_PADDING_TOKEN],paddingRight:s[COMPOSER_PADDING_TOKEN],paddingBottom:s[COMPOSER_PADDING_TOKEN],paddingLeft:s.lg+s[COMPOSER_LEAD_EXTRA_TOKEN],backgroundColor:c.chatGround,border:`${COMPOSER_BORDER_WIDTH}px solid ${c.composerBorder}`,borderRadius:r.xl,...slotBoxCss(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerFocused:{border:`${COMPOSER_BORDER_WIDTH}px solid ${slots.composerInput?.borderColor??c.brandInk}`,outline:`${FOCUS_RING_WIDTH}px solid ${c.brandInk}`,outlineOffset:FOCUS_RING_WIDTH},inputWrap:{position:"relative",flex:"1 1 auto",minWidth:0,minHeight:INPUT_MIN_HEIGHT,display:"flex",alignItems:"center"},placeholder:{position:"absolute",top:"50%",left:0,right:0,transform:"translateY(-50%)",pointerEvents:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.placeholder,...slotText(slots.composerInput)},input:{boxSizing:"border-box",flex:"1 1 auto",width:"100%",maxHeight:INPUT_MAX_HEIGHT,margin:0,padding:`${Math.max(0,(INPUT_MIN_HEIGHT-inputLine)/2)}px 0`,border:0,outline:"none",resize:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.primary,...slotText(slots.composerInput)},iconControl:{...control,flexShrink:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",color:c.brandInk},actionButton:{...control,flexShrink:0,padding:0,backgroundColor:"transparent",borderRadius:r.pill},sendDisc:{boxSizing:"border-box",width:SEND_DISC_SIZE,height:SEND_DISC_SIZE,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:SEND_DISC_SIZE/2,backgroundColor:discFill,border:"1px solid transparent",...primaryOutline!==null&&discFill===c.primary?{border:`1.5px solid ${primaryOutline}`}:{},...slotBoxCss(sendSlot)},actionButtonDisabled:{opacity:DISABLED_OPACITY,cursor:"not-allowed"},footnote:{margin:`${s.md}px 0 ${s.sm}px`,padding:`0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:linePx(t.size.caption,FOOTNOTE_LINE_HEIGHT)},poweredBy:{margin:0,padding:`0 0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:compactSize.micro,lineHeight:`${Math.round(compactSize.micro*t.lineHeight.normal)}px`,textAlign:"center"}}}function sendGlyphInk(theme){return theme.slots.sendButton?.textColor??theme.color.onPrimary}var UNREAD_DOT_SIZE3=8;function HistoryBar({bar:bar,history:history,triggerRef:triggerRef,empty:empty,unread:unread=false}){let{theme:theme}=useChatTheme(),cls=bar.classNames,{open:open}=history,count3=history.cursor===null?history.rows.length:0,pill={display:"inline-flex",alignItems:"center",gap:6,minHeight:36,padding:"0 12px",border:"none",borderRadius:999,background:theme.color.surfaceSubtle,color:theme.color.text.primary,font:"inherit",fontSize:theme.type.size.caption,cursor:"pointer"};/* @__PURE__ */
|
|
237
147
|
return jsxs("div",{className:cls?.bar,style:cls?.bar?void 0:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 12px"},children:[
|
|
238
|
-
/* @__PURE__ */jsxs("button",{ref:triggerRef,type:"button",className:cls?.chats,style:cls?.chats?void 0:pill,"aria-expanded":open,onClick:open?history.close:history.show,children:[bar.renderIcon?bar.renderIcon("history"):null,bar.chats,
|
|
148
|
+
/* @__PURE__ */jsxs("button",{ref:triggerRef,type:"button",className:cls?.chats,style:cls?.chats?void 0:pill,"aria-expanded":open,onClick:open?history.close:history.show,children:[bar.renderIcon?bar.renderIcon("history"):null,bar.chats,count3>0?/* @__PURE__ */jsx("span",{className:cls?.count,style:cls?.count?void 0:{fontWeight:700},children:count3}):null,unread?/* @__PURE__ */jsx("span",{"aria-hidden":"true","data-testid":"everfur-chat-history-bar-unread",className:cls?.unreadDot,style:cls?.unreadDot?void 0:{width:UNREAD_DOT_SIZE3,height:UNREAD_DOT_SIZE3,borderRadius:999,background:theme.color.danger,flexShrink:0}}):null]}),bar.extra??null,empty?null:/* @__PURE__ */jsxs("button",{type:"button",className:cls?.newChat,style:cls?.newChat?void 0:pill,onClick:history.newConversation,children:[bar.renderIcon?bar.renderIcon("edit"):null,bar.newChat]})]})}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf2(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf2(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}function definedPresentation(input){let out={};for(let[key,value]of Object.entries(input))value!==void 0&&(out[key]=value);return out}var TELEVET_FOLLOW_UP=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function excludes(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpPolicyFor(host2,presentation,countLocked){let televet=presentation.chatFollowUpsExcludeTelevet,count3=host2?.count!==void 0&&!countLocked?host2.count:presentation.chatFollowUpCount;if(host2===void 0&&count3===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count3<=0)return{...host2??{},count:1,exclude:NONE,fill:[]};let hostExclude=host2?.exclude,exclude=televet?prompt=>TELEVET_FOLLOW_UP.test(prompt)||excludes(hostExclude,prompt):hostExclude;return{...host2??{},count:count3,...exclude!==void 0?{exclude:exclude}:{}}}function historyDayLabel(iso,now=/* @__PURE__ */new Date,locale){let date2=new Date(iso);if(Number.isNaN(date2.getTime()))return null;let a=new Date(now);a.setHours(0,0,0,0);let b=new Date(date2);b.setHours(0,0,0,0);let days=Math.round((a.getTime()-b.getTime())/864e5);if(days===0||days===1)try{let word=new Intl.RelativeTimeFormat(locale,{numeric:"auto"}).format(-days,"day");return word.charAt(0).toLocaleUpperCase(locale)+word.slice(1)}catch{}return date2.toLocaleDateString(locale,{month:"short",day:"numeric"})}function historyTime(iso,locale){let date2=new Date(iso);return Number.isNaN(date2.getTime())?null:date2.toLocaleTimeString(locale,{hour:"numeric",minute:"2-digit"})}function groupByDay(rows,now=/* @__PURE__ */new Date){let groups=[];for(let row of rows){let day=historyDayLabel(row.updatedAt,now)??"",last=groups[groups.length-1];last!==void 0&&last.day===day?last.rows.push(row):groups.push({day:day,rows:[row]})}return groups}function sheetIcon(sheet,name,fallback){if(sheet?.renderIcon!==void 0)try{return sheet.renderIcon(name)}catch{}return fallback}function HistorySheet({chat:chat,history:history,sheet:sheet,returnFocusTo:returnFocusTo}){let{theme:theme}=useChatTheme(),open=history.open,dialog=useModalDialog(open,history.close,returnFocusTo),cls=sheet?.classNames??{},groups=useMemo(()=>groupByDay(history.rows),[history.rows]);if(!open)return null;let c=theme.color,mono={...faceCss(theme,"mono"),fontSize:10.5,letterSpacing:".06em",textTransform:"uppercase",color:c.text.muted},inline=(key,style)=>cls[key]?void 0:style,join=key=>cls[key]?[cls[key],cls.open].filter(Boolean).join(" "):void 0,title=sheet?.title??HISTORY_COPY.heading,container=null;try{container=sheet?.container?.()??null}catch{container=null}let body=/* @__PURE__ */jsxs(Fragment,{children:[
|
|
239
149
|
/* @__PURE__ */jsx("div",{className:join("scrim"),onClick:history.close,style:inline("scrim",{position:"absolute",inset:0,zIndex:40,background:"rgba(38, 37, 35, .38)"})}),
|
|
240
150
|
/* @__PURE__ */jsxs("div",{ref:node=>{dialog.dialogRef.current=node},className:join("sheet"),role:"dialog","aria-modal":"true","aria-label":title,tabIndex:-1,onKeyDown:dialog.onKeyDown,style:inline("sheet",{position:"absolute",left:0,right:0,bottom:0,zIndex:41,maxHeight:"80%",overflowY:"auto",boxSizing:"border-box",background:c.surface,borderRadius:"28px 28px 0 0",padding:"10px 20px 40px"}),children:[
|
|
241
151
|
/* @__PURE__ */jsx("div",{className:cls.grab,"aria-hidden":"true",style:inline("grab",{width:40,height:5,borderRadius:3,background:c.borderRingCream,margin:"0 auto 10px"})}),
|
|
@@ -282,7 +192,7 @@ return jsxs("div",{ref:ref,role:urgent?"alert":"status","aria-hidden":exiting?tr
|
|
|
282
192
|
/* @__PURE__ */jsx("span",{children:label})]}),poison=emergency?/* @__PURE__ */jsxs("a",{href:POISON_CONTROL_TEL,style:{...styles.pill,...styles.ghost,borderColor:paint.title,color:paint.title},children:[
|
|
283
193
|
/* @__PURE__ */jsx(Glyph,{name:"phone",size:PIN_GLYPH_SIZE,color:paint.title}),
|
|
284
194
|
/* @__PURE__ */jsx("span",{children:CHAT_COPY.poisonControlWeb})]}):null,vet=renderVetAction!==void 0?/* @__PURE__ */jsx(HostRender,{render:()=>renderVetAction(level),fallback:pill,resetKey:level}):pill;return vet===null&&poison===null?null:/* @__PURE__ */jsxs("div",{style:styles.actionRow,children:[vet,poison]})}function CompactIcon({exiting:exiting,onExpand:onExpand,styles:styles}){let ref=useRef(null),motion=useChatMotion(),theme=useEverfurTheme();return useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.iconInMs,fromOpacity:0});return()=>animation?.cancel()},[motion.iconInMs]),useEffect(()=>{exiting&&animateExit(ref.current,motion.iconOutMs)},[exiting,motion.iconOutMs]),/* @__PURE__ */jsx("div",{ref:ref,"aria-hidden":exiting?true:void 0,style:styles.iconRow,children:/* @__PURE__ */jsx("button",{type:"button",onClick:onExpand,"aria-label":CHAT_COPY.showLatestVetAlert,style:styles.iconButton,children:/* @__PURE__ */jsx(Glyph,{name:"info",size:INFO_GLYPH_SIZE,color:theme.color.text.muted})})})}function makeStyles7(theme){let s=theme.space,r=theme.radius,t=theme.type,heading=t.tierSizes.heading,control=t.tierSizes.control;return{banner:{position:"relative",boxSizing:"border-box",width:`calc(100% - ${s.lg*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:`${s.sm}px auto ${s.xs}px`,padding:`${s.lg}px ${s.lg+s.xs/2}px`,borderRadius:r.lg,borderStyle:"solid",borderWidth:BANNER_BORDER,display:"flex",flexDirection:"column",gap:s.xs},label:{margin:0,paddingRight:DISMISS_SIZE,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,...faceCss(theme,"bold"),fontSize:heading.body,lineHeight:`${Math.round(heading.body*t.lineHeight.snug)}px`},reason:{margin:0,paddingRight:DISMISS_SIZE,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*1.5)}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},erLine:{...faceCss(theme,"bold")},actionRow:{display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm,marginTop:s.sm},pill:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET7,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`0 ${s.lg}px`,borderRadius:r.pill,borderStyle:"solid",borderWidth:ACTION_EDGE,cursor:"pointer",textDecoration:"none",...faceCss(theme,"bold"),fontSize:control.bodyTight,lineHeight:`${Math.round(control.bodyTight*t.lineHeight.snug)}px`},ghost:{backgroundColor:"transparent"},dismissHit:{position:"absolute",top:6-(MIN_TOUCH_TARGET7-DISMISS_SIZE)/2,right:6-(MIN_TOUCH_TARGET7-DISMISS_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET7,height:MIN_TOUCH_TARGET7,minWidth:MIN_TOUCH_TARGET7,minHeight:MIN_TOUCH_TARGET7,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},dismissDisc:{boxSizing:"border-box",width:DISMISS_SIZE,height:DISMISS_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center"},iconRow:{display:"flex",flexDirection:"row",justifyContent:"flex-end",padding:`2px ${s.lg}px ${s.xs}px`},iconButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET7,minHeight:MIN_TOUCH_TARGET7,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}}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}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}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 httpsUrl2(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__ */
|
|
285
|
-
return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl2(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(
|
|
195
|
+
return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl2(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(count3){return count3===1?`1 ${CHAT_COPY.sourceSingular}`:`${count3} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count3,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count3)}`}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(". ")}function answerParagraphs(text3){let parts=text3.split(/\n\s*\n/).map(part=>part.trim()).filter(part=>part.length>0);return parts.length>0?parts:[text3]}var BULLET_LINE=/^\s*[-*]\s+(\S.*)$/,NUMBERED_LINE=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function answerBlocks(paragraph){let blocks=[],text3=[],list=null,flushText=()=>{text3.length>0&&blocks.push({kind:"text",text:text3.join(`\n`)}),text3=[]},flushList=()=>{list!==null&&blocks.push(list.ordered?{kind:"list",ordered:true,start:list.start,items:list.items}:{kind:"list",ordered:false,items:list.items}),list=null};for(let line of paragraph.split(`\n`)){let bullet=BULLET_LINE.exec(line),numbered=bullet===null?NUMBERED_LINE.exec(line):null,item=bullet?.[1]??numbered?.[2];if(item===void 0){flushList(),text3.push(line);continue}let ordered=numbered!==null;flushText(),list!==null&&list.ordered!==ordered&&flushList(),list===null&&(list={ordered:ordered,start:numbered===null?1:Number(numbered[1]),items:[]}),list.items.push(item.trim())}return flushText(),flushList(),blocks}function questionFor(messages,messageId){let at=messages.findIndex(message=>message.id===messageId);for(let i=at-1;i>=0;i-=1){let message=messages[i];if(message!==void 0&&message.role==="user")return message.text}return null}function hostList(fn,context){if(fn===void 0)return[];try{let out=fn(context);return Array.isArray(out)?out:[]}catch{return[]}}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"})}var MIN_TOUCH_TARGET8=44,RADIO_SIZE=20,NOTES_ROWS=3,PENDING_OPACITY2=.6;function FeedbackReasons(props){let{open:open,onSubmit:onSubmit,onClose:onClose,returnFocusTo:returnFocusTo}=props,theme=useEverfurTheme(),styles=useMemo(()=>makeStyles8(theme),[theme]),dialog=useModalDialog(open,onClose,returnFocusTo),[reason,setReason]=useState(null),[notes,setNotes]=useState(""),[pending3,setPending]=useState(false),[failed,setFailed]=useState(false);if(!open)return null;let submit=()=>{if(pending3)return;setPending(true),setFailed(false);let trimmed=notes.trim();onSubmit(reason,trimmed.length>0?trimmed:null).then(took=>{setPending(false),took?onClose():setFailed(true)})};/* @__PURE__ */
|
|
286
196
|
return jsxs("dialog",{ref:dialog.dialogRef,"aria-label":CHAT_COPY.feedbackTitle,"aria-busy":pending3?true:void 0,onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.sheet,children:[
|
|
287
197
|
/* @__PURE__ */jsx("h2",{style:styles.title,children:CHAT_COPY.feedbackTitle}),
|
|
288
198
|
/* @__PURE__ */jsx("p",{style:styles.subtitle,children:CHAT_COPY.feedbackSubtitle}),
|
|
@@ -299,17 +209,17 @@ return jsxs("div",{style:{...styles.footer,...role==="user"?styles.footerUser:st
|
|
|
299
209
|
/* @__PURE__ */jsx(CopyMessageButton,{role:role,text:text3}),role==="assistant"&&responseId!==void 0?SENTIMENT_OPTIONS.map(option=>{let active=sentiment===option.sentiment,color=active?theme.color.sentiment[option.sentiment]:theme.color.text.timestamp;/* @__PURE__ */
|
|
300
210
|
return jsx("button",{ref:option.sentiment==="down"?downRef:void 0,type:"button","aria-pressed":active,"aria-label":option.label,onClick:()=>flow.onSentiment(option.sentiment),style:styles.iconButton,children:/* @__PURE__ */jsx(Glyph,{name:option.sentiment==="up"?"thumbsUp":"thumbsDown",size:GLYPH_SIZE,color:color,fill:active?color:"transparent"})},option.sentiment)}):null]}),
|
|
301
211
|
/* @__PURE__ */jsx(FeedbackOutcome,{flow:flow,returnFocusTo:downRef})]})}function CopyMessageButton({role:role,text:text3,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles9(theme),[theme]),motion=useChatMotion(),copyable=role!=="vet"&&canCopyToClipboard()&&text3.length>0,[copied,setCopied]=useState(false),copyTimer=useRef(null);useEffect(()=>()=>{copyTimer.current!==null&&clearTimeout(copyTimer.current)},[]);let onCopy=useCallback(()=>{navigator.clipboard.writeText(text3).catch(()=>{}),setCopied(true),copyTimer.current!==null&&clearTimeout(copyTimer.current),copyTimer.current=setTimeout(()=>{setCopied(false),copyTimer.current=null},motion.copiedMs)},[text3,motion.copiedMs]);return copyable?/* @__PURE__ */jsx("button",{type:"button",onClick:onCopy,"aria-label":copied?CHAT_COPY.copied:role==="user"?CHAT_COPY.copyUserMessage:CHAT_COPY.copyAssistantMessage,className:className,style:className?void 0:styles.iconButton,children:copied?/* @__PURE__ */jsx(Glyph,{name:"check",size:GLYPH_SIZE,color:theme.color.success}):/* @__PURE__ */jsx(Glyph,{name:"copy",size:GLYPH_SIZE,color:theme.color.text.timestamp})}):null}function useFeedbackFlow(responseId,sentiment,feedback){let[reasonsOpen,setReasonsOpen]=useState(false),[thanked,setThanked]=useState(false),[failed,setFailed]=useState(false),onSentiment=useCallback(next=>{if(responseId===void 0)return;setThanked(false),setFailed(false);let clearing=sentiment===next;feedback(responseId,next).then(result=>{result.ok||setFailed(true)}),next==="down"&&!clearing&&setReasonsOpen(true)},[responseId,sentiment,feedback]),onSubmitReason=useCallback(async(reason,notes)=>{if(responseId===void 0)return false;if(reason===null&¬es===null)return setThanked(true),true;let result=await feedback(responseId,"down",reason??"other",notes);return result.ok&&setThanked(true),result.ok},[responseId,feedback]),closeReasons=useCallback(()=>setReasonsOpen(false),[]);return{reasonsOpen:reasonsOpen,thanked:thanked,failed:failed,closeReasons:closeReasons,onSentiment:onSentiment,onSubmitReason:onSubmitReason}}function FeedbackOutcome({flow:flow,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles9(theme),[theme]);/* @__PURE__ */
|
|
302
|
-
return jsxs(Fragment,{children:[flow.thanked?/* @__PURE__ */jsx("p",{role:"status",style:styles.thanks,children:CHAT_COPY.feedbackThanks}):null,flow.failed?/* @__PURE__ */jsx("p",{role:"alert",style:styles.failed,children:CHAT_COPY.feedbackFailed}):null,flow.reasonsOpen?/* @__PURE__ */jsx(FeedbackReasons,{open:true,onSubmit:flow.onSubmitReason,onClose:flow.closeReasons,returnFocusTo:returnFocusTo}):null]})}function makeStyles9(theme){let c=theme.color,s=theme.space,t=theme.type;return{footer:{display:"flex",flexDirection:"column",gap:s.xs,paddingTop:s.xs+2},footerUser:{alignItems:"flex-end"},footerAssistant:{alignItems:"flex-start"},row:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm+2,minHeight:ROW_HEIGHT},timestamp:{...faceCss(theme,"monoMedium"),fontSize:t.tierSizes.compact.nano,lineHeight:`${t.tierSizes.compact.nano+2}px`,color:theme.color.text.timestamp},iconButton:{boxSizing:"border-box",width:MIN_TOUCH_TARGET9,height:MIN_TOUCH_TARGET9,minWidth:MIN_TOUCH_TARGET9,minHeight:MIN_TOUCH_TARGET9,margin:`${-28/2}px 0`,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},thanks:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.text.secondary},failed:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger}}}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g
|
|
303
|
-
return jsx("strong",{style:styles.bold,children:run.text},key);case"italic":return styles.italic?/* @__PURE__ */jsx("em",{style:styles.italic,children:run.text},key):run.text;case"code":return styles.code?/* @__PURE__ */jsx("code",{style:styles.code,children:run.text},key):run.text;default:return run.text}}):text3}function tileImageUrl(url){let trimmed=url.trim();return/^\/(?![/\\])\S*$/.test(trimmed)?trimmed:hardenHttpsUrl(trimmed)}function cx(...names){let out=names.filter(name=>typeof name=="string"&&name.length>0).join(" ");return out.length>0?out:void 0}function useCardStyles(){let{theme:theme}=useChatTheme();return useMemo(()=>{let c=theme.color,t=theme.type,muted=c.text.muted,mono={...faceCss(theme,"mono"),fontSize:10.5,letterSpacing:".04em",textTransform:"uppercase",color:muted};return{answer:{display:"flex",flexDirection:"column",gap:12,width:"100%"},byline:{display:"flex",alignItems:"center",gap:10,margin:0,minHeight:14,...mono,letterSpacing:".06em"},body:{display:"grid",gap:10,...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:1.5,color:c.text.primary,overflowWrap:"break-word"},paragraph:{margin:0,whiteSpace:"pre-wrap"},list:{margin:0,paddingLeft:20,display:"grid",gap:4},cards:{display:"grid",gap:8},card:{width:"100%",display:"grid",gridTemplateColumns:"38px minmax(0, 1fr) auto 16px",alignItems:"center",gap:12,boxSizing:"border-box",padding:12,border:"none",borderRadius:theme.radius.lg,background:c.surface,color:c.text.primary,boxShadow:`0 0 0 1px ${c.borderRingCream}`,textAlign:"left",font:"inherit"},cardStat:{gridTemplateColumns:"minmax(0, 1fr) auto"},tile:{width:38,height:38,borderRadius:11,background:c.surfaceSubtle,display:"grid",placeItems:"center",overflow:"hidden",color:c.brandInk},title:{display:"block",...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:1.25},meta:{display:"block",marginTop:3,...mono},pill:{display:"inline-flex",alignItems:"center",minHeight:26,padding:"0 10px",borderRadius:999,background:c.surfaceSubtle,...faceCss(theme,"bold"),fontSize:13,whiteSpace:"nowrap"},value:{...faceCss(theme,"mono"),fontSize:22},feedback:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center"},chip:{minHeight:32,padding:"0 12px",borderRadius:999,border:`1px solid ${c.borderRingCream}`,background:"transparent",color:c.text.primary,...faceCss(theme,"bold"),fontSize:13.5,cursor:"pointer"},chipOn:{background:c.surfaceSubtle},followUps:{display:"grid",gap:8},label:{margin:"2px 0 0",...faceCss(theme,"bold"),fontSize:13,color:muted},row:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 16px",alignItems:"center",gap:10,boxSizing:"border-box",padding:"11px 12px 11px 14px",border:"none",borderRadius:14,background:c.surface,boxShadow:`0 0 0 1px ${c.borderRingCream}`,...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:1.3,color:c.brandInk,textAlign:"left",cursor:"pointer"},rowAction:{gridTemplateColumns:"20px minmax(0, 1fr) 16px",color:c.text.primary},muted:muted}},[theme])}function Chevron({options:options,color:color}){if(options?.renderIcon!==void 0)try{return options.renderIcon("chevron")}catch{}/* @__PURE__ */
|
|
212
|
+
return jsxs(Fragment,{children:[flow.thanked?/* @__PURE__ */jsx("p",{role:"status",style:styles.thanks,children:CHAT_COPY.feedbackThanks}):null,flow.failed?/* @__PURE__ */jsx("p",{role:"alert",style:styles.failed,children:CHAT_COPY.feedbackFailed}):null,flow.reasonsOpen?/* @__PURE__ */jsx(FeedbackReasons,{open:true,onSubmit:flow.onSubmitReason,onClose:flow.closeReasons,returnFocusTo:returnFocusTo}):null]})}function makeStyles9(theme){let c=theme.color,s=theme.space,t=theme.type;return{footer:{display:"flex",flexDirection:"column",gap:s.xs,paddingTop:s.xs+2},footerUser:{alignItems:"flex-end"},footerAssistant:{alignItems:"flex-start"},row:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm+2,minHeight:ROW_HEIGHT},timestamp:{...faceCss(theme,"monoMedium"),fontSize:t.tierSizes.compact.nano,lineHeight:`${t.tierSizes.compact.nano+2}px`,color:theme.color.text.timestamp},iconButton:{boxSizing:"border-box",width:MIN_TOUCH_TARGET9,height:MIN_TOUCH_TARGET9,minWidth:MIN_TOUCH_TARGET9,minHeight:MIN_TOUCH_TARGET9,margin:`${-28/2}px 0`,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},thanks:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.text.secondary},failed:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger}}}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,LINK_TOKEN=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${MAX_LINK_LENGTH}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${MAX_LINK_LENGTH}})`,"gi"),HAS_ADDRESS=/https:\/\//i,SENTENCE_END=`.,;:!?'"`;function hasInlineMarkup(text3,linkHosts){return text3.includes("*")||text3.includes("`")||linkHosts!==void 0&&HAS_ADDRESS.test(text3)}function tokenizeInlineMarkdown(text3,linkHosts){let runs=[],plain=slice=>{linkHosts===void 0?runs.push({kind:"text",text:slice}):pushLinked(runs,slice,linkHosts)},cursor2=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor2&&plain(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&&plain(text3.slice(cursor2)),runs}function trimAddress(address){let end=address.length;for(;;){let last=address[end-1];if(last===void 0)break;if(SENTENCE_END.includes(last))end-=1;else if(last===")"&&count2(address,"(",end)<count2(address,")",end))end-=1;else break}return address.slice(0,end)}function count2(value,char,end){let n=0;for(let i=0;i<end;i+=1)value[i]===char&&(n+=1);return n}function pushLinked(runs,slice,linkHosts){if(!HAS_ADDRESS.test(slice)){runs.push({kind:"text",text:slice});return}let cursor2=0;LINK_TOKEN.lastIndex=0;for(let match=LINK_TOKEN.exec(slice);match!==null;match=LINK_TOKEN.exec(slice)){let label=match[1],labelled=match[2],raw=match[3],text3,href,consumed;if(label!==void 0&&labelled!==void 0)text3=label.trim(),href=text3.length>0?linkHref(labelled,linkHosts):null,consumed=match[0].length;else if(raw!==void 0)text3=trimAddress(raw),href=linkHref(text3,linkHosts),consumed=text3.length;else continue;href!==null&&(match.index>cursor2&&runs.push({kind:"text",text:slice.slice(cursor2,match.index)}),runs.push({kind:"link",text:text3,href:href}),cursor2=match.index+consumed,LINK_TOKEN.lastIndex=cursor2)}cursor2<slice.length&&runs.push({kind:"text",text:slice.slice(cursor2)})}function renderInlineMarkdown(text3,styles,links){let hosts=links?.hosts;return hasInlineMarkup(text3,hosts)?tokenizeInlineMarkdown(text3,hosts).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
|
|
213
|
+
return jsx("strong",{style:styles.bold,children:run.text},key);case"italic":return styles.italic?/* @__PURE__ */jsx("em",{style:styles.italic,children:run.text},key):run.text;case"code":return styles.code?/* @__PURE__ */jsx("code",{style:styles.code,children:run.text},key):run.text;case"link":return links?/* @__PURE__ */jsx(MessageLink,{href:run.href,text:run.text,open:links.open},key):run.text;default:return run.text}}):text3}function tileImageUrl(url){let trimmed=url.trim();return/^\/(?![/\\])\S*$/.test(trimmed)?trimmed:hardenHttpsUrl(trimmed)}function cx(...names){let out=names.filter(name=>typeof name=="string"&&name.length>0).join(" ");return out.length>0?out:void 0}function useCardStyles(){let{theme:theme}=useChatTheme();return useMemo(()=>{let c=theme.color,t=theme.type,muted=c.text.muted,mono={...faceCss(theme,"mono"),fontSize:10.5,letterSpacing:".04em",textTransform:"uppercase",color:muted};return{answer:{display:"flex",flexDirection:"column",gap:12,width:"100%"},byline:{display:"flex",alignItems:"center",gap:10,margin:0,minHeight:14,...mono,letterSpacing:".06em"},body:{display:"grid",gap:10,...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:1.5,color:c.text.primary,overflowWrap:"break-word"},paragraph:{margin:0,whiteSpace:"pre-wrap"},list:{margin:0,paddingLeft:20,display:"grid",gap:4},cards:{display:"grid",gap:8},card:{width:"100%",display:"grid",gridTemplateColumns:"38px minmax(0, 1fr) auto 16px",alignItems:"center",gap:12,boxSizing:"border-box",padding:12,border:"none",borderRadius:theme.radius.lg,background:c.surface,color:c.text.primary,boxShadow:`0 0 0 1px ${c.borderRingCream}`,textAlign:"left",font:"inherit"},cardStat:{gridTemplateColumns:"minmax(0, 1fr) auto"},tile:{width:38,height:38,borderRadius:11,background:c.surfaceSubtle,display:"grid",placeItems:"center",overflow:"hidden",color:c.brandInk},title:{display:"block",...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:1.25},meta:{display:"block",marginTop:3,...mono},pill:{display:"inline-flex",alignItems:"center",minHeight:26,padding:"0 10px",borderRadius:999,background:c.surfaceSubtle,...faceCss(theme,"bold"),fontSize:13,whiteSpace:"nowrap"},value:{...faceCss(theme,"mono"),fontSize:22},feedback:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center"},chip:{minHeight:32,padding:"0 12px",borderRadius:999,border:`1px solid ${c.borderRingCream}`,background:"transparent",color:c.text.primary,...faceCss(theme,"bold"),fontSize:13.5,cursor:"pointer"},chipOn:{background:c.surfaceSubtle},followUps:{display:"grid",gap:8},label:{margin:"2px 0 0",...faceCss(theme,"bold"),fontSize:13,color:muted},row:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 16px",alignItems:"center",gap:10,boxSizing:"border-box",padding:"11px 12px 11px 14px",border:"none",borderRadius:14,background:c.surface,boxShadow:`0 0 0 1px ${c.borderRingCream}`,...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:1.3,color:c.brandInk,textAlign:"left",cursor:"pointer"},rowAction:{gridTemplateColumns:"20px minmax(0, 1fr) 16px",color:c.text.primary},muted:muted}},[theme])}function Chevron({options:options,color:color}){if(options?.renderIcon!==void 0)try{return options.renderIcon("chevron")}catch{}/* @__PURE__ */
|
|
304
214
|
return jsx(Glyph,{name:"chevronRight",size:16,color:color})}function AnswerCard({card:card,options:options,styles:styles}){let cls=options?.classNames??{};if(card.render!==void 0){let variant=card.variant!==void 0?cls.cardVariant?.[card.variant]:void 0;/* @__PURE__ */
|
|
305
215
|
return jsx("div",{role:"group","aria-label":card.title,className:cx(cls.card,variant),style:cls.card?void 0:styles.card,"data-everfur-host-card":"",children:/* @__PURE__ */jsx(HostRender,{render:card.render,fallback:null})})}let stat=card.value!==void 0,className=cx(cls.card,stat&&cls.cardStat,card.variant!==void 0&&cls.cardVariant?.[card.variant]),style=cls.card?void 0:{...styles.card,...stat?styles.cardStat:null,...card.onPress?{cursor:"pointer"}:null},image=card.tile?.imageUrl!==void 0?tileImageUrl(card.tile.imageUrl):null,tile=stat?null:/* @__PURE__ */jsx("span",{className:cx(cls.tile,card.tile?.tone!==void 0&&cls.tileTone?.[card.tile.tone]),style:cls.tile?void 0:styles.tile,children:image!==null?/* @__PURE__ */jsx("img",{alt:"",src:image,style:cls.tile?void 0:{width:"100%",height:"100%",objectFit:"cover"}}):card.tile?.icon??null}),words2=/* @__PURE__ */jsxs("span",{children:[
|
|
306
216
|
/* @__PURE__ */jsx("span",{className:cls.title,style:cls.title?void 0:styles.title,children:card.title}),card.meta!==void 0?/* @__PURE__ */jsx("span",{className:cls.meta,style:cls.meta?void 0:styles.meta,children:card.meta}):null]}),end=stat?/* @__PURE__ */jsxs("span",{className:cls.value,style:cls.value?void 0:styles.value,children:[card.value?.amount,card.value?.unit!==void 0?/* @__PURE__ */jsx("small",{children:card.value.unit}):null]}):/* @__PURE__ */jsxs(Fragment,{children:[card.pill!==void 0?/* @__PURE__ */jsx("span",{className:cx(cls.pill,card.pill.tone!==void 0&&cls.pillTone?.[card.pill.tone]),style:cls.pill?void 0:styles.pill,children:card.pill.label}):cls.card?null:/* @__PURE__ */jsx("span",{}),card.onPress!==void 0?/* @__PURE__ */jsx(Chevron,{options:options,color:styles.muted}):cls.card?null:/* @__PURE__ */jsx("span",{})]});if(card.onPress!==void 0){let onPress=card.onPress;/* @__PURE__ */
|
|
307
217
|
return jsxs("button",{type:"button",className:className,style:style,onClick:()=>{try{onPress()}catch{}},children:[tile,words2,end]})}/* @__PURE__ */
|
|
308
|
-
return jsxs("div",{className:className,style:style,children:[tile,words2,end]})}function CardsAnswer({message:message,text:text3,streaming:streaming,chat:chat,options:options,hiddenSender:hiddenSender,showFooter:showFooter,renderFooter:renderFooter}){let{styles:chatStyles}=useChatTheme(),styles=useCardStyles(),links=useCitationLinks(),cls=options?.classNames??{},context=useMemo(()=>({answer:message.text,question:questionFor(chat.messages,message.id),messageId:message.id}),[message.text,message.id,chat.messages]),settled=!streaming&&message.pending!==true,hostCards=settled?hostList(options?.cards,context):[],sources=useMemo(()=>settled?toCitationCards(message.citations):[],[settled,message.citations]),sentiment=chat.sentimentByMessage[message.id]??null,responseId=message.responseId,flow=useFeedbackFlow(responseId,sentiment,chat.feedback),downChip=useRef(null),byline=options?.byline,inline={bold:chatStyles.bubbleBold,italic:chatStyles.bubbleItalic,code:chatStyles.bubbleCode};/* @__PURE__ */
|
|
218
|
+
return jsxs("div",{className:className,style:style,children:[tile,words2,end]})}function CardsAnswer({message:message,text:text3,streaming:streaming,chat:chat,options:options,hiddenSender:hiddenSender,showFooter:showFooter,renderFooter:renderFooter}){let{styles:chatStyles}=useChatTheme(),styles=useCardStyles(),links=useCitationLinks(),cls=options?.classNames??{},context=useMemo(()=>({answer:message.text,question:questionFor(chat.messages,message.id),messageId:message.id}),[message.text,message.id,chat.messages]),settled=!streaming&&message.pending!==true,hostCards=settled?hostList(options?.cards,context):[],sources=useMemo(()=>settled?toCitationCards(message.citations):[],[settled,message.citations]),sentiment=chat.sentimentByMessage[message.id]??null,responseId=message.responseId,flow=useFeedbackFlow(responseId,sentiment,chat.feedback),downChip=useRef(null),byline=options?.byline,inline={bold:chatStyles.bubbleBold,italic:chatStyles.bubbleItalic,code:chatStyles.bubbleCode},messageLinks=useMessageLinks(),textLinks=settled?messageLinks:void 0;/* @__PURE__ */
|
|
309
219
|
return jsxs("div",{className:cls.answer,style:cls.answer?void 0:styles.answer,"data-everfur-answer":"cards",children:[byline!==void 0?/* @__PURE__ */jsxs("p",{className:cls.byline,style:cls.byline?void 0:styles.byline,children:[byline.icon??null,
|
|
310
220
|
/* @__PURE__ */jsx("span",{children:byline.label})]}):null,
|
|
311
221
|
/* @__PURE__ */jsxs("div",{className:cls.body,style:cls.body?void 0:styles.body,children:[hiddenSender!==null?/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:`${hiddenSender}: `}):null,answerParagraphs(text3).flatMap((paragraph,index)=>answerBlocks(paragraph).map((block,at)=>{let key=`${index}-${at}`;if(block.kind==="text")/* @__PURE__ */
|
|
312
|
-
return jsx("p",{style:styles.paragraph,children:renderInlineMarkdown(block.text,inline)},key);let items=block.items.map((item,n)=>/* @__PURE__ */jsx("li",{children:renderInlineMarkdown(item,inline)},n)),listStyle=cls.body?void 0:styles.list;return block.ordered?/* @__PURE__ */jsx("ol",{start:block.start===1?void 0:block.start,style:listStyle,children:items},key):/* @__PURE__ */jsx("ul",{style:listStyle,children:items},key)}))]}),hostCards.length>0?/* @__PURE__ */jsx("div",{className:cls.cards,style:cls.cards?void 0:styles.cards,children:hostCards.map(card=>/* @__PURE__ */jsx(AnswerCard,{card:card,options:options,styles:styles},card.key))}):null,sources.length>0?/* @__PURE__ */jsxs("div",{className:cls.cards,style:cls.cards?void 0:styles.cards,role:"group","aria-label":sourcesLabel(sources.length),children:[
|
|
222
|
+
return jsx("p",{style:styles.paragraph,children:renderInlineMarkdown(block.text,inline,textLinks)},key);let items=block.items.map((item,n)=>/* @__PURE__ */jsx("li",{children:renderInlineMarkdown(item,inline,textLinks)},n)),listStyle=cls.body?void 0:styles.list;return block.ordered?/* @__PURE__ */jsx("ol",{start:block.start===1?void 0:block.start,style:listStyle,children:items},key):/* @__PURE__ */jsx("ul",{style:listStyle,children:items},key)}))]}),hostCards.length>0?/* @__PURE__ */jsx("div",{className:cls.cards,style:cls.cards?void 0:styles.cards,children:hostCards.map(card=>/* @__PURE__ */jsx(AnswerCard,{card:card,options:options,styles:styles},card.key))}):null,sources.length>0?/* @__PURE__ */jsxs("div",{className:cls.cards,style:cls.cards?void 0:styles.cards,role:"group","aria-label":sourcesLabel(sources.length),children:[
|
|
313
223
|
/* @__PURE__ */jsx("p",{className:cls.followUpsLabel,style:cls.followUpsLabel?void 0:styles.label,children:sourcesLabel(sources.length)}),sources.map(source=>{let url=links.kind==="host"?source.url:null,open=links.kind==="host"&&url!==null?links.open:null;/* @__PURE__ */
|
|
314
224
|
return jsx(AnswerCard,{card:{key:source.key,title:source.title,...source.meta!==null?{meta:source.meta}:{},tile:{icon:/* @__PURE__ */jsx(Glyph,{name:"bookOpen",size:20,color:"currentColor"})},...open!==null&&url!==null?{onPress:()=>open(url)}:{}},options:options,styles:styles},source.key)})]}):null,showFooter&&options?.feedback!==void 0&&responseId!==void 0?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
315
225
|
/* @__PURE__ */jsxs("div",{className:cls.feedback,style:cls.feedback?void 0:styles.feedback,children:[
|
|
@@ -370,12 +280,12 @@ return jsxs("div",{role:"alert",style:styles.centered,children:[
|
|
|
370
280
|
/* @__PURE__ */jsx("p",{style:styles.errorText,children:error.displayMessage}),addPet!==null?/* @__PURE__ */jsx("button",{type:"button",onClick:addPet,style:styles.retryButton,children:CHAT_COPY.addPet}):null,error.retryable?/* @__PURE__ */jsx("button",{type:"button",onClick:onRetry,style:styles.retryButton,children:CHAT_COPY.retry}):null]})}function PopulatedState({options:options,chat:chat,onSelectPrompt:onSelectPrompt,onAnswerCheckin:onAnswerCheckin,imagesFor:imagesFor,onPreview:onPreview,onCheckinFindVet:onCheckinFindVet,petName:petName}){let{styles:styles}=useChatTheme(),{messages:messages,isStreaming:isStreaming}=chat,settledIds=useSettledIds(messages,chat.conversationId),prompts=followUpsWithPolicy(chat,options.followUpPolicy),cards=options.answerStyle==="cards",actions=cards?followUpActionsFor(chat,options.answerCards):[],opening=options.openingCard,first=messages[0],openingId=opening!==void 0&&first!==void 0&&first.role==="user"&&first.text.trim()===opening.prompt?first.id:null,awaiting=awaitingAssistant(messages,isStreaming),notice=turnNotice(chat,"web"),liveCheckins=useMemo(()=>liveCheckinIds(placeCheckins(messages)),[messages]),aside=options.threadAside??null,{scrollerRef:scrollerRef,listRef:listRef,onScroll:onScroll,asideRef:asideRef}=useTranscriptFollow(messages,isStreaming,{awaiting:awaiting,prompts:prompts.length+actions.length,notice:notice!==null,reconnecting:chat.reconnecting===true,aside:aside===null?null:options.threadAsideKey??"shown"}),last=messages[messages.length-1],streamingId=isStreaming&&last!==void 0&&last.role==="assistant"?last.id:null;
|
|
371
281
|
/* @__PURE__ */
|
|
372
282
|
return jsxs("div",{ref:scrollerRef,onScroll:onScroll,role:"region","aria-label":CHAT_COPY.transcript,tabIndex:0,style:styles.list,children:[options.threadTop??null,chat.historyCursor?/* @__PURE__ */jsx("button",{type:"button",disabled:chat.isLoadingHistory,onClick:()=>{chat.loadOlderMessages()},style:styles.earlierButton,children:chat.isLoadingHistory?HISTORY_COPY.loadingEarlier:HISTORY_COPY.earlier}):null,
|
|
373
|
-
/* @__PURE__ */jsx("ol",{ref:listRef,style:styles.messageList,children:messages.map(message=>message.id===openingId&&opening!==void 0?/* @__PURE__ */jsx(OpeningCard,{card:opening.card},message.id):message.checkin&&liveCheckins.has(message.id)?/* @__PURE__ */jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,onFindVet:onCheckinFindVet},message.id):/* @__PURE__ */jsx(MessageRow,{message:message,streaming:message.id===streamingId,chat:chat,images:imagesFor(message),onPreview:onPreview,enters:!settledIds.has(message.id),answerCards:cards?options.answerCards??NO_ANSWER_CARDS:null},message.id))}),chat.reconnecting===true?/* @__PURE__ */jsx("p",{style:styles.reconnectingCaption,children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsx(TurnNoticeCard,{notice:notice,onRetry:chat.retryLast,onStartNew:chat.newConversation}):null,cards?/* @__PURE__ */jsx(CardsFollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label,actions:actions,options:options.answerCards}):/* @__PURE__ */jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label}),aside!==null?/* @__PURE__ */jsx("div",{ref:asideRef,style:{display:"flex",flexDirection:"column"},children:aside}):null,options.answerFooter??null]})}var NO_IDS=/* @__PURE__ */new Set,NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({});function useSettledIds(messages,conversationId2){let ref=useRef(null);if(ref.current===null||ref.current.scope!==conversationId2){let carried=ref.current!==null&&ref.current.scope===null?ref.current.ids:null,opened=conversationId2===null?NO_IDS:new Set(messages.map(message=>message.id));ref.current={scope:conversationId2,ids:carried??opened}}return ref.current.ids}function AssistantSender({showName:showName}){let{theme:theme,styles:styles}=useChatTheme(),avatarUrl=theme.meta.assistantAvatarUrl,[avatarFailed,setAvatarFailed]=useState(null),avatar=avatarUrl!==null&&avatarFailed!==avatarUrl?avatarUrl:null;return!showName&&avatar===null?null:/* @__PURE__ */jsxs("p",{style:styles.senderRow,children:[avatar!==null?/* @__PURE__ */jsx(BrandImage,{src:avatar,alt:"",decorative:true,style:styles.assistantAvatar,onFailed:()=>setAvatarFailed(avatar)}):null,showName?/* @__PURE__ */jsx("span",{style:styles.assistantName,children:CHAT_COPY.assistantName}):null]})}function MessageRow({message:message,streaming:streaming,chat:chat,images:images,onPreview:onPreview,enters:enters,answerCards:answerCards}){let{theme:theme,styles:styles}=useChatTheme(),motion=useChatMotion(),bubbleRef=useRef(null),isUser=message.role==="user",isVet=message.role==="vet";useEffect(()=>{if(!enters)return;let animation=popIn(bubbleRef.current,motion);return()=>animation?.cancel()},[]);let text3=useRevealedText(message.text,streaming&&message.role==="assistant",motion),showAssistantName=message.role==="assistant"&&!theme.meta.hidePoweredBy,hiddenSender=isUser?CHAT_COPY.senderUser:message.role==="assistant"&&!showAssistantName?CHAT_COPY.senderAssistant:null,showFooter=message.pending!==true&&!streaming,footer=()=>/* @__PURE__ */jsx(MessageFooter,{role:message.role,text:message.text,createdAt:message.createdAt,...message.responseId!==void 0?{responseId:message.responseId}:{},sentiment:chat.sentimentByMessage[message.id]??null,feedback:chat.feedback});if(answerCards!==null&&(message.role==="assistant"||isUser)){let questionClass=answerCards.classNames?.question;/* @__PURE__ */
|
|
283
|
+
/* @__PURE__ */jsx("ol",{ref:listRef,style:styles.messageList,children:messages.map(message=>message.id===openingId&&opening!==void 0?/* @__PURE__ */jsx(OpeningCard,{card:opening.card},message.id):message.checkin&&liveCheckins.has(message.id)?/* @__PURE__ */jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,onFindVet:onCheckinFindVet},message.id):/* @__PURE__ */jsx(MessageRow,{message:message,streaming:message.id===streamingId,chat:chat,images:imagesFor(message),onPreview:onPreview,enters:!settledIds.has(message.id),answerCards:cards?options.answerCards??NO_ANSWER_CARDS:null},message.id))}),chat.reconnecting===true?/* @__PURE__ */jsx("p",{style:styles.reconnectingCaption,children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsx(TurnNoticeCard,{notice:notice,onRetry:chat.retryLast,onStartNew:chat.newConversation}):null,cards?/* @__PURE__ */jsx(CardsFollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label,actions:actions,options:options.answerCards}):/* @__PURE__ */jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label}),aside!==null?/* @__PURE__ */jsx("div",{ref:asideRef,style:{display:"flex",flexDirection:"column"},children:aside}):null,options.answerFooter??null]})}var NO_IDS=/* @__PURE__ */new Set,NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({});function useSettledIds(messages,conversationId2){let ref=useRef(null);if(ref.current===null||ref.current.scope!==conversationId2){let carried=ref.current!==null&&ref.current.scope===null?ref.current.ids:null,opened=conversationId2===null?NO_IDS:new Set(messages.map(message=>message.id));ref.current={scope:conversationId2,ids:carried??opened}}return ref.current.ids}function AssistantSender({showName:showName}){let{theme:theme,styles:styles}=useChatTheme(),avatarUrl=theme.meta.assistantAvatarUrl,[avatarFailed,setAvatarFailed]=useState(null),avatar=avatarUrl!==null&&avatarFailed!==avatarUrl?avatarUrl:null;return!showName&&avatar===null?null:/* @__PURE__ */jsxs("p",{style:styles.senderRow,children:[avatar!==null?/* @__PURE__ */jsx(BrandImage,{src:avatar,alt:"",decorative:true,style:styles.assistantAvatar,onFailed:()=>setAvatarFailed(avatar)}):null,showName?/* @__PURE__ */jsx("span",{style:styles.assistantName,children:CHAT_COPY.assistantName}):null]})}function MessageRow({message:message,streaming:streaming,chat:chat,images:images,onPreview:onPreview,enters:enters,answerCards:answerCards}){let{theme:theme,styles:styles}=useChatTheme(),motion=useChatMotion(),links=useMessageLinks(),bubbleRef=useRef(null),isUser=message.role==="user",isVet=message.role==="vet";useEffect(()=>{if(!enters)return;let animation=popIn(bubbleRef.current,motion);return()=>animation?.cancel()},[]);let text3=useRevealedText(message.text,streaming&&message.role==="assistant",motion),showAssistantName=message.role==="assistant"&&!theme.meta.hidePoweredBy,hiddenSender=isUser?CHAT_COPY.senderUser:message.role==="assistant"&&!showAssistantName?CHAT_COPY.senderAssistant:null,showFooter=message.pending!==true&&!streaming,footer=()=>/* @__PURE__ */jsx(MessageFooter,{role:message.role,text:message.text,createdAt:message.createdAt,...message.responseId!==void 0?{responseId:message.responseId}:{},sentiment:chat.sentimentByMessage[message.id]??null,feedback:chat.feedback});if(answerCards!==null&&(message.role==="assistant"||isUser)){let questionClass=answerCards.classNames?.question;/* @__PURE__ */
|
|
374
284
|
return jsx("li",{style:isUser?{...styles.row,...styles.rowUser}:{listStyle:"none",display:"flex",width:"100%"},"aria-busy":message.pending===true?true:void 0,children:isUser?/* @__PURE__ */jsxs("div",{ref:bubbleRef,className:questionClass,style:questionClass?void 0:{...styles.bubble,...styles.bubbleUser,...message.pending?styles.bubblePending:null},children:[
|
|
375
285
|
/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:`${CHAT_COPY.senderUser}: `}),images.length>0?/* @__PURE__ */jsx(MessageAttachments,{images:images,onPreview:onPreview}):null,questionClass?/* @__PURE__ */jsx("span",{style:{whiteSpace:"pre-wrap"},children:text3}):/* @__PURE__ */jsx("p",{style:styles.bubbleTextUser,children:text3})]}):/* @__PURE__ */jsx("div",{ref:bubbleRef,style:{width:"100%"},children:/* @__PURE__ */jsx(CardsAnswer,{message:message,text:text3,streaming:streaming,chat:chat,options:answerCards,hiddenSender:CHAT_COPY.senderAssistant,showFooter:showFooter,renderFooter:footer})})})}/* @__PURE__ */
|
|
376
286
|
return jsxs("li",{style:{...styles.row,...isUser?styles.rowUser:styles.rowAssistant},"aria-busy":message.pending===true?true:void 0,children:[message.role==="assistant"?/* @__PURE__ */jsx(AssistantSender,{showName:showAssistantName}):null,isVet?/* @__PURE__ */jsx("p",{style:styles.senderRow,children:/* @__PURE__ */jsx("span",{style:styles.vetSender,children:vetSenderLabel(message)})}):null,
|
|
377
287
|
/* @__PURE__ */jsxs("div",{ref:bubbleRef,style:{...styles.bubble,...isUser?styles.bubbleUser:isVet?styles.bubbleVet:styles.bubbleAssistant,...message.pending?styles.bubblePending:null},children:[hiddenSender!==null?/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:`${hiddenSender}: `}):null,images.length>0?/* @__PURE__ */jsx(MessageAttachments,{images:images,onPreview:onPreview}):null,
|
|
378
|
-
/* @__PURE__ */jsx("p",{style:isUser?styles.bubbleTextUser:isVet?styles.bubbleTextVet:styles.bubbleTextAssistant,children:message.role==="assistant"?renderInlineMarkdown(text3,{bold:styles.bubbleBold,italic:styles.bubbleItalic,code:styles.bubbleCode}):text3})]}),message.role==="assistant"&&!streaming?/* @__PURE__ */jsx(CitationCards,{citations:message.citations}):null,showFooter?footer():null]})}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT2:source.getSnapshot,snapshot2=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot2!==null&&decideCapability("texting",snapshot2.decisions,{isPending:snapshot2.isPending}).enabled,[snapshot2])}var pending2=null,loaded2=null;function loadTextingModule(){if(pending2!==null)return pending2;let started=import("@everfur/sdk/web/texting");return pending2=started,started.then(module=>{loaded2=module},()=>{pending2===started&&(pending2=null)}),started}var NOTHING=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function useChatTextingAsk(enabled,chat,headerEntry=false,inRow=false){let{userRef:userRef2}=useEverfurContext(),granted=useTextingGranted(),wanted=enabled&&userRef2!==null&&granted,[module,setModule]=useState(loaded2),[ask,setAsk]=useState(null);if(useEffect(()=>{if(!wanted||module!==null)return;let live=true;return loadTextingModule().then(next=>{live&&setModule(next)},()=>{}),()=>{live=false}},[wanted,module]),!wanted||module===null)return NOTHING;let runner=/* @__PURE__ */jsx(module.ChatTextingAskController,{enabled:true,ready:textingAskThreadReady(chat),onAsk:setAsk,entry:headerEntry}),chipEntry=headerEntry&&ask!==null&&ask.canOpen?{label:module.textingAskLines(ask).accept,onOpen:ask.open}:null,chip=chipEntry===null?null:inRow?/* @__PURE__ */jsx(TextingEntryRow,{entry:chipEntry}):/* @__PURE__ */jsx(TextingEntryChip,{entry:chipEntry});if(ask===null||ask.stage==="hidden"||ask.stage==="dismissed")return{runner:runner,line:null,entry:null,stage:null,headerEntry:chip};let lines=module.textingAskLines(ask),line=/* @__PURE__ */jsx(AskLine,{stage:ask.stage,text:ask.stage==="verified"?lines.verified:lines.line,accept:lines.accept,dismiss:lines.dismiss,onAccept:ask.accept,onDismiss:ask.dismiss}),entry=ask.stage==="enrolling"?/* @__PURE__ */jsx(EntryGap,{children:/* @__PURE__ */jsx(module.ChatTextingAskComposer,{ask:ask})}):null;return{runner:runner,line:line,entry:entry,stage:ask.stage,headerEntry:chip}}function TextingEntryRow({entry:entry}){let{theme:theme}=useChatTheme(),s=theme.space;/* @__PURE__ */
|
|
288
|
+
/* @__PURE__ */jsx("p",{style:isUser?styles.bubbleTextUser:isVet?styles.bubbleTextVet:styles.bubbleTextAssistant,children:message.role==="assistant"?renderInlineMarkdown(text3,{bold:styles.bubbleBold,italic:styles.bubbleItalic,code:styles.bubbleCode},streaming?void 0:links):text3})]}),message.role==="assistant"&&!streaming?/* @__PURE__ */jsx(CitationCards,{citations:message.citations}):null,showFooter?footer():null]})}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT2:source.getSnapshot,snapshot2=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot2!==null&&decideCapability("texting",snapshot2.decisions,{isPending:snapshot2.isPending}).enabled,[snapshot2])}var pending2=null,loaded2=null;function loadTextingModule(){if(pending2!==null)return pending2;let started=import("@everfur/sdk/web/texting");return pending2=started,started.then(module=>{loaded2=module},()=>{pending2===started&&(pending2=null)}),started}var NOTHING=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function useChatTextingAsk(enabled,chat,headerEntry=false,inRow=false){let{userRef:userRef2}=useEverfurContext(),granted=useTextingGranted(),wanted=enabled&&userRef2!==null&&granted,[module,setModule]=useState(loaded2),[ask,setAsk]=useState(null);if(useEffect(()=>{if(!wanted||module!==null)return;let live=true;return loadTextingModule().then(next=>{live&&setModule(next)},()=>{}),()=>{live=false}},[wanted,module]),!wanted||module===null)return NOTHING;let runner=/* @__PURE__ */jsx(module.ChatTextingAskController,{enabled:true,ready:textingAskThreadReady(chat),onAsk:setAsk,entry:headerEntry}),chipEntry=headerEntry&&ask!==null&&ask.canOpen?{label:module.textingAskLines(ask).accept,onOpen:ask.open}:null,chip=chipEntry===null?null:inRow?/* @__PURE__ */jsx(TextingEntryRow,{entry:chipEntry}):/* @__PURE__ */jsx(TextingEntryChip,{entry:chipEntry});if(ask===null||ask.stage==="hidden"||ask.stage==="dismissed")return{runner:runner,line:null,entry:null,stage:null,headerEntry:chip};let lines=module.textingAskLines(ask),line=/* @__PURE__ */jsx(AskLine,{stage:ask.stage,text:ask.stage==="verified"?lines.verified:lines.line,accept:lines.accept,dismiss:lines.dismiss,onAccept:ask.accept,onDismiss:ask.dismiss}),entry=ask.stage==="enrolling"?/* @__PURE__ */jsx(EntryGap,{children:/* @__PURE__ */jsx(module.ChatTextingAskComposer,{ask:ask})}):null;return{runner:runner,line:line,entry:entry,stage:ask.stage,headerEntry:chip}}function TextingEntryRow({entry:entry}){let{theme:theme}=useChatTheme(),s=theme.space;/* @__PURE__ */
|
|
379
289
|
return jsx("div",{style:{boxSizing:"border-box",display:"flex",justifyContent:"flex-end",width:`calc(100% - ${s.md*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:`${s.sm}px auto 0`,flexShrink:0},children:/* @__PURE__ */jsx(TextingEntryChip,{entry:entry})})}function TextingEntryChip({entry:entry}){let{theme:theme}=useChatTheme();/* @__PURE__ */
|
|
380
290
|
return jsx("button",{type:"button",onClick:entry.onOpen,"data-everfur-texting-entry":"",style:{...headerEntryPillCss(theme),maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis"},children:entry.label})}function EntryGap({children:children}){let{theme:theme}=useChatTheme(),ref=useRef(null);return useLayoutEffect(()=>{let column=ref.current?.parentElement?.parentElement;if(column!=null){for(let node of Array.from(column.querySelectorAll("*")))if(node.scrollHeight>node.clientHeight&&getComputedStyle(node).overflowY==="auto"){node.scrollTop=node.scrollHeight;return}}},[]),/* @__PURE__ */jsx("div",{ref:ref,style:{paddingTop:theme.space.md},children:children})}function AskLine({stage:stage,text:text3,accept:accept,dismiss:dismiss,onAccept:onAccept,onDismiss:onDismiss}){let{theme:theme,styles:styles}=useChatTheme(),showName=!theme.meta.hidePoweredBy;/* @__PURE__ */
|
|
381
291
|
return jsxs("div",{"data-everfur-texting-ask":stage,style:{...styles.row,...styles.rowAssistant,marginTop:theme.space.lg},children:[
|
|
@@ -388,23 +298,23 @@ return jsxs("span",{style:styles.wrap,children:[listening?/* @__PURE__ */jsx("sp
|
|
|
388
298
|
/* @__PURE__ */jsx("button",{type:"button",disabled:disabled,onClick:()=>onToggle(),"aria-label":active?CHAT_COPY.stopDictation:CHAT_COPY.dictate,"aria-pressed":active,style:{...styles.button,...disabled?styles.buttonDisabled:null},children:active?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
389
299
|
/* @__PURE__ */jsx(Pulse,{style:styles.pulse}),
|
|
390
300
|
/* @__PURE__ */jsx(Glyph,{name:"square",size:STOP_GLYPH_SIZE2,color:theme.color.brandInk,fill:theme.color.brandInk,style:{position:"relative"}})]}):/* @__PURE__ */jsx(Glyph,{name:"mic",size:MIC_GLYPH_SIZE,color:theme.color.brandInk})}),
|
|
391
|
-
/* @__PURE__ */jsx("span",{role:"status","aria-live":"polite",style:VISUALLY_HIDDEN,children:listening?CHAT_COPY.listening:""})]})}function Pulse({style:style}){let ref=useRef(null),motion=useChatMotion();return useEffect(()=>{let node=ref.current;if(motion.reduced||!canAnimate(node))return;let animation=node.animate([{opacity:1},{opacity:.4},{opacity:1}],{duration:PULSE_LOOP_MS,iterations:1/0,easing:"ease-in-out"});return()=>animation.cancel()},[motion.reduced]),/* @__PURE__ */jsx("span",{ref:ref,"aria-hidden":"true",style:style})}function makeStyles15(theme){let c=theme.color,r=theme.radius,t=theme.type;return{wrap:{display:"inline-flex",flexShrink:0,alignItems:"center",gap:theme.space.xs},timer:{...faceCss(theme,"mono"),fontSize:t.tierSizes.compact.micro,lineHeight:`${t.tierSizes.compact.micro+2}px`,fontVariantNumeric:"tabular-nums",color:c.text.muted},button:{position:"relative",boxSizing:"border-box",width:MIN_TOUCH_TARGET14,height:MIN_TOUCH_TARGET14,minWidth:MIN_TOUCH_TARGET14,minHeight:MIN_TOUCH_TARGET14,margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:c.brandInk},buttonDisabled:{opacity:DISABLED_OPACITY2,cursor:"not-allowed"},pulse:{position:"absolute",top:PULSE_INSET,right:PULSE_INSET,bottom:PULSE_INSET,left:PULSE_INSET,borderRadius:r.pill,backgroundColor:c.brandSofter}}}var DICTATION_MAX_DURATION_MS=6e4;function getRecognitionConstructor(env){if(!env)return null;let ctor=env.SpeechRecognition??env.webkitSpeechRecognition;return typeof ctor=="function"?ctor:null}function resolveDictationLang(language){return typeof language=="string"&&language.toLowerCase().startsWith("en")?language:"en-US"}async function probeDictationCapability(env,lang){let ctor=getRecognitionConstructor(env);if(!ctor)return"none";if(typeof ctor.available!="function")return"browser";try{let status=await ctor.available({langs:[lang],processLocally:!0});return status==="available"?"on_device":status==="downloadable"?"downloadable":"browser"}catch{return"browser"}}function joinRecognitionResults(results){let pieces=[];for(let index=0;index<results.length;index+=1){let piece=results[index]?.[0]?.transcript?.trim();if(!piece)continue;let previous=pieces[pieces.length-1];previous&&piece.toLowerCase().startsWith(previous.toLowerCase())?pieces[pieces.length-1]=piece:pieces.push(piece)}return pieces.join(" ")}function mapDictationError(code){return code==="not-allowed"||code==="service-not-allowed"?"permissionDenied":code==="no-speech"?"noSpeech":"unavailable"}var ON_DEVICE_FALLBACK_CODES=/* @__PURE__ */new Set(["language-not-supported","service-not-allowed"]),defaultTimers3={setTimeout:(run,ms)=>globalThis.setTimeout(run,ms),clearTimeout:handle=>globalThis.clearTimeout(handle)};function startDictation(options){let{env:env,capability:capability,lang:lang,callbacks:callbacks}=options,timers=options.timers??defaultTimers3,maxDurationMs=options.maxDurationMs??DICTATION_MAX_DURATION_MS,ctor=getRecognitionConstructor(env),mode=capability==="on_device"?"on_device":"browser",usePhrases=mode==="on_device"&&(options.phrases?.length??0)>0&&typeof env.SpeechRecognitionPhrase=="function",fellBack=false,retriedWithoutPhrases=false,pendingRelaunch=false,recognition=null,generation=0,started=false,finished=false,stopRequested=false,stoppedByOwner=false,heardAnything=false,transcript="",lastError=null,timer=null,finish=()=>{if(finished)return;finished=true,generation+=1,timer!==null&&timers.clearTimeout(timer),timer=null;let error=lastError;error===null&&!stoppedByOwner&&transcript.trim()===""&&(error="noSpeech"),callbacks.onEnd?.({mode:mode,transcript:transcript,error:error})},launch=()=>{if(!ctor){lastError="unavailable",finish();return}generation+=1;let token=generation,live=()=>token===generation&&!finished,next=new ctor;if(recognition=next,next.lang=lang,next.continuous=true,next.interimResults=true,mode==="on_device")try{next.processLocally=!0}catch{mode="browser"}if(mode==="on_device"&&usePhrases)try{let Phrase=env.SpeechRecognitionPhrase;next.phrases=(options.phrases??[]).map(phrase=>new Phrase(phrase))}catch{usePhrases=false,retriedWithoutPhrases=true}next.onstart=()=>{!live()||started||(started=true,callbacks.onStart?.(mode))},next.onresult=event=>{live()&&(heardAnything=true,transcript=joinRecognitionResults(event.results),callbacks.onTranscript?.(transcript))},next.onerror=event=>{if(!live())return;let code=event?.error??"";if(!(code==="aborted"&&stopRequested)){if(code==="phrases-not-supported"&&!retriedWithoutPhrases&&!heardAnything&&!stopRequested){usePhrases=false,retriedWithoutPhrases=true,pendingRelaunch=true;return}if(mode==="on_device"&&!fellBack&&!heardAnything&&!stopRequested&&ON_DEVICE_FALLBACK_CODES.has(code)){mode="browser",usePhrases=false,fellBack=true,pendingRelaunch=true;return}code==="no-speech"&&transcript.trim()!==""||(lastError=mapDictationError(code))}},next.onend=()=>{if(live()){if(pendingRelaunch&&!stopRequested){pendingRelaunch=false,launch();return}finish()}};try{next.start()}catch{if(mode==="on_device"&&!fellBack){mode="browser",usePhrases=false,fellBack=true,launch();return}lastError="unavailable",finish()}};if(capability==="downloadable"&&ctor&&typeof ctor.install=="function")try{Promise.resolve(ctor.install({langs:[lang],processLocally:!0})).catch(()=>{})}catch{}let stopListening=()=>{if(!(finished||stopRequested)){stopRequested=true,pendingRelaunch=false,timer!==null&&timers.clearTimeout(timer),timer=null;try{recognition?.stop()}catch{finish()}}};timer=timers.setTimeout(()=>{timer=null,stopListening()},maxDurationMs);let session={get mode(){return mode},stop(){finished||stopRequested||(stoppedByOwner=true,stopListening())},cancel(){if(finished)return;stopRequested=true,stoppedByOwner=true,pendingRelaunch=false;let current=recognition;finish();try{current?.abort()}catch{}}};return launch(),session}function browserEnv(){return typeof window>"u"?null:window}function useDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry,env:env}){let[capability,setCapability]=useState("none"),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),sessionRef=useRef(null),startedAtRef=useRef(null),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let[probeCount,setProbeCount]=useState(0),resolveEnv=useCallback(()=>env??browserEnv(),[env]);useEffect(()=>{if(!enabled){setCapability("none");return}let target=resolveEnv();if(!target)return;let live=true;return probeDictationCapability(target,resolveDictationLang(target.navigator?.language)).then(next=>{live&&setCapability(next)}),()=>{live=false}},[enabled,resolveEnv,probeCount]);let start=useCallback(()=>{let target=resolveEnv();if(!target||capability==="none")return;setError(null),setElapsedMs(0),startedAtRef.current=null,setStatus("starting");let base2=inputRef.current,probedAs=capability,ended=false,session=startDictation({env:target,capability:capability,lang:resolveDictationLang(target.navigator?.language),...phrases!==void 0?{phrases:phrases}:{},callbacks:{onStart:mode=>{startedAtRef.current=Date.now(),setStatus("listening"),trackDictationEvent(telemetryRef.current,"chat_dictation_started",{mode:mode})},onTranscript:transcript=>{setInputRef.current(composeDictatedText(base2,transcript,maxLength))},onEnd:({mode:mode,transcript:transcript,error:endError})=>{ended=true,sessionRef.current=null;let startedAt=startedAtRef.current;startedAtRef.current=null,endError?(setError(endError),setStatus("error"),trackDictationEvent(telemetryRef.current,"chat_dictation_failed",{mode:mode,error:endError})):(setStatus("idle"),trackDictationEvent(telemetryRef.current,"chat_dictation_completed",{mode:mode,duration_ms:startedAt===null?0:Date.now()-startedAt,char_count:transcript.trim().length})),probedAs==="downloadable"&&setProbeCount(count2=>count2+1)}}});ended||(sessionRef.current=session)},[capability,maxLength,phrases,resolveEnv]),stop=useCallback(()=>{sessionRef.current?.stop()},[]),cancel=useCallback(()=>{sessionRef.current?.cancel()},[]),active=status==="starting"||status==="listening",toggle=useCallback(()=>{if(sessionRef.current){sessionRef.current.stop();return}start()},[start]);return useEffect(()=>{if(status!=="listening")return;let tick=()=>{let startedAt=startedAtRef.current;startedAt!==null&&setElapsedMs(Date.now()-startedAt)};tick();let handle=setInterval(tick,1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(!active||typeof document>"u")return;let onVisibility=()=>{document.visibilityState==="hidden"&&sessionRef.current?.stop()};return document.addEventListener("visibilitychange",onVisibility),()=>document.removeEventListener("visibilitychange",onVisibility)},[active]),useEffect(()=>{if(!active||typeof document>"u")return;let onKey=event=>{event.key==="Escape"&&sessionRef.current?.stop()};return document.addEventListener("keydown",onKey),()=>document.removeEventListener("keydown",onKey)},[active]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>()=>{sessionRef.current?.cancel()},[]),{supported:enabled&&capability!=="none",status:status,active:active,error:error,elapsedMs:elapsedMs,toggle:toggle,stop:stop,cancel:cancel}}var DICTATION_VOCABULARY=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function buildDictationPhrases(pet={}){let seen=/* @__PURE__ */new Set,phrases=[];for(let candidate of[pet.name,pet.breed,...DICTATION_VOCABULARY]){let phrase=(candidate??"").trim();if(!phrase)continue;let key=phrase.toLowerCase();if(!seen.has(key)&&(seen.add(key),phrases.push(phrase),phrases.length>=100))break}return phrases}function composerPlaceholder(branded,mood,petName,petPlaceholder=false){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}var COMPACT_HEIGHT=52,COMPACT_DISC_SIZE=40,COMPACT_ATTACH_GLYPH=22,COMPACT_SEND_GLYPH=20,COMPACT_PILL={alignItems:"center",gap:6,minHeight:COMPACT_HEIGHT,paddingTop:0,paddingBottom:0,paddingLeft:8,paddingRight:6,borderRadius:COMPACT_HEIGHT/2},COMPACT_BLOCK_TOP=6,COMPACT_BLOCK_FOOT=10,COMPACT_BLOCK={width:"calc(100% - 28px)",paddingTop:COMPACT_BLOCK_TOP,paddingBottom:COMPACT_BLOCK_FOOT},COMPACT_ATTACH={marginLeft:-3,marginRight:-3},COMPACT_SEND={marginLeft:-2,marginRight:-2},COMPACT_DISC={width:COMPACT_DISC_SIZE,height:COMPACT_DISC_SIZE,borderRadius:COMPACT_DISC_SIZE/2};function Composer({send:send,draftScope:draftScope,stop:stop,isStreaming:isStreaming,inputRef:inputRef,conversationId:conversationId2,seed:seed,draftStore:draftStore,attachments:attachments,onPreview:onPreview,dictation:dictation,pet:pet,telemetry:telemetry,mood:mood="ask",compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false,children:children}){let{theme:theme,styles:styles}=useChatTheme(),[draft,setDraft]=useChatDraft(draftScope,conversationId2,seed);usePersistedDraft(draftStore,conversationId2===null?null:String(conversationId2),draft,setDraft);let[focused,setFocused]=useState(false),placeholder=composerPlaceholder(theme.meta.placeholder,mood,pet?.name,petPlaceholder),phrases=useMemo(()=>buildDictationPhrases({name:pet?.name??null,breed:pet?.breed??null}),[pet?.name,pet?.breed]),voice=useDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active,fileInput=useRef(null),liveUrls=useRef(/* @__PURE__ */new Set),sentUrls=useRef(/* @__PURE__ */new Set);useEffect(()=>()=>{for(let url of liveUrls.current)revokeObjectUrl(url);for(let url of sentUrls.current)revokeObjectUrl(url)},[]);let onPick=useCallback(event=>{if(attachments===null)return;let files=Array.from(event.target.files??[]);if(event.target.value="",files.length===0)return;attachments.dismissRejected();let handles=files.map(fileToAttachmentHandle),outcomes=attachments.add(handles);handles.forEach((handle,index)=>{outcomes[index]?.ok===true?liveUrls.current.add(handle.uri):revokeObjectUrl(handle.uri)})},[attachments]),onRemove=useCallback(id=>{if(attachments===null)return;let row=attachments.attachments.find(entry=>entry.id===id);attachments.remove(id),row!==void 0&&liveUrls.current.delete(row.previewUri)&&revokeObjectUrl(row.previewUri)},[attachments]),uploading=attachments!==null&&attachments.uploading,uploadFailed=attachments!==null&&attachments.failed,uploadBlocked=uploading||uploadFailed,isOverLimit=useMemo(()=>[...draft].length>MESSAGE_MAX_CHARS,[draft]),onSend=useCallback(()=>{if(draft.trim().length===0||[...draft].length>MESSAGE_MAX_CHARS||uploadBlocked)return;dictating&&cancelDictation();let images=attachments===null?NO_IMAGES:attachments.attachments.flatMap(row=>row.status==="uploaded"?[{uri:row.previewUri,filename:row.filename}]:[]);for(let image of images)liveUrls.current.delete(image.uri),sentUrls.current.add(image.uri);send(draft,images),setDraft("")},[draft,send,uploadBlocked,dictating,cancelDictation,attachments,setDraft]),onStop=useCallback(()=>{stop()},[stop]),onKeyDown2=useCallback(event=>{event.key!=="Enter"||event.shiftKey||event.altKey||event.ctrlKey||event.metaKey||event.nativeEvent.isComposing||(event.preventDefault(),onSend())},[onSend]),onChange=useCallback(event=>{dictating&&cancelDictation(),setDraft(event.target.value)},[dictating,cancelDictation,setDraft]);useLayoutEffect(()=>{let node=inputRef.current;node!==null&&(node.style.height="auto",node.style.height=`${Math.min(node.scrollHeight,INPUT_MAX_HEIGHT)}px`)},[draft,inputRef]);let sendBlocked=isOverLimit||uploadBlocked||draft.trim().length===0,sendDimmed=isOverLimit||uploadBlocked||dimEmptySend&&draft.trim().length===0,attachFull=attachments!==null&&attachments.attachments.length>=attachments.maxPerMessage,onPillPress=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),inputRef.current?.focus())},[inputRef]),sendInk=sendGlyphInk(theme);/* @__PURE__ */
|
|
301
|
+
/* @__PURE__ */jsx("span",{role:"status","aria-live":"polite",style:VISUALLY_HIDDEN,children:listening?CHAT_COPY.listening:""})]})}function Pulse({style:style}){let ref=useRef(null),motion=useChatMotion();return useEffect(()=>{let node=ref.current;if(motion.reduced||!canAnimate(node))return;let animation=node.animate([{opacity:1},{opacity:.4},{opacity:1}],{duration:PULSE_LOOP_MS,iterations:1/0,easing:"ease-in-out"});return()=>animation.cancel()},[motion.reduced]),/* @__PURE__ */jsx("span",{ref:ref,"aria-hidden":"true",style:style})}function makeStyles15(theme){let c=theme.color,r=theme.radius,t=theme.type;return{wrap:{display:"inline-flex",flexShrink:0,alignItems:"center",gap:theme.space.xs},timer:{...faceCss(theme,"mono"),fontSize:t.tierSizes.compact.micro,lineHeight:`${t.tierSizes.compact.micro+2}px`,fontVariantNumeric:"tabular-nums",color:c.text.muted},button:{position:"relative",boxSizing:"border-box",width:MIN_TOUCH_TARGET14,height:MIN_TOUCH_TARGET14,minWidth:MIN_TOUCH_TARGET14,minHeight:MIN_TOUCH_TARGET14,margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:c.brandInk},buttonDisabled:{opacity:DISABLED_OPACITY2,cursor:"not-allowed"},pulse:{position:"absolute",top:PULSE_INSET,right:PULSE_INSET,bottom:PULSE_INSET,left:PULSE_INSET,borderRadius:r.pill,backgroundColor:c.brandSofter}}}var DICTATION_MAX_DURATION_MS=6e4;function getRecognitionConstructor(env){if(!env)return null;let ctor=env.SpeechRecognition??env.webkitSpeechRecognition;return typeof ctor=="function"?ctor:null}function resolveDictationLang(language){return typeof language=="string"&&language.toLowerCase().startsWith("en")?language:"en-US"}async function probeDictationCapability(env,lang){let ctor=getRecognitionConstructor(env);if(!ctor)return"none";if(typeof ctor.available!="function")return"browser";try{let status=await ctor.available({langs:[lang],processLocally:!0});return status==="available"?"on_device":status==="downloadable"?"downloadable":"browser"}catch{return"browser"}}function joinRecognitionResults(results){let pieces=[];for(let index=0;index<results.length;index+=1){let piece=results[index]?.[0]?.transcript?.trim();if(!piece)continue;let previous=pieces[pieces.length-1];previous&&piece.toLowerCase().startsWith(previous.toLowerCase())?pieces[pieces.length-1]=piece:pieces.push(piece)}return pieces.join(" ")}function mapDictationError(code){return code==="not-allowed"||code==="service-not-allowed"?"permissionDenied":code==="no-speech"?"noSpeech":"unavailable"}var ON_DEVICE_FALLBACK_CODES=/* @__PURE__ */new Set(["language-not-supported","service-not-allowed"]),defaultTimers3={setTimeout:(run,ms)=>globalThis.setTimeout(run,ms),clearTimeout:handle=>globalThis.clearTimeout(handle)};function startDictation(options){let{env:env,capability:capability,lang:lang,callbacks:callbacks}=options,timers=options.timers??defaultTimers3,maxDurationMs=options.maxDurationMs??DICTATION_MAX_DURATION_MS,ctor=getRecognitionConstructor(env),mode=capability==="on_device"?"on_device":"browser",usePhrases=mode==="on_device"&&(options.phrases?.length??0)>0&&typeof env.SpeechRecognitionPhrase=="function",fellBack=false,retriedWithoutPhrases=false,pendingRelaunch=false,recognition=null,generation=0,started=false,finished=false,stopRequested=false,stoppedByOwner=false,heardAnything=false,transcript="",lastError=null,timer=null,finish=()=>{if(finished)return;finished=true,generation+=1,timer!==null&&timers.clearTimeout(timer),timer=null;let error=lastError;error===null&&!stoppedByOwner&&transcript.trim()===""&&(error="noSpeech"),callbacks.onEnd?.({mode:mode,transcript:transcript,error:error})},launch=()=>{if(!ctor){lastError="unavailable",finish();return}generation+=1;let token=generation,live=()=>token===generation&&!finished,next=new ctor;if(recognition=next,next.lang=lang,next.continuous=true,next.interimResults=true,mode==="on_device")try{next.processLocally=!0}catch{mode="browser"}if(mode==="on_device"&&usePhrases)try{let Phrase=env.SpeechRecognitionPhrase;next.phrases=(options.phrases??[]).map(phrase=>new Phrase(phrase))}catch{usePhrases=false,retriedWithoutPhrases=true}next.onstart=()=>{!live()||started||(started=true,callbacks.onStart?.(mode))},next.onresult=event=>{live()&&(heardAnything=true,transcript=joinRecognitionResults(event.results),callbacks.onTranscript?.(transcript))},next.onerror=event=>{if(!live())return;let code=event?.error??"";if(!(code==="aborted"&&stopRequested)){if(code==="phrases-not-supported"&&!retriedWithoutPhrases&&!heardAnything&&!stopRequested){usePhrases=false,retriedWithoutPhrases=true,pendingRelaunch=true;return}if(mode==="on_device"&&!fellBack&&!heardAnything&&!stopRequested&&ON_DEVICE_FALLBACK_CODES.has(code)){mode="browser",usePhrases=false,fellBack=true,pendingRelaunch=true;return}code==="no-speech"&&transcript.trim()!==""||(lastError=mapDictationError(code))}},next.onend=()=>{if(live()){if(pendingRelaunch&&!stopRequested){pendingRelaunch=false,launch();return}finish()}};try{next.start()}catch{if(mode==="on_device"&&!fellBack){mode="browser",usePhrases=false,fellBack=true,launch();return}lastError="unavailable",finish()}};if(capability==="downloadable"&&ctor&&typeof ctor.install=="function")try{Promise.resolve(ctor.install({langs:[lang],processLocally:!0})).catch(()=>{})}catch{}let stopListening=()=>{if(!(finished||stopRequested)){stopRequested=true,pendingRelaunch=false,timer!==null&&timers.clearTimeout(timer),timer=null;try{recognition?.stop()}catch{finish()}}};timer=timers.setTimeout(()=>{timer=null,stopListening()},maxDurationMs);let session={get mode(){return mode},stop(){finished||stopRequested||(stoppedByOwner=true,stopListening())},cancel(){if(finished)return;stopRequested=true,stoppedByOwner=true,pendingRelaunch=false;let current=recognition;finish();try{current?.abort()}catch{}}};return launch(),session}function browserEnv(){return typeof window>"u"?null:window}function useDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry,env:env}){let[capability,setCapability]=useState("none"),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),sessionRef=useRef(null),startedAtRef=useRef(null),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let[probeCount,setProbeCount]=useState(0),resolveEnv=useCallback(()=>env??browserEnv(),[env]);useEffect(()=>{if(!enabled){setCapability("none");return}let target=resolveEnv();if(!target)return;let live=true;return probeDictationCapability(target,resolveDictationLang(target.navigator?.language)).then(next=>{live&&setCapability(next)}),()=>{live=false}},[enabled,resolveEnv,probeCount]);let start=useCallback(()=>{let target=resolveEnv();if(!target||capability==="none")return;setError(null),setElapsedMs(0),startedAtRef.current=null,setStatus("starting");let base2=inputRef.current,probedAs=capability,ended=false,session=startDictation({env:target,capability:capability,lang:resolveDictationLang(target.navigator?.language),...phrases!==void 0?{phrases:phrases}:{},callbacks:{onStart:mode=>{startedAtRef.current=Date.now(),setStatus("listening"),trackDictationEvent(telemetryRef.current,"chat_dictation_started",{mode:mode})},onTranscript:transcript=>{setInputRef.current(composeDictatedText(base2,transcript,maxLength))},onEnd:({mode:mode,transcript:transcript,error:endError})=>{ended=true,sessionRef.current=null;let startedAt=startedAtRef.current;startedAtRef.current=null,endError?(setError(endError),setStatus("error"),trackDictationEvent(telemetryRef.current,"chat_dictation_failed",{mode:mode,error:endError})):(setStatus("idle"),trackDictationEvent(telemetryRef.current,"chat_dictation_completed",{mode:mode,duration_ms:startedAt===null?0:Date.now()-startedAt,char_count:transcript.trim().length})),probedAs==="downloadable"&&setProbeCount(count3=>count3+1)}}});ended||(sessionRef.current=session)},[capability,maxLength,phrases,resolveEnv]),stop=useCallback(()=>{sessionRef.current?.stop()},[]),cancel=useCallback(()=>{sessionRef.current?.cancel()},[]),active=status==="starting"||status==="listening",toggle=useCallback(()=>{if(sessionRef.current){sessionRef.current.stop();return}start()},[start]);return useEffect(()=>{if(status!=="listening")return;let tick=()=>{let startedAt=startedAtRef.current;startedAt!==null&&setElapsedMs(Date.now()-startedAt)};tick();let handle=setInterval(tick,1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(!active||typeof document>"u")return;let onVisibility=()=>{document.visibilityState==="hidden"&&sessionRef.current?.stop()};return document.addEventListener("visibilitychange",onVisibility),()=>document.removeEventListener("visibilitychange",onVisibility)},[active]),useEffect(()=>{if(!active||typeof document>"u")return;let onKey=event=>{event.key==="Escape"&&sessionRef.current?.stop()};return document.addEventListener("keydown",onKey),()=>document.removeEventListener("keydown",onKey)},[active]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>()=>{sessionRef.current?.cancel()},[]),{supported:enabled&&capability!=="none",status:status,active:active,error:error,elapsedMs:elapsedMs,toggle:toggle,stop:stop,cancel:cancel}}var DICTATION_VOCABULARY=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function buildDictationPhrases(pet={}){let seen=/* @__PURE__ */new Set,phrases=[];for(let candidate of[pet.name,pet.breed,...DICTATION_VOCABULARY]){let phrase=(candidate??"").trim();if(!phrase)continue;let key=phrase.toLowerCase();if(!seen.has(key)&&(seen.add(key),phrases.push(phrase),phrases.length>=100))break}return phrases}function composerPlaceholder(branded,mood,petName,petPlaceholder=false){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}var COMPACT_HEIGHT=52,COMPACT_DISC_SIZE=40,COMPACT_ATTACH_GLYPH=22,COMPACT_SEND_GLYPH=20,COMPACT_PILL={alignItems:"center",gap:6,minHeight:COMPACT_HEIGHT,paddingTop:0,paddingBottom:0,paddingLeft:8,paddingRight:6,borderRadius:COMPACT_HEIGHT/2},COMPACT_BLOCK_TOP=6,COMPACT_BLOCK_FOOT=10,COMPACT_BLOCK={width:"calc(100% - 28px)",paddingTop:COMPACT_BLOCK_TOP,paddingBottom:COMPACT_BLOCK_FOOT},COMPACT_ATTACH={marginLeft:-3,marginRight:-3},COMPACT_SEND={marginLeft:-2,marginRight:-2},COMPACT_DISC={width:COMPACT_DISC_SIZE,height:COMPACT_DISC_SIZE,borderRadius:COMPACT_DISC_SIZE/2};function Composer({send:send,draftScope:draftScope,stop:stop,isStreaming:isStreaming,inputRef:inputRef,conversationId:conversationId2,seed:seed,draftStore:draftStore,attachments:attachments,onPreview:onPreview,dictation:dictation,pet:pet,telemetry:telemetry,mood:mood="ask",compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false,children:children}){let{theme:theme,styles:styles}=useChatTheme(),[draft,setDraft]=useChatDraft(draftScope,conversationId2,seed);usePersistedDraft(draftStore,conversationId2===null?null:String(conversationId2),draft,setDraft);let[focused,setFocused]=useState(false),placeholder=composerPlaceholder(theme.meta.placeholder,mood,pet?.name,petPlaceholder),phrases=useMemo(()=>buildDictationPhrases({name:pet?.name??null,breed:pet?.breed??null}),[pet?.name,pet?.breed]),voice=useDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active,fileInput=useRef(null),liveUrls=useRef(/* @__PURE__ */new Set),sentUrls=useRef(/* @__PURE__ */new Set);useEffect(()=>()=>{for(let url of liveUrls.current)revokeObjectUrl(url);for(let url of sentUrls.current)revokeObjectUrl(url)},[]);let onPick=useCallback(event=>{if(attachments===null)return;let files=Array.from(event.target.files??[]);if(event.target.value="",files.length===0)return;attachments.dismissRejected();let handles=files.map(fileToAttachmentHandle),outcomes=attachments.add(handles);handles.forEach((handle,index)=>{outcomes[index]?.ok===true?liveUrls.current.add(handle.uri):revokeObjectUrl(handle.uri)})},[attachments]),onRemove=useCallback(id=>{if(attachments===null)return;let row=attachments.attachments.find(entry=>entry.id===id);attachments.remove(id),row!==void 0&&liveUrls.current.delete(row.previewUri)&&revokeObjectUrl(row.previewUri)},[attachments]),uploading=attachments!==null&&attachments.uploading,uploadFailed=attachments!==null&&attachments.failed,uploadBlocked=uploading||uploadFailed,isOverLimit=useMemo(()=>[...draft].length>MESSAGE_MAX_CHARS,[draft]),onSend=useCallback(()=>{if(draft.trim().length===0||[...draft].length>MESSAGE_MAX_CHARS||uploadBlocked)return;dictating&&cancelDictation();let images=attachments===null?NO_IMAGES:attachments.attachments.flatMap(row=>row.status==="uploaded"?[{uri:row.previewUri,filename:row.filename}]:[]);for(let image of images)liveUrls.current.delete(image.uri),sentUrls.current.add(image.uri);send(draft,images),setDraft("")},[draft,send,uploadBlocked,dictating,cancelDictation,attachments,setDraft]),onStop=useCallback(()=>{stop()},[stop]),onKeyDown2=useCallback(event=>{event.key!=="Enter"||event.shiftKey||event.altKey||event.ctrlKey||event.metaKey||event.nativeEvent.isComposing||(event.preventDefault(),onSend())},[onSend]),onChange=useCallback(event=>{dictating&&cancelDictation(),setDraft(event.target.value)},[dictating,cancelDictation,setDraft]);useLayoutEffect(()=>{let node=inputRef.current;node!==null&&(node.style.height="auto",node.style.height=`${Math.min(node.scrollHeight,INPUT_MAX_HEIGHT)}px`)},[draft,inputRef]);let sendBlocked=isOverLimit||uploadBlocked||draft.trim().length===0,sendDimmed=isOverLimit||uploadBlocked||dimEmptySend&&draft.trim().length===0,attachFull=attachments!==null&&attachments.attachments.length>=attachments.maxPerMessage,onPillPress=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),inputRef.current?.focus())},[inputRef]),sendInk=sendGlyphInk(theme);/* @__PURE__ */
|
|
392
302
|
return jsxs("div",{style:compact?{...styles.composerBlock,...COMPACT_BLOCK}:styles.composerBlock,children:[uploadFailed?/* @__PURE__ */jsx("p",{role:"alert",style:styles.composerError,children:CHAT_COPY.attachmentsFailedBlocked}):null,attachments!==null&&attachments.rejected!==null?/* @__PURE__ */jsx("p",{role:"alert",style:styles.composerError,children:attachmentErrorMessage(attachments.rejected)}):null,voice.supported&&voice.error!==null?/* @__PURE__ */jsx("p",{role:"alert",style:styles.composerError,children:dictationErrorMessage(voice.error)}):null,attachments!==null?/* @__PURE__ */jsx(AttachmentTray,{attachments:attachments.attachments,onRetry:attachments.retry,onRemove:onRemove,onPreview:onPreview}):null,
|
|
393
303
|
/* @__PURE__ */jsxs("div",{style:{...styles.composer,...attachments!==null?{paddingLeft:theme.space.sm}:null,...compact?COMPACT_PILL:null,...focused?styles.composerFocused:null},onMouseDown:onPillPress,children:[attachments!==null?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
394
304
|
/* @__PURE__ */jsx("input",{ref:fileInput,type:"file",accept:ATTACHMENT_ACCEPT,multiple:attachments.maxPerMessage>1,onChange:onPick,tabIndex:-1,"aria-hidden":"true",style:VISUALLY_HIDDEN}),
|
|
395
305
|
/* @__PURE__ */jsx("button",{type:"button",onClick:()=>fileInput.current?.click(),"aria-label":attachControlLabel(attachments.attachments.length,attachments.maxPerMessage),"aria-disabled":attachFull,style:{...styles.iconControl,...compact?COMPACT_ATTACH:null,...attachFull?styles.actionButtonDisabled:null},children:/* @__PURE__ */jsx(Glyph,{name:"upload",size:compact?COMPACT_ATTACH_GLYPH:ATTACH_GLYPH_SIZE,color:theme.color.brandInk})})]}):null,
|
|
396
306
|
/* @__PURE__ */jsxs("div",{style:styles.inputWrap,children:[draft.length===0?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.placeholder,children:placeholder}):null,
|
|
397
307
|
/* @__PURE__ */jsx("textarea",{ref:inputRef,rows:1,value:draft,onChange:onChange,onKeyDown:onKeyDown2,onFocus:()=>setFocused(true),onBlur:()=>setFocused(false),"data-ef-focus-ring":"self","aria-label":CHAT_COPY.composerLabel,"aria-description":placeholder,style:styles.input})]}),voice.supported?/* @__PURE__ */jsx(DictationButton,{active:voice.active,listening:voice.status==="listening",elapsedMs:voice.elapsedMs,onToggle:voice.toggle}):null,isStreaming?/* @__PURE__ */jsx("button",{type:"button",onClick:onStop,"aria-label":CHAT_COPY.stop,style:{...styles.actionButton,...compact?COMPACT_SEND:null},children:/* @__PURE__ */jsx("span",{"data-everfur-send-disc":"",style:{...styles.sendDisc,...compact?COMPACT_DISC:null},children:/* @__PURE__ */jsx(Glyph,{name:"square",size:STOP_GLYPH_SIZE,color:sendInk,fill:sendInk})})}):/* @__PURE__ */jsx("button",{type:"button",onClick:onSend,"aria-label":CHAT_COPY.send,"aria-disabled":sendBlocked,style:{...styles.actionButton,...compact?COMPACT_SEND:null,...sendDimmed?styles.actionButtonDisabled:null},children:/* @__PURE__ */jsx("span",{"data-everfur-send-disc":"",style:{...styles.sendDisc,...compact?COMPACT_DISC:null},children:compact?/* @__PURE__ */jsx(Glyph,{name:"arrowUp",size:COMPACT_SEND_GLYPH,color:sendInk,strokeWidth:2.3}):/* @__PURE__ */jsx(Glyph,{name:"send",size:SEND_GLYPH_SIZE,color:sendInk})})})]}),children]})}var WEB_ATTACHMENT_TRANSPORT=createWebAttachmentTransport(),NO_IMAGES2=/* @__PURE__ */Object.freeze([]),TELEVET_HOST_SCOPE=/* @__PURE__ */Object.freeze({display:"contents"});function EverfurChat(props){let{style:style,className:className,renderPending:renderPending}=props;/* @__PURE__ */
|
|
398
|
-
return jsx(CapabilityGate,{capability:"chat",style:style,className:className,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(CitationLinksScope,{onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(ChatLayoutScope,{headingLevel:props.headingLevel,children:/* @__PURE__ */jsx(ChatBody,{...props})})})})}function ChatBody(props){let{petRef:petRef2,conversationId:conversationId2,style:style,className:className,renderPending:renderPending,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer}=props,maxPerMessage=props.attachments===false?void 0:props.attachments?.maxPerMessage,{presentation:hostPresentation,dictation:dictation,attachments:attachmentsProp,topCard:hostTopCard}=props,{presentation:presentation,isLocked:isLocked2}=useEverfurPresentationState(definedPresentation({...hostPresentation,chatComposerMic:hostPresentation?.chatComposerMic??(dictation===void 0?void 0:dictation!==false),chatComposerUpload:hostPresentation?.chatComposerUpload??(attachmentsProp===void 0?void 0:attachmentsProp!==false)})),attachmentsEnabled=presentation.chatComposerUpload,dictationEnabled=presentation.chatComposerMic,answerFooter=presentation.safetyDisclaimerPlacement==="answer_footer",sheet=presentation.chatHistoryStyle==="sheet",topCardState=useTopCardState(),{activePet:activePet}=useEverfurContext(),planPetRef=petRef2??activePet??null,planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&hostTopCard===void 0&&planEnabled,planPage=useHealthPlanPage({petRef:planPetRef,enabled:wantsPlan}),onOpenHealthPlan=props.onOpenHealthPlan,resultsCard=props.resultsCard,openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>wantsPlan&&planPage.phase==="ready"?healthPlanTopCard2(planPage.page,{onOpenPlan:openPlan,...resultsCard===void 0?{}:{results:resultsCard}}):void 0,[wantsPlan,planPage.phase,planPage.page,openPlan,resultsCard]),topCard=hostTopCard??planCard,showTopCard=topCard!==void 0&&presentation.chatTopCard==="focus",{theme:theme,styles:styles}=useChatTheme(),hostPoweredBy=useHostPoweredBy(),{starterPrompts:starterPrompts,renderEmptyHeader:renderEmptyHeader,emptyState:emptyState,initialAskCard:initialAskCard,answerCards:answerCards}=props,countLocked=isLocked2("chatFollowUpCount"),followUpPolicy=useMemo(()=>followUpPolicyFor(props.followUpPolicy,presentation,countLocked),[props.followUpPolicy,presentation,countLocked]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),historyBar=useMemo(()=>{let bar=props.historyBar;return bar===void 0||!showTopCard||topCard===void 0?bar:{...bar,extra:/* @__PURE__ */jsxs(Fragment,{children:[bar.extra??null,
|
|
399
|
-
/* @__PURE__ */jsx(TopCardPill,{card:topCard,state:topCardState})]})}},[props.historyBar,showTopCard,topCard,topCardState]),chatOpts=useMemo(()=>buildChatOpts(petRef2,conversationId2),[petRef2,conversationId2]),chat=useEverfurChat(chatOpts),view=selectView2(chat),pets=useEverfurPets(),headerPet=useMemo(()=>headerPetOf(pets.pets,chat.petRef),[pets.pets,chat.petRef]),disclaimerClass=answerCards?.classNames?.disclaimer,footnoteInThread=answerFooter&&(view==="populated"||view==="empty"),barInThread=presentation.chatHistoryBar==="scroll"&&(view==="populated"||view==="empty"),footnote=/* @__PURE__ */jsx("p",{role:"note","data-everfur-footnote":"",className:footnoteInThread?disclaimerClass:void 0,style:footnoteInThread&&disclaimerClass?void 0:styles.footnote,children:forPet(CHAT_COPY.footnoteWeb,headerPet?.name)}),history=useHistoryPanel(chat),historyTrigger=useRef(null),threadEmpty=chat.messages.length===0,unread=(chat.hasUnreadThreads??false)||(chat.unreadCount??0)>0||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0),historyBarNode=useMemo(()=>historyBar===void 0?null:/* @__PURE__ */jsx(HistoryBar,{bar:historyBar,history:history,triggerRef:historyTrigger,empty:threadEmpty,unread:unread}),[historyBar,history,threadEmpty,unread]),textingAsk=useChatTextingAsk(presentation.chatTextingAsk,chat,presentation.chatTextingAsk&&props.textingEntry!==false,props.header===false),onTopCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),emptyOptions=useMemo(()=>({...starterPrompts!==void 0?{starterPrompts:starterPrompts}:{},...renderEmptyHeader!==void 0?{renderEmptyHeader:renderEmptyHeader}:{},...emptyState!==void 0?{emptyState:emptyState}:{},...followUpPolicy!==void 0?{followUpPolicy:followUpPolicy}:{},...initialAskCard!==void 0&&askPrompt!==null?{openingCard:{card:initialAskCard,prompt:askPrompt}}:{},...presentation.chatAnswerStyle==="cards"?{answerStyle:"cards",answerCards:answerCards}:{},...footnoteInThread?{answerFooter:footnote}:{},...showTopCard&&topCard!==void 0?{topCard:/* @__PURE__ */jsx(TopCard,{card:topCard,state:topCardState,ask:onTopCardAsk})}:{},...barInThread&&historyBarNode!==null?{threadTop:historyBarNode}:{},...textingAsk.line!==null?{threadAside:textingAsk.line,...textingAsk.stage!==null?{threadAsideKey:textingAsk.stage}:{}}:{}}),[starterPrompts,renderEmptyHeader,emptyState,followUpPolicy,initialAskCard,askPrompt,presentation.chatAnswerStyle,answerCards,footnoteInThread,headerPet?.name,disclaimerClass,showTopCard,topCard,topCardState,onTopCardAsk,barInThread,historyBarNode,textingAsk.line,textingAsk.stage]),inputRef=useRef(null),context=useEverfurContext(),announcement=useReplyAnnouncement(chat,headerPet?.name??null),addPet=useMemo(()=>onAddPet===void 0?null:()=>{callHost(onAddPet)},[onAddPet]),onSelectPet=useCallback(next=>{context.handle.setActivePet(next),callHost(onPetChange,next)},[context.handle,onPetChange]),barShown=historyBar!==void 0,historyLoad=history.load,historyOpen=history.open;useEffect(()=>{barShown&&!historyOpen&&historyLoad()},[barShown,historyOpen,chat.conversationId,historyLoad]);let layout=useChatLayout();useCheckinTarget(chat.openCheckin,checkinTarget),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),lifecyclePort=useMemo(()=>lifecycle===void 0?createBrowserLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refresh:chat.refreshActiveThread});let urgency=useUrgencySurface(useMemo(()=>latestUrgencySource(chat.messages),[chat.messages])),vetOptions=useMemo(()=>chatVetVisitOptions(chat.petRef,vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer}),[chat.petRef,vetReturnTo,vetUsState,vetPrefer]),vetVisit=useVetVisit(vetOptions),openVetVisit=vetVisit.open,vetEntry=useMemo(()=>({available:vetVisit.available,open:()=>{openVetVisit()}}),[vetVisit.available,openVetVisit]),checkinFindVet=useMemo(()=>vetEntry.available?vetEntry.open:onFindVet!==void 0?()=>{callHost(onFindVet,"emergency")}:null,[vetEntry,onFindVet]),vetPrep=useMemo(()=>onVetPrep!==void 0?()=>{callHost(onVetPrep,chat.petRef)}:vetEntry.available?vetEntry.open:null,[onVetPrep,chat.petRef,vetEntry]),attachments=useChatAttachments({transport:WEB_ATTACHMENT_TRANSPORT,...maxPerMessage!==void 0?{maxPerMessage:maxPerMessage}:{}}),sentImages=useSentImages(chat.messages),[lightbox,setLightbox]=useState(null),lightboxTrigger=useRef(null),onPreview=useCallback((image,trigger)=>{lightboxTrigger.current=trigger,setLightbox(image)},[]),closeLightbox=useCallback(()=>setLightbox(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt),inputRef.current?.focus()},[chat.send]),onSend=useCallback((text3,images)=>{sentImages.record(text3,images),attachments.s3Keys.length>0?chat.send(text3,{imageS3Keys:attachments.s3Keys}):chat.send(text3),attachments.clear()},[chat.send,attachments,sentImages]),telemetry=context.runtime.registry?.services?.telemetry??null,rootRef=useRef(null);return useKeyboardFocusRing(rootRef,theme.color.brandInk),useMeasuredLayout(rootRef),/* @__PURE__ */jsxs("div",{ref:rootRef,className:className,style:{...styles.container,...style},children:[props.header===false?null:/* @__PURE__ */jsx(ChatHeader,{pets:pets.pets,activePet:headerPet,unread:unread,onOpenHistory:history.open?history.close:history.show,historyTriggerRef:historyTrigger,onSelectPet:onSelectPet,onAddPet:addPet,rail:layout.rail,historyOpen:history.open,onNewChat:history.newConversation,vetEntry:vetEntry.available?vetEntry.open:null,textingEntry:textingAsk.headerEntry}),pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef2??null,pet:pet,onRegistered:pets.refresh}):null,
|
|
308
|
+
return jsx(CapabilityGate,{capability:"chat",style:style,className:className,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(CitationLinksScope,{onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(MessageLinksScope,{linkHosts:props.linkHosts,onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(ChatLayoutScope,{headingLevel:props.headingLevel,children:/* @__PURE__ */jsx(ChatBody,{...props})})})})})}function ChatBody(props){let{petRef:petRef2,conversationId:conversationId2,style:style,className:className,renderPending:renderPending,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,handoffToken:handoffToken,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,openUnreadOnRefresh:openUnreadOnRefresh,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer}=props,maxPerMessage=props.attachments===false?void 0:props.attachments?.maxPerMessage,{presentation:hostPresentation,dictation:dictation,attachments:attachmentsProp,topCard:hostTopCard}=props,{presentation:presentation,isLocked:isLocked2}=useEverfurPresentationState(definedPresentation({...hostPresentation,chatComposerMic:hostPresentation?.chatComposerMic??(dictation===void 0?void 0:dictation!==false),chatComposerUpload:hostPresentation?.chatComposerUpload??(attachmentsProp===void 0?void 0:attachmentsProp!==false)})),attachmentsEnabled=presentation.chatComposerUpload,dictationEnabled=presentation.chatComposerMic,answerFooter=presentation.safetyDisclaimerPlacement==="answer_footer",sheet=presentation.chatHistoryStyle==="sheet",topCardState=useTopCardState(),{activePet:activePet}=useEverfurContext(),planPetRef=petRef2??activePet??null,planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&hostTopCard===void 0&&planEnabled,planPage=useHealthPlanPage({petRef:planPetRef,enabled:wantsPlan}),onOpenHealthPlan=props.onOpenHealthPlan,resultsCard=props.resultsCard,openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>wantsPlan&&planPage.phase==="ready"?healthPlanTopCard2(planPage.page,{onOpenPlan:openPlan,...resultsCard===void 0?{}:{results:resultsCard}}):void 0,[wantsPlan,planPage.phase,planPage.page,openPlan,resultsCard]),topCard=hostTopCard??planCard,showTopCard=topCard!==void 0&&presentation.chatTopCard==="focus",{theme:theme,styles:styles}=useChatTheme(),hostPoweredBy=useHostPoweredBy(),{starterPrompts:starterPrompts,renderEmptyHeader:renderEmptyHeader,emptyState:emptyState,initialAskCard:initialAskCard,answerCards:answerCards}=props,countLocked=isLocked2("chatFollowUpCount"),followUpPolicy=useMemo(()=>followUpPolicyFor(props.followUpPolicy,presentation,countLocked),[props.followUpPolicy,presentation,countLocked]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),historyBar=useMemo(()=>{let bar=props.historyBar;return bar===void 0||!showTopCard||topCard===void 0?bar:{...bar,extra:/* @__PURE__ */jsxs(Fragment,{children:[bar.extra??null,
|
|
309
|
+
/* @__PURE__ */jsx(TopCardPill,{card:topCard,state:topCardState})]})}},[props.historyBar,showTopCard,topCard,topCardState]),chatOpts=useMemo(()=>buildChatOpts(petRef2,conversationId2),[petRef2,conversationId2]),chat=useEverfurChat(chatOpts),view=selectView2(chat),pets=useEverfurPets(),headerPet=useMemo(()=>headerPetOf(pets.pets,chat.petRef),[pets.pets,chat.petRef]),disclaimerClass=answerCards?.classNames?.disclaimer,footnoteInThread=answerFooter&&(view==="populated"||view==="empty"),barInThread=presentation.chatHistoryBar==="scroll"&&(view==="populated"||view==="empty"),footnote=/* @__PURE__ */jsx("p",{role:"note","data-everfur-footnote":"",className:footnoteInThread?disclaimerClass:void 0,style:footnoteInThread&&disclaimerClass?void 0:styles.footnote,children:forPet(CHAT_COPY.footnoteWeb,headerPet?.name)}),history=useHistoryPanel(chat),historyTrigger=useRef(null),threadEmpty=chat.messages.length===0,unread=(chat.hasUnreadThreads??false)||(chat.unreadCount??0)>0||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0),historyBarNode=useMemo(()=>historyBar===void 0?null:/* @__PURE__ */jsx(HistoryBar,{bar:historyBar,history:history,triggerRef:historyTrigger,empty:threadEmpty,unread:unread}),[historyBar,history,threadEmpty,unread]),textingAsk=useChatTextingAsk(presentation.chatTextingAsk,chat,presentation.chatTextingAsk&&props.textingEntry!==false,props.header===false),onTopCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),emptyOptions=useMemo(()=>({...starterPrompts!==void 0?{starterPrompts:starterPrompts}:{},...renderEmptyHeader!==void 0?{renderEmptyHeader:renderEmptyHeader}:{},...emptyState!==void 0?{emptyState:emptyState}:{},...followUpPolicy!==void 0?{followUpPolicy:followUpPolicy}:{},...initialAskCard!==void 0&&askPrompt!==null?{openingCard:{card:initialAskCard,prompt:askPrompt}}:{},...presentation.chatAnswerStyle==="cards"?{answerStyle:"cards",answerCards:answerCards}:{},...footnoteInThread?{answerFooter:footnote}:{},...showTopCard&&topCard!==void 0?{topCard:/* @__PURE__ */jsx(TopCard,{card:topCard,state:topCardState,ask:onTopCardAsk})}:{},...barInThread&&historyBarNode!==null?{threadTop:historyBarNode}:{},...textingAsk.line!==null?{threadAside:textingAsk.line,...textingAsk.stage!==null?{threadAsideKey:textingAsk.stage}:{}}:{}}),[starterPrompts,renderEmptyHeader,emptyState,followUpPolicy,initialAskCard,askPrompt,presentation.chatAnswerStyle,answerCards,footnoteInThread,headerPet?.name,disclaimerClass,showTopCard,topCard,topCardState,onTopCardAsk,barInThread,historyBarNode,textingAsk.line,textingAsk.stage]),inputRef=useRef(null),context=useEverfurContext(),announcement=useReplyAnnouncement(chat,headerPet?.name??null),addPet=useMemo(()=>onAddPet===void 0?null:()=>{callHost(onAddPet)},[onAddPet]),onSelectPet=useCallback(next=>{context.handle.setActivePet(next),callHost(onPetChange,next)},[context.handle,onPetChange]),barShown=historyBar!==void 0,historyLoad=history.load,historyOpen=history.open;useEffect(()=>{barShown&&!historyOpen&&historyLoad()},[barShown,historyOpen,chat.conversationId,historyLoad]);let layout=useChatLayout(),handoffTarget=useChatHandoffTarget(handoffToken,context);useCheckinTarget(chat.openCheckin,checkinTarget??handoffTarget,{petRef:chat.petRef,pinned:petRef2!==void 0,ready:!chat.isBootstrapping,selectPet:onSelectPet}),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),lifecyclePort=useMemo(()=>lifecycle===void 0?createBrowserLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refreshesBlankThread:openUnreadOnRefresh===true,refresh:openUnreadOnRefresh===true?()=>chat.refreshActiveThread?.(OPEN_UNREAD_HEAD)??Promise.resolve():chat.refreshActiveThread});let urgency=useUrgencySurface(useMemo(()=>latestUrgencySource(chat.messages),[chat.messages])),vetOptions=useMemo(()=>chatVetVisitOptions(chat.petRef,vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer}),[chat.petRef,vetReturnTo,vetUsState,vetPrefer]),vetVisit=useVetVisit(vetOptions),openVetVisit=vetVisit.open,vetEntry=useMemo(()=>({available:vetVisit.available,open:()=>{openVetVisit()}}),[vetVisit.available,openVetVisit]),checkinFindVet=useMemo(()=>vetEntry.available?vetEntry.open:onFindVet!==void 0?()=>{callHost(onFindVet,"emergency")}:null,[vetEntry,onFindVet]),vetPrep=useMemo(()=>onVetPrep!==void 0?()=>{callHost(onVetPrep,chat.petRef)}:vetEntry.available?vetEntry.open:null,[onVetPrep,chat.petRef,vetEntry]),attachments=useChatAttachments({transport:WEB_ATTACHMENT_TRANSPORT,...maxPerMessage!==void 0?{maxPerMessage:maxPerMessage}:{}}),sentImages=useSentImages(chat.messages),[lightbox,setLightbox]=useState(null),lightboxTrigger=useRef(null),onPreview=useCallback((image,trigger)=>{lightboxTrigger.current=trigger,setLightbox(image)},[]),closeLightbox=useCallback(()=>setLightbox(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt),inputRef.current?.focus()},[chat.send]),onSend=useCallback((text3,images)=>{sentImages.record(text3,images),attachments.s3Keys.length>0?chat.send(text3,{imageS3Keys:attachments.s3Keys}):chat.send(text3),attachments.clear()},[chat.send,attachments,sentImages]),telemetry=context.runtime.registry?.services?.telemetry??null,rootRef=useRef(null);return useKeyboardFocusRing(rootRef,theme.color.brandInk),useMeasuredLayout(rootRef),/* @__PURE__ */jsxs("div",{ref:rootRef,className:className,style:{...styles.container,...style},children:[props.header===false?null:/* @__PURE__ */jsx(ChatHeader,{pets:pets.pets,activePet:headerPet,unread:unread,onOpenHistory:history.open?history.close:history.show,historyTriggerRef:historyTrigger,onSelectPet:onSelectPet,onAddPet:addPet,rail:layout.rail,historyOpen:history.open,onNewChat:history.newConversation,vetEntry:vetEntry.available?vetEntry.open:null,textingEntry:textingAsk.headerEntry}),pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef2??null,pet:pet,onRegistered:pets.refresh}):null,
|
|
400
310
|
/* @__PURE__ */jsxs("div",{style:styles.split,children:[
|
|
401
311
|
/* @__PURE__ */jsxs("div",{style:styles.main,children:[props.header===false?textingAsk.headerEntry:null,barInThread?null:historyBarNode,!presentation.chatGeneralBanner&&urgency.tier?.level==="general"?null:/* @__PURE__ */jsx(UrgencyBanner,{surface:urgency,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}),
|
|
402
312
|
/* @__PURE__ */jsx("div",{style:styles.body,children:renderView(view,chat,onSelectPrompt,renderPending,headerPet,vetPrep,sentImages.imagesFor,onPreview,addPet,checkinFindVet,emptyOptions)}),textingAsk.runner,textingAsk.entry!==null?/* @__PURE__ */jsxs("div",{style:styles.composerBlock,children:[textingAsk.entry,footnoteInThread?null:footnote]}):/* @__PURE__ */jsx(Composer,{send:onSend,draftScope:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,inputRef:inputRef,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,attachments:attachmentsEnabled&&attachments.available?attachments:null,onPreview:onPreview,dictation:dictationEnabled,pet:headerPet,telemetry:telemetry,mood:composerMood(view,urgency.source?.level??null),compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",children:footnoteInThread?null:footnote}),theme.meta.hidePoweredBy||hostPoweredBy?null:/* @__PURE__ */jsx("p",{style:styles.poweredBy,children:CHAT_COPY.poweredBy})]}),sheet?null:/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history,mode:layout.rail?"rail":"dialog",returnFocusTo:historyTrigger})]}),
|
|
403
313
|
/* @__PURE__ */jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:VISUALLY_HIDDEN,children:announcement}),sheet?/* @__PURE__ */jsx(HistorySheet,{chat:chat,history:history,sheet:props.historySheet,returnFocusTo:historyTrigger}):null,
|
|
404
314
|
/* @__PURE__ */jsx(AttachmentImageLightbox,{image:lightbox,onClose:closeLightbox,returnFocusTo:lightboxTrigger}),
|
|
405
|
-
/* @__PURE__ */jsx("div",{"data-ef-focus-ring":"self",style:TELEVET_HOST_SCOPE,children:/* @__PURE__ */jsx(EverfurTelevetHost,{})})]})}function useSentImages(messages){let store=useRef({pending:[],byMessage:/* @__PURE__ */new Map}),latest=useRef(messages);latest.current=messages;let
|
|
315
|
+
/* @__PURE__ */jsx("div",{"data-ef-focus-ring":"self",style:TELEVET_HOST_SCOPE,children:/* @__PURE__ */jsx(EverfurTelevetHost,{})})]})}function useSentImages(messages){let store=useRef({pending:[],byMessage:/* @__PURE__ */new Map}),latest=useRef(messages);latest.current=messages;let record2=useCallback((text3,images)=>{images.length!==0&&store.current.pending.push({text:text3,images:images,before:new Set(latest.current.map(message=>message.id))})},[]),imagesFor=useCallback(message=>{let current=store.current,known=current.byMessage.get(message.id);if(known!==void 0)return known;if(message.role!=="user")return NO_IMAGES2;let at=current.pending.findIndex(entry2=>entry2.text===message.text&&!entry2.before.has(message.id));if(at<0)return NO_IMAGES2;let[entry]=current.pending.splice(at,1);return entry===void 0?NO_IMAGES2:(current.byMessage.set(message.id,entry.images),entry.images)},[]);return useMemo(()=>({record:record2,imagesFor:imagesFor}),[record2,imagesFor])}function useReplyAnnouncement(chat,petName){let awaiting=awaitingAssistant(chat.messages,chat.isStreaming),[settled,setSettled]=useState({send:chat.send,id:chat.conversationId,text:""}),wasStreaming=useRef(false),previousScope=useRef({send:chat.send,id:chat.conversationId});return useEffect(()=>{let previous=previousScope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),previousScope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];setSettled({send:chat.send,id:chat.conversationId,text:last!==void 0&&last.role==="assistant"?CHAT_COPY.answered:""})}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId]),awaiting?forPet(CHAT_COPY.reading,petName):settled.send===chat.send&&settled.id===chat.conversationId?settled.text:""}function composerMood(view,level){return level==="emergency"?"urgent":view==="populated"?"followUp":"ask"}function PetSetupNotice({petRef:petRef2,pet:pet,onRegistered:onRegistered}){let{styles:styles}=useChatTheme(),setup=useChatPetRegistration(petRef2,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxs("div",{role:"alert",style:styles.setupNotice,children:[
|
|
406
316
|
/* @__PURE__ */jsx("span",{style:styles.setupNoticeText,children:setup.error.displayMessage}),
|
|
407
|
-
/* @__PURE__ */jsx("button",{type:"button",onClick:setup.retry,style:styles.setupNoticeAction,children:CHAT_COPY.retry})]})}var SIGNALS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanSignals@v1"),signalHost=globalThis;function isSignalState(value){if(typeof value!="object"||value===null)return false;let v=value;return v.landed instanceof Set&&v.noVet instanceof Set&&v.noVetByPet instanceof Map}var stored=signalHost[SIGNALS_SYMBOL],fresh2=()=>({landed:/* @__PURE__ */new Set,noVet:/* @__PURE__ */new Set,noVetByPet:/* @__PURE__ */new Map}),state=isSignalState(stored)?stored:signalHost[SIGNALS_SYMBOL]=fresh2(),landedListeners=state.landed,noVetListeners=state.noVet,noVetByPet=state.noVetByPet;function notifyHealthPlanRecordsLanded(petRef2,source="host"){for(let listener of[...landedListeners])try{listener(petRef2,source)}catch{}}function onHealthPlanRecordsLanded(listener){return landedListeners.add(listener),()=>{landedListeners.delete(listener)}}function setHealthPlanNoVet(petRef2,noVet){if((noVetByPet.get(petRef2)??false)!==noVet){noVet?noVetByPet.set(petRef2,true):noVetByPet.delete(petRef2);for(let listener of[...noVetListeners])try{listener(petRef2,noVet)}catch{}}}function healthPlanNoVet(petRef2){return noVetByPet.get(petRef2)??false}function onHealthPlanNoVet(listener){return noVetListeners.add(listener),()=>{noVetListeners.delete(listener)}}var INTRO_PATH="/widget/v1/me/intro";function disposed2(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function malformed5(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the documented shape`})}function introStateFromWire(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let o=raw;if(!("seen_at"in o))return null;let at=o.seen_at;return at===null?/* @__PURE__ */Object.freeze({seenAt:null}):typeof at!="string"||at.length===0||at.length>64||Number.isNaN(Date.parse(at))?null:/* @__PURE__ */Object.freeze({seenAt:at})}function createIntroRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createIntroRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{read:opts=>runtime.isDisposed?gone("read"):over().read(opts),markSeen:()=>runtime.isDisposed?gone("markSeen"):over().markSeen()}}function createIntroRepositoryOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),call=async(name,req,opts)=>{let res=await funnel.send(name,req,opts);if(!res.ok)return err(res.error);let state3=introStateFromWire(res.value);return state3===null?err(malformed5(name)):ok(state3)};return{read(opts){let req=opts?.signal?{method:"GET",path:INTRO_PATH,signal:opts.signal}:{method:"GET",path:INTRO_PATH};return call("intro.read",req,{maxAttempts:1})},markSeen(){return call("intro.markSeen",{method:"PUT",path:INTRO_PATH,body:{seen:true}})}}}var INTRO_SEEN_KV_PREFIX="everfur.intro.seen.v1:",keyFor=userRef2=>`${INTRO_SEEN_KV_PREFIX}${userRef2}`;async function readIntroSeenLocally(kv,userRef2){try{return await kv.getItem(keyFor(userRef2))!==null}catch{return false}}async function keepIntroSeenLocally(kv,userRef2,at){try{await kv.setItem(keyFor(userRef2),at)}catch{}}async function shouldPlayIntro(deps){let{repo:repo,kv:kv,userRef:userRef2,signal:signal}=deps;if(userRef2===null||await readIntroSeenLocally(kv,userRef2))return false;let read;try{read=await repo.read(signal?{signal:signal}:void 0)}catch{return false}return signal?.aborted===true||!read.ok?false:read.value.seenAt!==null?(await keepIntroSeenLocally(kv,userRef2,read.value.seenAt),false):true}async function markIntroSeen(deps){let{repo:repo,kv:kv,userRef:userRef2}=deps;if(userRef2!==null){await keepIntroSeenLocally(kv,userRef2,(deps.now?.()??/* @__PURE__ */new Date).toISOString());try{await repo.markSeen()}catch{}}}function mix2(color,share,ground){let over=withAlpha(color,share);return(over===null?null:flattenOnto(over,ground))??ground}function askIntroColors(theme){let v=v3Palette(theme),c=theme.color,card=v.card;return{ink:v.ink,ink2:v.ink2,ink3:v.ink3,paper:v.paper,tile:v.tile,line:v.line,card:card,onInk:v.dark?c.background:"#FFFFFF",primary:v.primary,onPrimary:v.onPrimary,accent:v.accent,onAccent:v3InkOn(v.accent,[v.ink,v.onAccent]),accent2:mix2(v.accent,.75,card),accent4:mix2(v.accent,.17,card),accentChip:mix2(v.accent,.47,card),link:v.link,linkChip:mix2(v.link,.2,card),riskDot:v.riskDot,riskChip:v.dark?c.badgeBgCritical:"#FFD8D6",clearBg:v.clearBg,clearInk:v.clearInk,clearChip:v.dark?c.badgeBgPositive:"#DDEFC4",byInk:c.brandInk}}function askIntroTokens(theme){return{...askIntroColors(theme),sans:faceCss(theme,"regular").fontFamily,serif:headingFaceCss(theme,"bold").fontFamily,mono:cssMonoFamily(theme.type.mono)}}var warned4=/* @__PURE__ */new Set;function warnUnknownRule(key){warned4.has(key)||!isWebDevelopment()||(warned4.add(key),globalThis.console?.warn?.(`[everfur] unknown style rule ${key}`))}var camel=prop=>prop.startsWith("--")?prop:prop.replace(/-([a-z])/g,(_m,ch)=>ch.toUpperCase());function askIntroSx(theme,rules,reduced){let tokens=askIntroTokens(theme),dark=theme.brightness==="dark",fill2=value=>value.replace(/\$(n_[0-9A-F]{6}|[a-zA-Z0-9]+)/g,(whole,key)=>key.startsWith("n_")?dark?tokens.line??whole:`#${key.slice(2)}`:tokens[key]??whole),cache2=/* @__PURE__ */new Map;return(...selectors)=>{let keys=selectors.filter(s=>typeof s=="string"&&s!==""),id=keys.join("|"),hit=cache2.get(id);if(hit!==void 0)return hit;let out={};for(let key of keys){let decls=rules[key];if(decls===void 0){warnUnknownRule(key);continue}for(let[prop,value]of decls)out[camel(prop)]=fill2(value);if(theme.motion.reducedMotion)for(let[prop,value]of reduced[key]??[])out[camel(prop)]=fill2(value)}let style=/* @__PURE__ */Object.freeze(out);return cache2.set(id,style),style}}function askIntroReset(theme){let tokens=askIntroTokens(theme);return{root:{boxSizing:"border-box",fontFamily:tokens.sans,fontSize:17,lineHeight:1.5,color:tokens.ink,WebkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",fontVariationSettings:'"SOFT" 0, "WONK" 0',fontVariantLigatures:"no-common-ligatures"},button:{boxSizing:"border-box",font:"inherit",color:"inherit",background:"none",border:0,padding:0,margin:0,cursor:"pointer",textAlign:"inherit",WebkitTapHighlightColor:"transparent",touchAction:"manipulation"},text:{margin:0,boxSizing:"border-box"},srOnly:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"}}}var INTRO_OPEN_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#IntroOpen@v1"),host=globalThis;function isIntroOpenState(value){if(typeof value!="object"||value===null)return false;let v=value;return v.holds instanceof Set&&v.listeners instanceof Set}var stored2=host[INTRO_OPEN_SYMBOL],fresh3=()=>({holds:/* @__PURE__ */new Set,listeners:/* @__PURE__ */new Set}),state2=isIntroOpenState(stored2)?stored2:host[INTRO_OPEN_SYMBOL]=fresh3();function notify2(){for(let listener of[...state2.listeners])try{listener()}catch{}}function holdIntroOpen(){let token={};return state2.holds.add(token),state2.holds.size===1&¬ify2(),()=>{state2.holds.delete(token)&&state2.holds.size===0&¬ify2()}}function useIntroOpenHold(held){useEffect(()=>held?holdIntroOpen():void 0,[held])}var EVERFUR_RECORDS_REQUESTED_EVENT="everfur:records-requested",EVERFUR_RECORDS_LANDED_EVENT="everfur:records-landed";function emitRecordsEvent(name,detail){try{if(typeof window>"u"||typeof CustomEvent!="function")return;window.dispatchEvent(new CustomEvent(name,{detail:detail}))}catch{}}function healthPlanPageDrawsWithoutItems(design){return design!=null&&(design.wait!==void 0||design.pick.hidden===true)}var EVERFUR_TABS_COPY=/* @__PURE__ */Object.freeze({ask:"Ask",plan:"Health Plan",records:"Records",listAll:"Ask, Health Plan and Records",listNoPlan:"Ask and Records"}),ALL=/* @__PURE__ */Object.freeze(["ask","plan","records"]),NO_PLAN=/* @__PURE__ */Object.freeze(["ask","records"]);function tabsFor(planHidden){return planHidden?NO_PLAN:ALL}function resolveTab(wanted,planHidden){return wanted==="plan"&&planHidden?"ask":wanted}function landingTab(opened,planHidden){return opened.via==="link"?resolveTab(opened.ask!==void 0?"ask":opened.tab,planHidden):resolveTab("plan",planHidden)}function openedKey(opened){let key=opened.key===void 0?"":String(opened.key);return opened.via==="link"?`link:${opened.tab}:${opened.ask?.prompt??""}:${key}`:`plain:${key}`}function tabKeyTarget(tabs,current,key){let at=Math.max(0,tabs.indexOf(current)),n=tabs.length;if(n===0)return null;let to=key==="ArrowRight"?(at+1)%n:key==="ArrowLeft"?(at-1+n)%n:key==="Home"?0:key==="End"?n-1:-1;return to<0?null:tabs[to]??null}var PLAN_STALE_MS=6e4;function isPlanReadStale(lastReadAt,now,staleMs=PLAN_STALE_MS){return lastReadAt!==null&&now-lastReadAt>=staleMs}function isPlanReturnReadDue(read){return read.pageVisible&&read.watching&&isPlanReadStale(read.lastReadAt,read.now)}function stableJson(value){return JSON.stringify(value,(_key,field)=>{if(field===null||typeof field!="object"||Array.isArray(field))return field;let sorted={};for(let key of Object.keys(field).sort())sorted[key]=field[key];return sorted})}function planSignature(plan){if(plan===null)return"";let items=plan.items.map(item=>[item.productId,item.partnerSku,item.title,item.description,item.category,item.price,item.currency,item.imageUrl,item.url,item.sample]).sort((a,b)=>a[0]<b[0]?-1:a[0]>b[0]?1:0);return JSON.stringify([plan.headline,items])}function pageSignature(page){return page===null?"":stableJson([page.checkout,page.page])}function readSignature(plan,page){return JSON.stringify([planSignature(plan),pageSignature(page)])}function isPlanReadSettled(planStatus,pagePhase){return planStatus!=="empty"&&planStatus!=="ready"?false:pagePhase==="ready"||pagePhase==="failed"||pagePhase==="idle"}function isPlanReadEmpty(planStatus,page){return planStatus==="empty"&&!healthPlanPageDrawsWithoutItems(page?.page)}function nextPlanVerdict(previous,read){return previous===void 0?{empty:read.empty,signature:read.signature,epoch:0}:previous.empty===read.empty&&previous.signature===read.signature?previous:{empty:read.empty,signature:read.signature,epoch:previous.signature===read.signature?previous.epoch:previous.epoch+1}}var INTRO_WAIT_MS=5e3;function introWantStep(state3){return state3.sameOpen?state3.plan===void 0?state3.planFailed?"drop":"wait":state3.plan.empty?"drop":!state3.moduleReady||state3.recordsPending?"wait":"play":"drop"}function createPaneShownSignal(){let listeners3=/* @__PURE__ */new Set;return{listen(listener){let entry=()=>listener();return listeners3.add(entry),()=>{listeners3.delete(entry)}},fire(){for(let listener of[...listeners3])try{listener()}catch{}}}}function withPaneShown(base2,shown){return{...{onForeground(listener){let stopBase=base2.onForeground(listener),stopShown=shown.listen(listener);return()=>{stopShown(),stopBase()}}},...base2.onOnline===void 0?{}:{onOnline:base2.onOnline.bind(base2)},...base2.onAnnounced===void 0?{}:{onAnnounced:base2.onAnnounced.bind(base2)},...base2.isOffline===void 0?{}:{isOffline:base2.isOffline.bind(base2)}}}function isPaneShownEdge(wasShown,shown){return!wasShown&&shown}function planProbeOver(m){return function({petRef:petRef2,pagePhase:pagePhase,page:page,refreshPage:refreshPage,watching:watching,onPlan:onPlan,onPlanFailed:onPlanFailed}){let{status:status,plan:plan,refresh:refresh}=m.useEverfurHealthPlan({petRef:petRef2}),readAt=useRef(null),latest=useRef({plan:refresh,page:refreshPage,watching:watching});latest.current={plan:refresh,page:refreshPage,watching:watching},useEffect(()=>{let settled=isPlanReadSettled(status,pagePhase);(status==="failed"||settled)&&(readAt.current=Date.now()),settled?onPlan(petRef2,{empty:isPlanReadEmpty(status,page),signature:readSignature(plan,page)}):status==="failed"&&onPlanFailed(petRef2)},[status,plan,pagePhase,page,petRef2,onPlan,onPlanFailed]);let readAgainIfDue=useRef(()=>{});return readAgainIfDue.current=()=>{let reads=latest.current,pageVisible=typeof document>"u"||document.visibilityState==="visible";isPlanReturnReadDue({pageVisible:pageVisible,watching:reads.watching,lastReadAt:readAt.current,now:Date.now()})&&(readAt.current=null,reads.plan(),reads.page())},useEffect(()=>{if(typeof document>"u")return;let onVisible=()=>readAgainIfDue.current();return document.addEventListener("visibilitychange",onVisible),()=>document.removeEventListener("visibilitychange",onVisible)},[]),useEffect(()=>{watching&&readAgainIfDue.current()},[watching]),null}}function recordsProbeOver(m){return function({petRef:petRef2,onRecords:onRecords}){let{status:status}=m.useEverfurRecords({petRef:petRef2});return useEffect(()=>{onRecords(petRef2,status==="empty"?"none":status==="populated"?"some":null)},[status,petRef2,onRecords]),null}}function NoPlan({petRef:petRef2,onPlanFailed:onPlanFailed}){return useEffect(()=>onPlanFailed(petRef2),[petRef2,onPlanFailed]),null}function NoRecords({petRef:petRef2,onRecords:onRecords}){return useEffect(()=>onRecords(petRef2,null),[petRef2,onRecords]),null}var LazyPlanProbe=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/health-plan").then(m=>({default:planProbeOver(m)}),()=>({default:NoPlan}))),LazyRecordsProbe=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/records").then(m=>({default:recordsProbeOver(m)}),()=>({default:NoRecords})));function PlanProbe(props){/* @__PURE__ */
|
|
317
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:setup.retry,style:styles.setupNoticeAction,children:CHAT_COPY.retry})]})}var NONE2=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function useUnreadState(petOption,lifecycle){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),store=runtime.unread??null,petRef2=petOption===void 0?activePet:petOption,subscribe2=useCallback(listener=>store===null?NO_SUBSCRIPTION():store.subscribe(listener),[store]),read=useCallback(()=>store===null||userRef2===null?NONE2:store.get(petRef2),[store,userRef2,petRef2]),unread=useSyncExternalStore(subscribe2,read,read),refresh=useCallback(()=>store===null||userRef2===null?Promise.resolve():store.refresh(petRef2),[store,userRef2,petRef2]);return useEffect(()=>{refresh()},[refresh,scopeEpoch]),useChatLifecycle(lifecycle,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:refresh}),useMemo(()=>({...unread,refresh:refresh}),[unread,refresh])}function useEverfurUnread(options={}){let{lifecycle:lifecycle}=options,port=useMemo(()=>lifecycle===void 0?createBrowserLifecycle():lifecycle??void 0,[lifecycle]);return useUnreadState(options.petRef,port)}function takeChatHandoffToken(){let href;try{if(typeof window>"u")return null;href=window.location.href}catch{return null}let scrubbed=withoutChatHandoffToken(href);if(scrubbed===href)return null;try{window.history.replaceState(window.history.state,"",scrubbed)}catch{}return chatHandoffTokenFromUrl(href)}var SIGNALS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanSignals@v1"),signalHost=globalThis;function isSignalState(value){if(typeof value!="object"||value===null)return false;let v=value;return v.landed instanceof Set&&v.noVet instanceof Set&&v.noVetByPet instanceof Map}var stored=signalHost[SIGNALS_SYMBOL],fresh2=()=>({landed:/* @__PURE__ */new Set,noVet:/* @__PURE__ */new Set,noVetByPet:/* @__PURE__ */new Map}),state=isSignalState(stored)?stored:signalHost[SIGNALS_SYMBOL]=fresh2(),landedListeners=state.landed,noVetListeners=state.noVet,noVetByPet=state.noVetByPet;function notifyHealthPlanRecordsLanded(petRef2,source="host"){for(let listener of[...landedListeners])try{listener(petRef2,source)}catch{}}function onHealthPlanRecordsLanded(listener){return landedListeners.add(listener),()=>{landedListeners.delete(listener)}}function setHealthPlanNoVet(petRef2,noVet){if((noVetByPet.get(petRef2)??false)!==noVet){noVet?noVetByPet.set(petRef2,true):noVetByPet.delete(petRef2);for(let listener of[...noVetListeners])try{listener(petRef2,noVet)}catch{}}}function healthPlanNoVet(petRef2){return noVetByPet.get(petRef2)??false}function onHealthPlanNoVet(listener){return noVetListeners.add(listener),()=>{noVetListeners.delete(listener)}}var INTRO_PATH="/widget/v1/me/intro";function disposed2(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function malformed5(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the documented shape`})}function introStateFromWire(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let o=raw;if(!("seen_at"in o))return null;let at=o.seen_at;return at===null?/* @__PURE__ */Object.freeze({seenAt:null}):typeof at!="string"||at.length===0||at.length>64||Number.isNaN(Date.parse(at))?null:/* @__PURE__ */Object.freeze({seenAt:at})}function createIntroRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createIntroRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{read:opts=>runtime.isDisposed?gone("read"):over().read(opts),markSeen:()=>runtime.isDisposed?gone("markSeen"):over().markSeen()}}function createIntroRepositoryOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),call=async(name,req,opts)=>{let res=await funnel.send(name,req,opts);if(!res.ok)return err(res.error);let state3=introStateFromWire(res.value);return state3===null?err(malformed5(name)):ok(state3)};return{read(opts){let req=opts?.signal?{method:"GET",path:INTRO_PATH,signal:opts.signal}:{method:"GET",path:INTRO_PATH};return call("intro.read",req,{maxAttempts:1})},markSeen(){return call("intro.markSeen",{method:"PUT",path:INTRO_PATH,body:{seen:true}})}}}var INTRO_SEEN_KV_PREFIX="everfur.intro.seen.v1:",keyFor=userRef2=>`${INTRO_SEEN_KV_PREFIX}${userRef2}`;async function readIntroSeenLocally(kv,userRef2){try{return await kv.getItem(keyFor(userRef2))!==null}catch{return false}}async function keepIntroSeenLocally(kv,userRef2,at){try{await kv.setItem(keyFor(userRef2),at)}catch{}}async function shouldPlayIntro(deps){let{repo:repo,kv:kv,userRef:userRef2,signal:signal}=deps;if(userRef2===null||await readIntroSeenLocally(kv,userRef2))return false;let read;try{read=await repo.read(signal?{signal:signal}:void 0)}catch{return false}return signal?.aborted===true||!read.ok?false:read.value.seenAt!==null?(await keepIntroSeenLocally(kv,userRef2,read.value.seenAt),false):true}async function markIntroSeen(deps){let{repo:repo,kv:kv,userRef:userRef2}=deps;if(userRef2!==null){await keepIntroSeenLocally(kv,userRef2,(deps.now?.()??/* @__PURE__ */new Date).toISOString());try{await repo.markSeen()}catch{}}}function mix2(color,share,ground){let over=withAlpha(color,share);return(over===null?null:flattenOnto(over,ground))??ground}function askIntroColors(theme){let v=v3Palette(theme),c=theme.color,card=v.card;return{ink:v.ink,ink2:v.ink2,ink3:v.ink3,paper:v.paper,tile:v.tile,line:v.line,card:card,onInk:v.dark?c.background:"#FFFFFF",primary:v.primary,onPrimary:v.onPrimary,accent:v.accent,onAccent:v3InkOn(v.accent,[v.ink,v.onAccent]),accent2:mix2(v.accent,.75,card),accent4:mix2(v.accent,.17,card),accentChip:mix2(v.accent,.47,card),link:v.link,linkChip:mix2(v.link,.2,card),riskDot:v.riskDot,riskChip:v.dark?c.badgeBgCritical:"#FFD8D6",clearBg:v.clearBg,clearInk:v.clearInk,clearChip:v.dark?c.badgeBgPositive:"#DDEFC4",byInk:c.brandInk}}function askIntroTokens(theme){return{...askIntroColors(theme),sans:faceCss(theme,"regular").fontFamily,serif:headingFaceCss(theme,"bold").fontFamily,mono:cssMonoFamily(theme.type.mono)}}var warned4=/* @__PURE__ */new Set;function warnUnknownRule(key){warned4.has(key)||!isWebDevelopment()||(warned4.add(key),globalThis.console?.warn?.(`[everfur] unknown style rule ${key}`))}var camel=prop=>prop.startsWith("--")?prop:prop.replace(/-([a-z])/g,(_m,ch)=>ch.toUpperCase());function askIntroSx(theme,rules,reduced){let tokens=askIntroTokens(theme),dark=theme.brightness==="dark",fill2=value=>value.replace(/\$(n_[0-9A-F]{6}|[a-zA-Z0-9]+)/g,(whole,key)=>key.startsWith("n_")?dark?tokens.line??whole:`#${key.slice(2)}`:tokens[key]??whole),cache2=/* @__PURE__ */new Map;return(...selectors)=>{let keys=selectors.filter(s=>typeof s=="string"&&s!==""),id=keys.join("|"),hit=cache2.get(id);if(hit!==void 0)return hit;let out={};for(let key of keys){let decls=rules[key];if(decls===void 0){warnUnknownRule(key);continue}for(let[prop,value]of decls)out[camel(prop)]=fill2(value);if(theme.motion.reducedMotion)for(let[prop,value]of reduced[key]??[])out[camel(prop)]=fill2(value)}let style=/* @__PURE__ */Object.freeze(out);return cache2.set(id,style),style}}function askIntroReset(theme){let tokens=askIntroTokens(theme);return{root:{boxSizing:"border-box",fontFamily:tokens.sans,fontSize:17,lineHeight:1.5,color:tokens.ink,WebkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",fontVariationSettings:'"SOFT" 0, "WONK" 0',fontVariantLigatures:"no-common-ligatures"},button:{boxSizing:"border-box",font:"inherit",color:"inherit",background:"none",border:0,padding:0,margin:0,cursor:"pointer",textAlign:"inherit",WebkitTapHighlightColor:"transparent",touchAction:"manipulation"},text:{margin:0,boxSizing:"border-box"},srOnly:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"}}}var INTRO_OPEN_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#IntroOpen@v1"),host=globalThis;function isIntroOpenState(value){if(typeof value!="object"||value===null)return false;let v=value;return v.holds instanceof Set&&v.listeners instanceof Set}var stored2=host[INTRO_OPEN_SYMBOL],fresh3=()=>({holds:/* @__PURE__ */new Set,listeners:/* @__PURE__ */new Set}),state2=isIntroOpenState(stored2)?stored2:host[INTRO_OPEN_SYMBOL]=fresh3();function notify2(){for(let listener of[...state2.listeners])try{listener()}catch{}}function holdIntroOpen(){let token={};return state2.holds.add(token),state2.holds.size===1&¬ify2(),()=>{state2.holds.delete(token)&&state2.holds.size===0&¬ify2()}}function useIntroOpenHold(held){useEffect(()=>held?holdIntroOpen():void 0,[held])}var EVERFUR_RECORDS_REQUESTED_EVENT="everfur:records-requested",EVERFUR_RECORDS_LANDED_EVENT="everfur:records-landed";function emitRecordsEvent(name,detail){try{if(typeof window>"u"||typeof CustomEvent!="function")return;window.dispatchEvent(new CustomEvent(name,{detail:detail}))}catch{}}function healthPlanPageDrawsWithoutItems(design){return design!=null&&(design.wait!==void 0||design.pick.hidden===true)}var EVERFUR_TABS_COPY=/* @__PURE__ */Object.freeze({ask:"Ask",plan:"Health Plan",records:"Records",listAll:"Ask, Health Plan and Records",listNoPlan:"Ask and Records"}),ALL=/* @__PURE__ */Object.freeze(["ask","plan","records"]),NO_PLAN=/* @__PURE__ */Object.freeze(["ask","records"]);function tabsFor(planHidden){return planHidden?NO_PLAN:ALL}function resolveTab(wanted,planHidden){return wanted==="plan"&&planHidden?"ask":wanted}function landingTab(opened,planHidden){return opened.via==="link"?resolveTab(opened.ask!==void 0?"ask":opened.tab,planHidden):resolveTab("plan",planHidden)}function openedKey(opened){let key=opened.key===void 0?"":String(opened.key);return opened.via==="link"?`link:${opened.tab}:${opened.ask?.prompt??""}:${key}`:`plain:${key}`}function tabKeyTarget(tabs,current,key){let at=Math.max(0,tabs.indexOf(current)),n=tabs.length;if(n===0)return null;let to=key==="ArrowRight"?(at+1)%n:key==="ArrowLeft"?(at-1+n)%n:key==="Home"?0:key==="End"?n-1:-1;return to<0?null:tabs[to]??null}var PLAN_STALE_MS=6e4;function isPlanReadStale(lastReadAt,now,staleMs=PLAN_STALE_MS){return lastReadAt!==null&&now-lastReadAt>=staleMs}function isPlanReturnReadDue(read){return read.pageVisible&&read.watching&&isPlanReadStale(read.lastReadAt,read.now)}function stableJson(value){return JSON.stringify(value,(_key,field)=>{if(field===null||typeof field!="object"||Array.isArray(field))return field;let sorted={};for(let key of Object.keys(field).sort())sorted[key]=field[key];return sorted})}function planSignature(plan){if(plan===null)return"";let items=plan.items.map(item=>[item.productId,item.partnerSku,item.title,item.description,item.category,item.price,item.currency,item.imageUrl,item.url,item.sample]).sort((a,b)=>a[0]<b[0]?-1:a[0]>b[0]?1:0);return JSON.stringify([plan.headline,items])}function pageSignature(page){return page===null?"":stableJson([page.checkout,page.page])}function readSignature(plan,page){return JSON.stringify([planSignature(plan),pageSignature(page)])}function isPlanReadSettled(planStatus,pagePhase){return planStatus!=="empty"&&planStatus!=="ready"?false:pagePhase==="ready"||pagePhase==="failed"||pagePhase==="idle"}function isPlanReadEmpty(planStatus,page){return planStatus==="empty"&&!healthPlanPageDrawsWithoutItems(page?.page)}function nextPlanVerdict(previous,read){return previous===void 0?{empty:read.empty,signature:read.signature,epoch:0}:previous.empty===read.empty&&previous.signature===read.signature?previous:{empty:read.empty,signature:read.signature,epoch:previous.signature===read.signature?previous.epoch:previous.epoch+1}}var INTRO_WAIT_MS=5e3;function introWantStep(state3){return state3.sameOpen?state3.plan===void 0?state3.planFailed?"drop":"wait":state3.plan.empty?"drop":!state3.moduleReady||state3.recordsPending?"wait":"play":"drop"}function createPaneShownSignal(){let listeners3=/* @__PURE__ */new Set;return{listen(listener){let entry=()=>listener();return listeners3.add(entry),()=>{listeners3.delete(entry)}},fire(){for(let listener of[...listeners3])try{listener()}catch{}}}}function withPaneShown(base2,shown){return{...{onForeground(listener){let stopBase=base2.onForeground(listener),stopShown=shown.listen(listener);return()=>{stopShown(),stopBase()}}},...base2.onOnline===void 0?{}:{onOnline:base2.onOnline.bind(base2)},...base2.onAnnounced===void 0?{}:{onAnnounced:base2.onAnnounced.bind(base2)},...base2.isOffline===void 0?{}:{isOffline:base2.isOffline.bind(base2)}}}function isPaneShownEdge(wasShown,shown){return!wasShown&&shown}function planProbeOver(m){return function({petRef:petRef2,pagePhase:pagePhase,page:page,refreshPage:refreshPage,watching:watching,onPlan:onPlan,onPlanFailed:onPlanFailed}){let{status:status,plan:plan,refresh:refresh}=m.useEverfurHealthPlan({petRef:petRef2}),readAt=useRef(null),latest=useRef({plan:refresh,page:refreshPage,watching:watching});latest.current={plan:refresh,page:refreshPage,watching:watching},useEffect(()=>{let settled=isPlanReadSettled(status,pagePhase);(status==="failed"||settled)&&(readAt.current=Date.now()),settled?onPlan(petRef2,{empty:isPlanReadEmpty(status,page),signature:readSignature(plan,page)}):status==="failed"&&onPlanFailed(petRef2)},[status,plan,pagePhase,page,petRef2,onPlan,onPlanFailed]);let readAgainIfDue=useRef(()=>{});return readAgainIfDue.current=()=>{let reads=latest.current,pageVisible=typeof document>"u"||document.visibilityState==="visible";isPlanReturnReadDue({pageVisible:pageVisible,watching:reads.watching,lastReadAt:readAt.current,now:Date.now()})&&(readAt.current=null,reads.plan(),reads.page())},useEffect(()=>{if(typeof document>"u")return;let onVisible=()=>readAgainIfDue.current();return document.addEventListener("visibilitychange",onVisible),()=>document.removeEventListener("visibilitychange",onVisible)},[]),useEffect(()=>{watching&&readAgainIfDue.current()},[watching]),null}}function recordsProbeOver(m){return function({petRef:petRef2,onRecords:onRecords}){let{status:status}=m.useEverfurRecords({petRef:petRef2});return useEffect(()=>{onRecords(petRef2,status==="empty"?"none":status==="populated"?"some":null)},[status,petRef2,onRecords]),null}}function NoPlan({petRef:petRef2,onPlanFailed:onPlanFailed}){return useEffect(()=>onPlanFailed(petRef2),[petRef2,onPlanFailed]),null}function NoRecords({petRef:petRef2,onRecords:onRecords}){return useEffect(()=>onRecords(petRef2,null),[petRef2,onRecords]),null}var LazyPlanProbe=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/health-plan").then(m=>({default:planProbeOver(m)}),()=>({default:NoPlan}))),LazyRecordsProbe=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/records").then(m=>({default:recordsProbeOver(m)}),()=>({default:NoRecords})));function PlanProbe(props){/* @__PURE__ */
|
|
408
318
|
return jsx(Suspense,{fallback:null,children:/* @__PURE__ */jsx(LazyPlanProbe,{...props})})}function RecordsProbe(props){/* @__PURE__ */
|
|
409
319
|
return jsx(Suspense,{fallback:null,children:/* @__PURE__ */jsx(LazyRecordsProbe,{...props})})}var TAB_RULES={".ph-sub":[["flex","none"],["display","grid"],["grid-template-columns","repeat(3, 1fr)"],["height","46px"],["background","$paper"],["box-shadow","inset 0 -1px 0 $line"]],".ph-sub button":[["position","relative"],["font-size","16px"],["font-weight","600"],["color","$ink3"],["text-align","center"],["isolation","isolate"],["transition","color 240ms ease"]],'.ph-sub button[aria-selected="true"]':[["color","$ink"],["font-weight","800"]],'.ph-sub button[aria-selected="true"]::after':[["position","absolute"],["left","18%"],["right","18%"],["bottom","0"],["height","3px"],["border-radius","3px 3px 0 0"],["background","$primary"]],".ph-sub button .ph-new":[["position","absolute"],["top","12px"],["margin-left","3px"],["width","7px"],["height","7px"],["border-radius","50%"],["background","$riskDot"]],".ph-toast":[["position","absolute"],["left","16px"],["right","16px"],["top","112px"],["z-index","50"],["background","$ink"],["color","$onInk"],["border-radius","16px"],["padding","12px 15px"],["font-size","14.5px"],["line-height","1.4"],["opacity","0"],["transform","translateY(-8px)"],["pointer-events","none"],["transition","opacity 160ms ease, transform 160ms cubic-bezier(0.23, 1, 0.32, 1)"]],".ph-toast.is-on":[["opacity","1"],["transform","none"],["transition-duration","220ms"]],".ph-sub button::before":[["position","absolute"],["inset","7px 8px"],["z-index","-1"],["border-radius","999px"],["background","var(--in-tint, transparent)"],["opacity","0"],["transform","scale(.94)"],["transition","opacity 200ms ease, transform 200ms cubic-bezier(0.23, 1, 0.32, 1)"]],'.ph-sub [data-sub="ask"]':[["--in-tint","$accentChip"],["--in-k","0"]],'.ph-sub [data-sub="plan"]':[["--in-tint","$linkChip"],["--in-k","1"]],'.ph-sub [data-sub="records"]':[["--in-tint","$clearChip"],["--in-k","2"]],'#ph[data-in-frame="tabs"] .ph-sub button':[["color","$ink"],["font-weight","800"]],'#ph[data-in-frame="tabs"] .ph-sub button::before':[["opacity","1"],["transform","none"],["transition","opacity 260ms ease, transform 260ms cubic-bezier(0.23, 1, 0.32, 1)"],["transition-delay","calc(560ms + var(--in-k) * 60ms)"]],'#ph[data-in-frame="tabs"] .ph-sub button::after':[["opacity","0"]]},TAB_REDUCED_RULES={".ph-sub button::before":[["transform","none"],["transition","opacity 150ms ease"],["transition-delay","0ms"]],'#ph[data-in-frame="tabs"] .ph-sub button::before':[["transform","none"],["transition","opacity 150ms ease"],["transition-delay","0ms"]]};var TabsContext=/* @__PURE__ */createContext(null);function useEverfurTabs(){return useContext(TabsContext)}var introLoad=null;function loadIntro(){return introLoad===null&&(introLoad=import("@everfur/sdk/web/intro").then(m=>m,()=>(introLoad=null,null))),introLoad}var NoPane=()=>null,LazyHealthPlan=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/health-plan").then(m=>({default:m.EverfurHealthPlan}),()=>({default:NoPane}))),LazyRecordsPage=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/records").then(m=>({default:m.EverfurRecordsPage}),()=>({default:NoPane}))),paneLoading=/* @__PURE__ */jsx("div",{role:"status","aria-busy":"true"}),INTRO_QUIET_MS=200,TOAST_INTO_BAR=4,TOAST_MS=2600,DEFAULT_INTRO_MAX_WIDTH=600,fill={flex:1,minHeight:0,display:"flex",flexDirection:"column"},scroller={flex:1,minHeight:0,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"none"};function EverfurTabs(props){let{petRef:petRef2,opened:opened,onTabChange:onTabChange,onRecordsRequested:onRecordsRequested,onRecordsLanded:onRecordsLanded,onToast:onToast}=props,visible=props.visible??true,theme=useEverfurTheme(),sx=useMemo(()=>askIntroSx(theme,TAB_RULES,TAB_REDUCED_RULES),[theme]),reset=useMemo(()=>askIntroReset(theme),[theme]),copy=useMemo(()=>({...EVERFUR_TABS_COPY,...props.copy}),[props.copy]),{runtime:runtime,userRef:userRef2}=useEverfurContext(),planEnabled=useCapabilityEnabled("healthPlan"),recordsEnabled=useCapabilityEnabled("records"),clinicEnabled=useCapabilityEnabled("recordsClinic"),[planVerdicts,setPlanVerdicts]=useState(()=>/* @__PURE__ */new Map),[planFailed,setPlanFailed]=useState(()=>/* @__PURE__ */new Set),onPlanRead=useCallback((ref,read)=>{setPlanVerdicts(previous=>{let before=previous.get(ref),next=nextPlanVerdict(before,read);return next===before?previous:new Map(previous).set(ref,next)}),setPlanFailed(previous=>previous.has(ref)?new Set([...previous].filter(pet=>pet!==ref)):previous)},[]),onPlanFailed=useCallback(ref=>{setPlanFailed(previous=>previous.has(ref)?previous:new Set(previous).add(ref))},[]),planVerdict=petRef2===null?void 0:planVerdicts.get(petRef2),planEmpty=!planEnabled||planVerdict?.empty===true,planOff=props.planTab===false,planHidden=planOff||planEmpty,planOutside=useRef(null);planOutside.current=planOff&&!planEmpty&&props.onOpenPlan!==void 0?props.onOpenPlan:null;let planKey=`${petRef2??"none"}:${planVerdict?.epoch??0}`,tabs=tabsFor(planHidden),planHiddenRef=useRef(planHidden);planHiddenRef.current=planHidden;let page=useHealthPlanPage({petRef:petRef2,enabled:planEnabled&&petRef2!==null}),[sub,setSub]=useState(()=>landingTab(opened,props.planTab===false)),[openedPanes,setOpenedPanes]=useState(()=>/* @__PURE__ */new Set(["ask",landingTab(opened,props.planTab===false)])),subRef=useRef(sub);subRef.current=sub;let open=useCallback(wanted=>{let outside=planOutside.current;if(wanted==="plan"&&outside!==null){try{outside({})}catch{}return}let next=resolveTab(wanted,planHiddenRef.current);setSub(next),setOpenedPanes(previous=>previous.has(next)?previous:new Set(previous).add(next))},[]);useEffect(()=>{planHidden&&sub==="plan"&&setSub("ask")},[planHidden,sub]);let tabChange=useRef(onTabChange);tabChange.current=onTabChange,useEffect(()=>{tabChange.current?.(sub)},[sub]),useEffect(()=>{!visible||props.documentTitle!==true||typeof document>"u"||(document.title=copy[sub])},[visible,sub,copy,props.documentTitle]);let[asked,setAsked]=useState(null),ask=useCallback((prompt,card)=>{prompt!==""&&setAsked(previous=>({id:(previous?.id??0)+1,prompt:prompt,petRef:petRef2,...card===void 0?{}:{card:card}})),open("ask")},[petRef2,open]),chatAsk=asked===null||asked.petRef!==petRef2?null:asked,key=openedKey(opened),handledKey=useRef(null),[plainOpen,setPlainOpen]=useState(null);useEffect(()=>{handledKey.current!==key&&(handledKey.current=key,opened.via==="link"&&opened.ask!==void 0?ask(opened.ask.prompt,opened.ask.card):opened.via==="link"&&opened.tab==="plan"&&planOutside.current!==null?(open("ask"),open("plan")):open(landingTab(opened,planHiddenRef.current)),setPlainOpen(opened.via==="plain"?key:null))},[key,opened,ask,open]);let paneShown=useMemo(()=>createPaneShownSignal(),[]),hostLifecycle=props.chat?.lifecycle,chatLifecycle=useMemo(()=>hostLifecycle===null?null:withPaneShown(hostLifecycle??createBrowserLifecycle(),paneShown),[hostLifecycle,paneShown]),askShown=visible&&sub==="ask",wasAskShown=useRef(askShown);useEffect(()=>{let edge=isPaneShownEdge(wasAskShown.current,askShown);wasAskShown.current=askShown,edge&&paneShown.fire()},[askShown,paneShown]);let[toast,setToast]=useState(null),[toastOn,setToastOn]=useState(false),say=useCallback(text3=>{text3!==""&&(onToast!==void 0?onToast(text3):setToast(previous=>({id:(previous?.id??0)+1,text:text3})))},[onToast]);useEffect(()=>{if(toast===null)return;let raf=requestAnimationFrame(()=>setToastOn(true)),timer=setTimeout(()=>setToastOn(false),TOAST_MS);return()=>{cancelAnimationFrame(raf),clearTimeout(timer),setToastOn(false)}},[toast]);let introOptions=props.intro===false?null:props.intro??{},[introModule,setIntroModule]=useState(null),[run,setRun]=useState(null),[introFrame,setIntroFrame]=useState(null),[wants,setWants]=useState(null),[requested,setRequested]=useState(null),[recordsVerdicts,setRecordsVerdicts]=useState(()=>/* @__PURE__ */new Map),[banner,setBanner]=useState(false),[noVet,setNoVet]=useState(false),[introUnavailable,setIntroUnavailable]=useState(false),introFrameRef=useRef(null),focusTabOnClosed=useRef(false),rootRef=useRef(null),barRef=useRef(null),tabRefs=useRef({}),repo=useMemo(()=>createIntroRepository(runtime),[runtime]),kv=runtime.registry.services.kv,ensureIntroModule=useCallback(onUnavailable=>{loadIntro().then(m=>{if(setIntroUnavailable(m===null),m!==null){setIntroModule(previous=>previous??m);return}setWants(null),setRun(null),onUnavailable?.()})},[]),maxWidth=introOptions?.maxWidth??DEFAULT_INTRO_MAX_WIDTH,introAllowed=introOptions!==null&&planEnabled,introAsks=introAllowed&&plainOpen!==null&&visible&&userRef2!==null&&petRef2!==null,[decided,setDecided]=useState(null);useEffect(()=>{if(!introAsks)return;let forKey=plainOpen,box=props.overlayContainer??rootRef.current;if((typeof window<"u"?window.innerWidth:box?.getBoundingClientRect().width??0)>=maxWidth){setDecided(forKey);return}let control=new AbortController,forPet2=petRef2;return shouldPlayIntro({repo:repo,kv:kv,userRef:userRef2,signal:control.signal}).then(play=>{control.signal.aborted||(setDecided(forKey),play&&(ensureIntroModule(),setWants({key:forKey,petRef:forPet2})))},()=>{control.signal.aborted||setDecided(forKey)}),()=>control.abort()},[introAsks,plainOpen,userRef2,petRef2,repo,kv,maxWidth,props.overlayContainer,ensureIntroModule]);let refsPending=introAllowed&&plainOpen!==null&&visible&&(userRef2===null||petRef2===null)&&(typeof window>"u"||window.innerWidth<maxWidth),[refsWaitOver,setRefsWaitOver]=useState(null);useEffect(()=>{if(!refsPending)return;let forKey=plainOpen,timer=setTimeout(()=>setRefsWaitOver(forKey),INTRO_WAIT_MS);return()=>clearTimeout(timer)},[refsPending,plainOpen]),useIntroOpenHold(refsPending&&refsWaitOver!==plainOpen||introAsks&&decided!==plainOpen||wants!==null||run!==null);let onRecordsVerdict=useCallback((ref,verdict)=>{setRecordsVerdicts(previous=>previous.get(ref)===verdict?previous:new Map(previous).set(ref,verdict))},[]),recordsVerdict=petRef2===null?void 0:recordsVerdicts.get(petRef2),recordsConnected=recordsVerdict==="some";useEffect(()=>{petRef2!==null&&recordsConnected&&setHealthPlanNoVet(petRef2,false)},[petRef2,recordsConnected]),useEffect(()=>{if(wants===null||run!==null)return;let step=introWantStep({sameOpen:wants.key===plainOpen&&wants.petRef===petRef2,plan:planVerdict,planFailed:planFailed.has(wants.petRef),moduleReady:introModule!==null,recordsPending:recordsEnabled&&recordsVerdict===void 0});if(step==="drop"&&setWants(null),step!=="play")return;open("ask");let timer=setTimeout(()=>{setWants(null),setRun(previous=>({mode:"intro",id:(previous?.id??0)+1}))},INTRO_QUIET_MS);return()=>clearTimeout(timer)},[wants,run,plainOpen,petRef2,planVerdict,planFailed,introModule,recordsEnabled,recordsVerdict,open]),useEffect(()=>{if(wants===null)return;let timer=setTimeout(()=>setWants(current=>current===wants?null:current),INTRO_WAIT_MS);return()=>clearTimeout(timer)},[wants]);let requestRecords=useCallback(()=>{petRef2!==null&&(ensureIntroModule(()=>open("records")),setRun(previous=>({mode:"records",id:(previous?.id??0)+1})))},[petRef2,ensureIntroModule,open]),onIntroClose=useCallback(close=>{(run?.mode??"intro")==="intro"&&markIntroSeen({repo:repo,kv:kv,userRef:userRef2}),introFrameRef.current==="novet"&&petRef2!==null&&setHealthPlanNoVet(petRef2,true),close.exit==="plan"?open("plan"):close.exit==="ask"&&open("ask"),focusTabOnClosed.current=close.exit!=="stay",close.notifications!==null&&setRequested(previous=>previous===null?previous:{...previous,notified:close.notifications}),close.toast!==null&&say(close.toast)},[run,repo,kv,userRef2,petRef2,open,say]),onIntroClosed=useCallback(()=>setRun(null),[]);useEffect(()=>{run!==null||!focusTabOnClosed.current||(focusTabOnClosed.current=false,tabRefs.current[subRef.current]?.focus({preventScroll:true}))},[run]);let onRequested=useCallback(event=>{setRequested({petRef:event.petRef,notified:null}),setHealthPlanNoVet(event.petRef,false),onRecordsRequested?.(event)},[onRecordsRequested]),onFrame=useCallback(frame=>{frame!==null&&(introFrameRef.current=frame),setIntroFrame(frame)},[]);useEffect(()=>{if(petRef2===null){setNoVet(false);return}return setNoVet(healthPlanNoVet(petRef2)),onHealthPlanNoVet((pet,none)=>{pet===petRef2&&setNoVet(none)})},[petRef2]),useEffect(()=>onHealthPlanRecordsLanded(pet=>setHealthPlanNoVet(pet,false)),[]);let landedFrom=useRef(void 0),land=useCallback(()=>{if(setBanner(false),open("plan"),introModule!==null&&petRef2!==null){let facts=introModule.introFacts(page.page,props.petName);say(introModule.introText({facts:facts,copy:{...introModule.EVERFUR_INTRO_COPY,...introOptions?.copy},blanks:0,resultsPending:false}).toast.landed)}},[open,introModule,petRef2,page.page,props.petName,introOptions?.copy,say]);useEffect(()=>{let before=landedFrom.current;if(landedFrom.current=recordsVerdict,requested===null||petRef2===null||requested.petRef!==petRef2||before!=="none"||recordsVerdict!=="some")return;let event={petRef:petRef2,at:/* @__PURE__ */(new Date).toISOString()};emitRecordsEvent(EVERFUR_RECORDS_LANDED_EVENT,event),onRecordsLanded?.(event),notifyHealthPlanRecordsLanded(petRef2),setRequested(null),requested.notified===true?setBanner(true):land()},[recordsVerdict,requested,petRef2,onRecordsLanded,land]);let covered=props.overlayContainer??null,[toastTop,setToastTop]=useState(null);useLayoutEffect(()=>{let bar2=barRef.current,box=covered??rootRef.current;if(bar2===null||box===null||toast===null)return;let a=box.getBoundingClientRect(),b=bar2.getBoundingClientRect();setToastTop(Math.round(b.top-a.top+TOAST_INTO_BAR))},[covered,toast]);let onTabKey=event=>{let next=tabKeyTarget(tabs,sub,event.key);next!==null&&(event.preventDefault(),open(next),tabRefs.current[next]?.focus())},lit=introFrame==="tabs",cls=props.classNames??{},bar=/* @__PURE__ */jsx("div",{ref:barRef,role:"tablist","aria-label":planHidden?copy.listNoPlan:copy.listAll,className:cls.bar,style:{...sx(".ph-sub"),gridTemplateColumns:`repeat(${tabs.length}, 1fr)`},onKeyDown:onTabKey,children:tabs.map(id=>{let selected=sub===id;/* @__PURE__ */
|
|
410
320
|
return jsxs("button",{ref:element=>{tabRefs.current[id]=element},type:"button",role:"tab",id:`everfur-tab-${id}`,"data-sub":id,"aria-selected":selected,...openedPanes.has(id)?{"aria-controls":`everfur-pane-${id}`}:{},tabIndex:selected?0:-1,className:cls.tab,style:{...reset.button,...sx(".ph-sub button",`.ph-sub [data-sub="${id}"]`,selected&&'.ph-sub button[aria-selected="true"]',lit&&'#ph[data-in-frame="tabs"] .ph-sub button')},onClick:()=>open(id),children:[
|
|
@@ -416,4 +326,4 @@ return jsx(TabsContext.Provider,{value:handle,children:/* @__PURE__ */jsxs("div"
|
|
|
416
326
|
/* @__PURE__ */jsx("div",{className:cls.scroll,style:scroller,children:/* @__PURE__ */jsx(Suspense,{fallback:paneLoading,children:/* @__PURE__ */jsx(LazyHealthPlan,{...plan,...planFocus===void 0?{}:{focus:planFocus},petRef:petRef2},planKey)})},petRef2??"none"),props.paneFooter?.plan]}):null,openedPanes.has("records")?/* @__PURE__ */jsxs("div",{className:cls.pane,id:"everfur-pane-records",role:"tabpanel","aria-labelledby":"everfur-tab-records",hidden:sub!=="records",style:pane("records"),children:[
|
|
417
327
|
/* @__PURE__ */jsx("div",{className:cls.scroll,style:scroller,children:/* @__PURE__ */jsx(Suspense,{fallback:paneLoading,children:props.renderRecords===void 0?recordsPage:props.renderRecords(recordsPage)})},petRef2??"none"),props.paneFooter?.records]}):null]}),onToast!==void 0?null:
|
|
418
328
|
/* @__PURE__ */jsx("div",{role:"status","aria-live":"polite",style:reset.srOnly,children:toast!==null&&toastOn&&run===null?toast.text:""}),toast===null||onToast!==void 0?null:overlay(
|
|
419
|
-
/* @__PURE__ */jsx("div",{"aria-hidden":"true",style:{...reset.root,...sx(".ph-toast",toastOn&&".ph-toast.is-on"),...toastTop===null?{}:{top:toastTop}},children:toast.text},`toast-${toast.id}`)),Banner2!==void 0&&bannerText!==null?overlay(/* @__PURE__ */jsx(Banner2,{text:bannerText,...introOptions?.bannerIcon===void 0?{}:{icon:introOptions.bannerIcon},onLand:land})):null,Intro===void 0||run===null||petRef2===null?null:/* @__PURE__ */jsx(Intro,{petRef:petRef2,mode:run.mode,page:page.page,petName:props.petName??null,recordsConnected:run.mode==="intro"&&(recordsConnected||!clinicEnabled),resultsPending:pending3,...introOptions?.copy===void 0?{}:{copy:introOptions.copy},...introOptions?.blanks===void 0?{}:{blanks:introOptions.blanks},container:covered??rootRef.current,tabBar:barRef.current,tabLabels:{ask:copy.ask,plan:copy.plan,records:copy.records},onFrame:onFrame,onClose:onIntroClose,onClosed:onIntroClosed,onRequested:onRequested,...introOptions?.onEnableNotifications===void 0?{}:{onEnableNotifications:introOptions.onEnableNotifications},onUpload:introOptions?.onUpload??openRecords,...introOptions?.ownerName===void 0?{}:{ownerName:introOptions.ownerName},...introOptions?.onCaptureSignature===void 0?{}:{onCaptureSignature:introOptions.onCaptureSignature}},`intro-${run.id}`)]})})}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state3,setState]=useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state3.key===key?state3:{profile:null,loading:petRef2!==null,error:null},generation=useRef(0),load=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 useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:webThemeSeams,children:props.children})}export{APPEARANCE_PRESETS,APPEARANCE_PRESET_NAMES,APPEARANCE_SIZE_RANGES,CapabilityGate,DEFAULT_PRESENTATION,EVERFUR_RECORDS_LANDED_EVENT,EVERFUR_RECORDS_REQUESTED_EVENT,EVERFUR_TABS_COPY,EverfurChat,EverfurConfigError,EverfurPoweredBy,EverfurProvider,EverfurTabs,EverfurThemeProvider,EverfurThrownError,THEME_SLOT_KEYS,THEME_SLOT_KEYS_BY_SLOT,THEME_SLOT_NAMES,canonicalPetSpecies,categoryFor,conversationId,createBrowserLifecycle,createLocalStorageKv,createWebAttachmentTransport,expandAppearance,face,faceCss,fileToAttachmentHandle,headingFace,headingFaceCss,isErr,isOk,isRetryableCode,parsePresentation,petRef,previewTheme,resolvePresentation,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurPresentation,useEverfurTabs,useEverfurTheme,useHostPoweredBy,userFacingError,userRef};
|
|
329
|
+
/* @__PURE__ */jsx("div",{"aria-hidden":"true",style:{...reset.root,...sx(".ph-toast",toastOn&&".ph-toast.is-on"),...toastTop===null?{}:{top:toastTop}},children:toast.text},`toast-${toast.id}`)),Banner2!==void 0&&bannerText!==null?overlay(/* @__PURE__ */jsx(Banner2,{text:bannerText,...introOptions?.bannerIcon===void 0?{}:{icon:introOptions.bannerIcon},onLand:land})):null,Intro===void 0||run===null||petRef2===null?null:/* @__PURE__ */jsx(Intro,{petRef:petRef2,mode:run.mode,page:page.page,petName:props.petName??null,recordsConnected:run.mode==="intro"&&(recordsConnected||!clinicEnabled),resultsPending:pending3,...introOptions?.copy===void 0?{}:{copy:introOptions.copy},...introOptions?.blanks===void 0?{}:{blanks:introOptions.blanks},container:covered??rootRef.current,tabBar:barRef.current,tabLabels:{ask:copy.ask,plan:copy.plan,records:copy.records},onFrame:onFrame,onClose:onIntroClose,onClosed:onIntroClosed,onRequested:onRequested,...introOptions?.onEnableNotifications===void 0?{}:{onEnableNotifications:introOptions.onEnableNotifications},onUpload:introOptions?.onUpload??openRecords,...introOptions?.ownerName===void 0?{}:{ownerName:introOptions.ownerName},...introOptions?.onCaptureSignature===void 0?{}:{onCaptureSignature:introOptions.onCaptureSignature}},`intro-${run.id}`)]})})}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state3,setState]=useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state3.key===key?state3:{profile:null,loading:petRef2!==null,error:null},generation=useRef(0),load=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 useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:webThemeSeams,children:props.children})}export{APPEARANCE_PRESETS,APPEARANCE_PRESET_NAMES,APPEARANCE_SIZE_RANGES,CapabilityGate,DEFAULT_PRESENTATION,EVERFUR_RECORDS_LANDED_EVENT,EVERFUR_RECORDS_REQUESTED_EVENT,EVERFUR_TABS_COPY,EverfurChat,EverfurConfigError,EverfurPoweredBy,EverfurProvider,EverfurTabs,EverfurThemeProvider,EverfurThrownError,THEME_SLOT_KEYS,THEME_SLOT_KEYS_BY_SLOT,THEME_SLOT_NAMES,canonicalPetSpecies,categoryFor,chatHandoffTokenFromUrl,conversationId,createBrowserLifecycle,createLocalStorageKv,createWebAttachmentTransport,expandAppearance,face,faceCss,fileToAttachmentHandle,headingFace,headingFaceCss,isErr,isOk,isRetryableCode,parsePresentation,petRef,previewTheme,resolvePresentation,takeChatHandoffToken,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurPresentation,useEverfurTabs,useEverfurTheme,useEverfurUnread,useHostPoweredBy,userFacingError,userRef};
|