@everfur/sdk 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +220 -0
- package/README.md +9 -8
- package/dist/{Chat-BZZ-Py5l.d.ts → Chat-Rzplrf5M.d.ts} +17 -3
- package/dist/{Chat-Dq4fffIO.d.cts → Chat-ypo6miKm.d.cts} +17 -3
- package/dist/{DepthViews-BG3E25MD.d.ts → DepthViews-CeTfPUBX.d.ts} +1 -1
- package/dist/{DepthViews-B_hIypI6.d.cts → DepthViews-ClykXOJj.d.cts} +1 -1
- package/dist/{DepthViews-CL75jyRA.d.cts → DepthViews-Cui3oonj.d.cts} +1 -1
- package/dist/{DepthViews-CkYri51q.d.ts → DepthViews-baYLMNQ-.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-CwbfmxzJ.d.ts → ErrorPolicyPort-D22LUVrK.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-CNf4uQZP.d.cts → ErrorPolicyPort-D6CybiqJ.d.cts} +1 -1
- package/dist/{EverfurResult-DN9pL2Ab.d.cts → EverfurError-DmELDpXp.d.cts} +1 -67
- package/dist/{EverfurResult-DN9pL2Ab.d.ts → EverfurError-DmELDpXp.d.ts} +1 -67
- package/dist/EverfurResult-SGvHKsCB.d.ts +69 -0
- package/dist/EverfurResult-ZtH-YV1h.d.cts +69 -0
- package/dist/animations/index.cjs +1 -1
- package/dist/animations/index.d.cts +6 -5
- package/dist/animations/index.d.ts +6 -5
- package/dist/animations/index.js +1 -1
- package/dist/{attachments-D_SECjr1.d.cts → attachments-CwsR-bPN.d.cts} +7 -6
- package/dist/{attachments-BrUWQYNK.d.ts → attachments-CzZ7in24.d.ts} +7 -6
- package/dist/{attachments-DpldrvIW.d.ts → attachments-D3HCBmOE.d.ts} +3 -3
- package/dist/{attachments-BorG422I.d.cts → attachments-Nk73Lll8.d.cts} +3 -3
- package/dist/{bookingCopy-SREvkG19.d.cts → bookingCopy-Dv8rKqyV.d.cts} +417 -14
- package/dist/{bookingCopy-CqtDYvCR.d.ts → bookingCopy-SDkXaxDf.d.ts} +417 -14
- package/dist/branding-Xb_wL8N1.d.cts +212 -0
- package/dist/branding-xpQ056sM.d.ts +212 -0
- package/dist/callCopy-rDH9JTFo.d.cts +45 -0
- package/dist/callCopy-rDH9JTFo.d.ts +45 -0
- package/dist/callRoom-7wrE3RP2.d.ts +62 -0
- package/dist/callRoom-B_EqaUzx.d.cts +62 -0
- package/dist/{casesRepository-v6QczS9N.d.ts → casesRepository-BTAecTnF.d.ts} +14 -2
- package/dist/{casesRepository-DwtZVsbj.d.cts → casesRepository-aryld7fJ.d.cts} +14 -2
- package/dist/chat/index.cjs +1 -1
- package/dist/chat/index.d.cts +12 -11
- package/dist/chat/index.d.ts +12 -11
- package/dist/chat/index.js +1 -1
- package/dist/client/index.cjs +5 -5
- package/dist/client/index.d.cts +14 -12
- package/dist/client/index.d.ts +14 -12
- package/dist/client/index.js +5 -5
- package/dist/{config-C7eb_IMD.d.ts → config-6qS7Sohy.d.cts} +3 -2
- package/dist/{config--Wu1Umhd.d.cts → config-X6BtwDwQ.d.ts} +3 -2
- package/dist/consent/index.cjs +1 -1
- package/dist/consent/index.d.cts +9 -8
- package/dist/consent/index.d.ts +9 -8
- package/dist/consent/index.js +1 -1
- package/dist/{context-CahAEha8.d.ts → context-7f3Nb_xE.d.ts} +9 -8
- package/dist/{context-CL3lyuy1.d.cts → context-CkqPM4Ml.d.cts} +9 -8
- package/dist/{copy-UeUJVk8X.d.cts → copy-Bd__Pw5s.d.cts} +5 -4
- package/dist/{copy-DdVFDL01.d.ts → copy-NgKgOOET.d.ts} +5 -4
- package/dist/core/index.cjs +9 -9
- package/dist/core/index.d.cts +19 -17
- package/dist/core/index.d.ts +19 -17
- package/dist/core/index.js +9 -9
- package/dist/{depth-DvPwPuT_.d.ts → depth-CYPH92jE.d.ts} +6 -5
- package/dist/{depth-D5HwcvKC.d.cts → depth-CyjaJJ6V.d.cts} +6 -5
- package/dist/{entitlementRepository-B7egEdW6.d.ts → entitlementRepository-DdeFuEKp.d.ts} +4 -4
- package/dist/{entitlementRepository-BpJ7tiwl.d.cts → entitlementRepository-Dl1qRLcJ.d.cts} +4 -4
- package/dist/{identity-C2-08BZW.d.cts → identity-DjqhDm5Z.d.cts} +2 -2
- package/dist/{identity-CEi9GRFZ.d.ts → identity-Dy_L7Yq4.d.ts} +2 -2
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +19 -17
- package/dist/index.d.ts +19 -17
- package/dist/index.js +6 -6
- package/dist/{models-D2EUxPZY.d.cts → models-Bn2z0NNo.d.cts} +1 -1
- package/dist/{models-B-Uh2LTf.d.ts → models-DSqA5Ahs.d.ts} +1 -1
- package/dist/notifications/index.cjs +2 -2
- package/dist/notifications/index.d.cts +5 -4
- package/dist/notifications/index.d.ts +5 -4
- package/dist/notifications/index.js +2 -2
- package/dist/{pets-JVCXgRgR.d.cts → pets-BSG2qbr_.d.cts} +2 -2
- package/dist/{pets-DJv2sj2H.d.ts → pets-D7cZutrX.d.ts} +2 -2
- package/dist/{petsRepository-B_gKbAzJ.d.cts → petsRepository-D1bnxDZg.d.cts} +2 -2
- package/dist/{petsRepository-Bk6GDwLs.d.ts → petsRepository-DhsX3GLw.d.ts} +2 -2
- package/dist/photo/index.cjs +1 -1
- package/dist/photo/index.d.cts +3 -2
- package/dist/photo/index.d.ts +3 -2
- package/dist/photo/index.js +1 -1
- package/dist/{ports-D7YW8qz9.d.ts → ports-C0m1G1fS.d.ts} +13 -6
- package/dist/{ports-BY2ph0_y.d.cts → ports-DNXyyzZF.d.cts} +13 -6
- package/dist/records/depth/index.cjs +2 -2
- package/dist/records/depth/index.d.cts +11 -10
- package/dist/records/depth/index.d.ts +11 -10
- package/dist/records/depth/index.js +2 -2
- package/dist/records/index.cjs +3 -3
- package/dist/records/index.d.cts +25 -14
- package/dist/records/index.d.ts +25 -14
- package/dist/records/index.js +3 -3
- package/dist/{requestFunnel-BjDpqqvm.d.cts → requestFunnel-Bqc1inM9.d.cts} +5 -4
- package/dist/{requestFunnel-DFMGcluw.d.ts → requestFunnel-FvE5yLDD.d.ts} +5 -4
- package/dist/{runtimeTypes-w5KqBMcs.d.ts → runtimeTypes-C0yPBz89.d.ts} +7 -7
- package/dist/{runtimeTypes-gZEJu-da.d.cts → runtimeTypes-RN-VXTFV.d.cts} +7 -7
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.d.cts +4 -3
- package/dist/server/events/index.d.ts +4 -3
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +5 -4
- package/dist/server/index.d.ts +5 -4
- package/dist/server/index.js +1 -1
- package/dist/televet/booking/index.cjs +1 -1
- package/dist/televet/booking/index.d.cts +310 -32
- package/dist/televet/booking/index.d.ts +310 -32
- package/dist/televet/booking/index.js +1 -1
- package/dist/televet/call/index.cjs +1 -1
- package/dist/televet/call/index.d.cts +25 -5
- package/dist/televet/call/index.d.ts +25 -5
- package/dist/televet/call/index.js +1 -1
- package/dist/televet/index.cjs +1 -1
- package/dist/televet/index.d.cts +41 -71
- package/dist/televet/index.d.ts +41 -71
- package/dist/televet/index.js +1 -1
- package/dist/televetGlobal-CEk0_cW9.d.cts +34 -0
- package/dist/televetGlobal-Cs9Wbqsy.d.ts +34 -0
- package/dist/testing/index.cjs +3 -3
- package/dist/testing/index.d.cts +3 -2
- package/dist/testing/index.d.ts +3 -2
- package/dist/testing/index.js +3 -3
- package/dist/testing/rn/index.cjs +1 -1
- package/dist/testing/rn/index.d.cts +13 -11
- package/dist/testing/rn/index.d.ts +13 -11
- package/dist/testing/rn/index.js +1 -1
- package/dist/testing/web/index.cjs +1 -1
- package/dist/testing/web/index.d.cts +14 -13
- package/dist/testing/web/index.d.ts +14 -13
- package/dist/testing/web/index.js +1 -1
- package/dist/{timelineRows-C15jxFFH.d.ts → timelineRows-D4U6A8zE.d.ts} +1 -1
- package/dist/{timelineRows-odO8g9r2.d.cts → timelineRows-DAB5dpjF.d.cts} +1 -1
- package/dist/{branding-CsRdeNwK.d.cts → tokens-CIngRkvt.d.cts} +7 -211
- package/dist/{branding-CsRdeNwK.d.ts → tokens-CIngRkvt.d.ts} +7 -211
- package/dist/{typeStyle-DmoyacDG.d.ts → typeStyle-DHJzDaUo.d.cts} +2 -1
- package/dist/{typeStyle-CKqVYD6L.d.cts → typeStyle-YPS_MXeI.d.ts} +2 -1
- package/dist/{useRecordsDepth-crhBllQK.d.ts → useRecordsDepth--ObtMyjH.d.ts} +24 -5
- package/dist/{useRecordsDepth-C6rjEaLn.d.cts → useRecordsDepth-B35y8bV-.d.cts} +24 -5
- package/dist/{useVetVisit-CjmMa896.d.ts → useVetVisit-BsjoDO-n.d.ts} +21 -6
- package/dist/{useVetVisit-Bc84hWUU.d.cts → useVetVisit-Ds8f1peV.d.cts} +21 -6
- package/dist/video/index.cjs +1 -1
- package/dist/video/index.d.cts +3 -2
- package/dist/video/index.d.ts +3 -2
- package/dist/video/index.js +1 -1
- package/dist/{view-DyitEO0m.d.cts → view-B-Toym_j.d.cts} +5 -4
- package/dist/{view-Bxwxp4xD.d.ts → view-D9JqNQai.d.ts} +5 -4
- package/dist/web/consent/index.cjs +1 -1
- package/dist/web/consent/index.d.cts +9 -8
- package/dist/web/consent/index.d.ts +9 -8
- package/dist/web/consent/index.js +1 -1
- package/dist/web/index.cjs +10 -10
- package/dist/web/index.d.cts +42 -19
- package/dist/web/index.d.ts +42 -19
- package/dist/web/index.js +10 -10
- package/dist/web/notifications/index.cjs +2 -2
- package/dist/web/notifications/index.d.cts +7 -6
- package/dist/web/notifications/index.d.ts +7 -6
- package/dist/web/notifications/index.js +2 -2
- package/dist/web/records/depth/index.cjs +2 -2
- package/dist/web/records/depth/index.d.cts +11 -10
- package/dist/web/records/depth/index.d.ts +11 -10
- package/dist/web/records/depth/index.js +2 -2
- package/dist/web/records/index.cjs +3 -3
- package/dist/web/records/index.d.cts +53 -35
- package/dist/web/records/index.d.ts +53 -35
- package/dist/web/records/index.js +3 -3
- package/dist/web/televet/booking/index.cjs +2 -1
- package/dist/web/televet/booking/index.d.cts +458 -33
- package/dist/web/televet/booking/index.d.ts +458 -33
- package/dist/web/televet/booking/index.js +2 -1
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.d.cts +3 -1
- package/dist/web/televet/call/index.d.ts +3 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +1 -1
- package/dist/web/televet/index.d.cts +40 -74
- package/dist/web/televet/index.d.ts +40 -74
- package/dist/web/televet/index.js +1 -1
- package/package.json +3 -2
- package/dist/callCopy-DoQKG3-L.d.cts +0 -40
- package/dist/callCopy-DoQKG3-L.d.ts +0 -40
package/dist/core/index.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
'use strict';var zod=require('zod');var si=Object.defineProperty;var i=(e,t)=>si(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 p(e){return Object.freeze({ok:false,error:e})}i(p,"err");var Fe=class Fe extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fe.prototype);}};i(Fe,"EverfurConfigError");var K=Fe;var iu=Object.freeze({isAvailable:false,async getSecret(){return null},async setSecret(){throw new K("not-initialized","EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort")},async deleteSecret(){}});var Me=Object.freeze({track(){},trackExpectedFailure(){}});var tt=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(tt.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"}),dr=Object.freeze(tt.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:ai[e.wireCode]}))),li=new Map(dr.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ui=Object.freeze(["http_envelope",...[...new Set(dr.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function De(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...ui]){let o=li.get(n+r);if(o)return o}}i(De,"contractErrorFor");function di(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(di,"contractDocUrl");function cr(e){return null}i(cr,"publishedDocUrl");var ci=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 ci[e]}i(pr,"categoryFor");function Y(e){let t=De(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":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(Y,"fromWire");function fr(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(fr,"fromHttpStatus");var pi=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function ee(e){return pi.has(e)}i(ee,"isAutoRetryable");var fi=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function mr(e){return ee(e)||fi.has(e)}i(mr,"isRetryableCode");function je(e,t=false){return t||ee(e)}i(je,"shouldRetry");var mi=500,rt=8e3,pe=4;function ze(e,t=Math.random){let r=Math.max(0,e),n=Math.min(mi*2**r,rt);return Math.floor(t()*n)}i(ze,"backoffDelayMs");function yr(e){return e==="conversationNotFound"}i(yr,"canRecreateOnNotFound");var gr=Object.freeze({shouldRetry(e,t){return ee(e)&&t<pe},maxAttempts(){return pe}});var hr=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Eu(e,t,r){let n;try{n=t();}catch(s){return nt(`optional peer '${e}' is not installed: ${gi(s)}`)}let o=yi(n);return o==null?nt(`optional peer '${e}' resolved to no module`):r&&!r(o)?nt(`optional peer '${e}' is present but failed its shape check`):Object.freeze({available:true,module:o})}i(Eu,"optionalModule");function yi(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}i(yi,"unwrapDefault");function nt(e){return Object.freeze({available:false,module:null,reason:e})}i(nt,"frozenUnavailable");function gi(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}i(gi,"describe");function Le(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Le,"assertNever");function br(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(br,"acceptedFrame");function vr(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(vr,"heartbeatFrame");function _r(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(_r,"deltaFrame");function Rr(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(Rr,"doneFrame");function N(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(N,"errorFrame");function Er(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Er,"analysisStartedFrame");function Cr(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(Cr,"analysisCompleteFrame");function Sr(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Sr,"unknownFrame");var vi=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 ot(e){return vi[e]}i(ot,"userFacingError");function wr(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(wr,"defineHidden");var _i=/^[a-z][a-z0-9_]{0,63}$/;function S(e,t){let r=De(t?.wireCode,t?.wireEnvelope),n={code:e,category:pr(e),retryable:t?.retryable??mr(e),displayMessage:ot(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&_i.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&wr(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&wr(n,"raw",t.raw),Object.freeze(n)}i(S,"makeEverfurError");function kr(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 K("invalid-argument","TokenProvider returned an empty token");return n=a,r?.(typeof u=="string"?null:Ri(u.expiresAt)),a}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(u){if(s)throw new K("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(kr,"createIdentityProvider");function Ri(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(Ri,"expiryMs");function st(){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(st,"newSessionId");function Ei(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(Ei,"authHeaders");function fe(e,t){return {...e,headers:{...Ci(e.headers),...Ei(t)}}}i(fe,"withAuthHeaders");function Ci(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(Ci,"stripAuthHeaders");async function Tr(e,t){if(t.mode==="anonymous")return t.transport.request(fe(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return p(it())}let n=await t.transport.request(fe(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 p(it())}let s=await t.transport.request(fe(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?p(it(s.error.httpStatus)):s}i(Tr,"authedSend");function it(e){return S("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(it,"authRejectedError");var Pr=`
|
|
1
|
+
'use strict';var zod=require('zod');var li=Object.defineProperty;var i=(e,t)=>li(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 p(e){return Object.freeze({ok:false,error:e})}i(p,"err");var Fe=class Fe extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fe.prototype);}};i(Fe,"EverfurConfigError");var K=Fe;var uu=Object.freeze({isAvailable:false,async getSecret(){return null},async setSecret(){throw new K("not-initialized","EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort")},async deleteSecret(){}});var Me=Object.freeze({track(){},trackExpectedFailure(){}});var tt=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(tt.map(e=>e.wireCode));var ui=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"}),cr=Object.freeze(tt.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:ui[e.wireCode]}))),di=new Map(cr.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ci=Object.freeze(["http_envelope",...[...new Set(cr.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function De(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...ci]){let o=di.get(n+r);if(o)return o}}i(De,"contractErrorFor");function pi(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(pi,"contractDocUrl");function pr(e){return null}i(pr,"publishedDocUrl");var fi=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 fr(e){return fi[e]}i(fr,"categoryFor");function Y(e){let t=De(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(Y,"fromWire");function mr(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(mr,"fromHttpStatus");var mi=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function ee(e){return mi.has(e)}i(ee,"isAutoRetryable");var yi=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function yr(e){return ee(e)||yi.has(e)}i(yr,"isRetryableCode");function je(e,t=false){return t||ee(e)}i(je,"shouldRetry");var gi=500,rt=8e3,pe=4;function ze(e,t=Math.random){let r=Math.max(0,e),n=Math.min(gi*2**r,rt);return Math.floor(t()*n)}i(ze,"backoffDelayMs");function gr(e){return e==="conversationNotFound"}i(gr,"canRecreateOnNotFound");var hr=Object.freeze({shouldRetry(e,t){return ee(e)&&t<pe},maxAttempts(){return pe}});var br=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function ku(e,t,r){let n;try{n=t();}catch(s){return nt(`optional peer '${e}' is not installed: ${bi(s)}`)}let o=hi(n);return o==null?nt(`optional peer '${e}' resolved to no module`):r&&!r(o)?nt(`optional peer '${e}' is present but failed its shape check`):Object.freeze({available:true,module:o})}i(ku,"optionalModule");function hi(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}i(hi,"unwrapDefault");function nt(e){return Object.freeze({available:false,module:null,reason:e})}i(nt,"frozenUnavailable");function bi(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}i(bi,"describe");function Le(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Le,"assertNever");function vr(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(vr,"acceptedFrame");function _r(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(_r,"heartbeatFrame");function Rr(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Rr,"deltaFrame");function Er(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(Er,"doneFrame");function N(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(N,"errorFrame");function Cr(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Cr,"analysisStartedFrame");function Sr(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(Sr,"analysisCompleteFrame");function wr(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(wr,"unknownFrame");var Ri=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 ot(e){return Ri[e]}i(ot,"userFacingError");function kr(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(kr,"defineHidden");var Ei=/^[a-z][a-z0-9_]{0,63}$/;function S(e,t){let r=De(t?.wireCode,t?.wireEnvelope),n={code:e,category:fr(e),retryable:t?.retryable??yr(e),displayMessage:ot(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Ei.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&kr(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&kr(n,"raw",t.raw),Object.freeze(n)}i(S,"makeEverfurError");function Tr(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 K("invalid-argument","TokenProvider returned an empty token");return n=a,r?.(typeof u=="string"?null:Ci(u.expiresAt)),a}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(u){if(s)throw new K("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(Tr,"createIdentityProvider");function Ci(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(Ci,"expiryMs");function st(){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(st,"newSessionId");function Si(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(Si,"authHeaders");function fe(e,t){return {...e,headers:{...wi(e.headers),...Si(t)}}}i(fe,"withAuthHeaders");function wi(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(wi,"stripAuthHeaders");async function Pr(e,t){if(t.mode==="anonymous")return t.transport.request(fe(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return p(it())}let n=await t.transport.request(fe(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 p(it())}let s=await t.transport.request(fe(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?p(it(s.error.httpStatus)):s}i(Pr,"authedSend");function it(e){return S("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(it,"authRejectedError");var xr=`
|
|
2
2
|
|
|
3
|
-
`,
|
|
3
|
+
`,ki=1048576,Ti=zod.z.record(zod.z.string(),zod.z.unknown()),Pi=["emergency","schedule_soon","home_care"];async function*Ue(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",l=0,u=false;for await(let a of e){for(s+=o.decode(a,{stream:true});;){let d=s.indexOf(xr,l);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+xr.length),l=0;let f=Ir(c,n());if(f!==null&&(f.kind==="delta"&&(u=true),yield f,f.terminal))return}if(l=s.length>0?s.length-1:0,s.length>ki){yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let a=Ir(s,n());if(a!==null&&(a.kind==="delta"&&(u=true),yield a,a.terminal))return}yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Ue,"parseSse");function Ir(e,t){let r=null,n=[];for(let l of e.split(`
|
|
4
4
|
`)){let u=l.replace(/\s+$/,"");u.length===0||u.startsWith(":")||(u.startsWith("id:")?r=u.slice(3).trim():u.startsWith("data:")&&n.push(u.slice(5).replace(/^ /,"")));}if(n.length===0)return null;let o;try{o=JSON.parse(n.join(`
|
|
5
|
-
`));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=
|
|
6
|
-
`);let c=a.data??"";for(let
|
|
7
|
-
`))d+=`data: ${
|
|
5
|
+
`));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=Ti.safeParse(o);return s.success?xi(s.data,r,t):null}i(Ir,"parseBlock");function xi(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return N({code:z(e.code)??"unknown",retryable:e.retryable===true,wireMessage:z(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Er({conversationId:z(e.conversation_id)??"",messageId:z(e.message_id),title:z(e.title),followUpQuestions:Ai(e.follow_up_questions),citations:Or(e.citations),citationStatus:z(e.citation_status),urgencyLevel:Ar(e.urgency_level),urgencyReason:z(e.urgency_reason),urgencyProvided:Oi(e),resultId:z(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return vr(z(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return _r(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=z(e.delta)??z(e.token)??"";return Rr(s,t,r)}return o==="analysis_started"?Cr(z(e.request_id),t,r):o==="analysis_complete"?Sr({resultId:z(e.result_id),analysisType:z(e.analysis_type),modelVersion:z(e.model_version),confidence:Ii(e.confidence),detections:Or(e.detections),interpretation:z(e.interpretation),lastEventId:t},r):wr(e,t,r)}i(xi,"frameFromWire");function z(e){return typeof e=="string"?e:null}i(z,"asString");function Ii(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Ii,"asNumber");function Ar(e){return typeof e=="string"&&Pi.includes(e)?e:null}i(Ar,"asUrgency");function Oi(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Ar(t)!==null}i(Oi,"urgencySlotProvided");function Ai(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Ai,"asStringList");function Fi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Fi,"isPlainObject");function Or(e){return Array.isArray(e)?e.filter(Fi):[]}i(Or,"asMapList");var Mi="0.5.1",Di="react-native",ji="2026-09-19",Fr="EVERFUR_API_BASE_URL";function me(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(me,"configFailure");function lt(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(lt,"checkPublishableKey");function Mr(e,t){let r=lt(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=zi(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||ji;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Mi,platform:t?.platform??Di,debug:e.debug===true})})}i(Mr,"tryResolveClientConfig");function zi(e){let t=e?.trim(),r=t&&t.length>0?t:$i(Fr);return r?Hi(r):me("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Fr}. The SDK never ships a hardcoded host.`)}i(zi,"tryResolveApiBaseUrl");function Dr(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(Dr,"buildBaseHeaders");var Li=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Ui(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Ui,"hostOf");function Ni(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Ni,"isPrintableHost");function Bi(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Ni(t)}i(Bi,"canEchoOrigin");function qi(e,t){return `${e}://${t}`}i(qi,"safeOrigin");function Hi(e){let t=e.trim(),r=Li.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=Ui(r[2]);if(o.length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=Bi(t,o)?`: ${qi(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&Ki(o)))return n==="http"?me("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):me("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let l=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:l})}i(Hi,"normalizeBaseUrl");function Ki(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(Ki,"isLoopbackHost");function $i(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i($i,"readEnv");var Vi=3e4,Ur="x-request-id";async function*jr(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(jr,"fetchByteSource");function Wi(e){let t=new TextEncoder,r=Yi(),n=false,o=i(a=>{let d="";a.lastEventId&&(d+=`id: ${a.lastEventId}
|
|
6
|
+
`);let c=a.data??"";for(let f of c.split(`
|
|
7
|
+
`))d+=`data: ${f}
|
|
8
8
|
`;d+=`
|
|
9
|
-
`,r.push(t.encode(d));},"onMessage"),s=i(()=>{u(),r.end();},"onDone"),l=i(a=>{let d=typeof a.xhrStatus=="number"?a.xhrStatus:0;if(d>=400){let c=
|
|
9
|
+
`,r.push(t.encode(d));},"onMessage"),s=i(()=>{u(),r.end();},"onDone"),l=i(a=>{let d=typeof a.xhrStatus=="number"?a.xhrStatus:0;if(d>=400){let c=qr(d),f=ee(Y(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:f})}
|
|
10
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"),Vi(r.source,u)}i($i,"eventSourceByteSource");async function*Vi(e,t){try{yield*e;}finally{t();}}i(Vi,"sourceWithCleanup");function Wi(){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(Wi,"createByteQueue");async function Gi(e,t){let r=t.fetchImpl??qr(),n=Hr(t.config.apiBaseUrl,e.path,e.query),o=Kr(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=es(Ki),l=ts(s.signal,e.signal),u;try{u=await r(n,$r({...e,signal:l},o));}catch(d){return p(ut(d))}finally{s.cancel();}let a=await Vr(u);return u.ok?_(a):p(Qi(u.status,a,Nr(u)))}i(Gi,"requestJson");function Ur(e){return {request:i(t=>Gi(t,e),"request"),stream:i((t,r)=>Yi(Zi(t,r),e),"stream")}}i(Ur,"createHttpTransport");async function*Yi(e,t){let r=Hr(t.config.apiBaseUrl,e.path,e.query),n=Kr(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let u=t.eventSourceFactory(r,Xi(e,n));yield*Ue($i(u),()=>Ji(u));return}let o=t.fetchImpl??qr(),s;try{s=await o(r,$r(e,n));}catch(u){yield jr("",true,Xr(u));return}let l=Nr(s);if(!s.ok){let u=await Vr(s),a=Wr(u)??Br(s.status),d=Yr(u)||ee(Y(a));yield jr(a,d,Gr(u),l);return}if(s.body){yield*Ue(Dr(s.body),l);return}yield*Ue(Dr(null),l);}i(Yi,"streamFrames");function Xi(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Xi,"buildEventSourceInit");function Qi(e,t,r){let n=Wr(t),o=n?Y(n):fr(e),s=Gr(t);return S(o,{httpStatus:e,...Yr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...zr(t)?{reasonCode:zr(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Qi,"errorFromResponse");function ut(e){return S("internalError",{retryable:true,wireMessage:Xr(e)})}i(ut,"networkError");function Nr(e){let t=e.headers.get(Lr);return typeof t=="string"&&t.length>0?t:null}i(Nr,"requestIdOf");function Ji(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Lr);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(Ji,"eventSourceRequestId");function Br(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(Br,"statusToWireCode");function jr(e,t,r,n=null){return N({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(jr,"syntheticErrorFrame");function qr(){let e=globalThis.fetch;if(typeof e!="function")throw new K("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(qr,"getGlobalFetch");function Hr(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(Hr,"buildUrl");function Kr(e,t,r,n){let o={...Mr(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Kr,"mergeHeaders");function $r(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($r,"buildInit");function Zi(e,t){return e.signal?e:{...e,signal:t}}i(Zi,"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 ts(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(ts,"mergeAbortSignals");async function Vr(e){try{return await e.json()}catch{return null}}i(Vr,"safeJson");function zr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(zr,"extractReasonCode");function Wr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Wr,"extractWireCode");function Gr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Gr,"extractWireMessage");function Yr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Yr,"extractRetryable");function Xr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Xr,"describeCause");var rs=3e4,ns=rt*2,os="idempotency-key",is=new Set(["POST","PUT","PATCH","DELETE"]),ss=Object.freeze({onEvent(){}}),as=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ls(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(ls,"seededIdempotencyKey");function $(e){let t=e.observer??ss,r=e.timers??as,n=e.rng??Math.random,o=e.sleep??((h,g)=>Rs(h,r,g)),s=e.maxAttempts??pe,l=e.unaryTimeoutMs??rs,u=e.newIdempotencyKey??ds(),a=i(h=>{try{t.onEvent(h);}catch{}},"emit");async function d(h,g,E){let T=E?.maxAttempts,C=Math.max(1,T??s),P=E?.idempotent??is.has(g.method),O=E?.idempotencyKey===void 0?null:ls(E.idempotencyKey),D=P?O??u():null,A=us(g,D),v=0;for(;;){let w=i(ue=>Object.freeze({call:h,method:g.method,path:g.path,attempt:v,...D?{idempotencyKey:D}:{},...ue}),"stamp");a(w({phase:"attempt"}));let j=vs(l,r),B=_s(j.signal,g.signal),q;try{q=await Tr({...A,signal:B.signal},e.auth);}catch(ue){q=p(ut(ue));}finally{B.dispose(),j.cancel();}if(q.ok)return a(w({phase:"settled",ok:true,reason:"ok"})),q;let H=q.error,ie=ps(H,v,{maxAttempts:C,rng:n,now:r.now(),aborted:g.signal?.aborted===true,...T!==void 0?{perCallMaxAttempts:T}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),ce={ok:false,code:H.code,reason:ie.reason,...H.httpStatus!==void 0?{httpStatus:H.httpStatus}:{},...H.requestId!==void 0?{requestId:H.requestId}:{}};if(!ie.retry)return a(w({phase:"settled",...ce})),p(H);if(a(w({phase:"retry",...ce,delayMs:ie.delayMs})),await o(ie.delayMs,g.signal),g.signal?.aborted===true)return a(w({phase:"settled",...ce,reason:"aborted"})),p(H);v+=1;}}i(d,"send");async function c(h){return fe(h,await bs(e.auth))}i(c,"authorize");async function*m(h,g,E){a(Object.freeze({call:h,phase:"stream.open",method:g.method,path:g.path,attempt:0}));try{yield*e.auth.transport.stream(g,E);}catch{yield N({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(m,"stream"),Object.freeze({send:d,authorize:c,stream:m})}i($,"createRequestFunnel");function us(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==os&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(us,"assembleHeaders");function ds(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(ds,"defaultIdempotencyKeyFactory");var cs=10;function ps(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=fs(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!ee(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(cs,Math.floor(d)))},"policyCeiling"),u=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=u)return {retry:false,reason:"attempts-exhausted"};let a=ms(e,r.now);return a!==null?a>ns?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:a}:{retry:true,reason:o,delayMs:ze(t,r.rng)}}i(ps,"decideRetry");function fs(e){let t=e.code==="unknown"?Y(hs(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(fs,"throttleKind");function ms(e,t){let r=ys(e.raw);if(r===null)return null;let n=r-t;return n>0?n:0}i(ms,"retryOverrideMs");function ys(e){for(let t of Jr(e)){let r=t.resets_at,n=gs(r);if(n!==null)return n}return null}i(ys,"findResetsAt");function Jr(e){if(!Qr(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Qr(n)&&t.push(n);}return t}i(Jr,"candidateScopes");function gs(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(gs,"parseInstantMs");function hs(e){for(let t of Jr(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(hs,"rawWireCode");function Qr(e){return typeof e=="object"&&e!==null}i(Qr,"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 vs(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(vs,"boundedSignal");function _s(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(_s,"mergeSignals");function Rs(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(Rs,"delayAbortable");function L(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(L,"hasLoneSurrogate");function Ne(e){return [...e].length}i(Ne,"serverLength");var rn=Object.freeze(["better","same","worse"]),ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Zr(e){return p(S("validationFailed",{retryable:false,wireMessage:e}))}i(Zr,"invalid");function dt(){return p(S("internalError",{retryable:false}))}i(dt,"malformed");function en(e){return typeof e!="string"||e.trim().length===0?S("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):L(e)?S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(en,"petPath");var te=i(e=>typeof e=="string"?e:null,"str");function tn(e){if(typeof e!="object"||e===null)return null;let t=e,r=te(t.case_id),n=te(t.status);if(r===null||n===null)return null;let o=te(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:te(t.body_location),lastResponse:o!==null&&rn.includes(o)?o:null,checkInDueAt:te(t.check_in_due_at),openedAt:te(t.opened_at),resolvedAt:te(t.resolved_at),resolutionText:te(t.resolution_text)})}i(tn,"caseFromWire");function nn(e){return {async list(t,r){let n=en(t);if(typeof n!="string")return p(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return p(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return dt();let l=s.map(tn);return l.every(u=>u!==null)?_(Object.freeze(l)):dt()},async checkin(t,r,n,o){let s=en(t);if(typeof s!="string")return p(s);if(typeof r!="string"||!ct.test(r))return Zr("case_id must be a UUID");if(!rn.includes(n))return Zr("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 p(l.error);let u=typeof l.value=="object"&&l.value!==null?l.value:{},a=tn(u.case);return a===null?dt():_(Object.freeze({case:a,ctaDeepLink:te(u.cta_deep_link)}))}}}i(nn,"createCasesRepositoryOver");var on=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var sn=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function qe(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(qe,"delayAbortable");function He(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(He,"mergeSignals");var pt=class pt{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?He(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(pt,"MediaStore");var Be=pt;function mt(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(mt,"makeUser");function yt(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(yt,"makeAssistant");function ge(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(ge,"stripPending");function an(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(an,"appendText");function gt(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(gt,"finalizeAssistant");function ln(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(ln,"freezeSnapshot");function R(e,t,r){return S(e,{retryable:t,...r?{wireMessage:r}:{}})}i(R,"makeError");function ht(e){let t=Y(e.code);return S(t,{retryable:e.retryable||je(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(ht,"errorFromFrame");function X(e){return N({code:Es(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(X,"synthErrorFrame");function Es(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 Le(e)}}i(Es,"canonicalWireCode");function un(e){let t=Array.isArray(e)?e:ft(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!ft(n))continue;let o=ye(n.category)??ye(n.title)??"",s=Cs(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(un,"parsePromptCategories");function bt(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(bt,"flattenPrompts");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ft,"isPlainObject");function ye(e){return typeof e=="string"?e:null}i(ye,"asStr");function Cs(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(ft(r)){let n=ye(r.text)??ye(r.prompt)??ye(r.title);n!==null&&t.push(n);}return t}i(Cs,"asPromptTextList");function dn(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(dn,"defaultIdFactory");function cn(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(cn,"defaultIdempotencyFactory");var fn={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*mn(e,t,r,n){let o=e[Symbol.asyncIterator](),s=pn(t.overallMs,n),l=pn(t.idleMs,n),u=ks(r);try{for(;;){if(r.aborted)return;let a=o.next().then(m=>({tag:"next",value:m}),()=>({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 ws();return}if(d.tag==="idle"||d.tag==="overall"){yield Ss();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(mn,"withWatchdog");function Ss(){return N({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ss,"synthTimeoutFrame");function ws(){return N({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(ws,"synthStreamErrorFrame");function pn(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(pn,"deadline");function ks(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(ks,"abortPromise");var Ts="checkin",Ps=/^\d{4}-\d{2}-\d{2}$/,he="watching";function xs(e){return e.status!=null&&e.status!==he}i(xs,"isCheckinSettled");function yn(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Ts||n===void 0||o===void 0||!ct.test(n)||!Ps.test(o)?null:n}i(yn,"parseCheckinOriginRef");function vt(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return p(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||L(o))return p(S("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),_(r.length?`?${r.join("&")}`:"")}i(vt,"historyQuery");function _e(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(_e,"validConversationId");function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(ve,"object");function gn(e){return e==null||typeof e=="string"&&e.length>0&&!L(e)}i(gn,"cursor");function be(){return p(S("internalError",{retryable:false}))}i(be,"malformed");function hn(e){let t=ve(e);if(!t||!Array.isArray(t.conversations)||!gn(t.next_cursor))return be();let r=[];for(let n of t.conversations){let o=ve(n);if(!o||typeof o.conversation_id!="string"||!_e(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return be();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return be();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(hn,"mapConversationPage");function bn(e){let t=ve(e);if(!t||!Array.isArray(t.messages)||!gn(t.next_cursor))return be();let r=[],n=new Set;for(let o of t.messages){let s=ve(o);if(!s||typeof s.message_id!="string"||!_e(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return be();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let l=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,u=s.role==="assistant"?yn(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:Is(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Os(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(bn,"mapMessagePage");function Is(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Is,"normalizeUrgency");function Os(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=ve(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(Os,"historyCitations");var Ke=5,_t=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Rt=4e3;var Et=4e3;function vn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:R("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:R("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(vn,"validateImageKeys");function Ct(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:R("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Et?{reason:"too_long",error:R("validationFailed",false,`message is ${r} characters; the server accepts at most ${Et}`)}:null}i(Ct,"validateMessageText");function _n(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(_n,"urgencyTier");async function*Re(e){yield e;}i(Re,"singleFrameStream");async function*Rn(){}i(Rn,"emptyStream");var As=6e4,Fs=18e4,Ms=24,Ds=512,js=false;function En(e){return new St(e)}i(En,"createChatController");var wt=class wt extends Be{constructor(r){super(ln({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.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??$({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=nn(this.funnel),this.telemetry=r.telemetry??Me,this.errorPolicy=r.errorPolicy??gr,this.timers=r.timers??fn,this.rng=r.rng??Math.random,this.newId=r.newId??dn(),this.makeIdempotencyKey=r.makeIdempotencyKey??cn(),this.budget={idleMs:r.budget?.idleMs??As,overallMs:r.budget?.overallMs??Fs};}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=R(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(a),()=>{}):Re(X(a))}let l=Ct(r)??vn(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),()=>{}):Re(X(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 Re(X(R("accessDenied",false)));let o=Ct(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Re(X(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):Rn()}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,mt(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?ge(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.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}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(bt(r));this.bootstrapPrompts=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=vt(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(R("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 p(R("accessDenied",false));if(!l.ok)return l;let u=hn(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 p(R("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let a=await this.resumeConversation(n);return a.ok?_(n):p(a.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return p(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):p(u.error)}async markRead(r){if(this.disposed)return p(R("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?p(R("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)):p(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return p(R("accessDenied",false));if(typeof r!="string"||r.trim().length===0||L(r))return p(R("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!_t.includes(n))return p(R("validationFailed",false,`feedback_type must be one of ${_t.join(", ")}`));let l=typeof o=="string"?o.trim():"";if([...l].length>Rt)return p(R("validationFailed",false,`notes is over ${Rt} 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 p(R("accessDenied",false));if(!d.ok)return p(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 p(R("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return p(R("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 p(R("accessDenied",false));if(!u.ok)return u;let a=Object.freeze({caseId:r,answer:n,resolutionText:u.value.case.resolutionText,status:u.value.case.status??null}),d=i(c=>c.checkin?.caseId===r,"carries");return this.snapshot.messages.some(d)&&this.patch({messages:this.snapshot.messages.map(c=>d(c)?Object.freeze({...c,checkin:a}):c)}),u}async getMessages(r,n){if(!_e(r))return p(R("validationFailed",false));let o=vt(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(R("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?p(R("accessDenied",false)):l.ok?bn(l.value):l}async resumeConversation(r){if(this.disposed)return p(R("accessDenied",false));if(!_e(r))return p(R("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 p(R("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===he).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 m=l.get(c.caseId);return Object.freeze({...d,checkin:Object.freeze({...c,status:s.has(c.caseId)?he:m?.status??"resolved",answer:c.answer??m?.lastResponse??null,resolutionText:c.resolutionText??m?.resolutionText??null})})});u&&this.patch({messages:a});}async refreshActiveThread(){if(this.disposed)return p(R("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 p(R("accessDenied",false));if(!o.ok)return p(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 p(R("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 p(R("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 X(n.error));}async primeConversation(r){if(this.disposed)return p(R("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?p(R("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return _(n);let o=this.snapshot.conversationId;return o!==null?_(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;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 p(R("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?p(R("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 p(s.error);let l=s.value?.conversation_id??s.value?.id;return typeof l!="string"||l.length===0?p(R("internalError",true)):_(l)}async getPrompts(r){let n=this.epoch;if(this.disposed)return p(R("accessDenied",false));let o=r?.petRef??null;if(o!==null&&L(o))return p(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?p(R("accessDenied",false)):l.ok?_(un(l.value)):p(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=He(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 m of a){if(d)break;o.onFrame(m),m.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,mt(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&&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,X(C.error));return}this.adoptConversation(C.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let C=R("internalError",!0);yield*this.emitTerminal(r,C,X(C));return}this.clearAssistantInProgress(r);let m=new AbortController,h=He(o.signal,m.signal),g=null;try{let C;try{C=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let O=this.authRejected();yield*this.emitTerminal(r,O,X(O));return}if(o.signal.aborted||!this.alive(o.epoch))return;let P=this.funnel.stream("chat.send",C,h);for await(let O of mn(P,this.budget,h,this.timers)){if(!this.alive(o.epoch))return;if(O.kind==="error"&&O.terminal){g=O;break}if(this.applyFrame(O,r),yield O,O.terminal){o.settle();return}}}finally{m.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(g===null){if(this.snapshot.status==="complete")return;let C=R("streamIncomplete",!0);yield*this.emitTerminal(r,C,X(C));return}let E=Y(g.code);if(E==="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,g);return}this.patch({reconnecting:!0});continue}if(E==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let C=this.authRejected();yield*this.emitTerminal(r,C,g);return}if(E==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,ht(g),g);return}if(yr(E)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let T=g.retryable&&je(E,!0);if(js&&T&&s+1<this.errorPolicy.maxAttempts(E));yield*this.emitTerminal(r,ht(g),g);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 Le(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?ge(l):l);this.patch({status:"streaming",isStreaming:true,messages:[...s,yt(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Ds){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);},Ms);}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?an(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?gt(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?ge(d):d),gt(yt(u,"",this.stamp()),r)];}let l=bt([{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=_n(u.value?.urgency),d=typeof u.value?.reason=="string"?u.value.reason:null,c=i(m=>m.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(m=>c(m)?Object.freeze({...m,urgencyLevel:a,urgencyReason:d,urgencyProvided:true}):m)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?ge(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 R("authRejected",false)}};i(wt,"ChatControllerImpl");var St=wt;async function wn(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,m=o?r.resumeConversation(o).then(A=>A.ok?_(o):A):r.primeConversation(n?{petRef:n}:void 0),h=r.getPrompts(n!==null?{petRef:n}:void 0),[g,E]=await Promise.all([m,h]),T=null;if(g.ok)T=g.value,s.push(g.value),r.getSnapshot().conversationId===null&&r.adoptConversation(g.value);else {let A=g.error;c=A,Cn(A)?(u=true,d=A):(Sn(A)&&(l=true),a=true);}let C=[];E.ok?C=E.value:P(E.error);function P(A){Cn(A)?(u=true,d===null&&(d=A)):Sn(A)&&(l=true);}i(P,"recordAuthSignals");let O=d!==null?d.displayMessage:null;return Object.freeze({conversationId:T,petRef:n,suggestedPrompts:C,error:O,warning:O===null&&T===null&&a?zs:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:l,sawUnauthorized:u,sawConversationInitFailure:a})})}i(wn,"bootstrapChat");var zs="Chat is ready. Your first message will start the conversation.";function Cn(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(Cn,"isUnauthorized");function Sn(e){return e.httpStatus===403||e.code==="accessDenied"}i(Sn,"isForbidden");var kt=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function kn(e){return e!==kt}i(kn,"isUploadTransportAvailable");var Tn=128,oe=128;var Ls=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),dc="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",xn=10*1024*1024,Us=5,Ee=120,Ns="/widget/v1/uploads/initiate";function Bs(e){return typeof e=="string"&&Ls.includes(e.trim().toLowerCase())}i(Bs,"isAttachmentMime");function qs(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<=Ee)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Ee);let n=t.slice(r);return n.length>=Ee?t.slice(0,Ee):`${t.slice(0,r).slice(0,Ee-n.length)}${n}`}i(qs,"sanitizeFilename");function cc(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(cc,"formatBytes");var Ce=i(e=>Object.freeze({ok:true,value:e}),"ok"),V=i(e=>Object.freeze({ok:false,error:e}),"err");function M(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(M,"failure");function Hs(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(Hs,"attachmentSize");function Ks(e){let t=qs(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!Bs(r))return V(M("unsupported_type",false,t));let n=Hs(e);return n===null?V(M("unknown",false,t)):n>xn?V(M("too_large",false,t,{sizeBytes:n})):Ce(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Ks,"validateAttachment");function $s(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)??xn,s3_key:l,purpose:r(t.purpose)})}i($s,"parsePolicy");function Vs(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return M("quota_exceeded",false,t,{cause:e});case "rateLimited":return M("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return M("idempotency_conflict",true,t,{cause:e});case "validationFailed":return M("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return M("network",true,t,{cause:e});default:return r===429?M("rate_limited",true,t,{cause:e}):r===503?M("network",true,t,{cause:e}):r===void 0?M("network",true,t,{cause:e}):M("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Vs,"initiateFailure");async function Ws(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Ns,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return V(Vs(n.error,t.filename));let o=$s(n.value);return o===null?V(M("server",false,t.filename)):Ce(o)}i(Ws,"initiateAttachmentUpload");async function Gs(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return V(M("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Ce(void 0)}catch{return o()?V(M("cancelled",true,r.filename)):V(M("server",true,r.filename))}}i(Gs,"uploadAttachmentBytes");var Ys=2,Xs=3,Qs=Object.freeze([1e3,2e3,4e3]),Pn=0;function Js(){return Pn+=1,`attachment-${Pn}`}i(Js,"defaultNewId");function pc(e){let t=Math.max(1,e.concurrency??Ys),r=Math.max(1,e.maxAttempts??Xs),n=e.backoffMs??Qs,o=Math.max(1,e.maxPerMessage??Us),s=e.timers??sn,l=e.newId??Js,u=kn(e.transport),a=new Map,d=[],c=[],m=new Set,h=new Set,g=Object.freeze({attachments:Object.freeze([])}),E=false,T=i(()=>{g=Object.freeze({attachments:Object.freeze(d.flatMap(v=>{let w=a.get(v);return w===void 0?[]:[w.state]}))});for(let v of h)v();},"publish"),C=i((v,w)=>{v.state=Object.freeze({...v.state,...w}),T();},"patch"),P=i(()=>{for(;!E&&m.size<t&&c.length>0;){let v=c.shift(),w=a.get(v);w!==void 0&&(m.add(v),O(w).finally(()=>{m.delete(v),P();}));}},"pump"),O=i(async v=>{let{attachment:w}=v;for(;v.attempts<r;){if(E||v.controller.signal.aborted)return;v.attempts+=1;let j=v.controller.signal;C(v,{status:"uploading",error:null,progress:0});let B=await Ws(e.funnel,w,{signal:j});if(E||j.aborted)return;let q;if(!B.ok)q=V(B.error);else {let ue=await Gs(e.transport,B.value,w,{signal:j,onProgress:i(ii=>{!j.aborted&&v.state.status==="uploading"&&C(v,{progress:Zs(ii)});},"onProgress")});if(E||j.aborted)return;q=ue.ok?Ce(B.value.s3_key):V(ue.error);}if(q.ok){C(v,{status:"uploaded",s3Key:q.value,error:null,progress:1});return}let H=q.error,ie=H.retryable&&v.attempts<r;if(C(v,{status:ie?"uploading":"failed",error:H,progress:0}),!ie)return;let ce=n[Math.min(v.attempts-1,n.length-1)]??0;await qe(ce,j,s);}},"run"),D=i(v=>{c.push(v.state.id),P();},"enqueue"),A={available:u,subscribe(v){return h.add(v),()=>{h.delete(v);}},getSnapshot:i(()=>g,"getSnapshot"),get uploading(){return g.attachments.some(v=>v.status==="uploading")},get s3Keys(){return g.attachments.flatMap(v=>v.status==="uploaded"&&v.s3Key!==null?[v.s3Key]:[])},add(v){let w=Ks(v);if(!w.ok)return w;if(E||d.length>=o)return V(M("too_many",false,w.value.filename));let j=l(),B={attachment:w.value,controller:new AbortController,attempts:0,state:Object.freeze({id:j,filename:w.value.filename,previewUri:v.uri,contentType:w.value.contentType,sizeBytes:w.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(j,B),d.push(j),T(),D(B),Ce(B.state)},retry(v){let w=a.get(v);w===void 0||E||w.state.status!=="failed"||(w.controller=new AbortController,w.attempts=0,C(w,{status:"uploading",error:null,progress:0,s3Key:null}),D(w));},remove(v){let w=a.get(v);if(w===void 0)return;w.controller.abort(),a.delete(v);let j=d.indexOf(v);j>=0&&d.splice(j,1);let B=c.indexOf(v);B>=0&&c.splice(B,1),T();},clear(){for(let v of [...d])A.remove(v);},dispose(){E=true;for(let v of a.values())v.controller.abort();a.clear(),d.length=0,c.length=0,h.clear(),g=Object.freeze({attachments:Object.freeze([])});}};return A}i(pc,"createAttachmentQueue");function Zs(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Zs,"clamp");var In=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function On(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(In,t)?In[t]:null}i(On,"canonicalPetSpecies");var An=50,ea=128,Tt=120,Fn=120,ta=2e3,Mn=120,ra=80,zn=new Set(["male","female","unknown"]),Ln=new Set(["day","month","year"]),Un=new Set(["low","medium","high","athletic"]),Nn=new Set(["indoor","outdoor","both"]),Bn=new Set(["mild","moderate","severe"]),na=/^(\d{4})-(\d{2})-(\d{2})$/,qn=[["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"]],Hn=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...qn,...Hn].map(([e])=>e));function oa(e){let t=na.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(oa,"isRealDate");var we=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),ia=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Ve=i((e,t)=>typeof t=="string"&&oa(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Q=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(L(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=Ne(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),sa={sex:we(zn),spayedNeutered:ia,birthDate:Ve,birthDatePrecision:we(Ln),activityLevel:we(Un),indoorOutdoor:we(Nn),foodBrand:Q(Mn),foodType:Q(Mn),microchipId:Q(ra)},Pt=["ref","ref",false,Q(ea,{required:true,trimmed:true})],xt=["notes","notes",false,Q(ta,{trimmed:true})],Dn=[Pt,["name","name",true,Q(Tt,{required:true,trimmed:true})],["dose","dose",false,Q(Fn,{trimmed:true})],["frequency","frequency",false,Q(Fn,{trimmed:true})],["startDate","start_date",false,Ve],["endDate","end_date",false,Ve],xt],aa={allergies:[Pt,["allergen","allergen",true,Q(Tt,{required:true,trimmed:true})],["severity","severity",false,we(Bn)],xt],medications:Dn,supplements:Dn,conditions:[Pt,["conditionName","condition_name",true,Q(Tt,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ve],xt]};function la(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,m]of aa[e]){let h=o[a];if(h==null){if(c)return {error:`${n}.${a} is required`};h===null&&(s[d]=null);continue}let g=m(`${n}.${a}`,h);if(g!==null)return {error:g};s[d]=h;}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(la,"itemToWire");function ua(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>An)return {error:`${e} has ${t.length} items; the server accepts at most ${An}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=la(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(ua,"listToWire");function Kn(e,t){let r=e,n={};for(let[l,u]of qn){let a=r[l];if(a!==void 0){if(a!==null){let d=sa[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 Hn){let a=r[l];if(a===void 0)continue;let d=ua(l,a);if("error"in d)return d;n[u]=d.items;}return Object.keys(n).length>0&&t!==void 0&&On(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(Kn,"petHealthToWire");var F=i(e=>typeof e=="string"?e:null,"str"),Se=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),da=i(e=>typeof e=="boolean"?e:null,"bool");function $e(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($e,"itemsFromWire");function jn(e){let t=F(e.name);return t===null||t.length===0?null:Object.freeze({ref:F(e.ref),name:t,dose:F(e.dose),frequency:F(e.frequency),startDate:F(e.start_date),endDate:F(e.end_date),notes:F(e.notes)})}i(jn,"medicationFromWire");function $n(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Se(zn,e.sex),spayedNeutered:da(e.spayed_neutered),birthDate:F(e.birth_date),birthDatePrecision:Se(Ln,e.birth_date_precision),activityLevel:Se(Un,e.activity_level),indoorOutdoor:Se(Nn,e.indoor_outdoor),foodBrand:F(e.food_brand),foodType:F(e.food_type),microchipId:F(e.microchip_id),allergies:$e(e.allergies,r=>{let n=F(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),allergen:n,severity:Se(Bn,r.severity),notes:F(r.notes)})}),medications:$e(e.medications,jn),supplements:$e(e.supplements,jn),conditions:$e(e.conditions,r=>{let n=F(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),conditionName:n,diagnosedDate:F(r.diagnosed_date),notes:F(r.notes)})})})}i($n,"petHealthFromWire");var Gn=100,Yn=50,Xn=100,Qn=50,Jn=500,ca=128,pa=6e4;function Z(e){return S("validationFailed",{retryable:false,wireMessage:e})}i(Z,"invalid");function se(e,t,r){if(typeof t!="string")return Z(`${e} must be a string`);let n=Ne(t);return n<=r?null:Z(`${e} is ${n} characters; the server accepts at most ${r}`)}i(se,"checkString");function We(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Z(`${e} must be a finite number between 0 and ${r}`)}i(We,"outOfRange");function Vn(e,t){if(typeof e!="string")return Z("pet_ref must be a string");if(e.trim().length===0)return Z("pet_ref must not be blank");if(L(e))return Z("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Z("profile must be an object");let r=[se("pet_ref",e,ca)];return t?.name!==void 0&&r.push(se("name",t.name,Gn)),t?.species!==void 0&&r.push(se("species",t.species,Yn)),t?.breed!==void 0&&r.push(se("breed",t.breed,Xn)),t?.ageYears!==void 0&&r.push(We("age_years",t.ageYears,Qn)),t?.weightKg!==void 0&&r.push(We("weight_kg",t.weightKg,Jn)),r.find(n=>n!==null)??null}i(Vn,"validate");function Zn(e,t){let r=Kn(e,t);return "error"in r?{error:Z(r.error)}:r}i(Zn,"healthToWire");function fa(e){if(typeof e!="object"||e===null)return {error:Z("patch must be an object")};let t=e,r=[["name","name",s=>se("name",s,Gn)],["species","species",s=>se("species",s,Yn)],["breed","breed",s=>se("breed",s,Xn)],["ageYears","age_years",s=>We("age_years",s,Qn)],["weightKg","weight_kg",s=>We("weight_kg",s,Jn)]],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=Zn(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Z("patch must change at least one field")}:{body:n})}i(fa,"patchToWire");function ma(e){if(e==null)return {body:{}};let t=Zn(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(ma,"toWire");var J=i(e=>typeof e=="string"?e:null,"str"),Ge=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Wn(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:J(r.pet_ref)??t,name:J(r.name),species:J(r.species),breed:J(r.breed),ageYears:Ge(r.age_years),weightKg:Ge(r.weight_kg)})}i(Wn,"fromWire");function eo(e){if(typeof e!="object"||e===null)return null;let t=e,r=J(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:J(t.pet_id),petRef:r,name:J(t.name),species:J(t.species),breed:J(t.breed),ageYears:Ge(t.age_years),weightKg:Ge(t.weight_kg),updatedAt:J(t.updated_at)})}i(eo,"widgetPetFromWire");function ya(e){let t=eo(e);return t===null?null:Object.freeze({...t,...$n(e)})}i(ya,"widgetPetProfileFromWire");function ga(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=eo(r);return n===null?[]:[n]}))}i(ga,"petListFromWire");function to(e){return ha($({auth:e}),$({auth:e,unaryTimeoutMs:pa}))}i(to,"createPetsRepository");function ha(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Vn(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?_(ga(s.value)):p(s.error)},async registerPet(o,s,l){let u=Vn(o,s);if(u!==null)return p(u);let a=ma(s);if("error"in a)return p(a.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:a.body},m=await e.send("pets.registerPet",l?.signal?{...c,signal:l.signal}:c);return m.ok?_(Wn(m.value,o)):p(m.error)},async updatePet(o,s,l){let u=n(o);if(typeof u!="string")return p(u);let a=fa(s);if("error"in a)return p(a.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:u,body:a.body},l?.signal));return d.ok?_(Wn(d.value,o)):p(d.error)},async getPetProfile(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},s?.signal));if(!u.ok)return p(u.error);let a=ya(u.value);return a===null?p(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 p(l);let u=await e.send("pets.deletePet",r({method:"DELETE",path:l},s?.signal));return u.ok?_(void 0):p(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):p(s.error)}}}i(ha,"createPetsRepositoryOver");var ro=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 no(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(ro))for(let l of ro[s])o.has(l)||(o.add(l),n.push(Object.freeze({resource:l,granted:false,disabled:r})));return Object.freeze(n)}i(no,"deniedDecisionsFor");function re(e){let t=ba(e);return t===null?null:_a(t)}i(re,"parseColor");function ba(e){if(typeof e=="number")return oo(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return It(t.slice(1));if(t.toLowerCase().startsWith("0x"))return It(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return va(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=It(t);if(r!==null)return r}return /^\d+$/.test(t)?oo(Number.parseInt(t,10)):null}i(ba,"toRgba");function It(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Ot(t[0]),g:Ot(t[1]),b:Ot(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(It,"fromHex");function va(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=At(Number(n[0])),s=At(Number(n[1])),l=At(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(va,"fromRgbFunc");function oo(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(oo,"argbIntToRgba");function ae(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ae,"byte");function Ot(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Ot,"dup");function At(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(At,"clampByte");function _a(e){if(e.a>=1)return Ra(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(_a,"normalizeRgba");function Ra(e,t,r){return `#${Ft(e)}${Ft(t)}${Ft(r)}`.toUpperCase()}i(Ra,"rgbToHex");function Ft(e){return e.toString(16).padStart(2,"0")}i(Ft,"hex2");var Mt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]);function Ea(e){return Mt.includes(e)}i(Ea,"isSlotName");function Ca(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(Ca,"parseRadius");function io(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(!Ea(n)||o===null||typeof o!="object")continue;let s=Sa(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(io,"parseThemeSlots");function Ye(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Ye,"pick");function Sa(e){let t={},r=re(Ye(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=re(Ye(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Ca(Ye(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=re(Ye(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Sa,"parseSlot");var lo=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"]),Xe="slots.";function uo(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(uo,"isEmptyBranding");function ka(e){return e==="hide_powered_by"||lo.includes(e)?true:e.startsWith(Xe)&&Mt.includes(e.slice(Xe.length))}i(ka,"isThemeLockName");function ke(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:le(x(t,"display_name","displayName")),logoUrl:le(x(t,"logo_url","logoUrl")),primaryColor:re(x(t,"primary_color","primaryColor")),accentColor:re(x(t,"accent_color","accentColor")),brightness:Ia(x(t,"brightness","color_scheme","colorScheme")),fontFamily:le(x(t,"font_family","fontFamily")),fontUrl:le(x(t,"font_url","fontUrl")),fonts:so(x(t,"fonts")),fontUrls:so(x(t,"font_urls","fontUrls")),placeholder:le(x(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Ta(x(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:re(x(t,"primary_color_dark","primaryColorDark")),accentColorDark:re(x(t,"accent_color_dark","accentColorDark")),surfaceStyle:ao(x(t,"surface_style","surfaceStyle"),Pa),radiusScale:ao(x(t,"radius_scale","radiusScale"),xa),logoUrlDark:le(x(t,"logo_url_dark","logoUrlDark")),slots:io(x(t,"slots")),accessibilityMaxFontScale:Aa(x(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Ma(x(t,"locked_fields","lockedFields")),schemaVersion:Fa(x(t,"schema_version","schemaVersion"))};return uo(r)?null:Object.freeze(r)}i(ke,"parseClientBranding");function Ta(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(Ta,"parseBool");function x(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(x,"pick");function le(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(le,"parseNonEmptyString");var co=["regular","medium","bold","mono","monoMedium","monoBold"];function so(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of co){let o=le(x(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(so,"parseFaceMap");var Pa=["white","cream","subtle"],xa=["sharp","default","round"];function ao(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(ao,"parseEnum");function Ia(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(Ia,"parseBrightness");function po(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(po,"parseNumber");var Oa=1,fo=3.1;function Aa(e){let t=po(e);return t===null?null:t<=0?0:Math.min(fo,Math.max(Oa,t))}i(Aa,"parseMaxFontScale");function Fa(e){if(e==null)return null;let t=po(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(Fa,"parseSchemaVersion");function mo(e){let t=e.trim();return t.startsWith(Xe)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(mo,"toWireName");function Ma(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=mo(r);ka(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(Ma,"parseLockedFields");var yo="/widget/v1/entitlements",Da=304,ja=Object.freeze({kind:"notModified"});async function ho(e,t={},r=$({auth:e})){let n=await r.send("entitlements.fetch",La(t));return n.ok?Ua(n.value):n.error.httpStatus===Da?ja:{kind:"failed",error:n.error}}i(ho,"fetchEntitlements");var za=64;function La(e){let t={};return Dt(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=za?{method:"GET",path:yo,headers:t,query:{region:e.region}}:{method:"GET",path:yo,headers:t}}i(La,"buildRequest");function Ua(e){if(e===null||typeof e!="object"||!Dt(e.revision))return go();let t=typeof e.region=="string"?e.region:"",r=Dt(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Ba(e.capabilities),branding:Na(e)})}i(Ua,"parseUpdated");function Na(e){let t=ke(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=ke(r.branding);return n!==null?n:ke(r)}return null}i(Na,"parseBranding");function Ba(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))qa(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Ba,"mapCapabilities");function qa(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(qa,"isEnabled");function go(){return {kind:"failed",error:S("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(go,"malformed");function Dt(e){return typeof e=="number"&&Number.isFinite(e)}i(Dt,"isFiniteNumber");var Ha=30;function bo(e){let t=e.scheduler??Ka,r=e.resolve??ho,n=Math.max(1,e.floorSeconds??Ha),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),l=false,u=false,a=null,d=null,c=n,m=0,h=i(()=>{a!==null&&(t.clear(a),a=null);},"clearTimer"),g=i(P=>{u||!l||(c=Math.max(n,P),a=t.set(()=>{a=null,C();},c*1e3));},"schedule"),E=null,T=i(async()=>{if(u)return null;let P=m;e.onFetch?.();let O=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},D;try{D=await r(e.authFor(),O);}catch(A){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:$a(A)}),!u&&P===m&&(e.onSettled?.(),g(s())),null}if(u||P!==m)return null;switch(D.kind){case "updated":d=D.revision,e.update(D.decisions,D.branding??null),g(D.ttlSeconds);break;case "notModified":g(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:D.error.code}),g(s());break;default:g(s());}return e.onSettled?.(),D},"tick"),C=i(()=>{let P=T().finally(()=>{E===P&&(E=null);});return E=P,P},"run");return {start(){l||u||(l=true,C());},prime(){return u?Promise.resolve(null):E??C()},stop(){u||(u=true,m++,h());},refresh(){u||!l||(m++,d=null,h(),C());}}}i(bo,"createEntitlementPoller");var Ka={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function $a(e){return e instanceof Error?e.message:"poll failed"}i($a,"describe");var vo="everfur.notifications.device";var Ro=3e3,_o=Object.freeze([vo]);function Eo(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(m=>m.status==="rejected").length;c>0&&u("failed",c);});return new Promise(d=>{let c=false,m=i(()=>{c||(c=true,clearTimeout(h),d());},"finish"),h=setTimeout(()=>{c||u("timeout",l.length),m();},Ro);a.then(m,m);})}i(Eo,"startBeforeLogoutHooks");function Co(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(Co,"graceAuth");async function So(e,t){if(_o.length===0)return;let r=await Promise.allSettled(_o.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(So,"sweepPerUserKv");function Va(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Va,"compiledDefaultDecisions");function jt(e=Va){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}),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(jt,"createEntitlementStore");function zt(e){return S("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(zt,"notConfiguredError");function wo(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 Fr(r,t===void 0?void 0:{platform:t})}i(wo,"tryResolveClient");function ko(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(ko,"guardTelemetry");function To(e,t){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. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(To,"reportConfigFailure");function Lt(e){return Object.freeze({request(){return Promise.resolve(p(zt(e)))},stream(t,r){let n=N({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(Lt,"refusingTransport");function Po(){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(Po,"createInMemoryKv");var xo=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function jp(e,t){return new Nt(e,t)}i(jp,"createEverfurRuntime");var Wa=6e4,Bt=class Bt{constructor(t,r){this.sessionId=st();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 K("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?ko(n.telemetry):Me;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=lt(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=Lt(s);else if(n.transport!==void 0)u=n.transport;else {let c=wo(n,r?.platform);c.ok?(a=c.config.apiBaseUrl,u=Ur({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,u=Lt(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=u,s!==null&&To(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??hr,this.upload=n.upload??on,this.uploadTransport=n.uploadTransport??kt,this.imageCache=n.imageCache??xo,this.kv=n.storage??Po(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?jt():jt(()=>no("sdk_config",ot("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",Ut(c),()=>this.buildChatController(c),Io),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Ut(c)}`)?.controller??null,"peekChat"),acquire:i((c,m,h,g)=>this.acquireInternal(c,m,h,g),"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=kr(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-Wa,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 bo({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"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=En({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=wn(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=st(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await So(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 Eo({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Co({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?p(Oo(t)):r(to(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?Oo("prepare"):n===null?null:zt(n),s=this.identity,[l,u,a]=await Promise.all([o?p(o):s===null?_(void 0):s.currentToken().then(()=>_(void 0),()=>p(S("authRejected",{retryable:false}))),o?p(o):this.primeEntitlements(),t===null?void 0:o?p(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"?p(t.error):_(void 0):p(S("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Ut(r),()=>this.buildChatController(r),Io,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?p(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(Bt,"EverfurRuntimeImpl");var Nt=Bt;function Ut(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Ut,"chatScopeKey");function Io(e){e.dispose();}i(Io,"disposeChat");function Oo(e){return S("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Oo,"disposedError");var Mo=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Ao=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 Ga(e){let t=Object.prototype.hasOwnProperty.call(Ao,e)?Ao[e]:void 0;if(t!==void 0)return t;let r=e;return Mo.has(r)?r:"parsing"}i(Ga,"normalizeStatus");function Ya(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Ya,"normalizeOrigin");var Xa=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 Do(e){let t=Xa.safeParse(e);if(!t.success)return null;let r=t.data,n=Qa(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??Ga(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:Fo(r.document_count,0),heldItemCount:Fo(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(Do,"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 Qa(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Mo.has(e)?e:null}i(Qa,"normalizeSimpleStatus");zod.z.object({source_doc_id:zod.z.string().min(1),request_id:zod.z.string().min(1)});var Ja=zod.z.object({label:zod.z.string(),value:zod.z.string()}),qt=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()}),Za=zod.z.object({at:zod.z.string(),value:zod.z.number().nullish(),display:zod.z.string().nullish(),origin:zod.z.string().nullish()}),el=zod.z.object({key:zod.z.string(),label:zod.z.string().optional(),points:zod.z.array(Za).optional()}),tl=zod.z.object({title:zod.z.string(),detail:zod.z.string().nullish(),due_at:zod.z.string().nullish()}),Ht=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 jo(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:Ya(e.origin),canonicalKey:e.canonical_key??null})}i(jo,"mapEntityRow");function zo(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(zo,"mapDocumentRow");zod.z.object({identity:zod.z.array(Ja).optional(),entities:zod.z.array(qt).optional(),entity_series:zod.z.array(el).optional(),forward_looking:zod.z.array(tl).optional(),documents:zod.z.array(Ht).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 Fo(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Fo,"numberOr");var Uo=10,Qe=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),Te=i((e,t=1)=>zod.z.string().refine(r=>!L(r)&&[...r].length>=t&&[...r].length<=e),"text"),No=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),rl=zod.z.object({clinicId:Qe.optional(),clinicFreeText:Te(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Te(320,3).refine(e=>!No(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Qe.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)),nl=zod.z.object({petRef:Te(128),ownerName:Te(200).refine(e=>e.trim().length>0&&!No(e)),authorizationVersion:Te(64),clinics:zod.z.array(rl).min(1).max(Uo)}).strict(),ol=zod.z.object({request_group_id:Qe,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:Qe.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 il(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!nl.safeParse(r).success)return p(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=ol.safeParse(n.value);if(!o.success||o.data.pet_ref!==r.petRef)return Lo();let s=[];for(let l of o.data.results){let u=l.request===void 0||l.request===null?null:Do(l.request);if(l.created!==(u!==null))return Lo();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(il,"createRecordsClinicBatchClient");function Lo(){return p(S("internalError",{retryable:false}))}i(Lo,"malformed");var sl="records_consent_required";function al(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(al,"recordsWireCodeOf");function Bo(e){return e===null||e.httpStatus!==409?false:al(e)===sl}i(Bo,"isRecordsConsentRequired");var Kt="value_text",qo=64,Ho=512;function ll(e){return e!==null&&e.httpStatus===409&&!Bo(e)}i(ll,"isFactReviewerLocked");function ul(e){return Object.freeze({[Kt]:e.trim()})}i(ul,"factValueCorrection");var Pe=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:Kt}),Ko=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,$o=/^\d{4}-\d{2}-\d{2}$/;function Vo(e){if(e==null)return "text";let t=e.trim();return Ko.test(t)?"num":$o.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(Vo,"inferFactValueKind");function dl(e,t){let r=t.trim(),n=Vo(e);if(n==="num"&&Ko.test(r)){let o=Number(r);if(Number.isFinite(o))return Object.freeze({[Pe.num]:o})}return n==="date"&&$o.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Pe.date]:r}):Object.freeze(n==="bool"&&(r==="true"||r==="false")?{[Pe.bool]:r==="true"}:{[Pe.text]:r})}i(dl,"factCorrectionFor");var k=zod.z.string().nullish(),Je=zod.z.number().nullish(),cl=zod.z.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,ref_low:Je,ref_high:Je,status:k,source_clinic:k,source_doc_id:k,doc_id:k,reviewed:zod.z.boolean().nullish()}),pl=zod.z.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,status:k}),fl=zod.z.object({marker_id:zod.z.string().min(1),canonical_name:k,name:k,loinc_code:k,canonical_unit:k,unit:k,panel_name:k,panel:k,meaning_text:k,meaning:k,latest:pl.nullish(),trajectory:k,points:zod.z.array(cl).optional()}),ml=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()}),yl=zod.z.object({markers:zod.z.array(fl).optional(),summary:ml.nullish(),disclaimer:zod.z.string().optional(),featured_marker_id:k});function gl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(gl,"isObject");function Wo(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Wo,"withheldMarkers");function $t(e,t){let r=gl(t)?t:{},n=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Wo(n);let o=yl.safeParse(r);if(!o.success)return Wo(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($t,"mapRecordMarkers");var hl=zod.z.string().min(1).refine(e=>e.startsWith("https://")),bl=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:hl,expires_in_seconds:zod.z.number().int().nonnegative().nullish()}),vl=zod.z.object({items:zod.z.array(zod.z.unknown()).optional()});function Go(e){let t=vl.safeParse(e);if(!t.success)return null;let r=[];for(let n of t.data.items??[]){let o=bl.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(Go,"mapRequestDocuments");var _l=zod.z.string().min(1).refine(e=>e.startsWith("https://")),xe=zod.z.string().nullish(),Rl=zod.z.object({share_id:zod.z.string().min(1),share_url:zod.z.string().min(1),expires_at:xe}),El=zod.z.object({shares:zod.z.array(zod.z.object({share_id:zod.z.string().min(1),expires_at:xe,created_at:xe,view_count:zod.z.number().int().nonnegative().nullish(),last_viewed_at:xe})).optional()}),Cl=zod.z.object({download_url:_l,expires_at:xe});function Yo(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(Yo,"resolveShareUrl");function Vt(e,t){let r=Rl.safeParse(e);if(!r.success)return null;let n=Yo(r.data.share_url,t);return n===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:n,expiresAt:r.data.expires_at??null})}i(Vt,"mapRecordShareLink");function Wt(e){let t=El.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}))):null}i(Wt,"mapRecordShareList");function Gt(e){let t=Cl.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Gt,"mapRecordPdfLink");var Sl=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 Yt(e){let t=Sl.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(Yt,"mapSignatureSuggestions");var b=zod.z.string().nullish(),Ie=zod.z.number().nullish(),wl=zod.z.object({at:b,value:Ie,unit:b,qualitative_result:b,ref_low:Ie,ref_high:Ie,status:b,doc_id:b}),kl=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:Ie,unit:b,qualitative_result:b,status:b}).nullish(),trajectory:b,points:zod.z.array(wl).optional()}),Tl=zod.z.object({encounter_id:zod.z.string(),date:b,type:b,clinic_name:b,veterinarian:b,doc_id:b}),Pl=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()}),xl=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()}),Il=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()}),Ol=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()}),Al=zod.z.object({lab_results:zod.z.array(kl).optional(),encounters:zod.z.array(Tl).optional(),clinician_notes:zod.z.array(Pl).optional(),physical_exams:zod.z.array(xl).optional(),completeness:Il.nullish(),conflicts:zod.z.array(Ol).optional()}),Fl=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:Ie,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()}),Ml=zod.z.object({document:Ht,contributions:zod.z.array(qt),contribution_count:zod.z.number().int().nonnegative().optional()});function Qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Qt,"isObject");function Jt(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Jt,"petOf");function Xt(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(Xt,"emptyDepth");function Qo(e,t){let r=Qt(t)?t:{},n=Jt(r,e);if(r.withheld===true)return Xt(n,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Xt(n,false);let s=Al.safeParse(r);if(!s.success)return Xt(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(Qo,"mapRecordDepth");function Xo(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Xo,"withheldTimeline");function Jo(e,t){let r=Qt(t)?t:{},n=Jt(r,e);if(r.withheld===true)return Xo(n);let o=Fl.safeParse(r);if(!o.success)return Xo(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(Jo,"mapRecordsTimeline");function Zo(e,t){let r=Qt(t)?t:{},n=Jt(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=Ml.safeParse(r);if(!s.success)return o();let l=Object.freeze(s.data.contributions.map(jo));return Object.freeze({petRef:n,withheld:false,document:zo(s.data.document),contributions:l,contributionCount:s.data.contribution_count??l.length})}i(Zo,"mapDocumentContributions");var Dl="/widget/v1/records/pets";function jl(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!L(a)&&[...a].length<=d,"segment"),n=i(async(a,d,c,m)=>{if(!r(d,oe))return ne();let h=await t.send(a,{method:"GET",path:c});if(!h.ok)return h;let g=m(h.value);return g.petRef===d?_(g):p(S("internalError",{retryable:false}))},"read"),o=i(a=>`${Dl}/${encodeURIComponent(a)}`,"pet"),s=i(a=>`${o(a)}/everfur_record`,"record"),l=i(async(a,d,c)=>{let m=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!m.ok)return m;let h=c(m.value);return h===null?p(S("internalError",{retryable:false})):_(h)},"parsed"),u=i((a,d)=>!r(a.entityType,qo)||!r(a.canonicalKey,Ho)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,Tn)||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=>Qo(a,d)),"getRecordDepth"),getTimeline:i(a=>n("records.depth.timeline",a,`${o(a)}/timeline`,d=>Jo(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?n("records.depth.contributions",a,`${o(a)}/documents/${encodeURIComponent(d)}/contributions`,c=>Zo(a,c)):ne()},getMarkers:i(a=>n("records.depth.markers",a,`${o(a)}/markers`,d=>$t(a,d)),"getMarkers"),createShare(a){return r(a,oe)?l("records.share.create",{method:"POST",path:`${s(a)}/share`},d=>Vt(d,e.apiBaseUrl)):ne()},listShares(a){return r(a,oe)?l("records.share.list",{method:"GET",path:`${s(a)}/shares`},Wt):ne()},async revokeShare(a,d){if(!r(a,oe)||!r(d,64))return ne();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`},Gt):ne()},async editFact(a,d){let c=r(a,oe)?u(d,d.correctedFields):null;if(c===null)return ne();let m=await t.send("records.fact.edit",{method:"POST",path:`${s(a)}/facts/edit`,body:c},{idempotent:false,maxAttempts:1});return m.ok?_(void 0):m},async removeFact(a,d){let c=r(a,oe)?u(d):null;if(c===null)return ne();let m=await t.send("records.fact.remove",{method:"POST",path:`${s(a)}/facts/remove`,body:c},{idempotent:false,maxAttempts:1});return m.ok?_(void 0):m},listRequestDocuments(a){return r(a,64)?l("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},Go):ne()},listAuthorizationSignatures:i(()=>l("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Yt),"listAuthorizationSignatures")}}i(jl,"createRecordsDepthClient");function ne(){return Promise.resolve(p(S("validationFailed",{retryable:false})))}i(ne,"invalid");var Ae=Object.freeze({width:360,height:120});function ni(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(ni,"blank");function oi(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(oi,"stamp");var zl=16384;function Ll(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(Ll,"padPoint");function Ul(e,t,r,n,o){let[s,l]=t,[u,a]=r,d=Math.abs(u-s),c=-Math.abs(a-l),m=s<u?1:-1,h=l<a?1:-1,g=d+c,E=0;for(;E<o&&(oi(e,s,l,n),E+=1,!(s===u&&l===a));){let T=2*g;T>=c&&(g+=c,s+=m),T<=d&&(g+=d,l+=h);}return E}i(Ul,"line");function Nl(e,t=1){let r=ni(Ae.width,Ae.height);for(let n of e){let o=[];for(let l of n){let u=Ll(l,r);u!==null&&o.push(u);}if(o.length===0)continue;if(o.length===1){let[l,u]=o[0];oi(r,l,u,t);continue}let s=zl;for(let l=1;l<o.length&&s>0;l+=1)s-=Ul(r,o[l-1],o[l],t,s);}return r}i(Nl,"rasterizeStrokes");var Bl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",ql="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",Hl="0123456789abcdefghijklmnopqrstuv",or=5,ir=7,Zt=or+1;function Kl(e,t){let r=Bl.indexOf(e);return r<0?0:Hl.indexOf(ql.charAt(r*ir+t))}i(Kl,"glyphRow");function $l(e){let t=ni(Ae.width,Ae.height),r=e.trim();if(r.length===0)return t;let n=[...r],o=4;for(;o>1&&(n.length*Zt-1)*o>t.width-8;)o-=1;let s=(n.length*Zt-1)*o,l=Math.max(0,Math.floor((t.width-s)/2)),u=Math.floor((t.height-ir*o)/2);return n.forEach((a,d)=>{let c=l+d*Zt*o;for(let m=0;m<ir;m+=1){let h=Kl(a,m);for(let g=0;g<or;g+=1)if((h>>or-1-g&1)!==0)for(let E=0;E<o;E+=1)for(let T=0;T<o;T+=1){let C=c+g*o+T,P=u+m*o+E;C<t.width&&P<t.height&&(t.pixels[P*t.width+C]=1);}}}),t}i($l,"rasterizeTypedName");var lr=class lr{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(lr,"BitWriter");var sr=lr;function ar(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(ar,"writeLiteral");var er=[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],ei=[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],tr=[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],ti=[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 Vl(e,t,r){let n=er.length-1;for(;er[n]>t;)n-=1;ar(e,257+n),ei[n]>0&&e.writeBits(t-er[n],ei[n]);let o=tr.length-1;for(;tr[o]>r;)o-=1;e.writeCode(o,5),ti[o]>0&&e.writeBits(r-tr[o],ti[o]);}i(Vl,"writeMatch");var Wl=32768,rr=3,Gl=258,ri=15,Yl=64;function Xl(e){let t=new sr;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<ri).fill(-1),n=new Int32Array(e.length).fill(-1),o=i(u=>(e[u]<<10^e[u+1]<<5^e[u+2])&(1<<ri)-1,"hashAt"),s=i(u=>{if(u+rr>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+rr<=e.length){let d=r[o(l)],c=0,m=Math.min(Gl,e.length-l);for(;d>=0&&c<Yl&&l-d<=Wl;){let h=0;for(;h<m&&e[d+h]===e[l+h];)h+=1;if(h>u&&(u=h,a=l-d,h===m))break;d=n[d],c+=1;}}if(u>=rr){Vl(t,u,a);for(let d=0;d<u;d+=1)s(l+d);l+=u;}else ar(t,e[l]),s(l),l+=1;}return ar(t,256),t.finish()}i(Xl,"deflate");function Ql(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(Ql,"adler32");var Ze=null;function Jl(e){if(Ze===null){Ze=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;Ze[r]=n>>>0;}}let t=4294967295;for(let r of e)t=Ze[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(Jl,"crc32");function Oe(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(Oe,"u32");function nr(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),[...Oe(t.length),...n,...Oe(Jl(n))]}i(nr,"chunk");var et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Zl(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+=et.charAt(l>>18&63)+et.charAt(l>>12&63),t+=r+1<e.length?et.charAt(l>>6&63):"=",t+=r+2<e.length?et.charAt(l&63):"=";}return t}i(Zl,"toBase64");function eu(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 m=c*o;s[m]=0,s.fill(255,m+1,m+o);for(let h=0;h<t;h+=1)if(n[c*t+h]===1){let g=m+1+(h>>3);s[g]=s[g]&~(128>>(h&7));}}let l=Xl(s),u=new Uint8Array(2+l.length+4);u[0]=120,u[1]=1,u.set(l,2),u.set(Oe(Ql(s)),2+l.length);let a=Uint8Array.from([...Oe(t),...Oe(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...nr("IHDR",a),...nr("IDAT",u),...nr("IEND",new Uint8Array(0))]);return Zl(d)}i(eu,"encodeSignaturePng");
|
|
13
|
-
exports.ATTACHMENT_ACCEPT=
|
|
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"),Gi(r.source,u)}i(Wi,"eventSourceByteSource");async function*Gi(e,t){try{yield*e;}finally{t();}}i(Gi,"sourceWithCleanup");function Yi(){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(Yi,"createByteQueue");async function Xi(e,t){let r=t.fetchImpl??Hr(),n=Kr(t.config.apiBaseUrl,e.path,e.query),o=$r(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=rs(Vi),l=ns(s.signal,e.signal),u;try{u=await r(n,Vr({...e,signal:l},o));}catch(d){return p(ut(d))}finally{s.cancel();}let a=await Wr(u);return u.ok?_(a):p(Zi(u.status,a,Br(u)))}i(Xi,"requestJson");function Nr(e){return {request:i(t=>Xi(t,e),"request"),stream:i((t,r)=>Qi(ts(t,r),e),"stream")}}i(Nr,"createHttpTransport");async function*Qi(e,t){let r=Kr(t.config.apiBaseUrl,e.path,e.query),n=$r(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let u=t.eventSourceFactory(r,Ji(e,n));yield*Ue(Wi(u),()=>es(u));return}let o=t.fetchImpl??Hr(),s;try{s=await o(r,Vr(e,n));}catch(u){yield zr("",true,Qr(u));return}let l=Br(s);if(!s.ok){let u=await Wr(s),a=Gr(u)??qr(s.status),d=Xr(u)||ee(Y(a));yield zr(a,d,Yr(u),l);return}if(s.body){yield*Ue(jr(s.body),l);return}yield*Ue(jr(null),l);}i(Qi,"streamFrames");function Ji(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Ji,"buildEventSourceInit");function Zi(e,t,r){let n=Gr(t),o=n?Y(n):mr(e),s=Yr(t);return S(o,{httpStatus:e,...Xr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Lr(t)?{reasonCode:Lr(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Zi,"errorFromResponse");function ut(e){return S("internalError",{retryable:true,wireMessage:Qr(e)})}i(ut,"networkError");function Br(e){let t=e.headers.get(Ur);return typeof t=="string"&&t.length>0?t:null}i(Br,"requestIdOf");function es(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Ur);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(es,"eventSourceRequestId");function qr(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(qr,"statusToWireCode");function zr(e,t,r,n=null){return N({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(zr,"syntheticErrorFrame");function Hr(){let e=globalThis.fetch;if(typeof e!="function")throw new K("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Hr,"getGlobalFetch");function Kr(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(Kr,"buildUrl");function $r(e,t,r,n){let o={...Dr(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i($r,"mergeHeaders");function Vr(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(Vr,"buildInit");function ts(e,t){return e.signal?e:{...e,signal:t}}i(ts,"withSignal");function rs(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(rs,"timeoutSignal");function ns(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(ns,"mergeAbortSignals");async function Wr(e){try{return await e.json()}catch{return null}}i(Wr,"safeJson");function Lr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Lr,"extractReasonCode");function Gr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Gr,"extractWireCode");function Yr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Yr,"extractWireMessage");function Xr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Xr,"extractRetryable");function Qr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Qr,"describeCause");var os=3e4,is=rt*2,ss="idempotency-key",as=new Set(["POST","PUT","PATCH","DELETE"]),ls=Object.freeze({onEvent(){}}),us=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ds(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(ds,"seededIdempotencyKey");function $(e){let t=e.observer??ls,r=e.timers??us,n=e.rng??Math.random,o=e.sleep??((h,y)=>Ss(h,r,y)),s=e.maxAttempts??pe,l=e.unaryTimeoutMs??os,u=e.newIdempotencyKey??ps(),a=i(h=>{try{t.onEvent(h);}catch{}},"emit");async function d(h,y,R){let T=R?.maxAttempts,C=Math.max(1,T??s),P=R?.idempotent??as.has(y.method),O=R?.idempotencyKey===void 0?null:ds(R.idempotencyKey),D=P?O??u():null,A=cs(y,D),v=0;for(;;){let w=i(ue=>Object.freeze({call:h,method:y.method,path:y.path,attempt:v,...D?{idempotencyKey:D}:{},...ue}),"stamp");a(w({phase:"attempt"}));let j=Es(l,r),B=Cs(j.signal,y.signal),q;try{q=await Pr({...A,signal:B.signal},e.auth);}catch(ue){q=p(ut(ue));}finally{B.dispose(),j.cancel();}if(q.ok)return a(w({phase:"settled",ok:true,reason:"ok"})),q;let H=q.error,ie=ms(H,v,{maxAttempts:C,rng:n,now:r.now(),aborted:y.signal?.aborted===true,...T!==void 0?{perCallMaxAttempts:T}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),ce={ok:false,code:H.code,reason:ie.reason,...H.httpStatus!==void 0?{httpStatus:H.httpStatus}:{},...H.requestId!==void 0?{requestId:H.requestId}:{}};if(!ie.retry)return a(w({phase:"settled",...ce})),p(H);if(a(w({phase:"retry",...ce,delayMs:ie.delayMs})),await o(ie.delayMs,y.signal),y.signal?.aborted===true)return a(w({phase:"settled",...ce,reason:"aborted"})),p(H);v+=1;}}i(d,"send");async function c(h){return fe(h,await Rs(e.auth))}i(c,"authorize");async function*f(h,y,R){a(Object.freeze({call:h,phase:"stream.open",method:y.method,path:y.path,attempt:0}));try{yield*e.auth.transport.stream(y,R);}catch{yield N({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(f,"stream"),Object.freeze({send:d,authorize:c,stream:f})}i($,"createRequestFunnel");function cs(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==ss&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(cs,"assembleHeaders");function ps(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(ps,"defaultIdempotencyKeyFactory");var fs=10;function ms(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=ys(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!ee(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=gs(e,r.now);return a!==null?a>is?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:a}:{retry:true,reason:o,delayMs:ze(t,r.rng)}}i(ms,"decideRetry");function ys(e){let t=e.code==="unknown"?Y(_s(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(ys,"throttleKind");function gs(e,t){let r=bs(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=hs(e.raw);return n===null?null:Math.round(n*1e3)}i(gs,"retryOverrideMs");function hs(e){for(let t of dt(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(hs,"findRetryAfterSeconds");function bs(e){for(let t of dt(e)){let r=t.resets_at,n=vs(r);if(n!==null)return n}return null}i(bs,"findResetsAt");function dt(e){if(!Jr(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Jr(n)&&t.push(n);}return t}i(dt,"candidateScopes");function vs(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(vs,"parseInstantMs");function _s(e){for(let t of dt(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(_s,"rawWireCode");function Jr(e){return typeof e=="object"&&e!==null}i(Jr,"isRecord");async function Rs(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(Rs,"resolveDeviceAuth");function Es(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Es,"boundedSignal");function Cs(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(Cs,"mergeSignals");function Ss(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(Ss,"delayAbortable");function L(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(L,"hasLoneSurrogate");function Ne(e){return [...e].length}i(Ne,"serverLength");var nn=Object.freeze(["better","same","worse"]),pt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Zr(e){return p(S("validationFailed",{retryable:false,wireMessage:e}))}i(Zr,"invalid");function ct(){return p(S("internalError",{retryable:false}))}i(ct,"malformed");function en(e){return typeof e!="string"||e.trim().length===0?S("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):L(e)?S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(en,"petPath");var te=i(e=>typeof e=="string"?e:null,"str"),tn=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function rn(e){if(typeof e!="object"||e===null)return null;let t=e,r=te(t.case_id),n=te(t.status);if(r===null||n===null)return null;let o=te(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:te(t.body_location),lastResponse:o!==null&&nn.includes(o)?o:null,checkInDueAt:te(t.check_in_due_at),openedAt:te(t.opened_at),resolvedAt:te(t.resolved_at),resolutionText:te(t.resolution_text),checkinAskCount:tn(t.checkin_ask_count),checkinAnswerCount:tn(t.checkin_answer_count)})}i(rn,"caseFromWire");function on(e){return {async list(t,r){let n=en(t);if(typeof n!="string")return p(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return p(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return ct();let l=s.map(rn);return l.every(u=>u!==null)?_(Object.freeze(l)):ct()},async checkin(t,r,n,o){let s=en(t);if(typeof s!="string")return p(s);if(typeof r!="string"||!pt.test(r))return Zr("case_id must be a UUID");if(!nn.includes(n))return Zr("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 p(l.error);let u=typeof l.value=="object"&&l.value!==null?l.value:{},a=rn(u.case);return a===null?ct():_(Object.freeze({case:a,ctaDeepLink:te(u.cta_deep_link)}))}}}i(on,"createCasesRepositoryOver");var sn=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var an=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function qe(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(qe,"delayAbortable");function He(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(He,"mergeSignals");var ft=class ft{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?He(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(ft,"MediaStore");var Be=ft;function yt(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(yt,"makeUser");function gt(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(gt,"makeAssistant");function ge(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(ge,"stripPending");function ln(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(ln,"appendText");function ht(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(ht,"finalizeAssistant");function un(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(un,"freezeSnapshot");function E(e,t,r){return S(e,{retryable:t,...r?{wireMessage:r}:{}})}i(E,"makeError");function bt(e){let t=Y(e.code);return S(t,{retryable:e.retryable||je(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(bt,"errorFromFrame");function X(e){return N({code:ws(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(X,"synthErrorFrame");function ws(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 Le(e)}}i(ws,"canonicalWireCode");function dn(e){let t=Array.isArray(e)?e:mt(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!mt(n))continue;let o=ye(n.category)??ye(n.title)??"",s=ks(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(dn,"parsePromptCategories");function vt(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(vt,"flattenPrompts");function mt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(mt,"isPlainObject");function ye(e){return typeof e=="string"?e:null}i(ye,"asStr");function ks(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(mt(r)){let n=ye(r.text)??ye(r.prompt)??ye(r.title);n!==null&&t.push(n);}return t}i(ks,"asPromptTextList");function cn(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(cn,"defaultIdFactory");function pn(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(pn,"defaultIdempotencyFactory");var mn={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*yn(e,t,r,n){let o=e[Symbol.asyncIterator](),s=fn(t.overallMs,n),l=fn(t.idleMs,n),u=xs(r);try{for(;;){if(r.aborted)return;let a=o.next().then(f=>({tag:"next",value:f}),()=>({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 Ps();return}if(d.tag==="idle"||d.tag==="overall"){yield Ts();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(yn,"withWatchdog");function Ts(){return N({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ts,"synthTimeoutFrame");function Ps(){return N({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ps,"synthStreamErrorFrame");function fn(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(fn,"deadline");function xs(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(xs,"abortPromise");var Is="checkin",Os=/^\d{4}-\d{2}-\d{2}$/,he="watching";function As(e){return e.status!=null&&e.status!==he}i(As,"isCheckinSettled");function gn(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(gn,"isLiveAskAnswered");function Fs(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Is||n===void 0||o===void 0||!pt.test(n)||!Os.test(o)?null:{caseId:n,dueDay:o}}i(Fs,"parseCheckinOrigin");function hn(e){return Fs(e)?.caseId??null}i(hn,"parseCheckinOriginRef");function _t(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return p(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||L(o))return p(S("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),_(r.length?`?${r.join("&")}`:"")}i(_t,"historyQuery");function _e(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(_e,"validConversationId");function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(ve,"object");function bn(e){return e==null||typeof e=="string"&&e.length>0&&!L(e)}i(bn,"cursor");function be(){return p(S("internalError",{retryable:false}))}i(be,"malformed");function vn(e){let t=ve(e);if(!t||!Array.isArray(t.conversations)||!bn(t.next_cursor))return be();let r=[];for(let n of t.conversations){let o=ve(n);if(!o||typeof o.conversation_id!="string"||!_e(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return be();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return be();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(vn,"mapConversationPage");function _n(e){let t=ve(e);if(!t||!Array.isArray(t.messages)||!bn(t.next_cursor))return be();let r=[],n=new Set;for(let o of t.messages){let s=ve(o);if(!s||typeof s.message_id!="string"||!_e(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return be();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let l=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,u=s.role==="assistant"?hn(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:Ms(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Ds(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(_n,"mapMessagePage");function Ms(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ms,"normalizeUrgency");function Ds(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=ve(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(Ds,"historyCitations");var Ke=5,Rt=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Et=4e3;var Ct=4e3;function Rn(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(Rn,"validateImageKeys");function St(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>Ct?{reason:"too_long",error:E("validationFailed",false,`message is ${r} characters; the server accepts at most ${Ct}`)}:null}i(St,"validateMessageText");function En(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(En,"urgencyTier");async function*Re(e){yield e;}i(Re,"singleFrameStream");async function*Cn(){}i(Cn,"emptyStream");var js=6e4,zs=18e4,Ls=24,Us=512,Ns=false;function Sn(e){return new wt(e)}i(Sn,"createChatController");var kt=class kt extends Be{constructor(r){super(un({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.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??$({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=on(this.funnel),this.telemetry=r.telemetry??Me,this.errorPolicy=r.errorPolicy??hr,this.timers=r.timers??mn,this.rng=r.rng??Math.random,this.newId=r.newId??cn(),this.makeIdempotencyKey=r.makeIdempotencyKey??pn(),this.budget={idleMs:r.budget?.idleMs??js,overallMs:r.budget?.overallMs??zs};}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),()=>{}):Re(X(a))}let l=St(r)??Rn(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),()=>{}):Re(X(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 Re(X(E("accessDenied",false)));let o=St(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Re(X(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):Cn()}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,yt(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?ge(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.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}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(vt(r));this.bootstrapPrompts=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=_t(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(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 p(E("accessDenied",false));if(!l.ok)return l;let u=vn(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 p(E("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let a=await this.resumeConversation(n);return a.ok?_(n):p(a.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return p(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):p(u.error)}async markRead(r){if(this.disposed)return p(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?p(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)):p(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return p(E("accessDenied",false));if(typeof r!="string"||r.trim().length===0||L(r))return p(E("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Rt.includes(n))return p(E("validationFailed",false,`feedback_type must be one of ${Rt.join(", ")}`));let l=typeof o=="string"?o.trim():"";if([...l].length>Et)return p(E("validationFailed",false,`notes is over ${Et} 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 p(E("accessDenied",false));if(!d.ok)return p(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 p(E("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return p(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 p(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(f=>f.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(f=>c(f)?Object.freeze({...f,checkin:d}):f)}),u}async getMessages(r,n){if(!_e(r))return p(E("validationFailed",false));let o=_t(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(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?p(E("accessDenied",false)):l.ok?_n(l.value):l}async resumeConversation(r){if(this.disposed)return p(E("accessDenied",false));if(!_e(r))return p(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 p(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===he).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 f=l.get(c.caseId),h=c.openedAt??f?.openedAt??null,y=s.has(c.caseId),R=f!==void 0&&(!y||gn({askCount:f.checkinAskCount,answerCount:f.checkinAnswerCount}))?f.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:y?he:f?.status??"resolved",answer:c.answer??R,resolutionText:c.resolutionText??f?.resolutionText??null,...h!==null?{openedAt:h}:{}})})});u&&this.patch({messages:a});}async refreshActiveThread(){if(this.disposed)return p(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 p(E("accessDenied",false));if(!o.ok)return p(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 p(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 p(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 X(n.error));}async primeConversation(r){if(this.disposed)return p(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?p(E("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return _(n);let o=this.snapshot.conversationId;return o!==null?_(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;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 p(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?p(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 p(s.error);let l=s.value?.conversation_id??s.value?.id;return typeof l!="string"||l.length===0?p(E("internalError",true)):_(l)}async getPrompts(r){let n=this.epoch;if(this.disposed)return p(E("accessDenied",false));let o=r?.petRef??null;if(o!==null&&L(o))return p(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?p(E("accessDenied",false)):l.ok?_(dn(l.value)):p(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=He(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 f of a){if(d)break;o.onFrame(f),f.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,yt(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&&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,X(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,X(C));return}this.clearAssistantInProgress(r);let f=new AbortController,h=He(o.signal,f.signal),y=null;try{let C;try{C=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let O=this.authRejected();yield*this.emitTerminal(r,O,X(O));return}if(o.signal.aborted||!this.alive(o.epoch))return;let P=this.funnel.stream("chat.send",C,h);for await(let O of yn(P,this.budget,h,this.timers)){if(!this.alive(o.epoch))return;if(O.kind==="error"&&O.terminal){y=O;break}if(this.applyFrame(O,r),yield O,O.terminal){o.settle();return}}}finally{f.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,X(C));return}let R=Y(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,bt(y),y);return}if(gr(R)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let T=y.retryable&&je(R,!0);if(Ns&&T&&s+1<this.errorPolicy.maxAttempts(R));yield*this.emitTerminal(r,bt(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 Le(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?ge(l):l);this.patch({status:"streaming",isStreaming:true,messages:[...s,gt(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Us){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);},Ls);}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?ln(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?ht(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?ge(d):d),ht(gt(u,"",this.stamp()),r)];}let l=vt([{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=En(u.value?.urgency),d=typeof u.value?.reason=="string"?u.value.reason:null,c=i(f=>f.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(f=>c(f)?Object.freeze({...f,urgencyLevel:a,urgencyReason:d,urgencyProvided:true}):f)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?ge(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(kt,"ChatControllerImpl");var wt=kt;async function Tn(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,f=o?r.resumeConversation(o).then(A=>A.ok?_(o):A):r.primeConversation(n?{petRef:n}:void 0),h=r.getPrompts(n!==null?{petRef:n}:void 0),[y,R]=await Promise.all([f,h]),T=null;if(y.ok)T=y.value,s.push(y.value),r.getSnapshot().conversationId===null&&r.adoptConversation(y.value);else {let A=y.error;c=A,wn(A)?(u=true,d=A):(kn(A)&&(l=true),a=true);}let C=[];R.ok?C=R.value:P(R.error);function P(A){wn(A)?(u=true,d===null&&(d=A)):kn(A)&&(l=true);}i(P,"recordAuthSignals");let O=d!==null?d.displayMessage:null;return Object.freeze({conversationId:T,petRef:n,suggestedPrompts:C,error:O,warning:O===null&&T===null&&a?Bs:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:l,sawUnauthorized:u,sawConversationInitFailure:a})})}i(Tn,"bootstrapChat");var Bs="Chat is ready. Your first message will start the conversation.";function wn(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(wn,"isUnauthorized");function kn(e){return e.httpStatus===403||e.code==="accessDenied"}i(kn,"isForbidden");var Tt=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Pn(e){return e!==Tt}i(Pn,"isUploadTransportAvailable");var xn=128,oe=128;var qs=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),mc="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",On=10*1024*1024,Hs=5,Ee=120,Ks="/widget/v1/uploads/initiate";function $s(e){return typeof e=="string"&&qs.includes(e.trim().toLowerCase())}i($s,"isAttachmentMime");function Vs(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<=Ee)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Ee);let n=t.slice(r);return n.length>=Ee?t.slice(0,Ee):`${t.slice(0,r).slice(0,Ee-n.length)}${n}`}i(Vs,"sanitizeFilename");function yc(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(yc,"formatBytes");var Ce=i(e=>Object.freeze({ok:true,value:e}),"ok"),V=i(e=>Object.freeze({ok:false,error:e}),"err");function M(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(M,"failure");function Ws(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(Ws,"attachmentSize");function Gs(e){let t=Vs(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!$s(r))return V(M("unsupported_type",false,t));let n=Ws(e);return n===null?V(M("unknown",false,t)):n>On?V(M("too_large",false,t,{sizeBytes:n})):Ce(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Gs,"validateAttachment");function Ys(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)??On,s3_key:l,purpose:r(t.purpose)})}i(Ys,"parsePolicy");function Xs(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return M("quota_exceeded",false,t,{cause:e});case "rateLimited":return M("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return M("idempotency_conflict",true,t,{cause:e});case "validationFailed":return M("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return M("network",true,t,{cause:e});default:return r===429?M("rate_limited",true,t,{cause:e}):r===503?M("network",true,t,{cause:e}):r===void 0?M("network",true,t,{cause:e}):M("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Xs,"initiateFailure");async function Qs(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Ks,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return V(Xs(n.error,t.filename));let o=Ys(n.value);return o===null?V(M("server",false,t.filename)):Ce(o)}i(Qs,"initiateAttachmentUpload");async function Js(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return V(M("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Ce(void 0)}catch{return o()?V(M("cancelled",true,r.filename)):V(M("server",true,r.filename))}}i(Js,"uploadAttachmentBytes");var Zs=2,ea=3,ta=Object.freeze([1e3,2e3,4e3]),In=0;function ra(){return In+=1,`attachment-${In}`}i(ra,"defaultNewId");function gc(e){let t=Math.max(1,e.concurrency??Zs),r=Math.max(1,e.maxAttempts??ea),n=e.backoffMs??ta,o=Math.max(1,e.maxPerMessage??Hs),s=e.timers??an,l=e.newId??ra,u=Pn(e.transport),a=new Map,d=[],c=[],f=new Set,h=new Set,y=Object.freeze({attachments:Object.freeze([])}),R=false,T=i(()=>{y=Object.freeze({attachments:Object.freeze(d.flatMap(v=>{let w=a.get(v);return w===void 0?[]:[w.state]}))});for(let v of h)v();},"publish"),C=i((v,w)=>{v.state=Object.freeze({...v.state,...w}),T();},"patch"),P=i(()=>{for(;!R&&f.size<t&&c.length>0;){let v=c.shift(),w=a.get(v);w!==void 0&&(f.add(v),O(w).finally(()=>{f.delete(v),P();}));}},"pump"),O=i(async v=>{let{attachment:w}=v;for(;v.attempts<r;){if(R||v.controller.signal.aborted)return;v.attempts+=1;let j=v.controller.signal;C(v,{status:"uploading",error:null,progress:0});let B=await Qs(e.funnel,w,{signal:j});if(R||j.aborted)return;let q;if(!B.ok)q=V(B.error);else {let ue=await Js(e.transport,B.value,w,{signal:j,onProgress:i(ai=>{!j.aborted&&v.state.status==="uploading"&&C(v,{progress:na(ai)});},"onProgress")});if(R||j.aborted)return;q=ue.ok?Ce(B.value.s3_key):V(ue.error);}if(q.ok){C(v,{status:"uploaded",s3Key:q.value,error:null,progress:1});return}let H=q.error,ie=H.retryable&&v.attempts<r;if(C(v,{status:ie?"uploading":"failed",error:H,progress:0}),!ie)return;let ce=n[Math.min(v.attempts-1,n.length-1)]??0;await qe(ce,j,s);}},"run"),D=i(v=>{c.push(v.state.id),P();},"enqueue"),A={available:u,subscribe(v){return h.add(v),()=>{h.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 w=Gs(v);if(!w.ok)return w;if(R||d.length>=o)return V(M("too_many",false,w.value.filename));let j=l(),B={attachment:w.value,controller:new AbortController,attempts:0,state:Object.freeze({id:j,filename:w.value.filename,previewUri:v.uri,contentType:w.value.contentType,sizeBytes:w.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(j,B),d.push(j),T(),D(B),Ce(B.state)},retry(v){let w=a.get(v);w===void 0||R||w.state.status!=="failed"||(w.controller=new AbortController,w.attempts=0,C(w,{status:"uploading",error:null,progress:0,s3Key:null}),D(w));},remove(v){let w=a.get(v);if(w===void 0)return;w.controller.abort(),a.delete(v);let j=d.indexOf(v);j>=0&&d.splice(j,1);let B=c.indexOf(v);B>=0&&c.splice(B,1),T();},clear(){for(let v of [...d])A.remove(v);},dispose(){R=true;for(let v of a.values())v.controller.abort();a.clear(),d.length=0,c.length=0,h.clear(),y=Object.freeze({attachments:Object.freeze([])});}};return A}i(gc,"createAttachmentQueue");function na(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(na,"clamp");var An=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function Fn(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(An,t)?An[t]:null}i(Fn,"canonicalPetSpecies");var Mn=50,oa=128,Pt=120,Dn=120,ia=2e3,jn=120,sa=80,Un=new Set(["male","female","unknown"]),Nn=new Set(["day","month","year"]),Bn=new Set(["low","medium","high","athletic"]),qn=new Set(["indoor","outdoor","both"]),Hn=new Set(["mild","moderate","severe"]),aa=/^(\d{4})-(\d{2})-(\d{2})$/,Kn=[["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"]],$n=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Kn,...$n].map(([e])=>e));function la(e){let t=aa.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(la,"isRealDate");var we=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),ua=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Ve=i((e,t)=>typeof t=="string"&&la(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Q=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(L(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=Ne(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),da={sex:we(Un),spayedNeutered:ua,birthDate:Ve,birthDatePrecision:we(Nn),activityLevel:we(Bn),indoorOutdoor:we(qn),foodBrand:Q(jn),foodType:Q(jn),microchipId:Q(sa)},xt=["ref","ref",false,Q(oa,{required:true,trimmed:true})],It=["notes","notes",false,Q(ia,{trimmed:true})],zn=[xt,["name","name",true,Q(Pt,{required:true,trimmed:true})],["dose","dose",false,Q(Dn,{trimmed:true})],["frequency","frequency",false,Q(Dn,{trimmed:true})],["startDate","start_date",false,Ve],["endDate","end_date",false,Ve],It],ca={allergies:[xt,["allergen","allergen",true,Q(Pt,{required:true,trimmed:true})],["severity","severity",false,we(Hn)],It],medications:zn,supplements:zn,conditions:[xt,["conditionName","condition_name",true,Q(Pt,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ve],It]};function pa(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,f]of ca[e]){let h=o[a];if(h==null){if(c)return {error:`${n}.${a} is required`};h===null&&(s[d]=null);continue}let y=f(`${n}.${a}`,h);if(y!==null)return {error:y};s[d]=h;}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(pa,"itemToWire");function fa(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>Mn)return {error:`${e} has ${t.length} items; the server accepts at most ${Mn}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=pa(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(fa,"listToWire");function Vn(e,t){let r=e,n={};for(let[l,u]of Kn){let a=r[l];if(a!==void 0){if(a!==null){let d=da[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 $n){let a=r[l];if(a===void 0)continue;let d=fa(l,a);if("error"in d)return d;n[u]=d.items;}return Object.keys(n).length>0&&t!==void 0&&Fn(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(Vn,"petHealthToWire");var F=i(e=>typeof e=="string"?e:null,"str"),Se=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),ma=i(e=>typeof e=="boolean"?e:null,"bool");function $e(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($e,"itemsFromWire");function Ln(e){let t=F(e.name);return t===null||t.length===0?null:Object.freeze({ref:F(e.ref),name:t,dose:F(e.dose),frequency:F(e.frequency),startDate:F(e.start_date),endDate:F(e.end_date),notes:F(e.notes)})}i(Ln,"medicationFromWire");function Wn(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Se(Un,e.sex),spayedNeutered:ma(e.spayed_neutered),birthDate:F(e.birth_date),birthDatePrecision:Se(Nn,e.birth_date_precision),activityLevel:Se(Bn,e.activity_level),indoorOutdoor:Se(qn,e.indoor_outdoor),foodBrand:F(e.food_brand),foodType:F(e.food_type),microchipId:F(e.microchip_id),allergies:$e(e.allergies,r=>{let n=F(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),allergen:n,severity:Se(Hn,r.severity),notes:F(r.notes)})}),medications:$e(e.medications,Ln),supplements:$e(e.supplements,Ln),conditions:$e(e.conditions,r=>{let n=F(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),conditionName:n,diagnosedDate:F(r.diagnosed_date),notes:F(r.notes)})})})}i(Wn,"petHealthFromWire");var Xn=100,Qn=50,Jn=100,Zn=50,eo=500,ya=128,ga=6e4;function Z(e){return S("validationFailed",{retryable:false,wireMessage:e})}i(Z,"invalid");function se(e,t,r){if(typeof t!="string")return Z(`${e} must be a string`);let n=Ne(t);return n<=r?null:Z(`${e} is ${n} characters; the server accepts at most ${r}`)}i(se,"checkString");function We(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Z(`${e} must be a finite number between 0 and ${r}`)}i(We,"outOfRange");function Gn(e,t){if(typeof e!="string")return Z("pet_ref must be a string");if(e.trim().length===0)return Z("pet_ref must not be blank");if(L(e))return Z("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Z("profile must be an object");let r=[se("pet_ref",e,ya)];return t?.name!==void 0&&r.push(se("name",t.name,Xn)),t?.species!==void 0&&r.push(se("species",t.species,Qn)),t?.breed!==void 0&&r.push(se("breed",t.breed,Jn)),t?.ageYears!==void 0&&r.push(We("age_years",t.ageYears,Zn)),t?.weightKg!==void 0&&r.push(We("weight_kg",t.weightKg,eo)),r.find(n=>n!==null)??null}i(Gn,"validate");function to(e,t){let r=Vn(e,t);return "error"in r?{error:Z(r.error)}:r}i(to,"healthToWire");function ha(e){if(typeof e!="object"||e===null)return {error:Z("patch must be an object")};let t=e,r=[["name","name",s=>se("name",s,Xn)],["species","species",s=>se("species",s,Qn)],["breed","breed",s=>se("breed",s,Jn)],["ageYears","age_years",s=>We("age_years",s,Zn)],["weightKg","weight_kg",s=>We("weight_kg",s,eo)]],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=to(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Z("patch must change at least one field")}:{body:n})}i(ha,"patchToWire");function ba(e){if(e==null)return {body:{}};let t=to(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(ba,"toWire");var J=i(e=>typeof e=="string"?e:null,"str"),Ge=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Yn(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:J(r.pet_ref)??t,name:J(r.name),species:J(r.species),breed:J(r.breed),ageYears:Ge(r.age_years),weightKg:Ge(r.weight_kg)})}i(Yn,"fromWire");function ro(e){if(typeof e!="object"||e===null)return null;let t=e,r=J(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:J(t.pet_id),petRef:r,name:J(t.name),species:J(t.species),breed:J(t.breed),ageYears:Ge(t.age_years),weightKg:Ge(t.weight_kg),updatedAt:J(t.updated_at)})}i(ro,"widgetPetFromWire");function va(e){let t=ro(e);return t===null?null:Object.freeze({...t,...Wn(e)})}i(va,"widgetPetProfileFromWire");function _a(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=ro(r);return n===null?[]:[n]}))}i(_a,"petListFromWire");function no(e){return Ra($({auth:e}),$({auth:e,unaryTimeoutMs:ga}))}i(no,"createPetsRepository");function Ra(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Gn(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?_(_a(s.value)):p(s.error)},async registerPet(o,s,l){let u=Gn(o,s);if(u!==null)return p(u);let a=ba(s);if("error"in a)return p(a.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:a.body},f=await e.send("pets.registerPet",l?.signal?{...c,signal:l.signal}:c);return f.ok?_(Yn(f.value,o)):p(f.error)},async updatePet(o,s,l){let u=n(o);if(typeof u!="string")return p(u);let a=ha(s);if("error"in a)return p(a.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:u,body:a.body},l?.signal));return d.ok?_(Yn(d.value,o)):p(d.error)},async getPetProfile(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},s?.signal));if(!u.ok)return p(u.error);let a=va(u.value);return a===null?p(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 p(l);let u=await e.send("pets.deletePet",r({method:"DELETE",path:l},s?.signal));return u.ok?_(void 0):p(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):p(s.error)}}}i(Ra,"createPetsRepositoryOver");var oo=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 io(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(oo))for(let l of oo[s])o.has(l)||(o.add(l),n.push(Object.freeze({resource:l,granted:false,disabled:r})));return Object.freeze(n)}i(io,"deniedDecisionsFor");function re(e){let t=Ea(e);return t===null?null:Sa(t)}i(re,"parseColor");function Ea(e){if(typeof e=="number")return so(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Ot(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Ot(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ca(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=Ot(t);if(r!==null)return r}return /^\d+$/.test(t)?so(Number.parseInt(t,10)):null}i(Ea,"toRgba");function Ot(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:At(t[0]),g:At(t[1]),b:At(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(Ot,"fromHex");function Ca(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=Ft(Number(n[0])),s=Ft(Number(n[1])),l=Ft(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(Ca,"fromRgbFunc");function so(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(so,"argbIntToRgba");function ae(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ae,"byte");function At(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(At,"dup");function Ft(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Ft,"clampByte");function Sa(e){if(e.a>=1)return wa(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Sa,"normalizeRgba");function wa(e,t,r){return `#${Mt(e)}${Mt(t)}${Mt(r)}`.toUpperCase()}i(wa,"rgbToHex");function Mt(e){return e.toString(16).padStart(2,"0")}i(Mt,"hex2");var Dt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]);function ka(e){return Dt.includes(e)}i(ka,"isSlotName");function Ta(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(Ta,"parseRadius");function ao(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(!ka(n)||o===null||typeof o!="object")continue;let s=Pa(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(ao,"parseThemeSlots");function Ye(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Ye,"pick");function Pa(e){let t={},r=re(Ye(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=re(Ye(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Ta(Ye(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=re(Ye(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Pa,"parseSlot");var co=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"]),Xe="slots.";function po(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(po,"isEmptyBranding");function Ia(e){return e==="hide_powered_by"||co.includes(e)?true:e.startsWith(Xe)&&Dt.includes(e.slice(Xe.length))}i(Ia,"isThemeLockName");function ke(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:le(x(t,"display_name","displayName")),logoUrl:le(x(t,"logo_url","logoUrl")),primaryColor:re(x(t,"primary_color","primaryColor")),accentColor:re(x(t,"accent_color","accentColor")),brightness:Ma(x(t,"brightness","color_scheme","colorScheme")),fontFamily:le(x(t,"font_family","fontFamily")),fontUrl:le(x(t,"font_url","fontUrl")),fonts:lo(x(t,"fonts")),fontUrls:lo(x(t,"font_urls","fontUrls")),placeholder:le(x(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Oa(x(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:re(x(t,"primary_color_dark","primaryColorDark")),accentColorDark:re(x(t,"accent_color_dark","accentColorDark")),surfaceStyle:uo(x(t,"surface_style","surfaceStyle"),Aa),radiusScale:uo(x(t,"radius_scale","radiusScale"),Fa),logoUrlDark:le(x(t,"logo_url_dark","logoUrlDark")),slots:ao(x(t,"slots")),accessibilityMaxFontScale:ja(x(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:La(x(t,"locked_fields","lockedFields")),schemaVersion:za(x(t,"schema_version","schemaVersion"))};return po(r)?null:Object.freeze(r)}i(ke,"parseClientBranding");function Oa(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(Oa,"parseBool");function x(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(x,"pick");function le(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(le,"parseNonEmptyString");var fo=["regular","medium","bold","mono","monoMedium","monoBold"];function lo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of fo){let o=le(x(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(lo,"parseFaceMap");var Aa=["white","cream","subtle"],Fa=["sharp","default","round"];function uo(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(uo,"parseEnum");function Ma(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(Ma,"parseBrightness");function mo(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(mo,"parseNumber");var Da=1,yo=3.1;function ja(e){let t=mo(e);return t===null?null:t<=0?0:Math.min(yo,Math.max(Da,t))}i(ja,"parseMaxFontScale");function za(e){if(e==null)return null;let t=mo(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(za,"parseSchemaVersion");function go(e){let t=e.trim();return t.startsWith(Xe)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(go,"toWireName");function La(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=go(r);Ia(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(La,"parseLockedFields");var ho="/widget/v1/entitlements",Ua=304,Na=Object.freeze({kind:"notModified"});async function vo(e,t={},r=$({auth:e})){let n=await r.send("entitlements.fetch",qa(t));return n.ok?Ha(n.value):n.error.httpStatus===Ua?Na:{kind:"failed",error:n.error}}i(vo,"fetchEntitlements");var Ba=64;function qa(e){let t={};return jt(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Ba?{method:"GET",path:ho,headers:t,query:{region:e.region}}:{method:"GET",path:ho,headers:t}}i(qa,"buildRequest");function Ha(e){if(e===null||typeof e!="object"||!jt(e.revision))return bo();let t=typeof e.region=="string"?e.region:"",r=jt(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:$a(e.capabilities),branding:Ka(e)})}i(Ha,"parseUpdated");function Ka(e){let t=ke(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=ke(r.branding);return n!==null?n:ke(r)}return null}i(Ka,"parseBranding");function $a(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Va(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i($a,"mapCapabilities");function Va(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Va,"isEnabled");function bo(){return {kind:"failed",error:S("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(bo,"malformed");function jt(e){return typeof e=="number"&&Number.isFinite(e)}i(jt,"isFiniteNumber");var Wa=30;function _o(e){let t=e.scheduler??Ga,r=e.resolve??vo,n=Math.max(1,e.floorSeconds??Wa),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),l=false,u=false,a=null,d=null,c=n,f=0,h=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,T=i(async()=>{if(u)return null;let P=f;e.onFetch?.();let O=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},D;try{D=await r(e.authFor(),O);}catch(A){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Ya(A)}),!u&&P===f&&(e.onSettled?.(),y(s())),null}if(u||P!==f)return null;switch(D.kind){case "updated":d=D.revision,e.update(D.decisions,D.branding??null),y(D.ttlSeconds);break;case "notModified":y(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:D.error.code}),y(s());break;default:y(s());}return e.onSettled?.(),D},"tick"),C=i(()=>{let P=T().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,f++,h());},refresh(){u||!l||(f++,d=null,h(),C());}}}i(_o,"createEntitlementPoller");var Ga={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function Ya(e){return e instanceof Error?e.message:"poll failed"}i(Ya,"describe");var Ro="everfur.notifications.device";var Co=3e3,Eo=Object.freeze([Ro]);function So(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(f=>f.status==="rejected").length;c>0&&u("failed",c);});return new Promise(d=>{let c=false,f=i(()=>{c||(c=true,clearTimeout(h),d());},"finish"),h=setTimeout(()=>{c||u("timeout",l.length),f();},Co);a.then(f,f);})}i(So,"startBeforeLogoutHooks");function wo(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(wo,"graceAuth");async function ko(e,t){if(Eo.length===0)return;let r=await Promise.allSettled(Eo.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(ko,"sweepPerUserKv");function Xa(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Xa,"compiledDefaultDecisions");function zt(e=Xa){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}),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(zt,"createEntitlementStore");function Lt(e){return S("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Lt,"notConfiguredError");function To(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 Mr(r,t===void 0?void 0:{platform:t})}i(To,"tryResolveClient");function Po(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Po,"guardTelemetry");function xo(e,t){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. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(xo,"reportConfigFailure");function Ut(e){return Object.freeze({request(){return Promise.resolve(p(Lt(e)))},stream(t,r){let n=N({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(Ut,"refusingTransport");function Io(){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(Io,"createInMemoryKv");var Oo=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function Np(e,t){return new Bt(e,t)}i(Np,"createEverfurRuntime");var Qa=6e4,qt=class qt{constructor(t,r){this.sessionId=st();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 K("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?Po(n.telemetry):Me;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=lt(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=Ut(s);else if(n.transport!==void 0)u=n.transport;else {let c=To(n,r?.platform);c.ok?(a=c.config.apiBaseUrl,u=Nr({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,u=Ut(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=u,s!==null&&xo(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??br,this.upload=n.upload??sn,this.uploadTransport=n.uploadTransport??Tt,this.imageCache=n.imageCache??Oo,this.kv=n.storage??Io(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?zt():zt(()=>io("sdk_config",ot("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",Nt(c),()=>this.buildChatController(c),Ao),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Nt(c)}`)?.controller??null,"peekChat"),acquire:i((c,f,h,y)=>this.acquireInternal(c,f,h,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=Tr(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-Qa,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 _o({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"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=Sn({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=Tn(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=st(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await ko(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 So({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>wo({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?p(Fo(t)):r(no(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?Fo("prepare"):n===null?null:Lt(n),s=this.identity,[l,u,a]=await Promise.all([o?p(o):s===null?_(void 0):s.currentToken().then(()=>_(void 0),()=>p(S("authRejected",{retryable:false}))),o?p(o):this.primeEntitlements(),t===null?void 0:o?p(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"?p(t.error):_(void 0):p(S("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Nt(r),()=>this.buildChatController(r),Ao,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?p(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(qt,"EverfurRuntimeImpl");var Bt=qt;function Nt(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Nt,"chatScopeKey");function Ao(e){e.dispose();}i(Ao,"disposeChat");function Fo(e){return S("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Fo,"disposedError");var jo=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Mo=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 Ja(e){let t=Object.prototype.hasOwnProperty.call(Mo,e)?Mo[e]:void 0;if(t!==void 0)return t;let r=e;return jo.has(r)?r:"parsing"}i(Ja,"normalizeStatus");function Za(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Za,"normalizeOrigin");var el=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 zo(e){let t=el.safeParse(e);if(!t.success)return null;let r=t.data,n=tl(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??Ja(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:Do(r.document_count,0),heldItemCount:Do(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(zo,"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 tl(e){return !e||e==="awaiting_upload"||e==="in_review"?null:jo.has(e)?e:null}i(tl,"normalizeSimpleStatus");zod.z.object({source_doc_id:zod.z.string().min(1),request_id:zod.z.string().min(1)});var rl=zod.z.object({label:zod.z.string(),value:zod.z.string()}),Ht=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()}),nl=zod.z.object({at:zod.z.string(),value:zod.z.number().nullish(),display:zod.z.string().nullish(),origin:zod.z.string().nullish()}),ol=zod.z.object({key:zod.z.string(),label:zod.z.string().optional(),points:zod.z.array(nl).optional()}),il=zod.z.object({title:zod.z.string(),detail:zod.z.string().nullish(),due_at:zod.z.string().nullish()}),Kt=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 Lo(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:Za(e.origin),canonicalKey:e.canonical_key??null})}i(Lo,"mapEntityRow");function Uo(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Uo,"mapDocumentRow");zod.z.object({identity:zod.z.array(rl).optional(),entities:zod.z.array(Ht).optional(),entity_series:zod.z.array(ol).optional(),forward_looking:zod.z.array(il).optional(),documents:zod.z.array(Kt).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 Do(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Do,"numberOr");var Bo=10,Qe=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),Te=i((e,t=1)=>zod.z.string().refine(r=>!L(r)&&[...r].length>=t&&[...r].length<=e),"text"),qo=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),sl=zod.z.object({clinicId:Qe.optional(),clinicFreeText:Te(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Te(320,3).refine(e=>!qo(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Qe.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)),al=zod.z.object({petRef:Te(128),ownerName:Te(200).refine(e=>e.trim().length>0&&!qo(e)),authorizationVersion:Te(64),clinics:zod.z.array(sl).min(1).max(Bo)}).strict(),ll=zod.z.object({request_group_id:Qe,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:Qe.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??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!al.safeParse(r).success)return p(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=ll.safeParse(n.value);if(!o.success||o.data.pet_ref!==r.petRef)return No();let s=[];for(let l of o.data.results){let u=l.request===void 0||l.request===null?null:zo(l.request);if(l.created!==(u!==null))return No();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 No(){return p(S("internalError",{retryable:false}))}i(No,"malformed");var dl="records_consent_required";function cl(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(cl,"recordsWireCodeOf");function Ho(e){return e===null||e.httpStatus!==409?false:cl(e)===dl}i(Ho,"isRecordsConsentRequired");var $t="value_text",Ko=64,$o=512;function pl(e){return e!==null&&e.httpStatus===409&&!Ho(e)}i(pl,"isFactReviewerLocked");function fl(e){return Object.freeze({[$t]:e.trim()})}i(fl,"factValueCorrection");var Pe=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:$t}),Vo=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Wo=/^\d{4}-\d{2}-\d{2}$/;function Go(e){if(e==null)return "text";let t=e.trim();return Vo.test(t)?"num":Wo.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(Go,"inferFactValueKind");function ml(e,t){let r=t.trim(),n=Go(e);if(n==="num"&&Vo.test(r)){let o=Number(r);if(Number.isFinite(o))return Object.freeze({[Pe.num]:o})}return n==="date"&&Wo.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Pe.date]:r}):Object.freeze(n==="bool"&&(r==="true"||r==="false")?{[Pe.bool]:r==="true"}:{[Pe.text]:r})}i(ml,"factCorrectionFor");var k=zod.z.string().nullish(),Je=zod.z.number().nullish(),yl=zod.z.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,ref_low:Je,ref_high:Je,status:k,source_clinic:k,source_doc_id:k,doc_id:k,reviewed:zod.z.boolean().nullish()}),gl=zod.z.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,status:k}),hl=zod.z.object({marker_id:zod.z.string().min(1),canonical_name:k,name:k,loinc_code:k,canonical_unit:k,unit:k,panel_name:k,panel:k,meaning_text:k,meaning:k,latest:gl.nullish(),trajectory:k,points:zod.z.array(yl).optional()}),bl=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()}),vl=zod.z.object({markers:zod.z.array(hl).optional(),summary:bl.nullish(),disclaimer:zod.z.string().optional(),featured_marker_id:k});function _l(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(_l,"isObject");function Yo(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Yo,"withheldMarkers");function Vt(e,t){let r=_l(t)?t:{},n=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Yo(n);let o=vl.safeParse(r);if(!o.success)return Yo(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(Vt,"mapRecordMarkers");var Rl=zod.z.string().min(1).refine(e=>e.startsWith("https://")),El=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:Rl,expires_in_seconds:zod.z.number().int().nonnegative().nullish()}),Cl=zod.z.object({items:zod.z.array(zod.z.unknown()).optional()});function Xo(e){let t=Cl.safeParse(e);if(!t.success)return null;let r=[];for(let n of t.data.items??[]){let o=El.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(Xo,"mapRequestDocuments");var Sl=zod.z.string().min(1).refine(e=>e.startsWith("https://")),xe=zod.z.string().nullish(),wl=zod.z.object({share_id:zod.z.string().min(1),share_url:zod.z.string().min(1),expires_at:xe}),kl=zod.z.object({shares:zod.z.array(zod.z.object({share_id:zod.z.string().min(1),expires_at:xe,created_at:xe,view_count:zod.z.number().int().nonnegative().nullish(),last_viewed_at:xe})).optional()}),Tl=zod.z.object({download_url:Sl,expires_at:xe});function Qo(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(Qo,"resolveShareUrl");function Wt(e,t){let r=wl.safeParse(e);if(!r.success)return null;let n=Qo(r.data.share_url,t);return n===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:n,expiresAt:r.data.expires_at??null})}i(Wt,"mapRecordShareLink");function Gt(e){let t=kl.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}))):null}i(Gt,"mapRecordShareList");function Yt(e){let t=Tl.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Yt,"mapRecordPdfLink");var Pl=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 Xt(e){let t=Pl.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(Xt,"mapSignatureSuggestions");var b=zod.z.string().nullish(),Ie=zod.z.number().nullish(),xl=zod.z.object({at:b,value:Ie,unit:b,qualitative_result:b,ref_low:Ie,ref_high:Ie,status:b,doc_id:b}),Il=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:Ie,unit:b,qualitative_result:b,status:b}).nullish(),trajectory:b,points:zod.z.array(xl).optional()}),Ol=zod.z.object({encounter_id:zod.z.string(),date:b,type:b,clinic_name:b,veterinarian:b,doc_id:b}),Al=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()}),Fl=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()}),Ml=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()}),Dl=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()}),jl=zod.z.object({lab_results:zod.z.array(Il).optional(),encounters:zod.z.array(Ol).optional(),clinician_notes:zod.z.array(Al).optional(),physical_exams:zod.z.array(Fl).optional(),completeness:Ml.nullish(),conflicts:zod.z.array(Dl).optional()}),zl=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:Ie,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()}),Ll=zod.z.object({document:Kt,contributions:zod.z.array(Ht),contribution_count:zod.z.number().int().nonnegative().optional()});function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Jt,"isObject");function Zt(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Zt,"petOf");function Qt(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(Qt,"emptyDepth");function Zo(e,t){let r=Jt(t)?t:{},n=Zt(r,e);if(r.withheld===true)return Qt(n,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Qt(n,false);let s=jl.safeParse(r);if(!s.success)return Qt(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(Zo,"mapRecordDepth");function Jo(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Jo,"withheldTimeline");function ei(e,t){let r=Jt(t)?t:{},n=Zt(r,e);if(r.withheld===true)return Jo(n);let o=zl.safeParse(r);if(!o.success)return Jo(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(ei,"mapRecordsTimeline");function ti(e,t){let r=Jt(t)?t:{},n=Zt(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=Ll.safeParse(r);if(!s.success)return o();let l=Object.freeze(s.data.contributions.map(Lo));return Object.freeze({petRef:n,withheld:false,document:Uo(s.data.document),contributions:l,contributionCount:s.data.contribution_count??l.length})}i(ti,"mapDocumentContributions");var Ul="/widget/v1/records/pets";function Nl(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!L(a)&&[...a].length<=d,"segment"),n=i(async(a,d,c,f)=>{if(!r(d,oe))return ne();let h=await t.send(a,{method:"GET",path:c});if(!h.ok)return h;let y=f(h.value);return y.petRef===d?_(y):p(S("internalError",{retryable:false}))},"read"),o=i(a=>`${Ul}/${encodeURIComponent(a)}`,"pet"),s=i(a=>`${o(a)}/everfur_record`,"record"),l=i(async(a,d,c)=>{let f=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!f.ok)return f;let h=c(f.value);return h===null?p(S("internalError",{retryable:false})):_(h)},"parsed"),u=i((a,d)=>!r(a.entityType,Ko)||!r(a.canonicalKey,$o)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,xn)||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=>Zo(a,d)),"getRecordDepth"),getTimeline:i(a=>n("records.depth.timeline",a,`${o(a)}/timeline`,d=>ei(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?n("records.depth.contributions",a,`${o(a)}/documents/${encodeURIComponent(d)}/contributions`,c=>ti(a,c)):ne()},getMarkers:i(a=>n("records.depth.markers",a,`${o(a)}/markers`,d=>Vt(a,d)),"getMarkers"),createShare(a){return r(a,oe)?l("records.share.create",{method:"POST",path:`${s(a)}/share`},d=>Wt(d,e.apiBaseUrl)):ne()},listShares(a){return r(a,oe)?l("records.share.list",{method:"GET",path:`${s(a)}/shares`},Gt):ne()},async revokeShare(a,d){if(!r(a,oe)||!r(d,64))return ne();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`},Yt):ne()},async editFact(a,d){let c=r(a,oe)?u(d,d.correctedFields):null;if(c===null)return ne();let f=await t.send("records.fact.edit",{method:"POST",path:`${s(a)}/facts/edit`,body:c},{idempotent:false,maxAttempts:1});return f.ok?_(void 0):f},async removeFact(a,d){let c=r(a,oe)?u(d):null;if(c===null)return ne();let f=await t.send("records.fact.remove",{method:"POST",path:`${s(a)}/facts/remove`,body:c},{idempotent:false,maxAttempts:1});return f.ok?_(void 0):f},listRequestDocuments(a){return r(a,64)?l("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},Xo):ne()},listAuthorizationSignatures:i(()=>l("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Xt),"listAuthorizationSignatures")}}i(Nl,"createRecordsDepthClient");function ne(){return Promise.resolve(p(S("validationFailed",{retryable:false})))}i(ne,"invalid");var Ae=Object.freeze({width:360,height:120});function ii(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(ii,"blank");function si(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(si,"stamp");var Bl=16384;function ql(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(ql,"padPoint");function Hl(e,t,r,n,o){let[s,l]=t,[u,a]=r,d=Math.abs(u-s),c=-Math.abs(a-l),f=s<u?1:-1,h=l<a?1:-1,y=d+c,R=0;for(;R<o&&(si(e,s,l,n),R+=1,!(s===u&&l===a));){let T=2*y;T>=c&&(y+=c,s+=f),T<=d&&(y+=d,l+=h);}return R}i(Hl,"line");function Kl(e,t=1){let r=ii(Ae.width,Ae.height);for(let n of e){let o=[];for(let l of n){let u=ql(l,r);u!==null&&o.push(u);}if(o.length===0)continue;if(o.length===1){let[l,u]=o[0];si(r,l,u,t);continue}let s=Bl;for(let l=1;l<o.length&&s>0;l+=1)s-=Hl(r,o[l-1],o[l],t,s);}return r}i(Kl,"rasterizeStrokes");var $l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",Vl="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",Wl="0123456789abcdefghijklmnopqrstuv",ir=5,sr=7,er=ir+1;function Gl(e,t){let r=$l.indexOf(e);return r<0?0:Wl.indexOf(Vl.charAt(r*sr+t))}i(Gl,"glyphRow");function Yl(e){let t=ii(Ae.width,Ae.height),r=e.trim();if(r.length===0)return t;let n=[...r],o=4;for(;o>1&&(n.length*er-1)*o>t.width-8;)o-=1;let s=(n.length*er-1)*o,l=Math.max(0,Math.floor((t.width-s)/2)),u=Math.floor((t.height-sr*o)/2);return n.forEach((a,d)=>{let c=l+d*er*o;for(let f=0;f<sr;f+=1){let h=Gl(a,f);for(let y=0;y<ir;y+=1)if((h>>ir-1-y&1)!==0)for(let R=0;R<o;R+=1)for(let T=0;T<o;T+=1){let C=c+y*o+T,P=u+f*o+R;C<t.width&&P<t.height&&(t.pixels[P*t.width+C]=1);}}}),t}i(Yl,"rasterizeTypedName");var ur=class ur{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(ur,"BitWriter");var ar=ur;function lr(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(lr,"writeLiteral");var tr=[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],ri=[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],rr=[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],ni=[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 Xl(e,t,r){let n=tr.length-1;for(;tr[n]>t;)n-=1;lr(e,257+n),ri[n]>0&&e.writeBits(t-tr[n],ri[n]);let o=rr.length-1;for(;rr[o]>r;)o-=1;e.writeCode(o,5),ni[o]>0&&e.writeBits(r-rr[o],ni[o]);}i(Xl,"writeMatch");var Ql=32768,nr=3,Jl=258,oi=15,Zl=64;function eu(e){let t=new ar;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<oi).fill(-1),n=new Int32Array(e.length).fill(-1),o=i(u=>(e[u]<<10^e[u+1]<<5^e[u+2])&(1<<oi)-1,"hashAt"),s=i(u=>{if(u+nr>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+nr<=e.length){let d=r[o(l)],c=0,f=Math.min(Jl,e.length-l);for(;d>=0&&c<Zl&&l-d<=Ql;){let h=0;for(;h<f&&e[d+h]===e[l+h];)h+=1;if(h>u&&(u=h,a=l-d,h===f))break;d=n[d],c+=1;}}if(u>=nr){Xl(t,u,a);for(let d=0;d<u;d+=1)s(l+d);l+=u;}else lr(t,e[l]),s(l),l+=1;}return lr(t,256),t.finish()}i(eu,"deflate");function tu(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(tu,"adler32");var Ze=null;function ru(e){if(Ze===null){Ze=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;Ze[r]=n>>>0;}}let t=4294967295;for(let r of e)t=Ze[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(ru,"crc32");function Oe(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(Oe,"u32");function or(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),[...Oe(t.length),...n,...Oe(ru(n))]}i(or,"chunk");var et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function nu(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+=et.charAt(l>>18&63)+et.charAt(l>>12&63),t+=r+1<e.length?et.charAt(l>>6&63):"=",t+=r+2<e.length?et.charAt(l&63):"=";}return t}i(nu,"toBase64");function ou(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 f=c*o;s[f]=0,s.fill(255,f+1,f+o);for(let h=0;h<t;h+=1)if(n[c*t+h]===1){let y=f+1+(h>>3);s[y]=s[y]&~(128>>(h&7));}}let l=eu(s),u=new Uint8Array(2+l.length+4);u[0]=120,u[1]=1,u.set(l,2),u.set(Oe(tu(s)),2+l.length);let a=Uint8Array.from([...Oe(t),...Oe(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...or("IHDR",a),...or("IDAT",u),...or("IEND",new Uint8Array(0))]);return nu(d)}i(ou,"encodeSignaturePng");
|
|
13
|
+
exports.ATTACHMENT_ACCEPT=mc;exports.ATTACHMENT_BACKOFF_MS=ta;exports.ATTACHMENT_INITIATE_PATH=Ks;exports.ATTACHMENT_MAX_ATTEMPTS=ea;exports.ATTACHMENT_MIME_TYPES=qs;exports.ATTACHMENT_QUEUE_CONCURRENCY=Zs;exports.CHAT_FEEDBACK_TYPES=Rt;exports.CHECKIN_ANSWERABLE_STATUS=he;exports.FACT_FIELD_BY_KIND=Pe;exports.FACT_VALUE_FIELD=$t;exports.FEEDBACK_NOTES_MAX_CHARS=Et;exports.LOGOUT_HOOK_BUDGET_MS=Co;exports.MAX_ATTACHMENTS_PER_MESSAGE=Hs;exports.MAX_ATTACHMENT_BYTES=On;exports.MAX_FILENAME_LENGTH=Ee;exports.MAX_IMAGE_KEYS_PER_MESSAGE=Ke;exports.MESSAGE_MAX_CHARS=Ct;exports.MIN_POLL_INTERVAL_SECONDS=Wa;exports.NULL_SECURE_STORE=uu;exports.RECORDS_CLINIC_BATCH_MAX=Bo;exports.SIGNATURE_CANVAS=Ae;exports.attachmentSize=Ws;exports.bootstrapChat=Tn;exports.createAttachmentQueue=gc;exports.createChatController=Sn;exports.createEntitlementPoller=_o;exports.createEverfurRuntime=Np;exports.createRecordsClinicBatchClient=ul;exports.createRecordsDepthClient=Nl;exports.defaultErrorPolicy=hr;exports.encodeSignaturePng=ou;exports.factCorrectionFor=ml;exports.factValueCorrection=fl;exports.formatBytes=yc;exports.inferFactValueKind=Go;exports.initiateAttachmentUpload=Qs;exports.isAttachmentMime=$s;exports.isCheckinSettled=As;exports.isFactReviewerLocked=pl;exports.mapDocumentContributions=ti;exports.mapRecordDepth=Zo;exports.mapRecordMarkers=Vt;exports.mapRecordPdfLink=Yt;exports.mapRecordShareLink=Wt;exports.mapRecordShareList=Gt;exports.mapRecordsTimeline=ei;exports.mapSignatureSuggestions=Xt;exports.noopTelemetry=Me;exports.optionalModule=ku;exports.rasterizeStrokes=Kl;exports.rasterizeTypedName=Yl;exports.resolveShareUrl=Qo;exports.sanitizeFilename=Vs;exports.unavailableCamera=br;exports.uploadAttachmentBytes=Js;exports.validateAttachment=Gs;
|