@everfur/sdk 0.7.1 → 0.8.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 +311 -0
- package/README.md +24 -16
- package/dist/{Chat-CFi5cNUF.d.ts → Chat-Cv9EYMYA.d.ts} +3 -3
- package/dist/{Chat-DQOsAumH.d.cts → Chat-s2vcPbw3.d.cts} +3 -3
- package/dist/{DepthViews-uilL1NJZ.d.ts → DepthViews-CVxUHOJ-.d.ts} +1 -1
- package/dist/{DepthViews-C409ubw-.d.cts → DepthViews-Cz7mSW7p.d.cts} +1 -1
- package/dist/{DepthViews-es8mIK0w.d.ts → DepthViews-DNRY0Ugm.d.ts} +1 -1
- package/dist/{DepthViews-D81c95Ra.d.cts → DepthViews-DvNixbxg.d.cts} +1 -1
- package/dist/{ErrorPolicyPort-D22LUVrK.d.ts → ErrorPolicyPort-DwSnmGcX.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-D6CybiqJ.d.cts → ErrorPolicyPort-NFDPe-5w.d.cts} +1 -1
- package/dist/{EverfurError-DmELDpXp.d.cts → EverfurError-pEXDbUJ1.d.cts} +9 -1
- package/dist/{EverfurError-DmELDpXp.d.ts → EverfurError-pEXDbUJ1.d.ts} +9 -1
- package/dist/{EverfurResult-ZtH-YV1h.d.cts → EverfurResult-dtl8ERAw.d.cts} +1 -1
- package/dist/{EverfurResult-SGvHKsCB.d.ts → EverfurResult-sKkoXew0.d.ts} +1 -1
- package/dist/IntakeMedia-BFZfBLjB.d.cts +116 -0
- package/dist/{IntakeMedia-BcjjUizr.d.ts → IntakeMedia-BH0fYDT2.d.cts} +19 -2
- package/dist/{IntakeMedia-CL_S2tZE.d.cts → IntakeMedia-Bavl7E4Z.d.ts} +19 -2
- package/dist/IntakeMedia-C8GlN_GK.d.ts +116 -0
- package/dist/animations/index.cjs +109 -1
- package/dist/animations/index.d.cts +6 -6
- package/dist/animations/index.d.ts +6 -6
- package/dist/animations/index.js +109 -1
- package/dist/{attachments-DNaSbmA3.d.ts → attachments-BaslXMdS.d.ts} +3 -3
- package/dist/{attachments-DI710no4.d.cts → attachments-DbFwz4iq.d.cts} +7 -7
- package/dist/{attachments-B2GjBgvF.d.cts → attachments-y3EcOX_w.d.cts} +3 -3
- package/dist/{attachments-SF88N654.d.ts → attachments-y_aO4hlk.d.ts} +7 -7
- package/dist/{bookingCopy-xlXxORCA.d.cts → bookingCopy-4i1R7klo.d.cts} +15 -7
- package/dist/{bookingCopy-D2N3RhsV.d.ts → bookingCopy-B3UMITD-.d.ts} +15 -7
- package/dist/{branding-ytH4jJq1.d.ts → branding-BYEqU855.d.ts} +1 -1
- package/dist/{branding-Bio5MM6g.d.cts → branding-BwEu68C8.d.cts} +1 -1
- package/dist/{callRoom-7wrE3RP2.d.ts → callRoom-B1qq_D-4.d.ts} +1 -1
- package/dist/{callRoom-B_EqaUzx.d.cts → callRoom-DfZTWFXh.d.cts} +1 -1
- package/dist/{casesRepository-B-md8h1S.d.cts → casesRepository-B6Z0XBIb.d.cts} +2 -2
- package/dist/{casesRepository-CC6951TK.d.ts → casesRepository-SI0zp5YH.d.ts} +2 -2
- package/dist/chat/index.cjs +333 -1
- package/dist/chat/index.d.cts +12 -12
- package/dist/chat/index.d.ts +12 -12
- package/dist/chat/index.js +333 -1
- package/dist/client/index.cjs +115 -11
- package/dist/client/index.d.cts +14 -14
- package/dist/client/index.d.ts +14 -14
- package/dist/client/index.js +115 -11
- package/dist/{config-BM0sv5jx.d.ts → config-Cvo47voG.d.ts} +3 -3
- package/dist/{config-Daa1plhQ.d.cts → config-v5k6NsK_.d.cts} +3 -3
- package/dist/consent/index.cjs +112 -1
- package/dist/consent/index.d.cts +9 -9
- package/dist/consent/index.d.ts +9 -9
- package/dist/consent/index.js +112 -1
- package/dist/{context-DQHtwcHN.d.cts → context-BZOtJbBO.d.cts} +9 -9
- package/dist/{context-CDV2pwGI.d.ts → context-cZ7NZ0sG.d.ts} +9 -9
- package/dist/{copy-Cl1l-qmY.d.ts → copy-CZBUHbyS.d.ts} +5 -5
- package/dist/{copy-BEx5F71o.d.cts → copy-ChJupm1p.d.cts} +5 -5
- package/dist/core/index.cjs +140 -13
- package/dist/core/index.d.cts +19 -19
- package/dist/core/index.d.ts +19 -19
- package/dist/core/index.js +140 -13
- package/dist/{depth-CAAwiStc.d.cts → depth-CRyU7-pf.d.cts} +7 -6
- package/dist/{depth-DfNRVtrV.d.ts → depth-vNpwOkZ8.d.ts} +7 -6
- package/dist/{entitlementRepository-DPvWjV-N.d.cts → entitlementRepository-Bv8nSYRd.d.cts} +4 -4
- package/dist/{entitlementRepository-CVWvND1P.d.ts → entitlementRepository-CUdxbQrP.d.ts} +4 -4
- package/dist/{identity-BhT7oJDS.d.ts → identity-B8GkH53J.d.ts} +2 -2
- package/dist/{identity-DUlshgow.d.cts → identity-BHaMJ3KK.d.cts} +2 -2
- package/dist/index.cjs +363 -12
- package/dist/index.d.cts +19 -19
- package/dist/index.d.ts +19 -19
- package/dist/index.js +363 -12
- package/dist/{models-DSqA5Ahs.d.ts → models-CrbUwbuS.d.ts} +1 -1
- package/dist/{models-Bn2z0NNo.d.cts → models-DzvqEjMm.d.cts} +1 -1
- package/dist/notifications/index.cjs +94 -2
- package/dist/notifications/index.d.cts +5 -5
- package/dist/notifications/index.d.ts +5 -5
- package/dist/notifications/index.js +94 -2
- package/dist/{pets-Bneph9m1.d.cts → pets-BI7Ji8hi.d.cts} +2 -2
- package/dist/{pets-DjcLmRrW.d.ts → pets-Dnn-DK1T.d.ts} +2 -2
- package/dist/{petsRepository-BwxmfX_s.d.ts → petsRepository-B2lO1sKS.d.ts} +2 -2
- package/dist/{petsRepository-BnVre3q7.d.cts → petsRepository-BP9nhM1R.d.cts} +2 -2
- package/dist/photo/index.cjs +131 -1
- package/dist/photo/index.d.cts +3 -3
- package/dist/photo/index.d.ts +3 -3
- package/dist/photo/index.js +131 -1
- package/dist/{ports-Di9rdLO9.d.ts → ports-BUXF0Rp3.d.ts} +7 -7
- package/dist/{ports-BPKxFOSe.d.cts → ports-C40S2V14.d.cts} +7 -7
- package/dist/records/depth/index.cjs +200 -2
- package/dist/records/depth/index.d.cts +11 -11
- package/dist/records/depth/index.d.ts +11 -11
- package/dist/records/depth/index.js +200 -2
- package/dist/records/index.cjs +742 -4
- package/dist/records/index.d.cts +22 -14
- package/dist/records/index.d.ts +22 -14
- package/dist/records/index.js +742 -4
- package/dist/{requestFunnel-CiSX2pun.d.ts → requestFunnel-BrOijMcw.d.ts} +5 -5
- package/dist/{requestFunnel-DMR_1T3O.d.cts → requestFunnel-BxNVGyGm.d.cts} +5 -5
- package/dist/{runtimeTypes-CkMFCbHW.d.ts → runtimeTypes-CvI1ZH8j.d.ts} +7 -7
- package/dist/{runtimeTypes-2gJ5hYoE.d.cts → runtimeTypes-DOO3f-W-.d.cts} +7 -7
- package/dist/server/events/index.cjs +92 -2
- package/dist/server/events/index.d.cts +4 -4
- package/dist/server/events/index.d.ts +4 -4
- package/dist/server/events/index.js +92 -2
- package/dist/server/index.cjs +95 -2
- package/dist/server/index.d.cts +5 -5
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +95 -2
- package/dist/televet/booking/index.cjs +394 -4
- package/dist/televet/booking/index.d.cts +24 -127
- package/dist/televet/booking/index.d.ts +24 -127
- package/dist/televet/booking/index.js +394 -4
- package/dist/televet/call/index.cjs +71 -1
- package/dist/televet/call/index.d.cts +3 -3
- package/dist/televet/call/index.d.ts +3 -3
- package/dist/televet/call/index.js +71 -1
- package/dist/televet/index.cjs +101 -1
- package/dist/televet/index.d.cts +25 -8
- package/dist/televet/index.d.ts +25 -8
- package/dist/televet/index.js +101 -1
- package/dist/{bookingTypes-D4pD3tHs.d.ts → televetGlobal-C5dTUACe.d.cts} +34 -1
- package/dist/{bookingTypes-D4pD3tHs.d.cts → televetGlobal-CnjrfhT4.d.ts} +34 -1
- package/dist/testing/index.cjs +98 -7
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +98 -7
- package/dist/testing/rn/index.cjs +101 -1
- package/dist/testing/rn/index.d.cts +13 -13
- package/dist/testing/rn/index.d.ts +13 -13
- package/dist/testing/rn/index.js +101 -1
- package/dist/testing/web/index.cjs +95 -1
- package/dist/testing/web/index.d.cts +14 -14
- package/dist/testing/web/index.d.ts +14 -14
- package/dist/testing/web/index.js +95 -1
- package/dist/{timelineRows-D3171ksh.d.ts → timelineRows-CEx2TzYB.d.ts} +1 -1
- package/dist/{timelineRows-DDnz4gx2.d.cts → timelineRows-Dffceql_.d.cts} +1 -1
- package/dist/{tokens-BYtbKwFh.d.cts → tokens-Tzo1KBND.d.cts} +43 -2
- package/dist/{tokens-BYtbKwFh.d.ts → tokens-Tzo1KBND.d.ts} +43 -2
- package/dist/{typeStyle-DKz02DGU.d.ts → typeStyle-C3IG9Sft.d.ts} +22 -3
- package/dist/{typeStyle-BqfwxZH4.d.cts → typeStyle-CZ3Tj60N.d.cts} +22 -3
- package/dist/{useRecordsDepth-COJ0wSYK.d.cts → useRecordsDepth-D6a6-_u_.d.cts} +7 -6
- package/dist/{useRecordsDepth-Z9FF5X4E.d.ts → useRecordsDepth-DuPUJFDQ.d.ts} +7 -6
- package/dist/{useVetVisit-Ds8f1peV.d.cts → useVetVisit-BQX_aTJs.d.cts} +2 -2
- package/dist/{useVetVisit-BsjoDO-n.d.ts → useVetVisit-RPBOabl8.d.ts} +2 -2
- package/dist/video/index.cjs +122 -1
- package/dist/video/index.d.cts +3 -3
- package/dist/video/index.d.ts +3 -3
- package/dist/video/index.js +122 -1
- package/dist/{view-DoQEHXJR.d.ts → view-BSmN5RWf.d.ts} +5 -5
- package/dist/{view-nRy6SitU.d.cts → view-UFwCG1Pn.d.cts} +5 -5
- package/dist/web/consent/index.cjs +111 -1
- package/dist/web/consent/index.d.cts +9 -9
- package/dist/web/consent/index.d.ts +9 -9
- package/dist/web/consent/index.js +111 -1
- package/dist/web/index.cjs +325 -14
- package/dist/web/index.d.cts +22 -22
- package/dist/web/index.d.ts +22 -22
- package/dist/web/index.js +325 -14
- package/dist/web/notifications/index.cjs +95 -2
- package/dist/web/notifications/index.d.cts +7 -7
- package/dist/web/notifications/index.d.ts +7 -7
- package/dist/web/notifications/index.js +95 -2
- package/dist/web/records/depth/index.cjs +169 -2
- package/dist/web/records/depth/index.d.cts +11 -11
- package/dist/web/records/depth/index.d.ts +11 -11
- package/dist/web/records/depth/index.js +169 -2
- package/dist/web/records/index.cjs +689 -4
- package/dist/web/records/index.d.cts +34 -37
- package/dist/web/records/index.d.ts +34 -37
- package/dist/web/records/index.js +689 -4
- package/dist/web/records/upload/index.cjs +3 -0
- package/dist/web/records/upload/index.d.cts +23 -0
- package/dist/web/records/upload/index.d.ts +23 -0
- package/dist/web/records/upload/index.js +3 -0
- package/dist/web/televet/booking/index.cjs +423 -4
- package/dist/web/televet/booking/index.d.cts +21 -35
- package/dist/web/televet/booking/index.d.ts +21 -35
- package/dist/web/televet/booking/index.js +423 -4
- package/dist/web/televet/call/index.cjs +28 -1
- package/dist/web/televet/call/index.d.cts +2 -2
- package/dist/web/televet/call/index.d.ts +2 -2
- package/dist/web/televet/call/index.js +28 -1
- package/dist/web/televet/index.cjs +102 -4
- package/dist/web/televet/index.d.cts +22 -11
- package/dist/web/televet/index.d.ts +22 -11
- package/dist/web/televet/index.js +102 -4
- package/package.json +20 -4
- package/web/records/upload/native-blocked.cjs +12 -0
- package/web/records/upload/package.json +8 -0
- package/dist/televetGlobal-CEk0_cW9.d.cts +0 -34
- package/dist/televetGlobal-Cs9Wbqsy.d.ts +0 -34
package/dist/core/index.cjs
CHANGED
|
@@ -1,13 +1,140 @@
|
|
|
1
|
-
'use strict';var zod=require('zod');var Pi=Object.defineProperty;var i=(e,t)=>Pi(e,"name",{value:t,configurable:true});function _(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_,"ok");function f(e){return Object.freeze({ok:false,error:e})}i(f,"err");var ze=class ze extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,ze.prototype);}};i(ze,"EverfurConfigError");var $=ze;var Ku=Object.freeze({isAvailable:false,async getSecret(){return null},async setSecret(){throw new $("not-initialized","EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort")},async deleteSecret(){}});var Le=Object.freeze({track(){},trackExpectedFailure(){}});var dt=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(dt.map(e=>e.wireCode));var Ai=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),Tr=Object.freeze(dt.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Ai[e.wireCode]}))),Oi=new Map(Tr.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Ii=Object.freeze(["http_envelope",...[...new Set(Tr.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Ne(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...Ii]){let o=Oi.get(n+r);if(o)return o}}i(Ne,"contractErrorFor");function Fi(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Fi,"contractDocUrl");function xr(e){return null}i(xr,"publishedDocUrl");var Mi=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function Pr(e){return Mi[e]}i(Pr,"categoryFor");function Q(e){let t=Ne(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":case "TELEVETRATELIMITED":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Q,"fromWire");function Ar(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(Ar,"fromHttpStatus");var Di=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function re(e){return Di.has(e)}i(re,"isAutoRetryable");var ji=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Or(e){return re(e)||ji.has(e)}i(Or,"isRetryableCode");function Ue(e,t=false){return t||re(e)}i(Ue,"shouldRetry");var zi=500,ct=8e3,ye=4;function Be(e,t=Math.random){let r=Math.max(0,e),n=Math.min(zi*2**r,ct);return Math.floor(t()*n)}i(Be,"backoffDelayMs");function Ir(e){return e==="conversationNotFound"}i(Ir,"canRecreateOnNotFound");var Fr=Object.freeze({shouldRetry(e,t){return re(e)&&t<ye},maxAttempts(){return ye}});var Mr=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function ad(e,t,r){let n;try{n=t();}catch(s){return pt(`optional peer '${e}' is not installed: ${Ni(s)}`)}let o=Li(n);return o==null?pt(`optional peer '${e}' resolved to no module`):r&&!r(o)?pt(`optional peer '${e}' is present but failed its shape check`):Object.freeze({available:true,module:o})}i(ad,"optionalModule");function Li(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}i(Li,"unwrapDefault");function pt(e){return Object.freeze({available:false,module:null,reason:e})}i(pt,"frozenUnavailable");function Ni(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}i(Ni,"describe");function qe(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(qe,"assertNever");function Dr(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Dr,"acceptedFrame");function jr(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(jr,"heartbeatFrame");function zr(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(zr,"deltaFrame");function Lr(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(Lr,"doneFrame");function B(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(B,"errorFrame");function Nr(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Nr,"analysisStartedFrame");function Ur(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Ur,"analysisCompleteFrame");function Br(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Br,"unknownFrame");var qi=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function ft(e){return qi[e]}i(ft,"userFacingError");function qr(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(qr,"defineHidden");var Hi=/^[a-z][a-z0-9_]{0,63}$/;function S(e,t){let r=Ne(t?.wireCode,t?.wireEnvelope),n={code:e,category:Pr(e),retryable:t?.retryable??Or(e),displayMessage:ft(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Hi.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&qr(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&qr(n,"raw",t.raw),Object.freeze(n)}i(S,"makeEverfurError");function Hr(e,t,r){let n=null,o=null,s=false,l=i(()=>o||(o=(async()=>{try{let u=await t(),a=typeof u=="string"?u:u?.token;if(typeof a!="string"||a.length===0)throw new $("invalid-argument","TokenProvider returned an empty token");return n=a,r?.(typeof u=="string"?null:Ki(u.expiresAt)),a}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(u){if(s)throw new $("not-initialized","This identity was cleared (sign-out); mint a new one.");return u?.forceRefresh&&(n=null),n!==null?n:l()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(Hr,"createIdentityProvider");function Ki(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(Ki,"expiryMs");function yt(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(yt,"newSessionId");function Vi(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(Vi,"authHeaders");function ge(e,t){return {...e,headers:{...$i(e.headers),...Vi(t)}}}i(ge,"withAuthHeaders");function $i(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i($i,"stripAuthHeaders");async function Kr(e,t){if(t.mode==="anonymous")return t.transport.request(ge(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return f(mt())}let n=await t.transport.request(ge(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return f(mt())}let s=await t.transport.request(ge(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?f(mt(s.error.httpStatus)):s}i(Kr,"authedSend");function mt(e){return S("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(mt,"authRejectedError");var Vr=`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`));}u(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",l);function u(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",l);try{e.close();}catch{}}}return i(u,"cleanup"),ms(r.source,u)}i(fs,"eventSourceByteSource");async function*ms(e,t){try{yield*e;}finally{t();}}i(ms,"sourceWithCleanup");function ys(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(l=>{r=l;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(ys,"createByteQueue");async function gs(e,t){let r=t.fetchImpl??on(),n=sn(t.config.apiBaseUrl,e.path,e.query),o=an(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=Es(ps),l=Cs(s.signal,e.signal),u;try{u=await r(n,ln({...e,signal:l},o));}catch(d){return f(vt(d))}finally{s.cancel();}let a=await un(u);return u.ok?_(a):f(vs(u.status,a,rn(u)))}i(gs,"requestJson");function tn(e){return {request:i(t=>gs(t,e),"request"),stream:i((t,r)=>hs(Rs(t,r),e),"stream")}}i(tn,"createHttpTransport");async function*hs(e,t){let r=sn(t.config.apiBaseUrl,e.path,e.query),n=an(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let u=t.eventSourceFactory(r,bs(e,n));yield*He(fs(u),()=>_s(u));return}let o=t.fetchImpl??on(),s;try{s=await o(r,ln(e,n));}catch(u){yield Zr("",true,fn(u));return}let l=rn(s);if(!s.ok){let u=await un(s),a=dn(u)??nn(s.status),d=pn(u)||re(Q(a));yield Zr(a,d,cn(u),l);return}if(s.body){yield*He(Qr(s.body),l);return}yield*He(Qr(null),l);}i(hs,"streamFrames");function bs(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(bs,"buildEventSourceInit");function vs(e,t,r){let n=dn(t),o=n?Q(n):Ar(e),s=cn(t);return S(o,{httpStatus:e,...pn(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Jr(t)?{reasonCode:Jr(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(vs,"errorFromResponse");function vt(e){return S("internalError",{retryable:true,wireMessage:fn(e)})}i(vt,"networkError");function rn(e){let t=e.headers.get(en);return typeof t=="string"&&t.length>0?t:null}i(rn,"requestIdOf");function _s(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(en);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(_s,"eventSourceRequestId");function nn(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(nn,"statusToWireCode");function Zr(e,t,r,n=null){return B({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(Zr,"syntheticErrorFrame");function on(){let e=globalThis.fetch;if(typeof e!="function")throw new $("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(on,"getGlobalFetch");function sn(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(l=>l[1]!==void 0).map(([l,u])=>`${encodeURIComponent(l)}=${encodeURIComponent(String(u))}`).join("&");s&&(o+=`?${s}`);}return o}i(sn,"buildUrl");function an(e,t,r,n){let o={...Xr(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(an,"mergeHeaders");function ln(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(ln,"buildInit");function Rs(e,t){return e.signal?e:{...e,signal:t}}i(Rs,"withSignal");function Es(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(Es,"timeoutSignal");function Cs(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Cs,"mergeAbortSignals");async function un(e){try{return await e.json()}catch{return null}}i(un,"safeJson");function Jr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Jr,"extractReasonCode");function dn(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(dn,"extractWireCode");function cn(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(cn,"extractWireMessage");function pn(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(pn,"extractRetryable");function fn(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(fn,"describeCause");var Ss=3e4,ks=ct*2,ws="idempotency-key",Ts=new Set(["POST","PUT","PATCH","DELETE"]),xs=Object.freeze({onEvent(){}}),Ps=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function As(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(As,"seededIdempotencyKey");function W(e){let t=e.observer??xs,r=e.timers??Ps,n=e.rng??Math.random,o=e.sleep??((g,y)=>Ks(g,r,y)),s=e.maxAttempts??ye,l=e.unaryTimeoutMs??Ss,u=e.newIdempotencyKey??Is(),a=i(g=>{try{t.onEvent(g);}catch{}},"emit");async function d(g,y,R){let x=R?.maxAttempts,C=Math.max(1,x??s),P=R?.idempotent??Ts.has(y.method),I=R?.idempotencyKey===void 0?null:As(R.idempotencyKey),j=P?I??u():null,F=Os(y,j),v=0;for(;;){let k=i(ue=>Object.freeze({call:g,method:y.method,path:y.path,attempt:v,...j?{idempotencyKey:j}:{},...ue}),"stamp");a(k({phase:"attempt"}));let L=qs(l,r),H=Hs(L.signal,y.signal),K;try{K=await Kr({...F,signal:H.signal},e.auth);}catch(ue){K=f(vt(ue));}finally{H.dispose(),L.cancel();}if(K.ok)return a(k({phase:"settled",ok:true,reason:"ok"})),K;let V=K.error,ie=Ms(V,v,{maxAttempts:C,rng:n,now:r.now(),aborted:y.signal?.aborted===true,...x!==void 0?{perCallMaxAttempts:x}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),me={ok:false,code:V.code,reason:ie.reason,...V.httpStatus!==void 0?{httpStatus:V.httpStatus}:{},...V.requestId!==void 0?{requestId:V.requestId}:{}};if(!ie.retry)return a(k({phase:"settled",...me})),f(V);if(a(k({phase:"retry",...me,delayMs:ie.delayMs})),await o(ie.delayMs,y.signal),y.signal?.aborted===true)return a(k({phase:"settled",...me,reason:"aborted"})),f(V);v+=1;}}i(d,"send");async function c(g){return ge(g,await Bs(e.auth))}i(c,"authorize");async function*p(g,y,R){a(Object.freeze({call:g,phase:"stream.open",method:y.method,path:y.path,attempt:0}));try{yield*e.auth.transport.stream(y,R);}catch{yield B({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(W,"createRequestFunnel");function Os(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==ws&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Os,"assembleHeaders");function Is(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Is,"defaultIdempotencyKeyFactory");var Fs=10;function Ms(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=Ds(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!re(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let l=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(Fs,Math.floor(d)))},"policyCeiling"),u=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=u)return {retry:false,reason:"attempts-exhausted"};let a=js(e,r.now);return a!==null?a>ks?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:a}:{retry:true,reason:o,delayMs:Be(t,r.rng)}}i(Ms,"decideRetry");function Ds(e){let t=e.code==="unknown"?Q(Us(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Ds,"throttleKind");function js(e,t){let r=Ls(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=zs(e.raw);return n===null?null:Math.round(n*1e3)}i(js,"retryOverrideMs");function zs(e){for(let t of _t(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(zs,"findRetryAfterSeconds");function Ls(e){for(let t of _t(e)){let r=t.resets_at,n=Ns(r);if(n!==null)return n}return null}i(Ls,"findResetsAt");function _t(e){if(!mn(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];mn(n)&&t.push(n);}return t}i(_t,"candidateScopes");function Ns(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(Ns,"parseInstantMs");function Us(e){for(let t of _t(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Us,"rawWireCode");function mn(e){return typeof e=="object"&&e!==null}i(mn,"isRecord");async function Bs(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Bs,"resolveDeviceAuth");function qs(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(qs,"boundedSignal");function Hs(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(Hs,"mergeSignals");function Ks(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(Ks,"delayAbortable");function M(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(M,"hasLoneSurrogate");function Ve(e){return [...e].length}i(Ve,"serverLength");var vn=Object.freeze(["better","same","worse"]),Et=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yn(e){return f(S("validationFailed",{retryable:false,wireMessage:e}))}i(yn,"invalid");function Rt(){return f(S("internalError",{retryable:false}))}i(Rt,"malformed");function gn(e){return typeof e!="string"||e.trim().length===0?S("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):M(e)?S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(gn,"petPath");var ne=i(e=>typeof e=="string"?e:null,"str"),hn=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function bn(e){if(typeof e!="object"||e===null)return null;let t=e,r=ne(t.case_id),n=ne(t.status);if(r===null||n===null)return null;let o=ne(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:ne(t.body_location),lastResponse:o!==null&&vn.includes(o)?o:null,checkInDueAt:ne(t.check_in_due_at),openedAt:ne(t.opened_at),resolvedAt:ne(t.resolved_at),resolutionText:ne(t.resolution_text),checkinAskCount:hn(t.checkin_ask_count),checkinAnswerCount:hn(t.checkin_answer_count)})}i(bn,"caseFromWire");function _n(e){return {async list(t,r){let n=gn(t);if(typeof n!="string")return f(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return f(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return Rt();let l=s.map(bn);return l.every(u=>u!==null)?_(Object.freeze(l)):Rt()},async checkin(t,r,n,o){let s=gn(t);if(typeof s!="string")return f(s);if(typeof r!="string"||!Et.test(r))return yn("case_id must be a UUID");if(!vn.includes(n))return yn("response must be one of better, same, worse");let l=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!l.ok)return f(l.error);let u=typeof l.value=="object"&&l.value!==null?l.value:{},a=bn(u.case);return a===null?Rt():_(Object.freeze({case:a,ctaDeepLink:ne(u.cta_deep_link)}))}}}i(_n,"createCasesRepositoryOver");var Rn=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var En=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function We(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(We,"delayAbortable");function Ge(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Ge,"mergeSignals");var Ct=class Ct{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?Ge(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(Ct,"MediaStore");var $e=Ct;function kt(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(kt,"makeUser");function wt(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(wt,"makeAssistant");function ve(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(ve,"stripPending");function Cn(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(Cn,"appendText");function Tt(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(Tt,"finalizeAssistant");function Sn(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(Sn,"freezeSnapshot");function E(e,t,r){return S(e,{retryable:t,...r?{wireMessage:r}:{}})}i(E,"makeError");function xt(e){let t=Q(e.code);return S(t,{retryable:e.retryable||Ue(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(xt,"errorFromFrame");function Z(e){return B({code:Vs(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Z,"synthErrorFrame");function Vs(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return qe(e)}}i(Vs,"canonicalWireCode");function kn(e){let t=Array.isArray(e)?e:St(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!St(n))continue;let o=be(n.category)??be(n.title)??"",s=$s(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(kn,"parsePromptCategories");function Pt(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(Pt,"flattenPrompts");function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(St,"isPlainObject");function be(e){return typeof e=="string"?e:null}i(be,"asStr");function $s(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(St(r)){let n=be(r.text)??be(r.prompt)??be(r.title);n!==null&&t.push(n);}return t}i($s,"asPromptTextList");function wn(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(wn,"defaultIdFactory");function Tn(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Tn,"defaultIdempotencyFactory");var Pn={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*An(e,t,r,n){let o=e[Symbol.asyncIterator](),s=xn(t.overallMs,n),l=xn(t.idleMs,n),u=Ys(r);try{for(;;){if(r.aborted)return;let a=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([a,l.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),u.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Gs();return}if(d.tag==="idle"||d.tag==="overall"){yield Ws();return}let c=d.value;if(c.done||(l.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{l.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(An,"withWatchdog");function Ws(){return B({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ws,"synthTimeoutFrame");function Gs(){return B({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Gs,"synthStreamErrorFrame");function xn(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(xn,"deadline");function Ys(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Ys,"abortPromise");var Xs="checkin",Qs=/^\d{4}-\d{2}-\d{2}$/,_e="watching";function Zs(e){return e.status!=null&&e.status!==_e}i(Zs,"isCheckinSettled");function On(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(On,"isLiveAskAnswered");function Js(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Xs||n===void 0||o===void 0||!Et.test(n)||!Qs.test(o)?null:{caseId:n,dueDay:o}}i(Js,"parseCheckinOrigin");function In(e){return Js(e)?.caseId??null}i(In,"parseCheckinOriginRef");function Ot(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return f(S("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||M(o))return f(S("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),_(r.length?`?${r.join("&")}`:"")}i(Ot,"historyQuery");function Ee(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(Ee,"validConversationId");function de(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(de,"object");function Fn(e){return e==null||typeof e=="string"&&e.length>0&&!M(e)}i(Fn,"cursor");function Re(){return f(S("internalError",{retryable:false}))}i(Re,"malformed");function Mn(e){let t=de(e);if(!t||!Array.isArray(t.conversations)||!Fn(t.next_cursor))return Re();let r=[];for(let n of t.conversations){let o=de(n);if(!o||typeof o.conversation_id!="string"||!Ee(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return Re();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return Re();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return _(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(Mn,"mapConversationPage");function Dn(e){let t=de(e);if(!t||!Array.isArray(t.messages)||!Fn(t.next_cursor))return Re();let r=[],n=new Set;for(let o of t.messages){let s=de(o);if(!s||typeof s.message_id!="string"||!Ee(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return Re();if(s.role!=="user"&&s.role!=="assistant"&&s.role!=="vet"||n.has(s.message_id))continue;if(n.add(s.message_id),s.role==="vet"){r.push(ea(s,s.message_id,s.content,s.created_at));continue}let l=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,u=s.role==="assistant"?In(l):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:ta(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:ra(s.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...u!==null?{checkin:Object.freeze({caseId:u,answer:null,resolutionText:null,status:null})}:{}}));}return _(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(Dn,"mapMessagePage");function ea(e,t,r,n){let o=de(e.sender),s=At(o?.display_name)??At(e.sender_display_name),l=At(o?.specialty);return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:Object.freeze({displayName:s,specialty:l})})}i(ea,"vetMessage");function At(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!M(t)?t:null}i(At,"trimmedText");function ta(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(ta,"normalizeUrgency");function ra(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=de(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let l=n[s];(typeof l=="string"||l===null)&&(o[s]=l);}return [Object.freeze(o)]}))}i(ra,"historyCitations");var Ye=5,It=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Ft=4e3;var Mt=4e3;function jn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:E("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:E("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(jn,"validateImageKeys");function Dt(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:E("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Mt?{reason:"too_long",error:E("validationFailed",false,`message is ${r} characters; the server accepts at most ${Mt}`)}:null}i(Dt,"validateMessageText");function zn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(zn,"urgencyTier");async function*Ce(e){yield e;}i(Ce,"singleFrameStream");async function*Ln(){}i(Ln,"emptyStream");var na=6e4,oa=18e4,ia=24,sa=512,aa=false;function Nn(e){return new jt(e)}i(Nn,"createChatController");var zt=class zt extends $e{constructor(r){super(Sn({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??W({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=_n(this.funnel),this.telemetry=r.telemetry??Le,this.errorPolicy=r.errorPolicy??Fr,this.timers=r.timers??Pn,this.rng=r.rng??Math.random,this.newId=r.newId??wn(),this.makeIdempotencyKey=r.makeIdempotencyKey??Tn(),this.budget={idleMs:r.budget?.idleMs??na,overallMs:r.budget?.overallMs??oa};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let a=E(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(a),()=>{}):Ce(Z(a))}let l=Dt(r)??jn(s.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),o?(o.onError(l.error),()=>{}):Ce(Z(l.error));if(o)return this.driveWithHandlers(r,s,o);let u=this.beginTurn(r,s);return this.runTurn(u,s.signal)}askEverfur(r,n){if(this.disposed)return Ce(Z(E("accessDenied",false)));let o=Dt(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Ce(Z(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):Ln()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,kt(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?ve(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(r=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=r,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:r,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}newConversation(){this.disposed||this.resetThread(this.scopePrompts);}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(Pt(r));this.bootstrapPrompts=n,this.scopePrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=Ot(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return f(E("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return f(E("accessDenied",false));if(!l.ok)return l;let u=Mn(l.value);if(u.ok){for(let c of u.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let a=this.snapshot.conversationId,d=a===null?void 0:this.unreadByConversation.get(a);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return u}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return f(E("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let a=await this.resumeConversation(n);return a.ok?_(n):f(a.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return f(s.error);let l=s.value.conversations[0];if(l===void 0)return _(null);let u=await this.resumeConversation(l.id);return u.ok?_(l.id):f(u.error)}async markRead(r){if(this.disposed)return f(E("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return _(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?f(E("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),_(void 0)):f(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return f(E("accessDenied",false));if(typeof r!="string"||r.trim().length===0||M(r))return f(E("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!It.includes(n))return f(E("validationFailed",false,`feedback_type must be one of ${It.join(", ")}`));let l=typeof o=="string"?o.trim():"";if([...l].length>Ft)return f(E("validationFailed",false,`notes is over ${Ft} characters`));let u={feedback_type:n};l.length>0&&(u.notes=l);let a=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:u},s?.signal);if(!this.alive(a)||this.disposed)return f(E("accessDenied",false));if(!d.ok)return f(d.error);let c=d.value?.feedback_id;return _(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return f(E("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return f(E("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,u=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(l)||this.disposed)return f(E("accessDenied",false));if(!u.ok)return u;let a=u.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:u.value.case.resolutionText,status:u.value.case.status??null,...a!==null?{openedAt:a}:{}}),c=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,checkin:d}):p)}),u}async getMessages(r,n){if(!Ee(r))return f(E("validationFailed",false));let o=Ot(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return f(E("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?f(E("accessDenied",false)):l.ok?Dn(l.value):l}async resumeConversation(r){if(this.disposed)return f(E("accessDenied",false));if(!Ee(r))return f(E("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return f(E("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),_(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===_e).map(d=>d.caseId)),l=new Map(o.value.map(d=>[d.caseId,d])),u=false,a=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;u=true;let p=l.get(c.caseId),g=c.openedAt??p?.openedAt??null,y=s.has(c.caseId),R=p!==void 0&&(!y||On({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:y?_e:p?.status??"resolved",answer:c.answer??R,resolutionText:c.resolutionText??p?.resolutionText??null,...g!==null?{openedAt:g}:{}})})});u&&this.patch({messages:a});}async refreshActiveThread(){if(this.disposed)return f(E("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return _(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return f(E("accessDenied",false));if(!o.ok)return f(o.error);let s=new Set(this.snapshot.messages.map(u=>u.id)),l=o.value.messages.filter(u=>!s.has(u.id));return l.length>0&&this.patch({messages:[...this.snapshot.messages,...l]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),_(void 0)}async loadOlderMessages(){if(this.disposed)return f(E("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return _(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return f(E("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let l=new Set(this.snapshot.messages.map(a=>a.id)),u=s.value.messages.filter(a=>!l.has(a.id));return this.patch({messages:[...u,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),_(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Z(n.error));}async primeConversation(r){if(this.disposed)return f(E("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?f(E("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);return n.ok?n.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n.value)).ok?_(n.value):_(this.snapshot.conversationId):n.error.code==="accessDenied"||n.error.httpStatus===403?_(null):f(n.error)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return f(n.error);let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?_(null):_(o.id)}async createConversation(r){let n=this.epoch;if(this.disposed)return f(E("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let l=await s.settled;return !this.alive(n)||this.disposed?f(E("accessDenied",false)):(!l.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),l)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return f(s.error);let l=s.value?.conversation_id??s.value?.id;return typeof l!="string"||l.length===0?f(E("internalError",true)):_(l)}async getPrompts(r){let n=this.epoch;if(this.disposed)return f(E("accessDenied",false));let o=r?.petRef??null;if(o!==null&&M(o))return f(S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?f(E("accessDenied",false)):l.ok?_(kn(l.value)):f(l.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,l=Ge(s.signal,n.signal),u=this.beginTurn(r,n),a=this.runTurn(u,l),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of a){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,kt(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,l=false,u=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let a=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=a?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let C=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;C.ok&&C.value!==null&&this.snapshot.conversationId===null&&this.adoptConversation(C.value);}if(a&&this.snapshot.conversationId===null){let C=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!C.ok){yield*this.emitTerminal(r,C.error,Z(C.error));return}this.adoptConversation(C.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let C=E("internalError",!0);yield*this.emitTerminal(r,C,Z(C));return}this.clearAssistantInProgress(r);let p=new AbortController,g=Ge(o.signal,p.signal),y=null;try{let C;try{C=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let I=this.authRejected();yield*this.emitTerminal(r,I,Z(I));return}if(o.signal.aborted||!this.alive(o.epoch))return;let P=this.funnel.stream("chat.send",C,g);for await(let I of An(P,this.budget,g,this.timers)){if(!this.alive(o.epoch))return;if(I.kind==="error"&&I.terminal){y=I;break}if(this.applyFrame(I,r),yield I,I.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(y===null){if(this.snapshot.status==="complete")return;let C=E("streamIncomplete",!0);yield*this.emitTerminal(r,C,Z(C));return}let R=Q(y.code);if(R==="authExpired"&&this.auth.mode==="personalized"&&!u){u=!0,this.telemetry.track("chat.auth.refresh",{});let C=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!C){let P=this.authRejected();yield*this.emitTerminal(r,P,y);return}this.patch({reconnecting:!0});continue}if(R==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let C=this.authRejected();yield*this.emitTerminal(r,C,y);return}if(R==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,xt(y),y);return}if(Ir(R)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let x=y.retryable&&Ue(R,!0);if(aa&&x&&s+1<this.errorPolicy.maxAttempts(R));yield*this.emitTerminal(r,xt(y),y);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return qe(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(l=>l.id===n.userMessageId&&l.pending===true?ve(l):l);this.patch({status:"streaming",isStreaming:true,messages:[...s,wt(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=sa){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},ia);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(l=>l.id===o?Cn(l,n):l);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(u=>u.id===n.assistantMessageId?Tt(u,r):u);else {let u=this.newId();n.assistantMessageId=u,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?ve(d):d),Tt(wt(u,"",this.stamp()),r)];}let l=Pt([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=l.length>0?Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,l=this.historyGeneration,u=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!u.ok||!this.alive(s)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==r)return;let a=zn(u.value?.urgency),d=typeof u.value?.reason=="string"?u.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:a,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?ve(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return E("authRejected",false)}};i(zt,"ChatControllerImpl");var jt=zt;async function qn(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],l=false,u=false,a=false,d=null,c=null,p=o?r.resumeConversation(o).then(F=>F.ok?_(o):f(F.error)):r.primeConversation(n?{petRef:n}:void 0),g=r.getPrompts(n!==null?{petRef:n}:void 0),[y,R]=await Promise.all([p,g]),x=null;if(y.ok)x=y.value,y.value!==null&&s.push(y.value),y.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(y.value);else {let F=y.error;c=F,Un(F)?(u=true,d=F):(Bn(F)&&(l=true),a=true);}let C=[];R.ok?C=R.value:P(R.error);function P(F){Un(F)?(u=true,d===null&&(d=F)):Bn(F)&&(l=true);}i(P,"recordAuthSignals");let I=d!==null?d.displayMessage:null;return Object.freeze({conversationId:x,petRef:n,suggestedPrompts:C,error:I,warning:I===null&&x===null&&a?la:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:l,sawUnauthorized:u,sawConversationInitFailure:a})})}i(qn,"bootstrapChat");var la="Chat is ready. Your first message will start the conversation.";function Un(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(Un,"isUnauthorized");function Bn(e){return e.httpStatus===403||e.code==="accessDenied"}i(Bn,"isForbidden");var Lt=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Hn(e){return e!==Lt}i(Hn,"isUploadTransportAvailable");var Kn=128,oe=128;var ua=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),Yc="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",$n=10*1024*1024,da=5,Se=120,ca="/widget/v1/uploads/initiate";function pa(e){return typeof e=="string"&&ua.includes(e.trim().toLowerCase())}i(pa,"isAttachmentMime");function fa(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=Se)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Se);let n=t.slice(r);return n.length>=Se?t.slice(0,Se):`${t.slice(0,r).slice(0,Se-n.length)}${n}`}i(fa,"sanitizeFilename");function Xc(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(Xc,"formatBytes");var ke=i(e=>Object.freeze({ok:true,value:e}),"ok"),G=i(e=>Object.freeze({ok:false,error:e}),"err");function z(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(z,"failure");function ma(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i(ma,"attachmentSize");function ya(e){let t=fa(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!pa(r))return G(z("unsupported_type",false,t));let n=ma(e);return n===null?G(z("unknown",false,t)):n>$n?G(z("too_large",false,t,{sizeBytes:n})):ke(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(ya,"validateAttachment");function ga(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),l=r(t.s3_key);if(o===null||s===null||l===null)return null;let u={},a=t.upload_fields;if(typeof a=="object"&&a!==null)for(let[d,c]of Object.entries(a))typeof c=="string"&&(u[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(u),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??$n,s3_key:l,purpose:r(t.purpose)})}i(ga,"parsePolicy");function ha(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return z("quota_exceeded",false,t,{cause:e});case "rateLimited":return z("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return z("idempotency_conflict",true,t,{cause:e});case "validationFailed":return z("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return z("network",true,t,{cause:e});default:return r===429?z("rate_limited",true,t,{cause:e}):r===503?z("network",true,t,{cause:e}):r===void 0?z("network",true,t,{cause:e}):z("server",e.retryable,t,{httpStatus:r,cause:e})}}i(ha,"initiateFailure");async function ba(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:ca,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return G(ha(n.error,t.filename));let o=ga(n.value);return o===null?G(z("server",false,t.filename)):ke(o)}i(ba,"initiateAttachmentUpload");async function va(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return G(z("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),ke(void 0)}catch{return o()?G(z("cancelled",true,r.filename)):G(z("server",true,r.filename))}}i(va,"uploadAttachmentBytes");var _a=2,Ra=3,Ea=Object.freeze([1e3,2e3,4e3]),Vn=0;function Ca(){return Vn+=1,`attachment-${Vn}`}i(Ca,"defaultNewId");function Qc(e){let t=Math.max(1,e.concurrency??_a),r=Math.max(1,e.maxAttempts??Ra),n=e.backoffMs??Ea,o=Math.max(1,e.maxPerMessage??da),s=e.timers??En,l=e.newId??Ca,u=Hn(e.transport),a=new Map,d=[],c=[],p=new Set,g=new Set,y=Object.freeze({attachments:Object.freeze([])}),R=false,x=i(()=>{y=Object.freeze({attachments:Object.freeze(d.flatMap(v=>{let k=a.get(v);return k===void 0?[]:[k.state]}))});for(let v of g)v();},"publish"),C=i((v,k)=>{v.state=Object.freeze({...v.state,...k}),x();},"patch"),P=i(()=>{for(;!R&&p.size<t&&c.length>0;){let v=c.shift(),k=a.get(v);k!==void 0&&(p.add(v),I(k).finally(()=>{p.delete(v),P();}));}},"pump"),I=i(async v=>{let{attachment:k}=v;for(;v.attempts<r;){if(R||v.controller.signal.aborted)return;v.attempts+=1;let L=v.controller.signal;C(v,{status:"uploading",error:null,progress:0});let H=await ba(e.funnel,k,{signal:L});if(R||L.aborted)return;let K;if(!H.ok)K=G(H.error);else {let ue=await va(e.transport,H.value,k,{signal:L,onProgress:i(xi=>{!L.aborted&&v.state.status==="uploading"&&C(v,{progress:Sa(xi)});},"onProgress")});if(R||L.aborted)return;K=ue.ok?ke(H.value.s3_key):G(ue.error);}if(K.ok){C(v,{status:"uploaded",s3Key:K.value,error:null,progress:1});return}let V=K.error,ie=V.retryable&&v.attempts<r;if(C(v,{status:ie?"uploading":"failed",error:V,progress:0}),!ie)return;let me=n[Math.min(v.attempts-1,n.length-1)]??0;await We(me,L,s);}},"run"),j=i(v=>{c.push(v.state.id),P();},"enqueue"),F={available:u,subscribe(v){return g.add(v),()=>{g.delete(v);}},getSnapshot:i(()=>y,"getSnapshot"),get uploading(){return y.attachments.some(v=>v.status==="uploading")},get s3Keys(){return y.attachments.flatMap(v=>v.status==="uploaded"&&v.s3Key!==null?[v.s3Key]:[])},add(v){let k=ya(v);if(!k.ok)return k;if(R||d.length>=o)return G(z("too_many",false,k.value.filename));let L=l(),H={attachment:k.value,controller:new AbortController,attempts:0,state:Object.freeze({id:L,filename:k.value.filename,previewUri:v.uri,contentType:k.value.contentType,sizeBytes:k.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(L,H),d.push(L),x(),j(H),ke(H.state)},retry(v){let k=a.get(v);k===void 0||R||k.state.status!=="failed"||(k.controller=new AbortController,k.attempts=0,C(k,{status:"uploading",error:null,progress:0,s3Key:null}),j(k));},remove(v){let k=a.get(v);if(k===void 0)return;k.controller.abort(),a.delete(v);let L=d.indexOf(v);L>=0&&d.splice(L,1);let H=c.indexOf(v);H>=0&&c.splice(H,1),x();},clear(){for(let v of [...d])F.remove(v);},dispose(){R=true;for(let v of a.values())v.controller.abort();a.clear(),d.length=0,c.length=0,g.clear(),y=Object.freeze({attachments:Object.freeze([])});}};return F}i(Qc,"createAttachmentQueue");function Sa(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Sa,"clamp");var Wn=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function Gn(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Wn,t)?Wn[t]:null}i(Gn,"canonicalPetSpecies");var Yn=50,ka=128,Nt=120,Xn=120,wa=2e3,Qn=120,Ta=80,eo=new Set(["male","female","unknown"]),to=new Set(["day","month","year"]),ro=new Set(["low","medium","high","athletic"]),no=new Set(["indoor","outdoor","both"]),oo=new Set(["mild","moderate","severe"]),xa=/^(\d{4})-(\d{2})-(\d{2})$/,io=[["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"]],so=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...io,...so].map(([e])=>e));function Pa(e){let t=xa.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(Pa,"isRealDate");var Te=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),Aa=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Qe=i((e,t)=>typeof t=="string"&&Pa(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),J=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(M(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=Ve(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),Oa={sex:Te(eo),spayedNeutered:Aa,birthDate:Qe,birthDatePrecision:Te(to),activityLevel:Te(ro),indoorOutdoor:Te(no),foodBrand:J(Qn),foodType:J(Qn),microchipId:J(Ta)},Ut=["ref","ref",false,J(ka,{required:true,trimmed:true})],Bt=["notes","notes",false,J(wa,{trimmed:true})],Zn=[Ut,["name","name",true,J(Nt,{required:true,trimmed:true})],["dose","dose",false,J(Xn,{trimmed:true})],["frequency","frequency",false,J(Xn,{trimmed:true})],["startDate","start_date",false,Qe],["endDate","end_date",false,Qe],Bt],Ia={allergies:[Ut,["allergen","allergen",true,J(Nt,{required:true,trimmed:true})],["severity","severity",false,Te(oo)],Bt],medications:Zn,supplements:Zn,conditions:[Ut,["conditionName","condition_name",true,J(Nt,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Qe],Bt]};function Fa(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[a,d,c,p]of Ia[e]){let g=o[a];if(g==null){if(c)return {error:`${n}.${a} is required`};g===null&&(s[d]=null);continue}let y=p(`${n}.${a}`,g);if(y!==null)return {error:y};s[d]=g;}let l=s.start_date,u=s.end_date;return typeof l=="string"&&typeof u=="string"&&u<l?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(Fa,"itemToWire");function Ma(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>Yn)return {error:`${e} has ${t.length} items; the server accepts at most ${Yn}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=Fa(e,o,t[o]);if("error"in s)return s;let l=s.item.ref;if(typeof l=="string"){let u=l.trim();if(n.has(u))return {error:`${e}: ref ${JSON.stringify(u)} is used twice; a ref names one item`};n.add(u);}r.push(s.item);}return {items:r}}i(Ma,"listToWire");function ao(e,t){let r=e,n={};for(let[l,u]of io){let a=r[l];if(a!==void 0){if(a!==null){let d=Oa[l](l,a);if(d!==null)return {error:d}}n[u]=a;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[l,u]of so){let a=r[l];if(a===void 0)continue;let d=Ma(l,a);if("error"in d)return d;n[u]=d.items;}return Object.keys(n).length>0&&t!==void 0&&Gn(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(ao,"petHealthToWire");var D=i(e=>typeof e=="string"?e:null,"str"),we=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),Da=i(e=>typeof e=="boolean"?e:null,"bool");function Xe(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(Xe,"itemsFromWire");function Jn(e){let t=D(e.name);return t===null||t.length===0?null:Object.freeze({ref:D(e.ref),name:t,dose:D(e.dose),frequency:D(e.frequency),startDate:D(e.start_date),endDate:D(e.end_date),notes:D(e.notes)})}i(Jn,"medicationFromWire");function lo(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:we(eo,e.sex),spayedNeutered:Da(e.spayed_neutered),birthDate:D(e.birth_date),birthDatePrecision:we(to,e.birth_date_precision),activityLevel:we(ro,e.activity_level),indoorOutdoor:we(no,e.indoor_outdoor),foodBrand:D(e.food_brand),foodType:D(e.food_type),microchipId:D(e.microchip_id),allergies:Xe(e.allergies,r=>{let n=D(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:D(r.ref),allergen:n,severity:we(oo,r.severity),notes:D(r.notes)})}),medications:Xe(e.medications,Jn),supplements:Xe(e.supplements,Jn),conditions:Xe(e.conditions,r=>{let n=D(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:D(r.ref),conditionName:n,diagnosedDate:D(r.diagnosed_date),notes:D(r.notes)})})})}i(lo,"petHealthFromWire");var po=100,fo=50,mo=100,yo=50,go=500,ja=128,za=6e4;function te(e){return S("validationFailed",{retryable:false,wireMessage:e})}i(te,"invalid");function se(e,t,r){if(typeof t!="string")return te(`${e} must be a string`);let n=Ve(t);return n<=r?null:te(`${e} is ${n} characters; the server accepts at most ${r}`)}i(se,"checkString");function Ze(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:te(`${e} must be a finite number between 0 and ${r}`)}i(Ze,"outOfRange");function uo(e,t){if(typeof e!="string")return te("pet_ref must be a string");if(e.trim().length===0)return te("pet_ref must not be blank");if(M(e))return te("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return te("profile must be an object");let r=[se("pet_ref",e,ja)];return t?.name!==void 0&&r.push(se("name",t.name,po)),t?.species!==void 0&&r.push(se("species",t.species,fo)),t?.breed!==void 0&&r.push(se("breed",t.breed,mo)),t?.ageYears!==void 0&&r.push(Ze("age_years",t.ageYears,yo)),t?.weightKg!==void 0&&r.push(Ze("weight_kg",t.weightKg,go)),r.find(n=>n!==null)??null}i(uo,"validate");function ho(e,t){let r=ao(e,t);return "error"in r?{error:te(r.error)}:r}i(ho,"healthToWire");function La(e){if(typeof e!="object"||e===null)return {error:te("patch must be an object")};let t=e,r=[["name","name",s=>se("name",s,po)],["species","species",s=>se("species",s,fo)],["breed","breed",s=>se("breed",s,mo)],["ageYears","age_years",s=>Ze("age_years",s,yo)],["weightKg","weight_kg",s=>Ze("weight_kg",s,go)]],n={};for(let[s,l,u]of r){let a=t[s];if(a!==void 0){if(a!==null){let d=u(a);if(d!==null)return {error:d}}n[l]=a;}}let o=ho(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:te("patch must change at least one field")}:{body:n})}i(La,"patchToWire");function Na(e){if(e==null)return {body:{}};let t=ho(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(Na,"toWire");var ee=i(e=>typeof e=="string"?e:null,"str"),Je=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function co(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:ee(r.pet_ref)??t,name:ee(r.name),species:ee(r.species),breed:ee(r.breed),ageYears:Je(r.age_years),weightKg:Je(r.weight_kg)})}i(co,"fromWire");function bo(e){if(typeof e!="object"||e===null)return null;let t=e,r=ee(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:ee(t.pet_id),petRef:r,name:ee(t.name),species:ee(t.species),breed:ee(t.breed),ageYears:Je(t.age_years),weightKg:Je(t.weight_kg),updatedAt:ee(t.updated_at)})}i(bo,"widgetPetFromWire");function Ua(e){let t=bo(e);return t===null?null:Object.freeze({...t,...lo(e)})}i(Ua,"widgetPetProfileFromWire");function Ba(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=bo(r);return n===null?[]:[n]}))}i(Ba,"petListFromWire");function vo(e){return qa(W({auth:e}),W({auth:e,unaryTimeoutMs:za}))}i(vo,"createPetsRepository");function qa(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>uo(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?_(Ba(s.value)):f(s.error)},async registerPet(o,s,l){let u=uo(o,s);if(u!==null)return f(u);let a=Na(s);if("error"in a)return f(a.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:a.body},p=await e.send("pets.registerPet",l?.signal?{...c,signal:l.signal}:c);return p.ok?_(co(p.value,o)):f(p.error)},async updatePet(o,s,l){let u=n(o);if(typeof u!="string")return f(u);let a=La(s);if("error"in a)return f(a.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:u,body:a.body},l?.signal));return d.ok?_(co(d.value,o)):f(d.error)},async getPetProfile(o,s){let l=n(o);if(typeof l!="string")return f(l);let u=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},s?.signal));if(!u.ok)return f(u.error);let a=Ua(u.value);return a===null?f(S("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):_(a)},async deletePet(o,s){let l=n(o);if(typeof l!="string")return f(l);let u=await e.send("pets.deletePet",r({method:"DELETE",path:l},s?.signal));return u.ok?_(void 0):f(u.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?_(void 0):f(s.error)}}}i(qa,"createPetsRepositoryOver");var _o=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function Ro(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(_o))for(let l of _o[s])o.has(l)||(o.add(l),n.push(Object.freeze({resource:l,granted:false,disabled:r})));return Object.freeze(n)}i(Ro,"deniedDecisionsFor");function q(e){let t=Ha(e);return t===null?null:Va(t)}i(q,"parseColor");function Ha(e){if(typeof e=="number")return Eo(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return qt(t.slice(1));if(t.toLowerCase().startsWith("0x"))return qt(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ka(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=qt(t);if(r!==null)return r}return /^\d+$/.test(t)?Eo(Number.parseInt(t,10)):null}i(Ha,"toRgba");function qt(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Ht(t[0]),g:Ht(t[1]),b:Ht(t[2]),a:1};if(t.length===6)return {r:ae(t,0),g:ae(t,2),b:ae(t,4),a:1};if(t.length===8){let r=ae(t,0);return {r:ae(t,2),g:ae(t,4),b:ae(t,6),a:r/255}}return null}i(qt,"fromHex");function Ka(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(a=>a.trim());if(n.length<3)return null;let o=Kt(Number(n[0])),s=Kt(Number(n[1])),l=Kt(Number(n[2]));if(o===null||s===null||l===null)return null;let u=1;if(n.length>=4){let a=Number(n[3]);if(!Number.isFinite(a))return null;u=Math.min(1,Math.max(0,a));}return {r:o,g:s,b:l,a:u}}i(Ka,"fromRgbFunc");function Eo(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(Eo,"argbIntToRgba");function ae(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ae,"byte");function Ht(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Ht,"dup");function Kt(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Kt,"clampByte");function Va(e){if(e.a>=1)return $a(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Va,"normalizeRgba");function $a(e,t,r){return `#${Vt(e)}${Vt(t)}${Vt(r)}`.toUpperCase()}i($a,"rgbToHex");function Vt(e){return e.toString(16).padStart(2,"0")}i(Vt,"hex2");var xe=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link"]);var Wa=Object.freeze({});function Ga(e){return xe.includes(e)}i(Ga,"isSlotName");function Ya(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Ya,"parseRadius");function Co(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Ga(n)||o===null||typeof o!="object")continue;let s=Xa(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(Co,"parseThemeSlots");function et(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(et,"pick");function Xa(e){let t={},r=q(et(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=q(et(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Ya(et(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=q(et(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Xa,"parseSlot");function So(e,t){return t===null||Object.keys(t).length===0?e??Wa:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(So,"mergeThemeSlots");var Qa=Object.freeze(["everfur","minimal","night"]),Za=Object.freeze({everfur:Object.freeze({}),minimal:Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:Object.freeze({colorScheme:"dark"})}),rt=Object.freeze({fontSizeBase:Object.freeze({min:12,max:20,default:14}),borderRadius:Object.freeze({min:0,max:32,default:14}),spacingUnit:Object.freeze({min:3,max:6,default:4})});function tt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(tt,"isRecord");function Ja(e){return typeof e=="string"&&Qa.includes(e.trim().toLowerCase())}i(Ja,"isPreset");function Pe(e,t){let r=e[t];return r??void 0}i(Pe,"present");var el=16;function tl(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>el)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}i(tl,"parsePx");var rl=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],nl=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function ko(e){if(!tt(e))return null;let t=Ja(e.theme)?Za[e.theme.trim().toLowerCase()]:{},r=tt(e.variables)?e.variables:{},n={...t};for(let[p,g]of Object.entries(r))g!=null&&(n[p]=g);let o={},s=Pe(n,"colorScheme"),l=typeof s=="string"?s.trim().toLowerCase():null;(l==="light"||l==="dark"||l==="auto")&&(o.color_scheme=l);let u=l==="dark"?"_dark":"";for(let[p,g]of rl){let y=Pe(n,p);y!==void 0&&(o[`${g}${u}`]=y);}let a=Pe(n,"colorDanger");a!==void 0&&(o[`danger_color${u}`]=a);let d=Pe(n,"fontFamily");typeof d=="string"&&d.trim().length>0&&(o.font_family=d.trim());for(let[p,g]of nl){let y=tl(Pe(n,p));y!==void 0&&(o[g]=y);}let c=e.rules;if(tt(c)){let p={};for(let g of xe){let y=c[g];tt(y)&&(p[g]=y);}Object.keys(p).length>0&&(o.slots=p);}return Object.keys(o).length===0?null:Object.freeze(o)}i(ko,"expandAppearance");var Po=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"]),nt="slots.";function Ao(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(Ao,"isEmptyBranding");function il(e){return e==="hide_powered_by"||Po.includes(e)?true:e.startsWith(nt)&&xe.includes(e.slice(nt.length))}i(il,"isThemeLockName");function Ae(e){if(e===null||typeof e!="object")return null;let t=e,r=wo(t),n=ko(w(t,"appearance")),o=n===null?r:sl(wo(n),r);return Ao(o)?null:Object.freeze(o)}i(Ae,"parseClientBranding");function sl(e,t){let r={...e};for(let[o,s]of Object.entries(t))s!=null&&(r[o]=s);let n=So(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}i(sl,"overlayFlat");function wo(e){return {displayName:le(w(e,"display_name","displayName")),logoUrl:le(w(e,"logo_url","logoUrl")),primaryColor:q(w(e,"primary_color","primaryColor")),accentColor:q(w(e,"accent_color","accentColor")),brightness:dl(w(e,"brightness","color_scheme","colorScheme")),fontFamily:le(w(e,"font_family","fontFamily")),fontUrl:le(w(e,"font_url","fontUrl")),fonts:To(w(e,"fonts")),fontUrls:To(w(e,"font_urls","fontUrls")),placeholder:le(w(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:al(w(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:q(w(e,"primary_color_dark","primaryColorDark")),accentColorDark:q(w(e,"accent_color_dark","accentColorDark")),surfaceStyle:xo(w(e,"surface_style","surfaceStyle"),ll),radiusScale:xo(w(e,"radius_scale","radiusScale"),ul),logoUrlDark:le(w(e,"logo_url_dark","logoUrlDark")),slots:Co(w(e,"slots")),accessibilityMaxFontScale:pl(w(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:ml(w(e,"locked_fields","lockedFields")),schemaVersion:fl(w(e,"schema_version","schemaVersion")),backgroundColor:q(w(e,"background_color","backgroundColor")),backgroundColorDark:q(w(e,"background_color_dark","backgroundColorDark")),textColor:q(w(e,"text_color","textColor")),textColorDark:q(w(e,"text_color_dark","textColorDark")),dangerColor:q(w(e,"danger_color","dangerColor")),dangerColorDark:q(w(e,"danger_color_dark","dangerColorDark")),fontSizeBase:$t(w(e,"font_size_base","fontSizeBase"),rt.fontSizeBase),borderRadius:$t(w(e,"border_radius","borderRadius"),rt.borderRadius),spacingUnit:$t(w(e,"spacing_unit","spacingUnit"),rt.spacingUnit)}}i(wo,"parseFlat");function $t(e,t){let r=ot(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}i($t,"parseClamped");function al(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(al,"parseBool");function w(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(w,"pick");function le(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(le,"parseNonEmptyString");var Oo=["regular","medium","bold","mono","monoMedium","monoBold"];function To(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of Oo){let o=le(w(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(To,"parseFaceMap");var ll=["white","cream","subtle"],ul=["sharp","default","round"];function xo(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(xo,"parseEnum");function dl(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(dl,"parseBrightness");function ot(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(ot,"parseNumber");var cl=1,Io=3.1;function pl(e){let t=ot(e);return t===null?null:t<=0?0:Math.min(Io,Math.max(cl,t))}i(pl,"parseMaxFontScale");function fl(e){if(e==null)return null;let t=ot(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(fl,"parseSchemaVersion");function Fo(e){let t=e.trim();return t.startsWith(nt)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Fo,"toWireName");function ml(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Fo(r);il(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(ml,"parseLockedFields");var Mo="/widget/v1/entitlements",yl=304,gl=Object.freeze({kind:"notModified"});async function jo(e,t={},r=W({auth:e})){let n=await r.send("entitlements.fetch",bl(t));return n.ok?vl(n.value):n.error.httpStatus===yl?gl:{kind:"failed",error:n.error}}i(jo,"fetchEntitlements");var hl=64;function bl(e){let t={};return Wt(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=hl?{method:"GET",path:Mo,headers:t,query:{region:e.region}}:{method:"GET",path:Mo,headers:t}}i(bl,"buildRequest");function vl(e){if(e===null||typeof e!="object"||!Wt(e.revision))return Do();let t=typeof e.region=="string"?e.region:"",r=Wt(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Rl(e.capabilities),branding:_l(e),livemode:e.livemode!==false})}i(vl,"parseUpdated");function _l(e){let t=Ae(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=Ae(r.branding);return n!==null?n:Ae(r)}return null}i(_l,"parseBranding");function Rl(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))El(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Rl,"mapCapabilities");function El(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(El,"isEnabled");function Do(){return {kind:"failed",error:S("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Do,"malformed");function Wt(e){return typeof e=="number"&&Number.isFinite(e)}i(Wt,"isFiniteNumber");var Cl=30;function zo(e){let t=e.scheduler??Sl,r=e.resolve??jo,n=Math.max(1,e.floorSeconds??Cl),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),l=false,u=false,a=null,d=null,c=n,p=0,g=i(()=>{a!==null&&(t.clear(a),a=null);},"clearTimer"),y=i(P=>{u||!l||(c=Math.max(n,P),a=t.set(()=>{a=null,C();},c*1e3));},"schedule"),R=null,x=i(async()=>{if(u)return null;let P=p;e.onFetch?.();let I=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},j;try{j=await r(e.authFor(),I);}catch(F){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:kl(F)}),!u&&P===p&&(e.onSettled?.(),y(s())),null}if(u||P!==p)return null;switch(j.kind){case "updated":d=j.revision,e.update(j.decisions,j.branding??null,j.livemode!==false),y(j.ttlSeconds);break;case "notModified":y(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:j.error.code}),y(s());break;default:y(s());}return e.onSettled?.(),j},"tick"),C=i(()=>{let P=x().finally(()=>{R===P&&(R=null);});return R=P,P},"run");return {start(){l||u||(l=true,C());},prime(){return u?Promise.resolve(null):R??C()},stop(){u||(u=true,p++,g());},refresh(){u||!l||(p++,d=null,g(),C());}}}i(zo,"createEntitlementPoller");var Sl={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function kl(e){return e instanceof Error?e.message:"poll failed"}i(kl,"describe");var Lo="everfur.notifications.device";var Uo=3e3,No=Object.freeze([Lo]);function Bo(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),l=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),u=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:l.length});}catch{}},"report"),a=Promise.allSettled(l).then(d=>{let c=d.filter(p=>p.status==="rejected").length;c>0&&u("failed",c);});return new Promise(d=>{let c=false,p=i(()=>{c||(c=true,clearTimeout(g),d());},"finish"),g=setTimeout(()=>{c||u("timeout",l.length),p();},Uo);a.then(p,p);})}i(Bo,"startBeforeLogoutHooks");function qo(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let l={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:l,userRef:t.userRef,sessionId:o}}i(qo,"graceAuth");async function Ho(e,t){if(No.length===0)return;let r=await Promise.allSettled(No.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Ho,"sweepPerUserKv");function wl(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(wl,"compiledDefaultDecisions");function Gt(e=wl){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null,...o.livemode===false?{livemode:false}:{}}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Gt,"createEntitlementStore");function Yt(e){return S("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Yt,"notConfiguredError");function Ko(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return Yr(r,t===void 0?void 0:{platform:t})}i(Ko,"tryResolveClient");function Vo(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Vo,"guardTelemetry");var Tl=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 ${Ke} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function $o(e,t,r=ht){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
|
|
12
|
-
[everfur] Every Everfur capability will render its off-state until this is fixed. `+Tl[r]);}i($o,"reportConfigFailure");function Xt(e){return Object.freeze({request(){return Promise.resolve(f(Yt(e)))},stream(t,r){let n=B({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(Xt,"refusingTransport");function Wo(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Wo,"createInMemoryKv");var Go=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function kf(e,t){return new Zt(e,t)}i(kf,"createEverfurRuntime");var xl=6e4,Jt=class Jt{constructor(t,r){this.sessionId=yt();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new $("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Vo(n.telemetry):Le;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=bt(n?.publishableKey),l=n.transport!==void 0,u,a=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)u=Xt(s);else if(n.transport!==void 0)u=n.transport;else {let c=Ko(n,r?.platform);c.ok?(a=c.config.apiBaseUrl,u=tn({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,u=Xt(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=u,s!==null&&$o(s,this.telemetry,r?.platform),this.errorPolicy=n.errorPolicy,this.camera=n.camera??Mr,this.upload=n.upload??Rn,this.uploadTransport=n.uploadTransport??Lt,this.imageCache=n.imageCache??Go,this.kv=n.storage??Wo(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?Gt():Gt(()=>Ro("sdk_config",ft("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",Qt(c),()=>this.buildChatController(c),Yo),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Qt(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,g,y)=>this.acquireInternal(c,p,g,y),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!l);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Hr(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-xl,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return zo({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n,o)=>this.updateEntitlements({decisions:r,isPending:false,branding:n,...o===false?{livemode:o}:{}}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let l=`${this.epoch}|${t}|${r}`,u=this.entries.get(l);if(u)return s||(u.warm?u.warm=false:u.refCount+=1),u.controller;let a=n();return this.entries.set(l,{controller:a,refCount:1,warm:s}),this.destroyers.set(a,o),a}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=Nn({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=qn(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=yt(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Ho(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Bo({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>qo({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?f(Xo(t)):r(vo(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(l=>(s.result=l,l))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Xo("prepare"):n===null?null:Yt(n),s=this.identity,[l,u,a]=await Promise.all([o?f(o):s===null?_(void 0):s.currentToken().then(()=>_(void 0),()=>f(S("authRejected",{retryable:false}))),o?f(o):this.primeEntitlements(),t===null?void 0:o?f(o):this.primeChat(t)]),d=l.ok?u.ok&&(a?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:l,entitlements:u,...a?{chat:a}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?f(t.error):_(void 0):f(S("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Qt(r),()=>this.buildChatController(r),Yo,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?f(o.cause):_(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Jt,"EverfurRuntimeImpl");var Zt=Jt;function Qt(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Qt,"chatScopeKey");function Yo(e){e.dispose();}i(Yo,"disposeChat");function Xo(e){return S("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Xo,"disposedError");var Jo=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Qo=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function Pl(e){let t=Object.prototype.hasOwnProperty.call(Qo,e)?Qo[e]:void 0;if(t!==void 0)return t;let r=e;return Jo.has(r)?r:"parsing"}i(Pl,"normalizeStatus");function Al(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Al,"normalizeOrigin");var Ol=zod.z.object({request_id:zod.z.string().min(1),pet_ref:zod.z.string().min(1),status:zod.z.string(),simple_status:zod.z.string().nullish(),simple_status_detail:zod.z.string().nullish(),status_label:zod.z.string().optional(),dispatch_status:zod.z.string().nullish(),can_retry_send:zod.z.boolean().optional(),can_revoke:zod.z.boolean().optional(),can_convert_to_upload:zod.z.boolean().optional(),can_update_clinic_email:zod.z.boolean().optional(),reminder_count:zod.z.number().int().nonnegative().optional(),last_reminder_at:zod.z.string().nullish(),waiting_expectation:zod.z.string().nullish(),document_count:zod.z.number().optional(),held_item_count:zod.z.number().optional(),received_at:zod.z.string().nullish(),parsing_started_at:zod.z.string().nullish(),review_started_at:zod.z.string().nullish(),created_at:zod.z.string().optional(),updated_at:zod.z.string().optional(),source:zod.z.string().nullish().catch(null),action_needed_label:zod.z.string().nullish().catch(null),failure_reason:zod.z.string().nullish().catch(null),failure_code:zod.z.string().nullish().catch(null),recovery_stage:zod.z.string().nullish().catch(null),show_clinic_phone:zod.z.boolean().optional().catch(void 0),clinic_name:zod.z.string().nullish().catch(null),clinic_email:zod.z.string().nullish().catch(null),clinic_phone:zod.z.string().nullish().catch(null),converted_to_upload_at:zod.z.string().nullish().catch(null),request_group_id:zod.z.string().nullish().catch(null)}).passthrough();function ei(e){let t=Ol.safeParse(e);if(!t.success)return null;let r=t.data,n=Il(r.simple_status),o=n==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":n==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":n??Pl(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:o,simpleStatus:n,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:Zo(r.document_count,0),heldItemCount:Zo(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(ei,"mapRequestView");zod.z.object({request_group_id:zod.z.string().min(1),pet_ref:zod.z.string().min(1),total:zod.z.number().int().nonnegative(),responded:zod.z.number().int().nonnegative(),pending:zod.z.number().int().nonnegative(),members:zod.z.array(zod.z.unknown())});function Il(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Jo.has(e)?e:null}i(Il,"normalizeSimpleStatus");zod.z.object({source_doc_id:zod.z.string().min(1),request_id:zod.z.string().min(1)});var Fl=zod.z.object({label:zod.z.string(),value:zod.z.string()}),er=zod.z.object({key:zod.z.string(),category:zod.z.string().optional(),label:zod.z.string().optional(),value:zod.z.string().nullish(),unit:zod.z.string().nullish(),observed_at:zod.z.string().nullish(),status:zod.z.string().nullish(),origin:zod.z.string().nullish(),canonical_key:zod.z.string().nullish()}),Ml=zod.z.object({at:zod.z.string(),value:zod.z.number().nullish(),display:zod.z.string().nullish(),origin:zod.z.string().nullish()}),Dl=zod.z.object({key:zod.z.string(),label:zod.z.string().optional(),points:zod.z.array(Ml).optional()}),jl=zod.z.object({title:zod.z.string(),detail:zod.z.string().nullish(),due_at:zod.z.string().nullish()}),tr=zod.z.object({doc_id:zod.z.string(),title:zod.z.string().nullish(),page_count:zod.z.number().nullish(),received_at:zod.z.string().nullish()});function ti(e){return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:Al(e.origin),canonicalKey:e.canonical_key??null})}i(ti,"mapEntityRow");function ri(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(ri,"mapDocumentRow");zod.z.object({identity:zod.z.array(Fl).optional(),entities:zod.z.array(er).optional(),entity_series:zod.z.array(Dl).optional(),forward_looking:zod.z.array(jl).optional(),documents:zod.z.array(tr).optional()});zod.z.object({pet_ref:zod.z.string().optional(),granted:zod.z.boolean().optional(),version:zod.z.string().nullish(),granted_at:zod.z.string().nullish()});function Zo(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Zo,"numberOr");var oi=10,it=zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Oe=i((e,t=1)=>zod.z.string().refine(r=>!M(r)&&[...r].length>=t&&[...r].length<=e),"text"),ii=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),zl=zod.z.object({clinicId:it.optional(),clinicFreeText:Oe(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Oe(320,3).refine(e=>!ii(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:it.optional(),signaturePngBase64:zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),Ll=zod.z.object({petRef:Oe(128),ownerName:Oe(200).refine(e=>e.trim().length>0&&!ii(e)),authorizationVersion:Oe(64),clinics:zod.z.array(zl).min(1).max(oi)}).strict(),Nl=zod.z.object({request_group_id:it,pet_ref:zod.z.string(),created_count:zod.z.number().int().nonnegative(),failed_count:zod.z.number().int().nonnegative(),results:zod.z.array(zod.z.object({idempotency_key:zod.z.string(),clinic_id:it.nullable().optional(),clinic_free_text:zod.z.string().nullable().optional(),created:zod.z.boolean(),request:zod.z.unknown().optional(),failure_code:zod.z.string().nullable().optional(),failure_reason:zod.z.string().nullable().optional()}))});function Ul(e){let t=e.funnel??W({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Ll.safeParse(r).success)return f(S("validationFailed",{retryable:false}));let n=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(l=>({...l.clinicId!==void 0?{clinic_id:l.clinicId}:{clinic_free_text:l.clinicFreeText},...l.clinicEmail!==void 0?{clinic_email:l.clinicEmail}:{},...l.signatureId!==void 0?{signature_id:l.signatureId}:{signature_png_base64:l.signaturePngBase64},idempotency_key:l.idempotencyKey}))}});if(!n.ok)return n;let o=Nl.safeParse(n.value);if(!o.success||o.data.pet_ref!==r.petRef)return ni();let s=[];for(let l of o.data.results){let u=l.request===void 0||l.request===null?null:ei(l.request);if(l.created!==(u!==null))return ni();s.push(Object.freeze({idempotencyKey:l.idempotency_key,clinicId:l.clinic_id??null,clinicFreeText:l.clinic_free_text??null,created:l.created,request:u,failureCode:l.failure_code??null,failureReason:l.failure_reason??null}));}return _(Object.freeze({requestGroupId:o.data.request_group_id,petRef:o.data.pet_ref,results:Object.freeze(s),createdCount:o.data.created_count,failedCount:o.data.failed_count}))}}}i(Ul,"createRecordsClinicBatchClient");function ni(){return f(S("internalError",{retryable:false}))}i(ni,"malformed");var Bl="records_consent_required";function ql(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,n=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof n=="string"&&n.length>0?n:null}i(ql,"recordsWireCodeOf");function si(e){return e===null||e.httpStatus!==409?false:ql(e)===Bl}i(si,"isRecordsConsentRequired");var rr="value_text",ai=64,li=512;function Hl(e){return e!==null&&e.httpStatus===409&&!si(e)}i(Hl,"isFactReviewerLocked");function Kl(e){return Object.freeze({[rr]:e.trim()})}i(Kl,"factValueCorrection");var Ie=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:rr}),ui=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,di=/^\d{4}-\d{2}-\d{2}$/;function ci(e){if(e==null)return "text";let t=e.trim();return ui.test(t)?"num":di.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(ci,"inferFactValueKind");function Vl(e,t){let r=t.trim(),n=ci(e);if(n==="num"&&ui.test(r)){let o=Number(r);if(Number.isFinite(o))return Object.freeze({[Ie.num]:o})}return n==="date"&&di.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Ie.date]:r}):Object.freeze(n==="bool"&&(r==="true"||r==="false")?{[Ie.bool]:r==="true"}:{[Ie.text]:r})}i(Vl,"factCorrectionFor");var T=zod.z.string().nullish(),st=zod.z.number().nullish(),$l=zod.z.object({collected_at:T,at:T,value:st,unit:T,qualitative_result:T,ref_low:st,ref_high:st,status:T,source_clinic:T,source_doc_id:T,doc_id:T,reviewed:zod.z.boolean().nullish()}),Wl=zod.z.object({collected_at:T,at:T,value:st,unit:T,qualitative_result:T,status:T}),Gl=zod.z.object({marker_id:zod.z.string().min(1),canonical_name:T,name:T,loinc_code:T,canonical_unit:T,unit:T,panel_name:T,panel:T,meaning_text:T,meaning:T,latest:Wl.nullish(),trajectory:T,points:zod.z.array($l).optional()}),Yl=zod.z.object({total_markers:zod.z.number().int().nonnegative(),in_range_count:zod.z.number().int().nonnegative(),out_of_range_count:zod.z.number().int().nonnegative(),unknown_count:zod.z.number().int().nonnegative()}),Xl=zod.z.object({markers:zod.z.array(Gl).optional(),summary:Yl.nullish(),disclaimer:zod.z.string().optional(),featured_marker_id:T});function Ql(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Ql,"isObject");function pi(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(pi,"withheldMarkers");function nr(e,t){let r=Ql(t)?t:{},n=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return pi(n);let o=Xl.safeParse(r);if(!o.success)return pi(n);let s=o.data,l=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),u=(s.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(l))}));return Object.freeze({petRef:n,withheld:false,markers:Object.freeze(u),summary:s.summary?Object.freeze({totalMarkers:s.summary.total_markers,inRangeCount:s.summary.in_range_count,outOfRangeCount:s.summary.out_of_range_count,unknownCount:s.summary.unknown_count}):null,disclaimer:s.disclaimer??"",featuredMarkerId:s.featured_marker_id??null})}i(nr,"mapRecordMarkers");var Zl=zod.z.string().min(1).refine(e=>e.startsWith("https://")),Jl=zod.z.object({source_doc_id:zod.z.string().min(1),file_name:zod.z.string().nullish(),doc_format:zod.z.string().nullish(),byte_size:zod.z.number().int().nonnegative().nullish(),received_at:zod.z.string().nullish(),download_url:Zl,expires_in_seconds:zod.z.number().int().nonnegative().nullish()}),eu=zod.z.object({items:zod.z.array(zod.z.unknown()).optional()});function fi(e){let t=eu.safeParse(e);if(!t.success)return null;let r=[];for(let n of t.data.items??[]){let o=Jl.safeParse(n);o.success&&r.push(Object.freeze({sourceDocId:o.data.source_doc_id,fileName:o.data.file_name??null,docFormat:o.data.doc_format??null,byteSize:o.data.byte_size??null,receivedAt:o.data.received_at??null,downloadUrl:o.data.download_url,expiresInSeconds:o.data.expires_in_seconds??0}));}return Object.freeze(r)}i(fi,"mapRequestDocuments");var Fe=Object.freeze(["vet","groomer","boarding"]),tu=zod.z.string().min(1).refine(e=>e.startsWith("https://")),ce=zod.z.string().nullish(),or=zod.z.unknown().optional(),ru=zod.z.object({share_id:zod.z.string().min(1),share_url:zod.z.string().min(1),expires_at:ce,audience:or}),nu=zod.z.object({shares:zod.z.array(zod.z.object({share_id:zod.z.string().min(1),expires_at:ce,created_at:ce,view_count:zod.z.number().int().nonnegative().nullish(),last_viewed_at:ce,audience:or})).optional()}),ou=zod.z.object({download_url:tu,expires_at:ce}),iu=zod.z.object({share_id:zod.z.string().min(1),expires_at:ce,audience:or}),su=zod.z.object({audience:zod.z.string().min(1),sections:zod.z.array(zod.z.string()),entity_types:zod.z.array(zod.z.string()).nullable()}),mi=254;function ir(e){let t=e.trim();return t.length>0&&t.length<=mi&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(t)}i(ir,"isShareRecipientEmail");var yi=i(e=>typeof e=="string"&&Fe.includes(e),"isAudience");function sr(e){return yi(e)?e:null}i(sr,"audienceOf");function ar(e){let t=zod.z.array(su).safeParse(e);if(!t.success)return Object.freeze([]);let r=new Set,n=[];for(let o of t.data)!yi(o.audience)||r.has(o.audience)||(r.add(o.audience),n.push(Object.freeze({audience:o.audience,sections:Object.freeze([...o.sections]),entityTypes:o.entity_types===null?null:Object.freeze([...o.entity_types])})));return Object.freeze(n)}i(ar,"mapShareAudiences");function gi(e,t){let r=e.trim();if(r.length===0)return null;try{let n=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return n===null||n.protocol!=="https:"?null:n.toString()}catch{return null}}i(gi,"resolveShareUrl");function lr(e,t){let r=ru.safeParse(e);if(!r.success)return null;let n=gi(r.data.share_url,t);return n===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:n,expiresAt:r.data.expires_at??null,audience:sr(r.data.audience)})}i(lr,"mapRecordShareLink");function ur(e){let t=nu.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null,audience:sr(r.audience)}))):null}i(ur,"mapRecordShareList");function dr(e){let t=iu.safeParse(e);return t.success?Object.freeze({shareId:t.data.share_id,expiresAt:t.data.expires_at??null,audience:sr(t.data.audience)}):null}i(dr,"mapRecordShareEmailReceipt");function cr(e){let t=ou.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(cr,"mapRecordPdfLink");var hi="application/pdf",au=Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),at=Object.freeze({features:Object.freeze({}),uploadContentTypes:Object.freeze([hi]),shareAudiences:Object.freeze([])}),lu=zod.z.object({features:zod.z.record(zod.z.boolean()),upload_content_types:zod.z.array(zod.z.string()).nullish(),share_audiences:zod.z.unknown().optional()});function bi(e){let t=lu.safeParse(e);if(!t.success)return at;let r=t.data.upload_content_types??[],n=au.filter(o=>r.includes(o));return Object.freeze({features:Object.freeze({...t.data.features}),uploadContentTypes:Object.freeze([hi,...n]),shareAudiences:ar(t.data.share_audiences)})}i(bi,"mapRecordsFeatures");var uu=zod.z.object({signatures:zod.z.array(zod.z.object({signature_id:zod.z.string().min(1),preview_url:zod.z.string().min(1).refine(e=>e.startsWith("https://")),created_at:zod.z.string().nullish()})).optional()});function pr(e){let t=uu.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(pr,"mapSignatureSuggestions");var b=zod.z.string().nullish(),Me=zod.z.number().nullish(),du=zod.z.object({at:b,value:Me,unit:b,qualitative_result:b,ref_low:Me,ref_high:Me,status:b,doc_id:b}),cu=zod.z.object({marker_id:zod.z.string(),name:zod.z.string(),loinc_code:b,unit:b,panel:b,meaning:b,latest:zod.z.object({at:b,value:Me,unit:b,qualitative_result:b,status:b}).nullish(),trajectory:b,points:zod.z.array(du).optional()}),pu=zod.z.object({encounter_id:zod.z.string(),date:b,type:b,clinic_name:b,veterinarian:b,doc_id:b}),fu=zod.z.object({note_id:zod.z.string(),encounter_id:b,observed_on:b,sections:zod.z.array(zod.z.object({section:zod.z.string(),text:zod.z.string()})).optional()}),mu=zod.z.object({exam_id:zod.z.string(),encounter_id:b,observed_on:b,doc_id:b,systems:zod.z.record(zod.z.object({finding_status:b,finding:b})).optional()}),yu=zod.z.object({has_lab_history:zod.z.boolean().optional(),has_vaccination_history:zod.z.boolean().optional(),has_weight_history:zod.z.boolean().optional(),has_vitals_history:zod.z.boolean().optional(),has_physical_exam_history:zod.z.boolean().optional(),has_procedure_history:zod.z.boolean().optional(),has_genetic_history:zod.z.boolean().optional(),has_reproductive_history:zod.z.boolean().optional(),has_parasite_prevention_history:zod.z.boolean().optional(),earliest_record_at:b,latest_record_at:b,documents_ingested:zod.z.number().int().nonnegative().optional(),documents_in_review:zod.z.number().int().nonnegative().optional(),entities_pending_review:zod.z.record(zod.z.number().int().nonnegative()).optional(),held_total:zod.z.number().int().nonnegative().optional()}),gu=zod.z.object({conflict_id:zod.z.string(),entity_type:zod.z.string(),field:b,severity:b,candidates:zod.z.array(zod.z.object({value:zod.z.string(),source_doc_id:b,doc_id:b,collected_at:b})).optional()}),hu=zod.z.object({lab_results:zod.z.array(cu).optional(),encounters:zod.z.array(pu).optional(),clinician_notes:zod.z.array(fu).optional(),physical_exams:zod.z.array(mu).optional(),completeness:yu.nullish(),conflicts:zod.z.array(gu).optional()}),bu=zod.z.object({visits:zod.z.array(zod.z.object({visit_id:zod.z.string(),visit_date:b,veterinarian:b,summary:b,doc_id:b})),vaccines:zod.z.array(zod.z.object({vaccine_id:zod.z.string(),product:b,lot:b,administered_on:b,expires_on:b,doc_id:b})),weights:zod.z.array(zod.z.object({weight_id:zod.z.string(),observed_on:b,weight_kg:Me,doc_id:b})),medications:zod.z.array(zod.z.object({medication_id:zod.z.string(),drug_name:b,dose:b,route:b,frequency:b,sig:b,rx_number:b,started_on:b,stopped_on:b,doc_id:b})),disclaimer:zod.z.string().optional()}),vu=zod.z.object({document:tr,contributions:zod.z.array(er),contribution_count:zod.z.number().int().nonnegative().optional()});function mr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(mr,"isObject");function yr(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(yr,"petOf");function fr(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(fr,"emptyDepth");function _i(e,t){let r=mr(t)?t:{},n=yr(r,e);if(r.withheld===true)return fr(n,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return fr(n,false);let s=hu.safeParse(r);if(!s.success)return fr(n,true);let l=s.data,u=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:n,available:true,withheld:false,labResults:Object.freeze((l.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(u))}))),encounters:Object.freeze((l.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((l.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((l.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,c])=>Object.freeze({system:d,findingStatus:c.finding_status??null,finding:c.finding??null})))}))),completeness:l.completeness?Object.freeze({hasLabHistory:l.completeness.has_lab_history===true,hasVaccinationHistory:l.completeness.has_vaccination_history===true,hasWeightHistory:l.completeness.has_weight_history===true,hasVitalsHistory:l.completeness.has_vitals_history===true,hasPhysicalExamHistory:l.completeness.has_physical_exam_history===true,hasProcedureHistory:l.completeness.has_procedure_history===true,hasGeneticHistory:l.completeness.has_genetic_history===true,hasReproductiveHistory:l.completeness.has_reproductive_history===true,hasParasitePreventionHistory:l.completeness.has_parasite_prevention_history===true,earliestRecordAt:l.completeness.earliest_record_at??null,latestRecordAt:l.completeness.latest_record_at??null,documentsIngested:l.completeness.documents_ingested??0,documentsInReview:l.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...l.completeness.entities_pending_review??{}}),heldTotal:l.completeness.held_total??0}):null,conflicts:Object.freeze((l.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(_i,"mapRecordDepth");function vi(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(vi,"withheldTimeline");function Ri(e,t){let r=mr(t)?t:{},n=yr(r,e);if(r.withheld===true)return vi(n);let o=bu.safeParse(r);if(!o.success)return vi(n);let s=o.data,l=s.visits.map(c=>Object.freeze({visitId:c.visit_id,visitDate:c.visit_date??null,veterinarian:c.veterinarian??null,summary:c.summary??null,docId:c.doc_id??null})),u=s.vaccines.map(c=>Object.freeze({vaccineId:c.vaccine_id,product:c.product??null,lot:c.lot??null,administeredOn:c.administered_on??null,expiresOn:c.expires_on??null,docId:c.doc_id??null})),a=s.weights.map(c=>Object.freeze({weightId:c.weight_id,observedOn:c.observed_on??null,weightKg:c.weight_kg??null,docId:c.doc_id??null})),d=s.medications.map(c=>Object.freeze({medicationId:c.medication_id,drugName:c.drug_name??null,dose:c.dose??null,route:c.route??null,frequency:c.frequency??null,sig:c.sig??null,rxNumber:c.rx_number??null,startedOn:c.started_on??null,stoppedOn:c.stopped_on??null,docId:c.doc_id??null}));return Object.freeze({petRef:n,withheld:false,isEmpty:l.length===0&&u.length===0&&a.length===0&&d.length===0,visits:Object.freeze(l),vaccines:Object.freeze(u),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:s.disclaimer??""})}i(Ri,"mapRecordsTimeline");function Ei(e,t){let r=mr(t)?t:{},n=yr(r,e),o=i(()=>Object.freeze({petRef:n,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return o();let s=vu.safeParse(r);if(!s.success)return o();let l=Object.freeze(s.data.contributions.map(ti));return Object.freeze({petRef:n,withheld:false,document:ri(s.data.document),contributions:l,contributionCount:s.data.contribution_count??l.length})}i(Ei,"mapDocumentContributions");var _u="/widget/v1/records/pets";function Ru(e){let t=e.funnel??W({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!M(a)&&[...a].length<=d,"segment"),n=i(async(a,d,c,p)=>{if(!r(d,oe))return X();let g=await t.send(a,{method:"GET",path:c});if(!g.ok)return g;let y=p(g.value);return y.petRef===d?_(y):f(S("internalError",{retryable:false}))},"read"),o=i(a=>`${_u}/${encodeURIComponent(a)}`,"pet"),s=i(a=>`${o(a)}/everfur_record`,"record"),l=i(async(a,d,c)=>{let p=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let g=c(p.value);return g===null?f(S("internalError",{retryable:false})):_(g)},"parsed"),u=i((a,d)=>!r(a.entityType,ai)||!r(a.canonicalKey,li)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,Kn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>n("records.depth.record",a,`${o(a)}/record`,d=>_i(a,d)),"getRecordDepth"),getTimeline:i(a=>n("records.depth.timeline",a,`${o(a)}/timeline`,d=>Ri(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?n("records.depth.contributions",a,`${o(a)}/documents/${encodeURIComponent(d)}/contributions`,c=>Ei(a,c)):X()},getMarkers:i(a=>n("records.depth.markers",a,`${o(a)}/markers`,d=>nr(a,d)),"getMarkers"),createShare(a,d){if(!r(a,oe))return X();let c=d?.audience;return c!==void 0&&!Fe.includes(c)?X():l("records.share.create",{method:"POST",path:`${s(a)}/share`,...c!==void 0?{body:{audience:c}}:{}},p=>lr(p,e.apiBaseUrl))},emailShare(a,d){let c=d.recipientKind,p=typeof d.recipientEmail=="string"?d.recipientEmail.trim():"",g=c==="other"||Fe.includes(c);return !r(a,oe)||!g||!ir(p)||M(p)?X():l("records.share.email",{method:"POST",path:`${s(a)}/share/email`,body:{recipient_email:p,recipient_kind:c}},dr)},async readFeatures(){try{let a=await t.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return a.ok?bi(a.value):at}catch{return at}},listShares(a){return r(a,oe)?l("records.share.list",{method:"GET",path:`${s(a)}/shares`},ur):X()},async revokeShare(a,d){if(!r(a,oe)||!r(d,64))return X();let c=await t.send("records.share.revoke",{method:"DELETE",path:`${s(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return c.ok?_(void 0):c},getPdfLink(a){return r(a,oe)?l("records.pdf.link",{method:"GET",path:`${s(a)}/pdf-link`},cr):X()},async editFact(a,d){let c=r(a,oe)?u(d,d.correctedFields):null;if(c===null)return X();let p=await t.send("records.fact.edit",{method:"POST",path:`${s(a)}/facts/edit`,body:c},{idempotent:false,maxAttempts:1});return p.ok?_(void 0):p},async removeFact(a,d){let c=r(a,oe)?u(d):null;if(c===null)return X();let p=await t.send("records.fact.remove",{method:"POST",path:`${s(a)}/facts/remove`,body:c},{idempotent:false,maxAttempts:1});return p.ok?_(void 0):p},listRequestDocuments(a){return r(a,64)?l("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},fi):X()},listAuthorizationSignatures:i(()=>l("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},pr),"listAuthorizationSignatures")}}i(Ru,"createRecordsDepthClient");function X(){return Promise.resolve(f(S("validationFailed",{retryable:false})))}i(X,"invalid");var je=Object.freeze({width:360,height:120});function wi(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(wi,"blank");function Ti(e,t,r,n){for(let o=-n;o<=n;o+=1)for(let s=-n;s<=n;s+=1){if(s*s+o*o>n*n+n)continue;let l=t+s,u=r+o;l<0||u<0||l>=e.width||u>=e.height||(e.pixels[u*e.width+l]=1);}}i(Ti,"stamp");var Eu=16384;function Cu(e,t){let[r,n]=e;if(!Number.isFinite(r)||!Number.isFinite(n))return null;let o=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),s=Math.min(2*t.height,Math.max(-t.height,Math.round(n)));return [o,s]}i(Cu,"padPoint");function Su(e,t,r,n,o){let[s,l]=t,[u,a]=r,d=Math.abs(u-s),c=-Math.abs(a-l),p=s<u?1:-1,g=l<a?1:-1,y=d+c,R=0;for(;R<o&&(Ti(e,s,l,n),R+=1,!(s===u&&l===a));){let x=2*y;x>=c&&(y+=c,s+=p),x<=d&&(y+=d,l+=g);}return R}i(Su,"line");function ku(e,t=1){let r=wi(je.width,je.height);for(let n of e){let o=[];for(let l of n){let u=Cu(l,r);u!==null&&o.push(u);}if(o.length===0)continue;if(o.length===1){let[l,u]=o[0];Ti(r,l,u,t);continue}let s=Eu;for(let l=1;l<o.length&&s>0;l+=1)s-=Su(r,o[l-1],o[l],t,s);}return r}i(ku,"rasterizeStrokes");var wu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",Tu="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",xu="0123456789abcdefghijklmnopqrstuv",Rr=5,Er=7,gr=Rr+1;function Pu(e,t){let r=wu.indexOf(e);return r<0?0:xu.indexOf(Tu.charAt(r*Er+t))}i(Pu,"glyphRow");function Au(e){let t=wi(je.width,je.height),r=e.trim();if(r.length===0)return t;let n=[...r],o=4;for(;o>1&&(n.length*gr-1)*o>t.width-8;)o-=1;let s=(n.length*gr-1)*o,l=Math.max(0,Math.floor((t.width-s)/2)),u=Math.floor((t.height-Er*o)/2);return n.forEach((a,d)=>{let c=l+d*gr*o;for(let p=0;p<Er;p+=1){let g=Pu(a,p);for(let y=0;y<Rr;y+=1)if((g>>Rr-1-y&1)!==0)for(let R=0;R<o;R+=1)for(let x=0;x<o;x+=1){let C=c+y*o+x,P=u+p*o+R;C<t.width&&P<t.height&&(t.pixels[P*t.width+C]=1);}}}),t}i(Au,"rasterizeTypedName");var kr=class kr{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let n=0;for(let o=0;o<r;o+=1)n=n<<1|t>>o&1;this.writeBits(n,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(kr,"BitWriter");var Cr=kr;function Sr(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(Sr,"writeLiteral");var hr=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Ci=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],br=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Si=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function Ou(e,t,r){let n=hr.length-1;for(;hr[n]>t;)n-=1;Sr(e,257+n),Ci[n]>0&&e.writeBits(t-hr[n],Ci[n]);let o=br.length-1;for(;br[o]>r;)o-=1;e.writeCode(o,5),Si[o]>0&&e.writeBits(r-br[o],Si[o]);}i(Ou,"writeMatch");var Iu=32768,vr=3,Fu=258,ki=15,Mu=64;function Du(e){let t=new Cr;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<ki).fill(-1),n=new Int32Array(e.length).fill(-1),o=i(u=>(e[u]<<10^e[u+1]<<5^e[u+2])&(1<<ki)-1,"hashAt"),s=i(u=>{if(u+vr>e.length)return;let a=o(u);n[u]=r[a],r[a]=u;},"insert"),l=0;for(;l<e.length;){let u=0,a=0;if(l+vr<=e.length){let d=r[o(l)],c=0,p=Math.min(Fu,e.length-l);for(;d>=0&&c<Mu&&l-d<=Iu;){let g=0;for(;g<p&&e[d+g]===e[l+g];)g+=1;if(g>u&&(u=g,a=l-d,g===p))break;d=n[d],c+=1;}}if(u>=vr){Ou(t,u,a);for(let d=0;d<u;d+=1)s(l+d);l+=u;}else Sr(t,e[l]),s(l),l+=1;}return Sr(t,256),t.finish()}i(Du,"deflate");function ju(e){let t=1,r=0;for(let n of e)t=(t+n)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(ju,"adler32");var lt=null;function zu(e){if(lt===null){lt=new Uint32Array(256);for(let r=0;r<256;r+=1){let n=r;for(let o=0;o<8;o+=1)n=n&1?3988292384^n>>>1:n>>>1;lt[r]=n>>>0;}}let t=4294967295;for(let r of e)t=lt[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(zu,"crc32");function De(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(De,"u32");function _r(e,t){let r=Uint8Array.from([...e].map(o=>o.charCodeAt(0))),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),[...De(t.length),...n,...De(zu(n))]}i(_r,"chunk");var ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Lu(e){let t="";for(let r=0;r<e.length;r+=3){let n=e[r],o=r+1<e.length?e[r+1]:0,s=r+2<e.length?e[r+2]:0,l=n<<16|o<<8|s;t+=ut.charAt(l>>18&63)+ut.charAt(l>>12&63),t+=r+1<e.length?ut.charAt(l>>6&63):"=",t+=r+2<e.length?ut.charAt(l&63):"=";}return t}i(Lu,"toBase64");function Nu(e){let{width:t,height:r,pixels:n}=e,o=Math.ceil(t/8)+1,s=new Uint8Array(o*r);for(let c=0;c<r;c+=1){let p=c*o;s[p]=0,s.fill(255,p+1,p+o);for(let g=0;g<t;g+=1)if(n[c*t+g]===1){let y=p+1+(g>>3);s[y]=s[y]&~(128>>(g&7));}}let l=Du(s),u=new Uint8Array(2+l.length+4);u[0]=120,u[1]=1,u.set(l,2),u.set(De(ju(s)),2+l.length);let a=Uint8Array.from([...De(t),...De(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,..._r("IHDR",a),..._r("IDAT",u),..._r("IEND",new Uint8Array(0))]);return Lu(d)}i(Nu,"encodeSignaturePng");
|
|
13
|
-
|
|
1
|
+
"use strict";var zod=require("zod");function ok(value,warning){/* @__PURE__ */
|
|
2
|
+
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
3
|
+
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var NULL_SECURE_STORE=/* @__PURE__ */Object.freeze({isAvailable:false,async getSecret(){return null},async setSecret(){throw new EverfurConfigError("not-initialized","EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort")},async deleteSecret(){}});var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
4
|
+
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
5
|
+
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
6
|
+
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
7
|
+
/* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
8
|
+
/* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
9
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
10
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
11
|
+
/* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
12
|
+
/* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
|
|
13
|
+
/* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
|
|
14
|
+
/* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
|
|
15
|
+
/* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
16
|
+
/* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
17
|
+
/* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
18
|
+
/* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
19
|
+
/* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
20
|
+
/* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
21
|
+
/* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
22
|
+
/* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
23
|
+
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
24
|
+
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
25
|
+
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
26
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
27
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
28
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
29
|
+
/* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
30
|
+
/* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
31
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
32
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
33
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
34
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
35
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
36
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
37
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
38
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
39
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
40
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
41
|
+
/* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
42
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
43
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
|
|
44
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
45
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
46
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
47
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
48
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
49
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
50
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
51
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
52
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
53
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
54
|
+
/* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
55
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
56
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
57
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
58
|
+
/* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
|
|
59
|
+
/* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
60
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
61
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
62
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
63
|
+
/* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
64
|
+
/* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
65
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
66
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
67
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
68
|
+
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
69
|
+
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
70
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
72
|
+
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
73
|
+
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
74
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
75
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
76
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
77
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
78
|
+
/* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
79
|
+
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
80
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
81
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
82
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
84
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
85
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
86
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
87
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
88
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
89
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
90
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}function shouldRetry(code,frameRetryable=false){return frameRetryable||isAutoRetryable(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}function canRecreateOnNotFound(code){return code==="conversationNotFound"}var 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 optionalModule(name,load,validate2){let candidate;try{candidate=load()}catch(cause){return frozenUnavailable(`optional peer '${name}' is not installed: ${describe(cause)}`)}let resolved=unwrapDefault(candidate);return resolved==null?frozenUnavailable(`optional peer '${name}' resolved to no module`):validate2&&!validate2(resolved)?frozenUnavailable(`optional peer '${name}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:resolved})}function unwrapDefault(candidate){return typeof candidate=="object"&&candidate!==null&&"default"in candidate&&Object.keys(candidate).length<=2?candidate.default:candidate}function frozenUnavailable(reason){/* @__PURE__ */
|
|
91
|
+
return Object.freeze({available:false,module:null,reason:reason})}function describe(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"unknown load error"}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function acceptedFrame(streamId,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
92
|
+
return Object.freeze({kind:"accepted",streamId:streamId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function heartbeatFrame(lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
93
|
+
return Object.freeze({kind:"heartbeat",lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function deltaFrame(delta,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
94
|
+
return Object.freeze({kind:"delta",delta:delta,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function doneFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
95
|
+
return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversationId,messageId:fields.messageId,title:fields.title,followUpQuestions:/* @__PURE__ */Object.freeze([...fields.followUpQuestions]),citations:/* @__PURE__ */Object.freeze([...fields.citations]),citationStatus:fields.citationStatus,urgencyLevel:fields.urgencyLevel,urgencyReason:fields.urgencyReason,urgencyProvided:fields.urgencyProvided??fields.urgencyLevel!==null,resultId:fields.resultId,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function errorFrame(fields){/* @__PURE__ */
|
|
96
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
97
|
+
return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
98
|
+
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
99
|
+
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function createIdentityProvider(userRef,getToken,onMinted){let cached=null,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk2 of bytes){for(buffer+=decoder.decode(chunk2,{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 line2=rawLine.replace(/\s+$/,"");line2.length===0||line2.startsWith(":")||(line2.startsWith("id:")?id=line2.slice(3).trim():line2.startsWith("data:")&&dataLines.push(line2.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.8.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
100
|
+
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
|
|
101
|
+
return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
|
|
102
|
+
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
|
|
103
|
+
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line2 of data.split(`\n`))block+=`data: ${line2}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline2=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline2.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline2.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline2,caller){if(!caller)return deadline2;let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline2=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline2.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline2.cancel()}if(settled.ok)return emit(stamp2({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(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
104
|
+
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null})}}/* @__PURE__ */
|
|
105
|
+
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline2,caller){let noop=()=>{};if(!caller)return{signal:deadline2,dispose:noop};let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline2.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}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(petRef){return typeof petRef!="string"||petRef.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):hasLoneSurrogate(petRef)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(petRef)}/cases`}var str=v=>typeof v=="string"?v:null,count=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function caseFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,caseId=str(o.case_id),status=str(o.status);if(caseId===null||status===null)return null;let last=str(o.last_response);/* @__PURE__ */
|
|
106
|
+
return Object.freeze({caseId:caseId,status:status,bodyLocation:str(o.body_location),lastResponse:last!==null&&CHECKIN_ANSWERS.includes(last)?last:null,checkInDueAt:str(o.check_in_due_at),openedAt:str(o.opened_at),resolvedAt:str(o.resolved_at),resolutionText:str(o.resolution_text),checkinAskCount:count(o.checkin_ask_count),checkinAnswerCount:count(o.checkin_answer_count)})}function createCasesRepositoryOver(funnel){return{async list(petRef,opts){let path=petPath(petRef);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(petRef,caseId,answer,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);if(typeof caseId!="string"||!CASE_ID_PATTERN.test(caseId))return invalid("case_id must be a UUID");if(!CHECKIN_ANSWERS.includes(answer))return invalid("response must be one of better, same, worse");let res=await funnel.send("cases.checkin",{method:"POST",path:`${path}/${caseId}/checkin`,body:{response:answer},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let o=typeof res.value=="object"&&res.value!==null?res.value:{},watchCase=caseFromWire(o.case);return watchCase===null?malformed():ok(/* @__PURE__ */Object.freeze({case:watchCase,ctaDeepLink:str(o.cta_deep_link)}))}}}var unavailableUpload=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}function mergeSignals2(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}var MediaStore=class{constructor(initial){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...initial})}subscribe(listener){return this.listeners.add(listener),()=>{this.listeners.delete(listener)}}getSnapshot(){return this.snapshot}patch(partial){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...partial});for(let listener of this.listeners)listener()}beginOperation(external){this.inFlight?.abort();let ctrl=new AbortController;this.inFlight=ctrl;let epoch=this.epoch;return{signal:external?mergeSignals2(ctrl.signal,external):ctrl.signal,epoch:epoch,settle:()=>{this.inFlight===ctrl&&(this.inFlight=null)}}}alive(epoch){return epoch===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear()}};function makeUser(id,text3,createdAt){/* @__PURE__ */
|
|
107
|
+
return Object.freeze({id:id,role:"user",text:text3,createdAt:createdAt,pending:true})}function makeAssistant(id,text3,createdAt){/* @__PURE__ */
|
|
108
|
+
return Object.freeze({id:id,role:"assistant",text:text3,createdAt:createdAt})}function stripPending(m){/* @__PURE__ */
|
|
109
|
+
return Object.freeze({id:m.id,role:m.role,text:m.text,createdAt:m.createdAt})}function appendText(m,text3){let next={id:m.id,role:m.role,text:m.text+text3,createdAt:m.createdAt};return m.citations&&(next.citations=m.citations),m.responseId&&(next.responseId=m.responseId),/* @__PURE__ */Object.freeze(next)}function finalizeAssistant(m,done){let next={id:done.messageId?done.messageId:m.id,role:"assistant",text:m.text,createdAt:m.createdAt};return done.citations.length>0&&(next.citations=done.citations),done.messageId&&(next.responseId=done.messageId),next.urgencyLevel=done.urgencyLevel,next.urgencyReason=done.urgencyReason,next.urgencyProvided=done.urgencyProvided,/* @__PURE__ */Object.freeze(next)}function freezeSnapshot(s){/* @__PURE__ */
|
|
110
|
+
return Object.freeze({status:s.status,messages:/* @__PURE__ */Object.freeze([...s.messages]),conversationId:s.conversationId,error:s.error,isStreaming:s.isStreaming,isBootstrapping:s.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...s.suggestedPrompts]),unreadCount:s.unreadCount})}function makeError(code,retryable,wireMessage){return makeEverfurError(code,{retryable:retryable,...wireMessage?{wireMessage:wireMessage}:{}})}function errorFromFrame(frame){let code=fromWire(frame.code);return makeEverfurError(code,{retryable:frame.retryable||shouldRetry(code),wireCode:frame.code,wireEnvelope:"sse_frame",...frame.serverRequestId?{requestId:frame.serverRequestId}:{},...frame.wireMessage?{wireMessage:frame.wireMessage}:{},raw:frame})}function synthErrorFrame(error){return errorFrame({code:canonicalWireCode(error.code),retryable:error.retryable,wireMessage:error.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:error.requestId??null})}function canonicalWireCode(code){switch(code){case"authExpired":return"AUTH_EXPIRED";case"authRejected":return"AuthorizationException";case"sessionRequired":return"session_required";case"accessDenied":return"ACCESS_DENIED";case"paymentRequired":return"TIER_UPGRADE_REQUIRED";case"quotaExceeded":return"QUOTA_EXCEEDED";case"rateLimited":return"RATE_LIMITED";case"validationFailed":return"ValidationException";case"sdkUpdateRequired":return"invalidRequest";case"conflict":return"ConflictException";case"idempotencyConflict":return"IDEMPOTENCY_CONFLICT";case"idempotencyInFlight":return"IDEMPOTENCY_KEY_IN_FLIGHT";case"conversationNotFound":return"CONVERSATION_NOT_FOUND";case"petNotFound":return"PET_NOT_FOUND";case"resourceNotFound":return"ResourceNotFoundException";case"streamTimeout":return"STREAM_TIMEOUT";case"mediaUploadFailed":return"MEDIA_UPLOAD_FAILED";case"moderationBlocked":return"MODERATION_BLOCKED";case"upstreamLlmTimeout":return"UPSTREAM_LLM_TIMEOUT";case"internalError":return"INTERNAL_ERROR";case"notImplemented":return"NotImplementedException";case"serviceUnavailable":return"ServiceUnavailableException";case"streamIncomplete":return"STREAM_INCOMPLETE";case"identitySignatureRequired":return"identitySignatureRequired";case"unknown":return"UNKNOWN";default:return assertNever(code)}}function parsePromptCategories(raw){let list=Array.isArray(raw)?raw:isPlainObject2(raw)&&Array.isArray(raw.categories)?raw.categories:[],out=[];for(let entry of list){if(!isPlainObject2(entry))continue;let category=asStr(entry.category)??asStr(entry.title)??"",prompts=asPromptTextList(entry.prompts??entry.questions);category.length===0&&prompts.length===0||out.push(/* @__PURE__ */Object.freeze({category:category,prompts:/* @__PURE__ */Object.freeze(prompts)}))}/* @__PURE__ */
|
|
111
|
+
return Object.freeze(out)}function flattenPrompts(categories){let seen=/* @__PURE__ */new Set,out=[];for(let category of categories)for(let prompt of category.prompts){let trimmed=prompt.trim();trimmed.length===0||seen.has(trimmed)||(seen.add(trimmed),out.push(trimmed))}return out}function isPlainObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asStr(v){return typeof v=="string"?v:null}function asPromptTextList(v){if(!Array.isArray(v))return[];let out=[];for(let entry of v)if(typeof entry=="string")out.push(entry);else if(isPlainObject2(entry)){let text3=asStr(entry.text)??asStr(entry.prompt)??asStr(entry.title);text3!==null&&out.push(text3)}return out}function defaultIdFactory(){let counter=0;return()=>`m-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function defaultIdempotencyFactory(){let counter=0;return()=>`chat-send-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var defaultTimers2={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()};async function*withWatchdog(source,budget,signal,timers){let it=source[Symbol.asyncIterator](),overall=deadline(budget.overallMs,timers),idle=deadline(budget.idleMs,timers),abort=abortPromise(signal);try{for(;;){if(signal.aborted)return;let nextTagged=it.next().then(value=>({tag:"next",value:value}),()=>({tag:"streamError"})),outcome=await Promise.race([nextTagged,idle.promise.then(()=>({tag:"idle"})),overall.promise.then(()=>({tag:"overall"})),abort.then(()=>({tag:"abort"}))]);if(outcome.tag==="abort")return;if(outcome.tag==="streamError"){if(signal.aborted)return;yield synthStreamErrorFrame();return}if(outcome.tag==="idle"||outcome.tag==="overall"){yield synthTimeoutFrame();return}let result=outcome.value;if(result.done||(idle.reset(budget.idleMs),yield result.value,result.value.terminal))return}}finally{idle.cancel(),overall.cancel(),Promise.resolve(it.return?.(void 0)).catch(()=>{})}}function synthTimeoutFrame(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function synthStreamErrorFrame(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function deadline(ms,timers){let resolveFn=()=>{},promise=new Promise(resolve=>{resolveFn=resolve}),handle=timers.setTimeout(()=>resolveFn(),ms);return{promise:promise,reset(next){timers.clearTimeout(handle),handle=timers.setTimeout(()=>resolveFn(),next)},cancel(){timers.clearTimeout(handle)}}}function abortPromise(signal){return new Promise(resolve=>{if(signal.aborted){resolve();return}signal.addEventListener("abort",()=>resolve(),{once:true})})}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function isLiveAskAnswered(counts){let{askCount:askCount,answerCount:answerCount}=counts;return typeof askCount!="number"||!Number.isFinite(askCount)||typeof answerCount!="number"||!Number.isFinite(answerCount)||askCount<=0?true:answerCount>=askCount}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}function parseCheckinOriginRef(ref){return parseCheckinOrigin(ref)?.caseId??null}function historyQuery(opts,max){if(opts?.limit!==void 0&&(!Number.isInteger(opts.limit)||opts.limit<1||opts.limit>max))return err(makeEverfurError("validationFailed"));let query=[];for(let[key,value]of[["cursor",opts?.cursor],["pet_ref",opts?.petRef]])if(value!==void 0){if(typeof value!="string"||value.length===0||hasLoneSurrogate(value))return err(makeEverfurError("validationFailed"));query.push(`${key}=${encodeURIComponent(value)}`)}return opts?.limit!==void 0&&query.push(`limit=${opts.limit}`),ok(query.length?`?${query.join("&")}`:"")}function validConversationId(id){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)}function object(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function cursor(value){return value==null||typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}function mapConversationPage(value){let page=object(value);if(!page||!Array.isArray(page.conversations)||!cursor(page.next_cursor))return malformed2();let conversations=[];for(let raw of page.conversations){let row=object(raw);if(!row||typeof row.conversation_id!="string"||!validConversationId(row.conversation_id)||!(row.title==null||typeof row.title=="string")||typeof row.created_at!="string"||typeof row.updated_at!="string")return malformed2();let unread=row.unread_message_count;if(!(unread==null||Number.isInteger(unread)&&unread>=0))return malformed2();conversations.push(/* @__PURE__ */Object.freeze({id:row.conversation_id,title:row.title??null,createdAt:row.created_at,updatedAt:row.updated_at,unreadCount:unread??null}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(conversations),nextCursor:page.next_cursor??null}))}function mapMessagePage(value){let page=object(value);if(!page||!Array.isArray(page.messages)||!cursor(page.next_cursor))return malformed2();let messages=[],seen=/* @__PURE__ */new Set;for(let raw of page.messages){let row=object(raw);if(!row||typeof row.message_id!="string"||!validConversationId(row.message_id)||typeof row.role!="string"||typeof row.content!="string"||typeof row.created_at!="string")return malformed2();if(row.role!=="user"&&row.role!=="assistant"&&row.role!=="vet"||seen.has(row.message_id))continue;if(seen.add(row.message_id),row.role==="vet"){messages.push(vetMessage(row,row.message_id,row.content,row.created_at));continue}let origin=typeof row.proactive_origin_ref=="string"?row.proactive_origin_ref:null,caseId=row.role==="assistant"?parseCheckinOriginRef(origin):null;messages.push(/* @__PURE__ */Object.freeze({id:row.message_id,role:row.role,text:row.content,createdAt:row.created_at,...row.role==="assistant"?{responseId:row.message_id}:{},...row.urgency_level!==void 0?{urgencyLevel:normalizeUrgency(row.urgency_level)}:{},...Array.isArray(row.citations)?{citations:historyCitations(row.citations)}:{},...origin!==null?{proactiveOriginRef:origin}:{},...caseId!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:caseId,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(messages),nextCursor:page.next_cursor??null}))}function vetMessage(row,id,text3,createdAt){let sender=object(row.sender),displayName=trimmedText(sender?.display_name)??trimmedText(row.sender_display_name),specialty=trimmedText(sender?.specialty);/* @__PURE__ */
|
|
112
|
+
return Object.freeze({id:id,role:"vet",text:text3,createdAt:createdAt,sender:/* @__PURE__ */Object.freeze({displayName:displayName,specialty:specialty})})}function trimmedText(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&!hasLoneSurrogate(trimmed)?trimmed:null}function normalizeUrgency(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}function historyCitations(values){let keys=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
|
|
113
|
+
return Object.freeze(values.flatMap(value=>{let row=object(value);if(!row||typeof row.source_name!="string"||typeof row.authority_tier!="string")return[];let citation={};for(let key of keys){let item=row[key];(typeof item=="string"||item===null)&&(citation[key]=item)}return[/* @__PURE__ */Object.freeze(citation)]}))}var MAX_IMAGE_KEYS_PER_MESSAGE=5,CHAT_FEEDBACK_TYPES=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;function validateImageKeys(keys){return keys===void 0?null:!Array.isArray(keys)||keys.length>5?{reason:"too_many_images",error:makeError("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:keys.some(key=>typeof key!="string"||key.trim().length===0)?{reason:"bad_image_key",error:makeError("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function validateMessageText(text3){let raw=typeof text3=="string"?text3:"";if(raw.trim().length===0)return{reason:"empty",error:makeError("validationFailed",false,"message is empty or whitespace-only")};let codePoints=[...raw].length;return codePoints>MESSAGE_MAX_CHARS?{reason:"too_long",error:makeError("validationFailed",false,`message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`)}:null}function urgencyTier(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}async function*singleFrameStream(frame){yield frame}async function*emptyStream(){}var DEFAULT_IDLE_MS=6e4,DEFAULT_OVERALL_MS=18e4,DELTA_FLUSH_MS=24,DELTA_FLUSH_CHARS=512,SEND_IS_SERVER_DEDUPED=false;function createChatController(deps){return new ChatControllerImpl(deps)}var ChatControllerImpl=class extends MediaStore{constructor(deps){super(freezeSnapshot({status:"idle",messages:[],conversationId:deps.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingDelta="";this.flushHandle=null;this.auth=deps.auth,this.funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),this.petRef=deps.petRef??null,this.cases=createCasesRepositoryOver(this.funnel),this.telemetry=deps.telemetry??noopTelemetry,this.errorPolicy=deps.errorPolicy??defaultErrorPolicy,this.timers=deps.timers??defaultTimers2,this.rng=deps.rng??Math.random,this.newId=deps.newId??defaultIdFactory(),this.makeIdempotencyKey=deps.makeIdempotencyKey??defaultIdempotencyFactory(),this.budget={idleMs:deps.budget?.idleMs??DEFAULT_IDLE_MS,overallMs:deps.budget?.overallMs??DEFAULT_OVERALL_MS}}patch(partial){if(partial.messages!==void 0){let frozen=/* @__PURE__ */Object.freeze([...partial.messages]);super.patch({...partial,messages:frozen});return}super.patch(partial)}send(text3,opts,handlers){let options=opts??{};if(this.disposed||this.snapshot.isBootstrapping){let error=makeError(this.disposed?"accessDenied":"internalError",!this.disposed);return handlers?(handlers.onError(error),()=>{}):singleFrameStream(synthErrorFrame(error))}let invalid4=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid4!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),this.patch({status:"error",isStreaming:false,error:invalid4.error}),handlers?(handlers.onError(invalid4.error),()=>{}):singleFrameStream(synthErrorFrame(invalid4.error));if(handlers)return this.driveWithHandlers(text3,options,handlers);let turn=this.beginTurn(text3,options);return this.runTurn(turn,options.signal)}askEverfur(prompt,opts){if(this.disposed)return singleFrameStream(synthErrorFrame(makeError("accessDenied",false)));let invalid4=validateMessageText(prompt);return invalid4!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),singleFrameStream(synthErrorFrame(invalid4.error))):(this.resetThread(),this.send(prompt,opts??{}))}retryLast(){let turn=this.lastTurn;if(turn===null){let id=this.snapshot.conversationId;return id!==null&&this.snapshot.status==="error"?this.retryHistory(id):emptyStream()}turn.assistantMessageId=null,turn.sawDelta=false,turn.conversationIdOverride=null,this.discardPendingDelta();let messages=this.snapshot.messages.some(m=>m.id===turn.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,makeUser(turn.userMessageId,turn.text,this.stamp())];return this.patch({error:null,stopped:false,messages:messages}),this.runTurn(turn,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let stopped=this.snapshot.messages.some(m=>m.role==="user"&&m.pending===true),messages=stopped?this.snapshot.messages.map(m=>m.pending===true?stripPending(m):m):this.snapshot.messages;(this.snapshot.status==="streaming"||stopped)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...stopped?{messages:messages,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot()}resetThread(prompts=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=prompts,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:prompts,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false})}newConversation(){this.disposed||this.resetThread(this.scopePrompts)}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let teardown of this.handlerTeardowns)teardown();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(id){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==id&&this.patch({conversationId:id}))}adoptPrompts(categories){if(this.disposed)return;let prompts=/* @__PURE__ */Object.freeze(flattenPrompts(categories));this.bootstrapPrompts=prompts,this.scopePrompts=prompts,this.replyPrompts===null&&(prompts.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:prompts}))}async listConversations(opts){return this.listConversationsWith(opts)}async listConversationsWith(opts,funnelOpts){let query=historyQuery(opts,100);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},opts?.signal,funnelOpts);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let page=mapConversationPage(result.value);if(page.ok){for(let conversation of page.value.conversations)conversation.unreadCount!==null&&this.unreadByConversation.set(conversation.id,conversation.unreadCount);let active=this.snapshot.conversationId,count2=active===null?void 0:this.unreadByConversation.get(active);count2!==void 0&&count2!==this.snapshot.unreadCount&&this.patch({unreadCount:count2}),this.reflectUnreadDot()}return page}reflectUnreadDot(){let unread=false;for(let count2 of this.unreadByConversation.values())if(count2>0){unread=true;break}unread!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:unread})}async openCheckin(target){if(this.disposed)return err(makeError("accessDenied",false));let named=target?.conversationId??null;if(named!==null){let opened2=await this.resumeConversation(named);return opened2.ok?ok(named):err(opened2.error)}let petRef=target?.petRef??this.petRef,listed=await this.listConversations({...petRef===null?{}:{petRef:petRef},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 petRef=opts?.petRef??this.petRef;if(petRef===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(petRef,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 petRef=this.petRef;if(petRef===null||!this.snapshot.messages.some(m=>m.checkin!==void 0&&m.checkin.status===null))return;let result=await this.cases.list(petRef);if(!result.ok||generation!==this.historyGeneration||this.disposed)return;let open=new Set(result.value.filter(row=>row.status===CHECKIN_ANSWERABLE_STATUS).map(row=>row.caseId)),byCase=new Map(result.value.map(row=>[row.caseId,row])),changed=false,messages=this.snapshot.messages.map(message=>{let checkin=message.checkin;if(checkin===void 0||checkin.status!==null)return message;changed=true;let row=byCase.get(checkin.caseId),openedAt=checkin.openedAt??row?.openedAt??null,watching=open.has(checkin.caseId),answerOnRecord=row!==void 0&&(!watching||isLiveAskAnswered({askCount:row.checkinAskCount,answerCount:row.checkinAnswerCount}))?row.lastResponse:null;/* @__PURE__ */
|
|
114
|
+
return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null||this.snapshot.isStreaming)return ok(void 0);let generation=this.historyGeneration,result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef=opts?.petRef??null,pending={petRef:petRef,settled:this.primeBounded(petRef)};this.unadoptedCreate=pending;let result=await pending.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async primeBounded(petRef){let head=await this.headThreadWithUnread(petRef);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(petRef){let listed=await this.listConversationsWith({...petRef===null?{}:{petRef:petRef},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 petRef=opts?.petRef??null,pending={petRef:petRef,settled:this.createConversationBounded(petRef)};this.unadoptedCreate=pending;let result=await pending.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef?{pet_ref:petRef}:{}},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 petRef=opts?.petRef??null;if(petRef!==null&&hasLoneSurrogate(petRef))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef!==null?`?pet_ref=${encodeURIComponent(petRef)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending=needsConversation?this.unadoptedCreate:null;if(pending!==null&&(turn.petRef===null||turn.petRef===pending.petRef)){let primed=await pending.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&this.adoptConversation(primed.value)}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk2=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk2):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(conversationId,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/${conversationId}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return makeError("authRejected",false)}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef=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(petRef?{petRef:petRef}:void 0),promptsPromise=controller.getPrompts(petRef!==null?{petRef:petRef}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId=null;if(conversationRes.ok)conversationId=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
|
|
115
|
+
return Object.freeze({conversationId:conversationId,petRef:petRef,suggestedPrompts:suggestedPrompts,error:error,warning:error===null&&conversationId===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 IDEMPOTENCY_KEY_MAX=128,PET_REF_MAX=128;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__ */
|
|
116
|
+
return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str7=v=>typeof v=="string"&&v.length>0?v:null,num4=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str7(o.upload_id),uploadUrl=str7(o.upload_url),s3Key=str7(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
|
|
117
|
+
return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num4(o.expires_in_seconds)??0,max_content_length:num4(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str7(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight3=/* @__PURE__ */new Set,listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed=false,publish=()=>{snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners2)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish()},pump=()=>{for(;!disposed&&inFlight3.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight3.add(id),run(row).finally(()=>{inFlight3.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot:()=>snapshot,get uploading(){return snapshot.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners2.clear(),snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str2=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str2(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(o.ref),name:name,dose:str2(o.dose),frequency:str2(o.frequency),startDate:str2(o.start_date),endDate:str2(o.end_date),notes:str2(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
118
|
+
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str2(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str2(o.food_brand),foodType:str2(o.food_type),microchipId:str2(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str2(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str2(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str2(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),conditionName:conditionName,diagnosedDate:str2(row.diagnosed_date),notes:str2(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX2=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid2(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid2(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid2(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid2("pet_ref must be a string");if(petRef.trim().length===0)return invalid2("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid2("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid2("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX2)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid2(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid2("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid2("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str3=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
|
|
119
|
+
return Object.freeze({petRef:str3(o.pet_ref)??petRef,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str3(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str3(o.pet_id),petRef:petRef,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str3(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
|
|
120
|
+
return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal2=(req,signal)=>signal?{...req,signal:signal}:req,petPath2=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal2({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid4=validate(petRef,profile);if(invalid4!==null)return err(invalid4);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath2(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal2({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath2(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal2({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath2(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal2({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal2({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function deniedDecisionsFor(level,reason){let disabled=/* @__PURE__ */Object.freeze({reason:reason,level:level,recoverable:false}),rows=[],seen=/* @__PURE__ */new Set;for(let name of Object.keys(REQUIRES))for(let resource of REQUIRES[name])seen.has(resource)||(seen.add(resource),rows.push(/* @__PURE__ */Object.freeze({resource:resource,granted:false,disabled:disabled}))/* @__PURE__ */);return Object.freeze(rows)}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending=inFlight2.get(scope);if(pending!==void 0)return pending;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link"]);var EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let slot=parseSlot(raw);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function pick2(raw,snake,camel){return raw[snake]!==void 0?raw[snake]:raw[camel]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base,over){return over===null||Object.keys(over).length===0?base??EMPTY:base===null||Object.keys(base).length===0?over:/* @__PURE__ */Object.freeze({...base,...over})}var APPEARANCE_PRESET_NAMES=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),APPEARANCE_PRESETS=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),APPEARANCE_SIZE_RANGES=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function isRecord2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPreset(value){return typeof value=="string"&&APPEARANCE_PRESET_NAMES.includes(value.trim().toLowerCase())}function present(vars,key){let value=vars[key];return value??void 0}var PX_MAX_LENGTH=16;function parsePx(value){if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value!="string"||value.length>PX_MAX_LENGTH)return;let match=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(value.trim());return match===null?void 0:Number(match[1])}var COLOR_VARIABLES=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],SIZE_VARIABLES=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(appearance){if(!isRecord2(appearance))return null;let preset=isPreset(appearance.theme)?APPEARANCE_PRESETS[appearance.theme.trim().toLowerCase()]:{},own=isRecord2(appearance.variables)?appearance.variables:{},vars={...preset};for(let[key,value]of Object.entries(own))value!=null&&(vars[key]=value);let out={},scheme=present(vars,"colorScheme"),schemeName=typeof scheme=="string"?scheme.trim().toLowerCase():null;(schemeName==="light"||schemeName==="dark"||schemeName==="auto")&&(out.color_scheme=schemeName);let suffix=schemeName==="dark"?"_dark":"";for(let[variable,field]of COLOR_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}let danger=present(vars,"colorDanger");danger!==void 0&&(out[`danger_color${suffix}`]=danger);let family=present(vars,"fontFamily");typeof family=="string"&&family.trim().length>0&&(out.font_family=family.trim());for(let[variable,field]of SIZE_VARIABLES){let px=parsePx(present(vars,variable));px!==void 0&&(out[field]=px)}let rules=appearance.rules;if(isRecord2(rules)){let slots={};for(let name of THEME_SLOT_NAMES){let paint=rules[name];isRecord2(paint)&&(slots[name]=paint)}Object.keys(slots).length>0&&(out.slots=slots)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var 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"]),SLOT_LOCK_PREFIX="slots.";function isEmptyBranding(b){return Object.keys(b).every(key=>key==="schemaVersion"||(b[key]??null)===null)}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)?true:name.startsWith(SLOT_LOCK_PREFIX)&&THEME_SLOT_NAMES.includes(name.slice(SLOT_LOCK_PREFIX.length))}function parseClientBranding(json){if(json===null||typeof json!="object")return null;let raw=json,flat=parseFlat(raw),expanded=expandAppearance(pick3(raw,"appearance")),branding=expanded===null?flat:overlayFlat(parseFlat(expanded),flat);return isEmptyBranding(branding)?null:/* @__PURE__ */Object.freeze(branding)}function overlayFlat(base,over){let out={...base};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base.slots??null,over.slots??null);return out.slots=Object.keys(slots).length===0?null:slots,out}function parseFlat(raw){return{displayName:parseNonEmptyString(pick3(raw,"display_name","displayName")),logoUrl:parseNonEmptyString(pick3(raw,"logo_url","logoUrl")),primaryColor:parseColor(pick3(raw,"primary_color","primaryColor")),accentColor:parseColor(pick3(raw,"accent_color","accentColor")),brightness:parseBrightness(pick3(raw,"brightness","color_scheme","colorScheme")),fontFamily:parseNonEmptyString(pick3(raw,"font_family","fontFamily")),fontUrl:parseNonEmptyString(pick3(raw,"font_url","fontUrl")),fonts:parseFaceMap(pick3(raw,"fonts")),fontUrls:parseFaceMap(pick3(raw,"font_urls","fontUrls")),placeholder:parseNonEmptyString(pick3(raw,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:parseBool(pick3(raw,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pick3(raw,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pick3(raw,"accent_color_dark","accentColorDark")),surfaceStyle:parseEnum(pick3(raw,"surface_style","surfaceStyle"),SURFACE_STYLES),radiusScale:parseEnum(pick3(raw,"radius_scale","radiusScale"),RADIUS_SCALES),logoUrlDark:parseNonEmptyString(pick3(raw,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pick3(raw,"slots")),accessibilityMaxFontScale:parseMaxFontScale(pick3(raw,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:parseLockedFields(pick3(raw,"locked_fields","lockedFields")),schemaVersion:parseSchemaVersion(pick3(raw,"schema_version","schemaVersion")),backgroundColor:parseColor(pick3(raw,"background_color","backgroundColor")),backgroundColorDark:parseColor(pick3(raw,"background_color_dark","backgroundColorDark")),textColor:parseColor(pick3(raw,"text_color","textColor")),textColorDark:parseColor(pick3(raw,"text_color_dark","textColorDark")),dangerColor:parseColor(pick3(raw,"danger_color","dangerColor")),dangerColorDark:parseColor(pick3(raw,"danger_color_dark","dangerColorDark")),fontSizeBase:parseClamped(pick3(raw,"font_size_base","fontSizeBase"),APPEARANCE_SIZE_RANGES.fontSizeBase),borderRadius:parseClamped(pick3(raw,"border_radius","borderRadius"),APPEARANCE_SIZE_RANGES.borderRadius),spacingUnit:parseClamped(pick3(raw,"spacing_unit","spacingUnit"),APPEARANCE_SIZE_RANGES.spacingUnit)}}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 pick3(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(pick3(raw,key));entry!==null&&(out[key]=entry)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var SURFACE_STYLES=["white","cream","subtle"],RADIUS_SCALES=["sharp","default","round"];function parseEnum(value,allowed){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return allowed.includes(lower)?lower:null}function parseBrightness(value){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return lower==="light"||lower==="dark"||lower==="auto"?lower:null}function parseNumber(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)&&(typeof value!="string"||value.trim().length>0)?n:null}var MAX_FONT_SCALE_FLOOR=1,MAX_FONT_SCALE_CEILING=3.1;function parseMaxFontScale(value){let n=parseNumber(value);return n===null?null:n<=0?0:Math.min(MAX_FONT_SCALE_CEILING,Math.max(MAX_FONT_SCALE_FLOOR,n))}function parseSchemaVersion(value){if(value==null)return null;let n=parseNumber(value);return n!==null&&Number.isInteger(n)&&n>=1?n:0}function toWireName(name){let trimmed=name.trim();return trimmed.startsWith(SLOT_LOCK_PREFIX)?trimmed:trimmed.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function parseLockedFields(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(typeof entry!="string")continue;let name=toWireName(entry);isThemeLockName(name)&&!out.includes(name)&&out.push(name)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}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__ */
|
|
121
|
+
return Object.freeze({kind:"updated",revision:body.revision,region:region,ttlSeconds:ttlSeconds,decisions:mapCapabilities(body.capabilities),branding:parseBranding(body),livemode:body.livemode!==false})}function parseBranding(body){let direct=parseClientBranding(body.branding);if(direct!==null)return direct;let hints=body.render_hints;if(hints!==null&&typeof hints=="object"){let nested=parseClientBranding(hints.branding);return nested!==null?nested:parseClientBranding(hints)}return null}function mapCapabilities(capabilities){if(capabilities===null||typeof capabilities!="object")/* @__PURE__ */return Object.freeze([]);let out=[];for(let[resource,value]of Object.entries(capabilities))isEnabled(value)&&out.push(/* @__PURE__ */Object.freeze({resource:resource,granted:true}));/* @__PURE__ */
|
|
122
|
+
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:describe2(cause)}),!stopped&&myGen===generation&&(deps.onSettled?.(),schedule(jitteredFloorSeconds())),null}if(stopped||myGen!==generation)return null;switch(resolution.kind){case"updated":cachedRevision=resolution.revision,deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false),schedule(resolution.ttlSeconds);break;case"notModified":schedule(lastCadenceSeconds);break;case"failed":deps.telemetry?.track("sdk.entitlements.poll_failed",{code:resolution.error.code}),schedule(jitteredFloorSeconds());break;default:schedule(jitteredFloorSeconds())}return deps.onSettled?.(),resolution},run=()=>{let current=tick().finally(()=>{inFlight3===current&&(inFlight3=null)});return inFlight3=current,current};return{start(){started||stopped||(started=true,run())},prime(){return stopped?Promise.resolve(null):inFlight3??run()},stop(){stopped||(stopped=true,generation++,clearTimer())},refresh(){stopped||!started||(generation++,cachedRevision=null,clearTimer(),run())}}}var defaultScheduler={set(callback,ms){let handle=setTimeout(callback,ms);return handle.unref?.(),handle},clear(handle){clearTimeout(handle)}};function describe2(cause){return cause instanceof Error?cause.message:"poll failed"}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3,PER_USER_KV_KEYS=/* @__PURE__ */Object.freeze([NOTIFICATIONS_DEVICE_KV_KEY]);function startBeforeLogoutHooks(deps){let{leaving:leaving,identity:identity,hooks:hooks,telemetry:telemetry}=deps;if(leaving===null||identity===null||hooks.size===0)return null;let context=/* @__PURE__ */Object.freeze({userRef:leaving.userRef,auth:deps.graceAuth()}),runs=[...hooks].map(hook=>{try{return Promise.resolve(hook(context))}catch(cause){return Promise.reject(cause)}}),report=(reason,count2)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count2,totalCount:runs.length})}catch{}},settled=Promise.allSettled(runs).then(outcomes=>{let failed=outcomes.filter(outcome=>outcome.status==="rejected").length;failed>0&&report("failed",failed)});return new Promise(resolve=>{let done=false,finish=()=>{done||(done=true,clearTimeout(timer),resolve())},timer=setTimeout(()=>{done||report("timeout",runs.length),finish()},LOGOUT_HOOK_BUDGET_MS);settled.then(finish,finish)})}function graceAuth(deps){let{leaving:leaving,identity:identity,transport:transport,sessionId:sessionId}=deps,token=identity.currentToken();token.catch(()=>{});let frozen={userRef:leaving.userRef,currentToken:()=>token,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:transport,identity:frozen,userRef:leaving.userRef,sessionId:sessionId}}async function sweepPerUserKv(kv,telemetry){if(PER_USER_KV_KEYS.length===0)return;let results=await Promise.allSettled(PER_USER_KV_KEYS.map(key=>kv.removeItem(key))),failedCount=results.filter(result=>result.status==="rejected").length;failedCount>0&&telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:failedCount,totalCount:results.length})}function compiledDefaultDecisions(){/* @__PURE__ */
|
|
123
|
+
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners2)listener()};return{subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot(){return snapshot},set(next){snapshot=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{}}),emit()},reset(){snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit()},setPending(pending){snapshot.isPending!==pending&&(snapshot=/* @__PURE__ */Object.freeze({...snapshot,isPending:pending}),emit())}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
|
|
124
|
+
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__ */
|
|
125
|
+
return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}function createInMemoryKv(){let map=/* @__PURE__ */new Map;return{async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}}}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&reportConfigFailure(failure2,this.telemetry,opts?.platform),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef=>this.buildAuth(userRef),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store;let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs));return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,branding,livemode)=>this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{}}),onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&¬ifyPetsChanged(this),result}prepare(opts){let petRef=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef??""}`,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(petRef).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),()=>err(makeEverfurError("authRejected",{retryable:false}))),refused?err(refused):this.primeEntitlements(),petRef===null?void 0:refused?err(refused):this.primeChat(petRef)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}/* @__PURE__ */
|
|
126
|
+
return Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll())}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var KNOWN_STATUSES=/* @__PURE__ */new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),STATUS_ALIASES=/* @__PURE__ */Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function normalizeStatus(raw){let aliased=Object.prototype.hasOwnProperty.call(STATUS_ALIASES,raw)?STATUS_ALIASES[raw]:void 0;if(aliased!==void 0)return aliased;let value=raw;return KNOWN_STATUSES.has(value)?value:"parsing"}function normalizeOrigin(raw){return raw==="owner_reported"||raw==="clinic_document"?raw:null}var requestSchema=/* @__PURE__ */zod.z.object({request_id:/* @__PURE__ */zod.z.string().min(1),pet_ref:/* @__PURE__ */zod.z.string().min(1),status:/* @__PURE__ */zod.z.string(),simple_status:/* @__PURE__ */zod.z.string().nullish(),simple_status_detail:/* @__PURE__ */zod.z.string().nullish(),status_label:/* @__PURE__ */zod.z.string().optional(),dispatch_status:/* @__PURE__ */zod.z.string().nullish(),can_retry_send:/* @__PURE__ */zod.z.boolean().optional(),can_revoke:/* @__PURE__ */zod.z.boolean().optional(),can_convert_to_upload:/* @__PURE__ */zod.z.boolean().optional(),can_update_clinic_email:/* @__PURE__ */zod.z.boolean().optional(),reminder_count:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),last_reminder_at:/* @__PURE__ */zod.z.string().nullish(),waiting_expectation:/* @__PURE__ */zod.z.string().nullish(),document_count:/* @__PURE__ */zod.z.number().optional(),held_item_count:/* @__PURE__ */zod.z.number().optional(),received_at:/* @__PURE__ */zod.z.string().nullish(),parsing_started_at:/* @__PURE__ */zod.z.string().nullish(),review_started_at:/* @__PURE__ */zod.z.string().nullish(),created_at:/* @__PURE__ */zod.z.string().optional(),updated_at:/* @__PURE__ */zod.z.string().optional(),source:/* @__PURE__ */zod.z.string().nullish().catch(null),action_needed_label:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_reason:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_code:/* @__PURE__ */zod.z.string().nullish().catch(null),recovery_stage:/* @__PURE__ */zod.z.string().nullish().catch(null),show_clinic_phone:/* @__PURE__ */zod.z.boolean().optional().catch(void 0),clinic_name:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_email:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_phone:/* @__PURE__ */zod.z.string().nullish().catch(null),converted_to_upload_at:/* @__PURE__ */zod.z.string().nullish().catch(null),request_group_id:/* @__PURE__ */zod.z.string().nullish().catch(null)}).passthrough();function mapRequestView(wire){let parsed=requestSchema.safeParse(wire);if(!parsed.success)return null;let w=parsed.data,simpleStatus=normalizeSimpleStatus(w.simple_status),status=simpleStatus==="requested"&&(w.status==="awaiting_upload"||w.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":simpleStatus==="parsing"&&(w.simple_status_detail==="in_review"||w.simple_status_detail==="review_email_failed")?"in_review":simpleStatus??normalizeStatus(w.status);/* @__PURE__ */
|
|
127
|
+
return Object.freeze({id:w.request_id,petRef:w.pet_ref,status:status,simpleStatus:simpleStatus,simpleStatusDetail:w.simple_status_detail??null,statusLabel:w.status_label??"",dispatchStatus:w.dispatch_status??null,canRetrySend:w.can_retry_send===true,canRevoke:w.can_revoke===true,canConvertToUpload:w.can_convert_to_upload===true,canUpdateClinicEmail:w.can_update_clinic_email===true,reminderCount:w.reminder_count??0,lastReminderAt:w.last_reminder_at??null,waitingExpectation:w.waiting_expectation??null,documentCount:numberOr(w.document_count,0),heldItemCount:numberOr(w.held_item_count,0),receivedAt:w.received_at??null,parsingStartedAt:w.parsing_started_at??null,reviewStartedAt:w.review_started_at??null,createdAt:w.created_at??"",updatedAt:w.updated_at??"",wireStatus:w.status,source:w.source??null,actionNeededLabel:w.action_needed_label??null,failureReason:w.failure_reason??null,failureCode:w.failure_code??null,recoveryStage:w.recovery_stage??null,showClinicPhone:w.show_clinic_phone===true,clinicName:w.clinic_name??null,clinicEmail:w.clinic_email??null,clinicPhone:w.clinic_phone??null,convertedToUploadAt:w.converted_to_upload_at??null,requestGroupId:w.request_group_id??null})}function normalizeSimpleStatus(raw){return!raw||raw==="awaiting_upload"||raw==="in_review"?null:KNOWN_STATUSES.has(raw)?raw:null}var entitySchema=/* @__PURE__ */zod.z.object({key:/* @__PURE__ */zod.z.string(),category:/* @__PURE__ */zod.z.string().optional(),label:/* @__PURE__ */zod.z.string().optional(),value:/* @__PURE__ */zod.z.string().nullish(),unit:/* @__PURE__ */zod.z.string().nullish(),observed_at:/* @__PURE__ */zod.z.string().nullish(),status:/* @__PURE__ */zod.z.string().nullish(),origin:/* @__PURE__ */zod.z.string().nullish(),canonical_key:/* @__PURE__ */zod.z.string().nullish()});var documentSchema=/* @__PURE__ */zod.z.object({doc_id:/* @__PURE__ */zod.z.string(),title:/* @__PURE__ */zod.z.string().nullish(),page_count:/* @__PURE__ */zod.z.number().nullish(),received_at:/* @__PURE__ */zod.z.string().nullish()});function mapEntityRow(e){/* @__PURE__ */
|
|
128
|
+
return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:normalizeOrigin(e.origin),canonicalKey:e.canonical_key??null})}function mapDocumentRow(d){/* @__PURE__ */
|
|
129
|
+
return Object.freeze({docId:d.doc_id,title:d.title??null,pageCount:d.page_count??null,receivedAt:d.received_at??null})}function numberOr(v,fallback){return typeof v=="number"&&Number.isFinite(v)?v:fallback}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text2=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),clinicSchema=/* @__PURE__ */zod.z.object({clinicId:/* @__PURE__ */uuid.optional(),clinicFreeText:text2(200).refine(value=>value.trim().length>0).optional(),clinicEmail:text2(320,3).refine(value=>!hasControl(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())).optional(),signatureId:/* @__PURE__ */uuid.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0)),inputSchema=/* @__PURE__ */zod.z.object({petRef:text2(128),ownerName:text2(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text2(64),clinics:/* @__PURE__ */zod.z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */zod.z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */zod.z.string(),created_count:/* @__PURE__ */zod.z.number().int().nonnegative(),failed_count:/* @__PURE__ */zod.z.number().int().nonnegative(),results:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({idempotency_key:/* @__PURE__ */zod.z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */zod.z.string().nullable().optional(),created:/* @__PURE__ */zod.z.boolean(),request:/* @__PURE__ */zod.z.unknown().optional(),failure_code:/* @__PURE__ */zod.z.string().nullable().optional(),failure_reason:/* @__PURE__ */zod.z.string().nullable().optional()}))});function createRecordsClinicBatchClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async createClinicRequestBatch(input){if(!inputSchema.safeParse(input).success)return err(makeEverfurError("validationFailed",{retryable:false}));let result=await funnel.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,clinics:input.clinics.map(clinic=>({...clinic.clinicId!==void 0?{clinic_id:clinic.clinicId}:{clinic_free_text:clinic.clinicFreeText},...clinic.clinicEmail!==void 0?{clinic_email:clinic.clinicEmail}:{},...clinic.signatureId!==void 0?{signature_id:clinic.signatureId}:{signature_png_base64:clinic.signaturePngBase64},idempotency_key:clinic.idempotencyKey}))}});if(!result.ok)return result;let parsed=responseSchema.safeParse(result.value);if(!parsed.success||parsed.data.pet_ref!==input.petRef)return malformed4();let results=[];for(let row of parsed.data.results){let request=row.request===void 0||row.request===null?null:mapRequestView(row.request);if(row.created!==(request!==null))return malformed4();results.push(/* @__PURE__ */Object.freeze({idempotencyKey:row.idempotency_key,clinicId:row.clinic_id??null,clinicFreeText:row.clinic_free_text??null,created:row.created,request:request,failureCode:row.failure_code??null,failureReason:row.failure_reason??null}))}return ok(/* @__PURE__ */Object.freeze({requestGroupId:parsed.data.request_group_id,petRef:parsed.data.pet_ref,results:/* @__PURE__ */Object.freeze(results),createdCount:parsed.data.created_count,failedCount:parsed.data.failed_count}))}}}function malformed4(){return err(makeEverfurError("internalError",{retryable:false}))}var RECORDS_CONSENT_REQUIRED_WIRE_CODE="records_consent_required";function recordsWireCodeOf(error){let raw=error.raw;if(raw===null||typeof raw!="object")return null;let body=raw,code=typeof body.error=="object"&&body.error!==null?body.error.code:body.code;return typeof code=="string"&&code.length>0?code:null}function isRecordsConsentRequired(error){return error===null||error.httpStatus!==409?false:recordsWireCodeOf(error)===RECORDS_CONSENT_REQUIRED_WIRE_CODE}var FACT_VALUE_FIELD="value_text",FACT_ENTITY_TYPE_MAX=64,FACT_CANONICAL_KEY_MAX=512;function isFactReviewerLocked(error){return error!==null&&error.httpStatus===409&&!isRecordsConsentRequired(error)}function factValueCorrection(value){/* @__PURE__ */
|
|
130
|
+
return Object.freeze({[FACT_VALUE_FIELD]:value.trim()})}var FACT_FIELD_BY_KIND=/* @__PURE__ */Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:FACT_VALUE_FIELD}),NUMERIC=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,ISO_DATE2=/^\d{4}-\d{2}-\d{2}$/;function inferFactValueKind(value){if(value==null)return"text";let trimmed=value.trim();return NUMERIC.test(trimmed)?"num":ISO_DATE2.test(trimmed)&&!Number.isNaN(Date.parse(trimmed))?"date":trimmed==="true"||trimmed==="false"?"bool":"text"}function factCorrectionFor(original,corrected){let next=corrected.trim(),kind=inferFactValueKind(original);if(kind==="num"&&NUMERIC.test(next)){let parsed=Number(next);if(Number.isFinite(parsed))/* @__PURE__ */return Object.freeze({[FACT_FIELD_BY_KIND.num]:parsed})}return kind==="date"&&ISO_DATE2.test(next)&&!Number.isNaN(Date.parse(next))?/* @__PURE__ */Object.freeze({[FACT_FIELD_BY_KIND.date]:next}):/* @__PURE__ */Object.freeze(kind==="bool"&&(next==="true"||next==="false")?{[FACT_FIELD_BY_KIND.bool]:next==="true"}:{[FACT_FIELD_BY_KIND.text]:next})}var str4=/* @__PURE__ */zod.z.string().nullish(),num2=/* @__PURE__ */zod.z.number().nullish(),pointSchema=/* @__PURE__ */zod.z.object({collected_at:str4,at:str4,value:num2,unit:str4,qualitative_result:str4,ref_low:num2,ref_high:num2,status:str4,source_clinic:str4,source_doc_id:str4,doc_id:str4,reviewed:/* @__PURE__ */zod.z.boolean().nullish()}),latestSchema=/* @__PURE__ */zod.z.object({collected_at:str4,at:str4,value:num2,unit:str4,qualitative_result:str4,status:str4}),markerSchema=/* @__PURE__ */zod.z.object({marker_id:/* @__PURE__ */zod.z.string().min(1),canonical_name:str4,name:str4,loinc_code:str4,canonical_unit:str4,unit:str4,panel_name:str4,panel:str4,meaning_text:str4,meaning:str4,latest:/* @__PURE__ */latestSchema.nullish(),trajectory:str4,points:/* @__PURE__ */zod.z.array(pointSchema).optional()}),summarySchema=/* @__PURE__ */zod.z.object({total_markers:/* @__PURE__ */zod.z.number().int().nonnegative(),in_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),out_of_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),unknown_count:/* @__PURE__ */zod.z.number().int().nonnegative()}),markersSchema=/* @__PURE__ */zod.z.object({markers:/* @__PURE__ */zod.z.array(markerSchema).optional(),summary:/* @__PURE__ */summarySchema.nullish(),disclaimer:/* @__PURE__ */zod.z.string().optional(),featured_marker_id:str4});function isObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function withheldMarkers(pet){/* @__PURE__ */
|
|
131
|
+
return Object.freeze({petRef:pet,withheld:true,markers:/* @__PURE__ */Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}function mapRecordMarkers(petRef,wire){let w=isObject(wire)?wire:{},pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldMarkers(pet);let parsed=markersSchema.safeParse(w);if(!parsed.success)return withheldMarkers(pet);let m=parsed.data,point=p=>/* @__PURE__ */Object.freeze({at:p.collected_at??p.at??null,value:p.value??null,unit:p.unit??null,qualitativeResult:p.qualitative_result??null,refLow:p.ref_low??null,refHigh:p.ref_high??null,status:p.status??null,sourceClinic:p.source_clinic??null,docId:p.source_doc_id??p.doc_id??null,reviewed:p.reviewed===true}),markers=(m.markers??[]).map(marker=>/* @__PURE__ */Object.freeze({markerId:marker.marker_id,name:marker.canonical_name??marker.name??marker.marker_id,loincCode:marker.loinc_code??null,unit:marker.canonical_unit??marker.unit??null,panel:marker.panel_name??marker.panel??null,meaning:marker.meaning_text??marker.meaning??null,latest:marker.latest?/* @__PURE__ */Object.freeze({at:marker.latest.collected_at??marker.latest.at??null,value:marker.latest.value??null,unit:marker.latest.unit??null,qualitativeResult:marker.latest.qualitative_result??null,status:marker.latest.status??null}):null,trajectory:marker.trajectory??null,points:/* @__PURE__ */Object.freeze((marker.points??[]).map(point))}));/* @__PURE__ */
|
|
132
|
+
return Object.freeze({petRef:pet,withheld:false,markers:/* @__PURE__ */Object.freeze(markers),summary:m.summary?/* @__PURE__ */Object.freeze({totalMarkers:m.summary.total_markers,inRangeCount:m.summary.in_range_count,outOfRangeCount:m.summary.out_of_range_count,unknownCount:m.summary.unknown_count}):null,disclaimer:m.disclaimer??"",featuredMarkerId:m.featured_marker_id??null})}var https=/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),itemSchema=/* @__PURE__ */zod.z.object({source_doc_id:/* @__PURE__ */zod.z.string().min(1),file_name:/* @__PURE__ */zod.z.string().nullish(),doc_format:/* @__PURE__ */zod.z.string().nullish(),byte_size:/* @__PURE__ */zod.z.number().int().nonnegative().nullish(),received_at:/* @__PURE__ */zod.z.string().nullish(),download_url:https,expires_in_seconds:/* @__PURE__ */zod.z.number().int().nonnegative().nullish()}),listSchema=/* @__PURE__ */zod.z.object({items:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.unknown()).optional()});function mapRequestDocuments(wire){let parsed=listSchema.safeParse(wire);if(!parsed.success)return null;let rows=[];for(let raw of parsed.data.items??[]){let item=itemSchema.safeParse(raw);item.success&&rows.push(
|
|
133
|
+
/* @__PURE__ */Object.freeze({sourceDocId:item.data.source_doc_id,fileName:item.data.file_name??null,docFormat:item.data.doc_format??null,byteSize:item.data.byte_size??null,receivedAt:item.data.received_at??null,downloadUrl:item.data.download_url,expiresInSeconds:item.data.expires_in_seconds??0}))}/* @__PURE__ */
|
|
134
|
+
return Object.freeze(rows)}var RECORD_SHARE_AUDIENCES=/* @__PURE__ */Object.freeze(["vet","groomer","boarding"]),https2=/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),str5=/* @__PURE__ */zod.z.string().nullish(),audienceField=/* @__PURE__ */zod.z.unknown().optional(),linkSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),share_url:/* @__PURE__ */zod.z.string().min(1),expires_at:str5,audience:audienceField}),listSchema2=/* @__PURE__ */zod.z.object({shares:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str5,created_at:str5,view_count:/* @__PURE__ */zod.z.number().int().nonnegative().nullish(),last_viewed_at:str5,audience:audienceField})).optional()}),pdfSchema=/* @__PURE__ */zod.z.object({download_url:https2,expires_at:str5}),emailSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str5,audience:audienceField}),scopeSchema=/* @__PURE__ */zod.z.object({audience:/* @__PURE__ */zod.z.string().min(1),sections:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()),entity_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullable()}),SHARE_RECIPIENT_EMAIL_MAX=254;function isShareRecipientEmail(value){let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=SHARE_RECIPIENT_EMAIL_MAX&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)}var isAudience=value=>typeof value=="string"&&RECORD_SHARE_AUDIENCES.includes(value);function audienceOf(value){return isAudience(value)?value:null}function mapShareAudiences(wire){let parsed=zod.z.array(scopeSchema).safeParse(wire);if(!parsed.success)/* @__PURE__ */return Object.freeze([]);let seen=/* @__PURE__ */new Set,scopes=[];for(let scope of parsed.data)!isAudience(scope.audience)||seen.has(scope.audience)||(seen.add(scope.audience),scopes.push(/* @__PURE__ */Object.freeze({audience:scope.audience,sections:/* @__PURE__ */Object.freeze([...scope.sections]),entityTypes:scope.entity_types===null?null:/* @__PURE__ */Object.freeze([...scope.entity_types])}))/* @__PURE__ */);return Object.freeze(scopes)}function resolveShareUrl(shareUrl,apiBaseUrl){let trimmed=shareUrl.trim();if(trimmed.length===0)return null;try{let absolute=/^[a-z][a-z0-9+.-]*:/i.test(trimmed)?new URL(trimmed):apiBaseUrl!==void 0?new URL(trimmed,apiBaseUrl):null;return absolute===null||absolute.protocol!=="https:"?null:absolute.toString()}catch{return null}}function mapRecordShareLink(wire,apiBaseUrl){let parsed=linkSchema.safeParse(wire);if(!parsed.success)return null;let shareUrl=resolveShareUrl(parsed.data.share_url,apiBaseUrl);return shareUrl===null?null:/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,shareUrl:shareUrl,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)})}function mapRecordShareList(wire){let parsed=listSchema2.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.shares??[]).map(share=>/* @__PURE__ */Object.freeze({shareId:share.share_id,expiresAt:share.expires_at??null,createdAt:share.created_at??null,viewCount:share.view_count??0,lastViewedAt:share.last_viewed_at??null,audience:audienceOf(share.audience)}))):null}function mapRecordShareEmailReceipt(wire){let parsed=emailSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)}):null}function mapRecordPdfLink(wire){let parsed=pdfSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({downloadUrl:parsed.data.download_url,expiresAt:parsed.data.expires_at??null}):null}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]);var RECORDS_FEATURES_PDF_ONLY=/* @__PURE__ */Object.freeze({features:/* @__PURE__ */Object.freeze({}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE]),shareAudiences:/* @__PURE__ */Object.freeze([])}),featuresSchema=/* @__PURE__ */zod.z.object({features:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.boolean()),upload_content_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullish(),share_audiences:/* @__PURE__ */zod.z.unknown().optional()});function mapRecordsFeatures(wire){let parsed=featuresSchema.safeParse(wire);if(!parsed.success)return RECORDS_FEATURES_PDF_ONLY;let listed=parsed.data.upload_content_types??[],photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>listed.includes(type));/* @__PURE__ */
|
|
135
|
+
return Object.freeze({features:/* @__PURE__ */Object.freeze({...parsed.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE,...photos]),shareAudiences:mapShareAudiences(parsed.data.share_audiences)})}var listSchema3=/* @__PURE__ */zod.z.object({signatures:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({signature_id:/* @__PURE__ */zod.z.string().min(1),preview_url:/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),created_at:/* @__PURE__ */zod.z.string().nullish()})).optional()});function mapSignatureSuggestions(wire){let parsed=listSchema3.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.signatures??[]).map(row=>/* @__PURE__ */Object.freeze({signatureId:row.signature_id,previewUrl:row.preview_url,createdAt:row.created_at??null}))):null}var str6=/* @__PURE__ */zod.z.string().nullish(),num3=/* @__PURE__ */zod.z.number().nullish(),labPointSchema=/* @__PURE__ */zod.z.object({at:str6,value:num3,unit:str6,qualitative_result:str6,ref_low:num3,ref_high:num3,status:str6,doc_id:str6}),labMarkerSchema=/* @__PURE__ */zod.z.object({marker_id:/* @__PURE__ */zod.z.string(),name:/* @__PURE__ */zod.z.string(),loinc_code:str6,unit:str6,panel:str6,meaning:str6,latest:/* @__PURE__ */zod.z.object({at:str6,value:num3,unit:str6,qualitative_result:str6,status:str6}).nullish(),trajectory:str6,points:/* @__PURE__ */zod.z.array(labPointSchema).optional()}),encounterSchema=/* @__PURE__ */zod.z.object({encounter_id:/* @__PURE__ */zod.z.string(),date:str6,type:str6,clinic_name:str6,veterinarian:str6,doc_id:str6}),noteSchema=/* @__PURE__ */zod.z.object({note_id:/* @__PURE__ */zod.z.string(),encounter_id:str6,observed_on:str6,sections:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({section:/* @__PURE__ */zod.z.string(),text:/* @__PURE__ */zod.z.string()})).optional()}),examSchema=/* @__PURE__ */zod.z.object({exam_id:/* @__PURE__ */zod.z.string(),encounter_id:str6,observed_on:str6,doc_id:str6,systems:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.object({finding_status:str6,finding:str6})).optional()}),completenessSchema=/* @__PURE__ */zod.z.object({has_lab_history:/* @__PURE__ */zod.z.boolean().optional(),has_vaccination_history:/* @__PURE__ */zod.z.boolean().optional(),has_weight_history:/* @__PURE__ */zod.z.boolean().optional(),has_vitals_history:/* @__PURE__ */zod.z.boolean().optional(),has_physical_exam_history:/* @__PURE__ */zod.z.boolean().optional(),has_procedure_history:/* @__PURE__ */zod.z.boolean().optional(),has_genetic_history:/* @__PURE__ */zod.z.boolean().optional(),has_reproductive_history:/* @__PURE__ */zod.z.boolean().optional(),has_parasite_prevention_history:/* @__PURE__ */zod.z.boolean().optional(),earliest_record_at:str6,latest_record_at:str6,documents_ingested:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),documents_in_review:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),entities_pending_review:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.number().int().nonnegative()).optional(),held_total:/* @__PURE__ */zod.z.number().int().nonnegative().optional()}),conflictSchema=/* @__PURE__ */zod.z.object({conflict_id:/* @__PURE__ */zod.z.string(),entity_type:/* @__PURE__ */zod.z.string(),field:str6,severity:str6,candidates:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({value:/* @__PURE__ */zod.z.string(),source_doc_id:str6,doc_id:str6,collected_at:str6})).optional()}),depthSchema=/* @__PURE__ */zod.z.object({lab_results:/* @__PURE__ */zod.z.array(labMarkerSchema).optional(),encounters:/* @__PURE__ */zod.z.array(encounterSchema).optional(),clinician_notes:/* @__PURE__ */zod.z.array(noteSchema).optional(),physical_exams:/* @__PURE__ */zod.z.array(examSchema).optional(),completeness:/* @__PURE__ */completenessSchema.nullish(),conflicts:/* @__PURE__ */zod.z.array(conflictSchema).optional()}),timelineSchema=/* @__PURE__ */zod.z.object({visits:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({visit_id:/* @__PURE__ */zod.z.string(),visit_date:str6,veterinarian:str6,summary:str6,doc_id:str6})),vaccines:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({vaccine_id:/* @__PURE__ */zod.z.string(),product:str6,lot:str6,administered_on:str6,expires_on:str6,doc_id:str6})),weights:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({weight_id:/* @__PURE__ */zod.z.string(),observed_on:str6,weight_kg:num3,doc_id:str6})),medications:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({medication_id:/* @__PURE__ */zod.z.string(),drug_name:str6,dose:str6,route:str6,frequency:str6,sig:str6,rx_number:str6,started_on:str6,stopped_on:str6,doc_id:str6})),disclaimer:/* @__PURE__ */zod.z.string().optional()}),contributionsSchema=/* @__PURE__ */zod.z.object({document:documentSchema,contributions:/* @__PURE__ */zod.z.array(entitySchema),contribution_count:/* @__PURE__ */zod.z.number().int().nonnegative().optional()});function isObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function petOf(w,petRef){return typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef}function emptyDepth(pet,withheld){/* @__PURE__ */
|
|
136
|
+
return Object.freeze({petRef:pet,available:false,withheld:withheld,labResults:/* @__PURE__ */Object.freeze([]),encounters:/* @__PURE__ */Object.freeze([]),clinicianNotes:/* @__PURE__ */Object.freeze([]),physicalExams:/* @__PURE__ */Object.freeze([]),completeness:null,conflicts:/* @__PURE__ */Object.freeze([])})}function mapRecordDepth(petRef,wire){let w=isObject2(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return emptyDepth(pet,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(key=>key in w))return emptyDepth(pet,false);let parsed=depthSchema.safeParse(w);if(!parsed.success)return emptyDepth(pet,true);let d=parsed.data,point=p=>/* @__PURE__ */Object.freeze({at:p.at??null,value:p.value??null,unit:p.unit??null,qualitativeResult:p.qualitative_result??null,refLow:p.ref_low??null,refHigh:p.ref_high??null,status:p.status??null,docId:p.doc_id??null});/* @__PURE__ */
|
|
137
|
+
return Object.freeze({petRef:pet,available:true,withheld:false,labResults:/* @__PURE__ */Object.freeze((d.lab_results??[]).map(m=>/* @__PURE__ */Object.freeze({markerId:m.marker_id,name:m.name,loincCode:m.loinc_code??null,unit:m.unit??null,panel:m.panel??null,meaning:m.meaning??null,latest:/* @__PURE__ */Object.freeze({at:m.latest?.at??null,value:m.latest?.value??null,unit:m.latest?.unit??null,qualitativeResult:m.latest?.qualitative_result??null,status:m.latest?.status??null}),trajectory:m.trajectory??null,points:/* @__PURE__ */Object.freeze((m.points??[]).map(point))}))),encounters:/* @__PURE__ */Object.freeze((d.encounters??[]).map(e=>/* @__PURE__ */Object.freeze({encounterId:e.encounter_id,date:e.date??null,type:e.type??null,clinicName:e.clinic_name??null,veterinarian:e.veterinarian??null,docId:e.doc_id??null}))),clinicianNotes:/* @__PURE__ */Object.freeze((d.clinician_notes??[]).map(n=>/* @__PURE__ */Object.freeze({noteId:n.note_id,encounterId:n.encounter_id??null,observedOn:n.observed_on??null,sections:/* @__PURE__ */Object.freeze((n.sections??[]).map(s=>/* @__PURE__ */Object.freeze({section:s.section,text:s.text})))}))),physicalExams:/* @__PURE__ */Object.freeze((d.physical_exams??[]).map(x=>/* @__PURE__ */Object.freeze({examId:x.exam_id,encounterId:x.encounter_id??null,observedOn:x.observed_on??null,docId:x.doc_id??null,systems:/* @__PURE__ */Object.freeze(Object.entries(x.systems??{}).map(([system,field])=>/* @__PURE__ */Object.freeze({system:system,findingStatus:field.finding_status??null,finding:field.finding??null})))}))),completeness:d.completeness?/* @__PURE__ */Object.freeze({hasLabHistory:d.completeness.has_lab_history===true,hasVaccinationHistory:d.completeness.has_vaccination_history===true,hasWeightHistory:d.completeness.has_weight_history===true,hasVitalsHistory:d.completeness.has_vitals_history===true,hasPhysicalExamHistory:d.completeness.has_physical_exam_history===true,hasProcedureHistory:d.completeness.has_procedure_history===true,hasGeneticHistory:d.completeness.has_genetic_history===true,hasReproductiveHistory:d.completeness.has_reproductive_history===true,hasParasitePreventionHistory:d.completeness.has_parasite_prevention_history===true,earliestRecordAt:d.completeness.earliest_record_at??null,latestRecordAt:d.completeness.latest_record_at??null,documentsIngested:d.completeness.documents_ingested??0,documentsInReview:d.completeness.documents_in_review??0,entitiesPendingReview:/* @__PURE__ */Object.freeze({...d.completeness.entities_pending_review??{}}),heldTotal:d.completeness.held_total??0}):null,conflicts:/* @__PURE__ */Object.freeze((d.conflicts??[]).map(c=>/* @__PURE__ */Object.freeze({conflictId:c.conflict_id,entityType:c.entity_type,field:c.field??null,severity:c.severity??"needs_review",candidates:/* @__PURE__ */Object.freeze((c.candidates??[]).map(k=>/* @__PURE__ */Object.freeze({value:k.value,docId:k.source_doc_id??k.doc_id??null,collectedAt:k.collected_at??null})))})))})}function withheldTimeline(pet){/* @__PURE__ */
|
|
138
|
+
return Object.freeze({petRef:pet,withheld:true,isEmpty:false,visits:/* @__PURE__ */Object.freeze([]),vaccines:/* @__PURE__ */Object.freeze([]),weights:/* @__PURE__ */Object.freeze([]),medications:/* @__PURE__ */Object.freeze([]),disclaimer:""})}function mapRecordsTimeline(petRef,wire){let w=isObject2(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return withheldTimeline(pet);let parsed=timelineSchema.safeParse(w);if(!parsed.success)return withheldTimeline(pet);let t=parsed.data,visits=t.visits.map(v=>/* @__PURE__ */Object.freeze({visitId:v.visit_id,visitDate:v.visit_date??null,veterinarian:v.veterinarian??null,summary:v.summary??null,docId:v.doc_id??null})),vaccines=t.vaccines.map(v=>/* @__PURE__ */Object.freeze({vaccineId:v.vaccine_id,product:v.product??null,lot:v.lot??null,administeredOn:v.administered_on??null,expiresOn:v.expires_on??null,docId:v.doc_id??null})),weights=t.weights.map(v=>/* @__PURE__ */Object.freeze({weightId:v.weight_id,observedOn:v.observed_on??null,weightKg:v.weight_kg??null,docId:v.doc_id??null})),medications=t.medications.map(m=>/* @__PURE__ */Object.freeze({medicationId:m.medication_id,drugName:m.drug_name??null,dose:m.dose??null,route:m.route??null,frequency:m.frequency??null,sig:m.sig??null,rxNumber:m.rx_number??null,startedOn:m.started_on??null,stoppedOn:m.stopped_on??null,docId:m.doc_id??null}));/* @__PURE__ */
|
|
139
|
+
return Object.freeze({petRef:pet,withheld:false,isEmpty:visits.length===0&&vaccines.length===0&&weights.length===0&&medications.length===0,visits:/* @__PURE__ */Object.freeze(visits),vaccines:/* @__PURE__ */Object.freeze(vaccines),weights:/* @__PURE__ */Object.freeze(weights),medications:/* @__PURE__ */Object.freeze(medications),disclaimer:t.disclaimer??""})}function mapDocumentContributions(petRef,wire){let w=isObject2(wire)?wire:{},pet=petOf(w,petRef),withheld=()=>/* @__PURE__ */Object.freeze({petRef:pet,withheld:true,document:null,contributions:/* @__PURE__ */Object.freeze([]),contributionCount:0});if(w.withheld===true)return withheld();let parsed=contributionsSchema.safeParse(w);if(!parsed.success)return withheld();let contributions=/* @__PURE__ */Object.freeze(parsed.data.contributions.map(mapEntityRow));/* @__PURE__ */
|
|
140
|
+
return Object.freeze({petRef:pet,withheld:false,document:mapDocumentRow(parsed.data.document),contributions:contributions,contributionCount:parsed.data.contribution_count??contributions.length})}var BASE="/widget/v1/records/pets";function createRecordsDepthClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),segment=(value,max)=>typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)&&[...value].length<=max,read=async(call,petRef,path,map)=>{if(!segment(petRef,PET_REF_MAX))return invalid3();let result=await funnel.send(call,{method:"GET",path:path});if(!result.ok)return result;let view=map(result.value);return view.petRef===petRef?ok(view):err(makeEverfurError("internalError",{retryable:false}))},pet=petRef=>`${BASE}/${encodeURIComponent(petRef)}`,record=petRef=>`${pet(petRef)}/everfur_record`,parsed=async(call,req,map)=>{let result=await funnel.send(call,req,req.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!result.ok)return result;let value=map(result.value);return value===null?err(makeEverfurError("internalError",{retryable:false})):ok(value)},factBody=(input,corrected)=>!segment(input.entityType,FACT_ENTITY_TYPE_MAX)||!segment(input.canonicalKey,FACT_CANONICAL_KEY_MAX)||input.idempotencyKey!==void 0&&!segment(input.idempotencyKey,IDEMPOTENCY_KEY_MAX)||corrected!==void 0&&Object.keys(corrected).length===0?null:{entity_type:input.entityType,canonical_key:input.canonicalKey,...corrected!==void 0?{corrected_fields:corrected}:{},...input.idempotencyKey!==void 0?{idempotency_key:input.idempotencyKey}:{}};return{getRecordDepth:petRef=>read("records.depth.record",petRef,`${pet(petRef)}/record`,wire=>mapRecordDepth(petRef,wire)),getTimeline:petRef=>read("records.depth.timeline",petRef,`${pet(petRef)}/timeline`,wire=>mapRecordsTimeline(petRef,wire)),getDocumentContributions(petRef,docId){return segment(docId,64)?read("records.depth.contributions",petRef,`${pet(petRef)}/documents/${encodeURIComponent(docId)}/contributions`,wire=>mapDocumentContributions(petRef,wire)):invalid3()},getMarkers:petRef=>read("records.depth.markers",petRef,`${pet(petRef)}/markers`,wire=>mapRecordMarkers(petRef,wire)),createShare(petRef,opts){if(!segment(petRef,PET_REF_MAX))return invalid3();let audience=opts?.audience;return audience!==void 0&&!RECORD_SHARE_AUDIENCES.includes(audience)?invalid3():parsed("records.share.create",{method:"POST",path:`${record(petRef)}/share`,...audience!==void 0?{body:{audience:audience}}:{}},wire=>mapRecordShareLink(wire,deps.apiBaseUrl))},emailShare(petRef,input){let kind=input.recipientKind,email=typeof input.recipientEmail=="string"?input.recipientEmail.trim():"",kindOk=kind==="other"||RECORD_SHARE_AUDIENCES.includes(kind);return!segment(petRef,PET_REF_MAX)||!kindOk||!isShareRecipientEmail(email)||hasLoneSurrogate(email)?invalid3():parsed("records.share.email",{method:"POST",path:`${record(petRef)}/share/email`,body:{recipient_email:email,recipient_kind:kind}},mapRecordShareEmailReceipt)},async readFeatures(){try{let result=await funnel.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return result.ok?mapRecordsFeatures(result.value):RECORDS_FEATURES_PDF_ONLY}catch{return RECORDS_FEATURES_PDF_ONLY}},listShares(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.share.list",{method:"GET",path:`${record(petRef)}/shares`},mapRecordShareList):invalid3()},async revokeShare(petRef,shareId){if(!segment(petRef,PET_REF_MAX)||!segment(shareId,64))return invalid3();let result=await funnel.send("records.share.revoke",{method:"DELETE",path:`${record(petRef)}/shares/${encodeURIComponent(shareId)}`},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},getPdfLink(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.pdf.link",{method:"GET",path:`${record(petRef)}/pdf-link`},mapRecordPdfLink):invalid3()},async editFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input,input.correctedFields):null;if(body===null)return invalid3();let result=await funnel.send("records.fact.edit",{method:"POST",path:`${record(petRef)}/facts/edit`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},async removeFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input):null;if(body===null)return invalid3();let result=await funnel.send("records.fact.remove",{method:"POST",path:`${record(petRef)}/facts/remove`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},listRequestDocuments(requestId){return segment(requestId,64)?parsed("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(requestId)}/documents`},mapRequestDocuments):invalid3()},listAuthorizationSignatures:()=>parsed("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mapSignatureSuggestions)}}function invalid3(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke of strokes){let points=[];for(let point of stroke){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text3=name.trim();if(text3.length===0)return bitmap;let chars=[...text3],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count2){for(this.acc|=value<<this.count,this.count+=count2;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],LENGTH_EXTRA=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],DIST_BASE=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],DIST_EXTRA=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte2 of bytes)a=(a+byte2)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n=0;n<256;n+=1){let c=n;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n]=c>>>0}}let crc=4294967295;for(let byte2 of bytes)crc=crcTable[(crc^byte2)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}exports.ATTACHMENT_ACCEPT=ATTACHMENT_ACCEPT;exports.ATTACHMENT_BACKOFF_MS=ATTACHMENT_BACKOFF_MS;exports.ATTACHMENT_INITIATE_PATH=ATTACHMENT_INITIATE_PATH;exports.ATTACHMENT_MAX_ATTEMPTS=ATTACHMENT_MAX_ATTEMPTS;exports.ATTACHMENT_MIME_TYPES=ATTACHMENT_MIME_TYPES;exports.ATTACHMENT_QUEUE_CONCURRENCY=ATTACHMENT_QUEUE_CONCURRENCY;exports.CHAT_FEEDBACK_TYPES=CHAT_FEEDBACK_TYPES;exports.CHECKIN_ANSWERABLE_STATUS=CHECKIN_ANSWERABLE_STATUS;exports.FACT_FIELD_BY_KIND=FACT_FIELD_BY_KIND;exports.FACT_VALUE_FIELD=FACT_VALUE_FIELD;exports.FEEDBACK_NOTES_MAX_CHARS=FEEDBACK_NOTES_MAX_CHARS;exports.LOGOUT_HOOK_BUDGET_MS=LOGOUT_HOOK_BUDGET_MS;exports.MAX_ATTACHMENTS_PER_MESSAGE=MAX_ATTACHMENTS_PER_MESSAGE;exports.MAX_ATTACHMENT_BYTES=MAX_ATTACHMENT_BYTES;exports.MAX_FILENAME_LENGTH=MAX_FILENAME_LENGTH;exports.MAX_IMAGE_KEYS_PER_MESSAGE=MAX_IMAGE_KEYS_PER_MESSAGE;exports.MESSAGE_MAX_CHARS=MESSAGE_MAX_CHARS;exports.MIN_POLL_INTERVAL_SECONDS=MIN_POLL_INTERVAL_SECONDS;exports.NULL_SECURE_STORE=NULL_SECURE_STORE;exports.RECORDS_CLINIC_BATCH_MAX=RECORDS_CLINIC_BATCH_MAX;exports.RECORD_SHARE_AUDIENCES=RECORD_SHARE_AUDIENCES;exports.SHARE_RECIPIENT_EMAIL_MAX=SHARE_RECIPIENT_EMAIL_MAX;exports.SIGNATURE_CANVAS=SIGNATURE_CANVAS;exports.attachmentSize=attachmentSize;exports.bootstrapChat=bootstrapChat;exports.createAttachmentQueue=createAttachmentQueue;exports.createChatController=createChatController;exports.createEntitlementPoller=createEntitlementPoller;exports.createEverfurRuntime=createEverfurRuntime;exports.createRecordsClinicBatchClient=createRecordsClinicBatchClient;exports.createRecordsDepthClient=createRecordsDepthClient;exports.defaultErrorPolicy=defaultErrorPolicy;exports.encodeSignaturePng=encodeSignaturePng;exports.factCorrectionFor=factCorrectionFor;exports.factValueCorrection=factValueCorrection;exports.formatBytes=formatBytes;exports.inferFactValueKind=inferFactValueKind;exports.initiateAttachmentUpload=initiateAttachmentUpload;exports.isAttachmentMime=isAttachmentMime;exports.isCheckinSettled=isCheckinSettled;exports.isFactReviewerLocked=isFactReviewerLocked;exports.isShareRecipientEmail=isShareRecipientEmail;exports.mapDocumentContributions=mapDocumentContributions;exports.mapRecordDepth=mapRecordDepth;exports.mapRecordMarkers=mapRecordMarkers;exports.mapRecordPdfLink=mapRecordPdfLink;exports.mapRecordShareEmailReceipt=mapRecordShareEmailReceipt;exports.mapRecordShareLink=mapRecordShareLink;exports.mapRecordShareList=mapRecordShareList;exports.mapRecordsTimeline=mapRecordsTimeline;exports.mapShareAudiences=mapShareAudiences;exports.mapSignatureSuggestions=mapSignatureSuggestions;exports.noopTelemetry=noopTelemetry;exports.optionalModule=optionalModule;exports.rasterizeStrokes=rasterizeStrokes;exports.rasterizeTypedName=rasterizeTypedName;exports.resolveShareUrl=resolveShareUrl;exports.sanitizeFilename=sanitizeFilename;exports.unavailableCamera=unavailableCamera;exports.uploadAttachmentBytes=uploadAttachmentBytes;exports.validateAttachment=validateAttachment;
|