@everfur/sdk 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +311 -0
- package/README.md +24 -16
- package/dist/{Chat-CFi5cNUF.d.ts → Chat-Cv9EYMYA.d.ts} +3 -3
- package/dist/{Chat-DQOsAumH.d.cts → Chat-s2vcPbw3.d.cts} +3 -3
- package/dist/{DepthViews-uilL1NJZ.d.ts → DepthViews-CVxUHOJ-.d.ts} +1 -1
- package/dist/{DepthViews-C409ubw-.d.cts → DepthViews-Cz7mSW7p.d.cts} +1 -1
- package/dist/{DepthViews-es8mIK0w.d.ts → DepthViews-DNRY0Ugm.d.ts} +1 -1
- package/dist/{DepthViews-D81c95Ra.d.cts → DepthViews-DvNixbxg.d.cts} +1 -1
- package/dist/{ErrorPolicyPort-D22LUVrK.d.ts → ErrorPolicyPort-DwSnmGcX.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-D6CybiqJ.d.cts → ErrorPolicyPort-NFDPe-5w.d.cts} +1 -1
- package/dist/{EverfurError-DmELDpXp.d.cts → EverfurError-pEXDbUJ1.d.cts} +9 -1
- package/dist/{EverfurError-DmELDpXp.d.ts → EverfurError-pEXDbUJ1.d.ts} +9 -1
- package/dist/{EverfurResult-ZtH-YV1h.d.cts → EverfurResult-dtl8ERAw.d.cts} +1 -1
- package/dist/{EverfurResult-SGvHKsCB.d.ts → EverfurResult-sKkoXew0.d.ts} +1 -1
- package/dist/IntakeMedia-BFZfBLjB.d.cts +116 -0
- package/dist/{IntakeMedia-BcjjUizr.d.ts → IntakeMedia-BH0fYDT2.d.cts} +19 -2
- package/dist/{IntakeMedia-CL_S2tZE.d.cts → IntakeMedia-Bavl7E4Z.d.ts} +19 -2
- package/dist/IntakeMedia-C8GlN_GK.d.ts +116 -0
- package/dist/animations/index.cjs +109 -1
- package/dist/animations/index.d.cts +6 -6
- package/dist/animations/index.d.ts +6 -6
- package/dist/animations/index.js +109 -1
- package/dist/{attachments-DNaSbmA3.d.ts → attachments-BaslXMdS.d.ts} +3 -3
- package/dist/{attachments-DI710no4.d.cts → attachments-DbFwz4iq.d.cts} +7 -7
- package/dist/{attachments-B2GjBgvF.d.cts → attachments-y3EcOX_w.d.cts} +3 -3
- package/dist/{attachments-SF88N654.d.ts → attachments-y_aO4hlk.d.ts} +7 -7
- package/dist/{bookingCopy-xlXxORCA.d.cts → bookingCopy-4i1R7klo.d.cts} +15 -7
- package/dist/{bookingCopy-D2N3RhsV.d.ts → bookingCopy-B3UMITD-.d.ts} +15 -7
- package/dist/{branding-ytH4jJq1.d.ts → branding-BYEqU855.d.ts} +1 -1
- package/dist/{branding-Bio5MM6g.d.cts → branding-BwEu68C8.d.cts} +1 -1
- package/dist/{callRoom-7wrE3RP2.d.ts → callRoom-B1qq_D-4.d.ts} +1 -1
- package/dist/{callRoom-B_EqaUzx.d.cts → callRoom-DfZTWFXh.d.cts} +1 -1
- package/dist/{casesRepository-B-md8h1S.d.cts → casesRepository-B6Z0XBIb.d.cts} +2 -2
- package/dist/{casesRepository-CC6951TK.d.ts → casesRepository-SI0zp5YH.d.ts} +2 -2
- package/dist/chat/index.cjs +333 -1
- package/dist/chat/index.d.cts +12 -12
- package/dist/chat/index.d.ts +12 -12
- package/dist/chat/index.js +333 -1
- package/dist/client/index.cjs +115 -11
- package/dist/client/index.d.cts +14 -14
- package/dist/client/index.d.ts +14 -14
- package/dist/client/index.js +115 -11
- package/dist/{config-BM0sv5jx.d.ts → config-Cvo47voG.d.ts} +3 -3
- package/dist/{config-Daa1plhQ.d.cts → config-v5k6NsK_.d.cts} +3 -3
- package/dist/consent/index.cjs +112 -1
- package/dist/consent/index.d.cts +9 -9
- package/dist/consent/index.d.ts +9 -9
- package/dist/consent/index.js +112 -1
- package/dist/{context-DQHtwcHN.d.cts → context-BZOtJbBO.d.cts} +9 -9
- package/dist/{context-CDV2pwGI.d.ts → context-cZ7NZ0sG.d.ts} +9 -9
- package/dist/{copy-Cl1l-qmY.d.ts → copy-CZBUHbyS.d.ts} +5 -5
- package/dist/{copy-BEx5F71o.d.cts → copy-ChJupm1p.d.cts} +5 -5
- package/dist/core/index.cjs +140 -13
- package/dist/core/index.d.cts +19 -19
- package/dist/core/index.d.ts +19 -19
- package/dist/core/index.js +140 -13
- package/dist/{depth-CAAwiStc.d.cts → depth-CRyU7-pf.d.cts} +7 -6
- package/dist/{depth-DfNRVtrV.d.ts → depth-vNpwOkZ8.d.ts} +7 -6
- package/dist/{entitlementRepository-DPvWjV-N.d.cts → entitlementRepository-Bv8nSYRd.d.cts} +4 -4
- package/dist/{entitlementRepository-CVWvND1P.d.ts → entitlementRepository-CUdxbQrP.d.ts} +4 -4
- package/dist/{identity-BhT7oJDS.d.ts → identity-B8GkH53J.d.ts} +2 -2
- package/dist/{identity-DUlshgow.d.cts → identity-BHaMJ3KK.d.cts} +2 -2
- package/dist/index.cjs +363 -12
- package/dist/index.d.cts +19 -19
- package/dist/index.d.ts +19 -19
- package/dist/index.js +363 -12
- package/dist/{models-DSqA5Ahs.d.ts → models-CrbUwbuS.d.ts} +1 -1
- package/dist/{models-Bn2z0NNo.d.cts → models-DzvqEjMm.d.cts} +1 -1
- package/dist/notifications/index.cjs +94 -2
- package/dist/notifications/index.d.cts +5 -5
- package/dist/notifications/index.d.ts +5 -5
- package/dist/notifications/index.js +94 -2
- package/dist/{pets-Bneph9m1.d.cts → pets-BI7Ji8hi.d.cts} +2 -2
- package/dist/{pets-DjcLmRrW.d.ts → pets-Dnn-DK1T.d.ts} +2 -2
- package/dist/{petsRepository-BwxmfX_s.d.ts → petsRepository-B2lO1sKS.d.ts} +2 -2
- package/dist/{petsRepository-BnVre3q7.d.cts → petsRepository-BP9nhM1R.d.cts} +2 -2
- package/dist/photo/index.cjs +131 -1
- package/dist/photo/index.d.cts +3 -3
- package/dist/photo/index.d.ts +3 -3
- package/dist/photo/index.js +131 -1
- package/dist/{ports-Di9rdLO9.d.ts → ports-BUXF0Rp3.d.ts} +7 -7
- package/dist/{ports-BPKxFOSe.d.cts → ports-C40S2V14.d.cts} +7 -7
- package/dist/records/depth/index.cjs +200 -2
- package/dist/records/depth/index.d.cts +11 -11
- package/dist/records/depth/index.d.ts +11 -11
- package/dist/records/depth/index.js +200 -2
- package/dist/records/index.cjs +742 -4
- package/dist/records/index.d.cts +22 -14
- package/dist/records/index.d.ts +22 -14
- package/dist/records/index.js +742 -4
- package/dist/{requestFunnel-CiSX2pun.d.ts → requestFunnel-BrOijMcw.d.ts} +5 -5
- package/dist/{requestFunnel-DMR_1T3O.d.cts → requestFunnel-BxNVGyGm.d.cts} +5 -5
- package/dist/{runtimeTypes-CkMFCbHW.d.ts → runtimeTypes-CvI1ZH8j.d.ts} +7 -7
- package/dist/{runtimeTypes-2gJ5hYoE.d.cts → runtimeTypes-DOO3f-W-.d.cts} +7 -7
- package/dist/server/events/index.cjs +92 -2
- package/dist/server/events/index.d.cts +4 -4
- package/dist/server/events/index.d.ts +4 -4
- package/dist/server/events/index.js +92 -2
- package/dist/server/index.cjs +95 -2
- package/dist/server/index.d.cts +5 -5
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +95 -2
- package/dist/televet/booking/index.cjs +394 -4
- package/dist/televet/booking/index.d.cts +24 -127
- package/dist/televet/booking/index.d.ts +24 -127
- package/dist/televet/booking/index.js +394 -4
- package/dist/televet/call/index.cjs +71 -1
- package/dist/televet/call/index.d.cts +3 -3
- package/dist/televet/call/index.d.ts +3 -3
- package/dist/televet/call/index.js +71 -1
- package/dist/televet/index.cjs +101 -1
- package/dist/televet/index.d.cts +25 -8
- package/dist/televet/index.d.ts +25 -8
- package/dist/televet/index.js +101 -1
- package/dist/{bookingTypes-D4pD3tHs.d.ts → televetGlobal-C5dTUACe.d.cts} +34 -1
- package/dist/{bookingTypes-D4pD3tHs.d.cts → televetGlobal-CnjrfhT4.d.ts} +34 -1
- package/dist/testing/index.cjs +98 -7
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +98 -7
- package/dist/testing/rn/index.cjs +101 -1
- package/dist/testing/rn/index.d.cts +13 -13
- package/dist/testing/rn/index.d.ts +13 -13
- package/dist/testing/rn/index.js +101 -1
- package/dist/testing/web/index.cjs +95 -1
- package/dist/testing/web/index.d.cts +14 -14
- package/dist/testing/web/index.d.ts +14 -14
- package/dist/testing/web/index.js +95 -1
- package/dist/{timelineRows-D3171ksh.d.ts → timelineRows-CEx2TzYB.d.ts} +1 -1
- package/dist/{timelineRows-DDnz4gx2.d.cts → timelineRows-Dffceql_.d.cts} +1 -1
- package/dist/{tokens-BYtbKwFh.d.cts → tokens-Tzo1KBND.d.cts} +43 -2
- package/dist/{tokens-BYtbKwFh.d.ts → tokens-Tzo1KBND.d.ts} +43 -2
- package/dist/{typeStyle-DKz02DGU.d.ts → typeStyle-C3IG9Sft.d.ts} +22 -3
- package/dist/{typeStyle-BqfwxZH4.d.cts → typeStyle-CZ3Tj60N.d.cts} +22 -3
- package/dist/{useRecordsDepth-COJ0wSYK.d.cts → useRecordsDepth-D6a6-_u_.d.cts} +7 -6
- package/dist/{useRecordsDepth-Z9FF5X4E.d.ts → useRecordsDepth-DuPUJFDQ.d.ts} +7 -6
- package/dist/{useVetVisit-Ds8f1peV.d.cts → useVetVisit-BQX_aTJs.d.cts} +2 -2
- package/dist/{useVetVisit-BsjoDO-n.d.ts → useVetVisit-RPBOabl8.d.ts} +2 -2
- package/dist/video/index.cjs +122 -1
- package/dist/video/index.d.cts +3 -3
- package/dist/video/index.d.ts +3 -3
- package/dist/video/index.js +122 -1
- package/dist/{view-DoQEHXJR.d.ts → view-BSmN5RWf.d.ts} +5 -5
- package/dist/{view-nRy6SitU.d.cts → view-UFwCG1Pn.d.cts} +5 -5
- package/dist/web/consent/index.cjs +111 -1
- package/dist/web/consent/index.d.cts +9 -9
- package/dist/web/consent/index.d.ts +9 -9
- package/dist/web/consent/index.js +111 -1
- package/dist/web/index.cjs +325 -14
- package/dist/web/index.d.cts +22 -22
- package/dist/web/index.d.ts +22 -22
- package/dist/web/index.js +325 -14
- package/dist/web/notifications/index.cjs +95 -2
- package/dist/web/notifications/index.d.cts +7 -7
- package/dist/web/notifications/index.d.ts +7 -7
- package/dist/web/notifications/index.js +95 -2
- package/dist/web/records/depth/index.cjs +169 -2
- package/dist/web/records/depth/index.d.cts +11 -11
- package/dist/web/records/depth/index.d.ts +11 -11
- package/dist/web/records/depth/index.js +169 -2
- package/dist/web/records/index.cjs +689 -4
- package/dist/web/records/index.d.cts +34 -37
- package/dist/web/records/index.d.ts +34 -37
- package/dist/web/records/index.js +689 -4
- package/dist/web/records/upload/index.cjs +3 -0
- package/dist/web/records/upload/index.d.cts +23 -0
- package/dist/web/records/upload/index.d.ts +23 -0
- package/dist/web/records/upload/index.js +3 -0
- package/dist/web/televet/booking/index.cjs +423 -4
- package/dist/web/televet/booking/index.d.cts +21 -35
- package/dist/web/televet/booking/index.d.ts +21 -35
- package/dist/web/televet/booking/index.js +423 -4
- package/dist/web/televet/call/index.cjs +28 -1
- package/dist/web/televet/call/index.d.cts +2 -2
- package/dist/web/televet/call/index.d.ts +2 -2
- package/dist/web/televet/call/index.js +28 -1
- package/dist/web/televet/index.cjs +102 -4
- package/dist/web/televet/index.d.cts +22 -11
- package/dist/web/televet/index.d.ts +22 -11
- package/dist/web/televet/index.js +102 -4
- package/package.json +20 -4
- package/web/records/upload/native-blocked.cjs +12 -0
- package/web/records/upload/package.json +8 -0
- package/dist/televetGlobal-CEk0_cW9.d.cts +0 -34
- package/dist/televetGlobal-Cs9Wbqsy.d.ts +0 -34
|
@@ -1,4 +1,689 @@
|
|
|
1
|
-
'use strict';var react=require('react'),zod=require('zod'),jsxRuntime=require('react/jsx-runtime');var du=Object.defineProperty;var i=(e,r)=>du(e,"name",{value:r,configurable:true});var di=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(di.map(e=>e.wireCode));var cu=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"}),is=Object.freeze(di.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:cu[e.wireCode]}))),uu=new Map(is.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),pu=Object.freeze(["http_envelope",...[...new Set(is.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function oo(e,r){if(typeof e!="string")return;let t=e.trim().toUpperCase();if(t.length!==0)for(let o of [r??"http_envelope",...pu]){let n=uu.get(o+t);if(n)return n}}i(oo,"contractErrorFor");function mu(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(mu,"contractDocUrl");function as(e){return null}i(as,"publishedDocUrl");var fu=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 ss(e){return fu[e]}i(ss,"categoryFor");function ls(e){let r=oo(e);if(r)return r.normalized;let t=(e??"").trim().toUpperCase(),o=t.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(t.startsWith("AUTH"))return "authExpired";switch(o){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(ls,"fromWire");var yu=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function ci(e){return yu.has(e)}i(ci,"isAutoRetryable");var gu=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function ds(e){return ci(e)||gu.has(e)}i(ds,"isRetryableCode");var bu=500,ui=8e3,cs=4;function us(e,r=Math.random){let t=Math.max(0,e),o=Math.min(bu*2**t,ui);return Math.floor(r()*o)}i(us,"backoffDelayMs");var hu=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 pi(e){return hu[e]}i(pi,"userFacingError");function ps(e,r,t){Object.defineProperty(e,r,{value:t,enumerable:false,writable:false,configurable:false});}i(ps,"defineHidden");var Ru=/^[a-z][a-z0-9_]{0,63}$/;function H(e,r){let t=oo(r?.wireCode,r?.wireEnvelope),o={code:e,category:ss(e),retryable:r?.retryable??ds(e),displayMessage:pi(e)};if(r?.httpStatus!==void 0&&(o.httpStatus=r.httpStatus),r?.requestId&&(o.requestId=r.requestId),typeof r?.reasonCode=="string"&&Ru.test(r.reasonCode)&&(o.reasonCode=r.reasonCode),t);return r?.wireMessage&&ps(o,"wireMessage",r.wireMessage),r?.raw!==void 0&&r.raw!==null&&ps(o,"raw",r.raw),Object.freeze(o)}i(H,"makeEverfurError");function Te(e,r){return Object.freeze(r===void 0?{ok:true,value:e}:{ok:true,value:e,warning:r})}i(Te,"ok");function J(e){return Object.freeze({ok:false,error:e})}i(J,"err");var io=class io extends Error{constructor(r,t){super(t),this.name="EverfurConfigError",this.kind=r,Object.setPrototypeOf(this,io.prototype);}};i(io,"EverfurConfigError");var Sn=io;var Kt=Object.freeze(["vet","groomer","boarding"]),vu=zod.z.string().min(1).refine(e=>e.startsWith("https://")),Yt=zod.z.string().nullish(),mi=zod.z.unknown().optional(),Cu=zod.z.object({share_id:zod.z.string().min(1),share_url:zod.z.string().min(1),expires_at:Yt,audience:mi}),Eu=zod.z.object({shares:zod.z.array(zod.z.object({share_id:zod.z.string().min(1),expires_at:Yt,created_at:Yt,view_count:zod.z.number().int().nonnegative().nullish(),last_viewed_at:Yt,audience:mi})).optional()}),Su=zod.z.object({download_url:vu,expires_at:Yt}),xu=zod.z.object({share_id:zod.z.string().min(1),expires_at:Yt,audience:mi}),wu=zod.z.object({audience:zod.z.string().min(1),sections:zod.z.array(zod.z.string()),entity_types:zod.z.array(zod.z.string()).nullable()}),fi=254;function ao(e){let r=e.trim();return r.length>0&&r.length<=fi&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(r)}i(ao,"isShareRecipientEmail");var ms=i(e=>typeof e=="string"&&Kt.includes(e),"isAudience");function yi(e){return ms(e)?e:null}i(yi,"audienceOf");function fs(e){let r=zod.z.array(wu).safeParse(e);if(!r.success)return Object.freeze([]);let t=new Set,o=[];for(let n of r.data)!ms(n.audience)||t.has(n.audience)||(t.add(n.audience),o.push(Object.freeze({audience:n.audience,sections:Object.freeze([...n.sections]),entityTypes:n.entity_types===null?null:Object.freeze([...n.entity_types])})));return Object.freeze(o)}i(fs,"mapShareAudiences");function ku(e,r){let t=e.trim();if(t.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(t)?new URL(t):r!==void 0?new URL(t,r):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i(ku,"resolveShareUrl");function ys(e,r){let t=Cu.safeParse(e);if(!t.success)return null;let o=ku(t.data.share_url,r);return o===null?null:Object.freeze({shareId:t.data.share_id,shareUrl:o,expiresAt:t.data.expires_at??null,audience:yi(t.data.audience)})}i(ys,"mapRecordShareLink");function gs(e){let r=Eu.safeParse(e);return r.success?Object.freeze((r.data.shares??[]).map(t=>Object.freeze({shareId:t.share_id,expiresAt:t.expires_at??null,createdAt:t.created_at??null,viewCount:t.view_count??0,lastViewedAt:t.last_viewed_at??null,audience:yi(t.audience)}))):null}i(gs,"mapRecordShareList");function bs(e){let r=xu.safeParse(e);return r.success?Object.freeze({shareId:r.data.share_id,expiresAt:r.data.expires_at??null,audience:yi(r.data.audience)}):null}i(bs,"mapRecordShareEmailReceipt");function hs(e){let r=Su.safeParse(e);return r.success?Object.freeze({downloadUrl:r.data.download_url,expiresAt:r.data.expires_at??null}):null}i(hs,"mapRecordPdfLink");var gi="application/pdf",Xt=Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),kr=Object.freeze({features:Object.freeze({}),uploadContentTypes:Object.freeze([gi]),shareAudiences:Object.freeze([])}),_u=zod.z.object({features:zod.z.record(zod.z.boolean()),upload_content_types:zod.z.array(zod.z.string()).nullish(),share_audiences:zod.z.unknown().optional()}),vs=i(e=>Xt.includes(e),"isPhotoType");function so(e){let r=_u.safeParse(e);if(!r.success)return kr;let t=r.data.upload_content_types??[],o=Xt.filter(n=>t.includes(n));return Object.freeze({features:Object.freeze({...r.data.features}),uploadContentTypes:Object.freeze([gi,...o]),shareAudiences:fs(r.data.share_audiences)})}i(so,"mapRecordsFeatures");function xn(e){return e!==void 0&&e.some(vs)}i(xn,"acceptsPhotos");function Gr(e,r){return e===gi||r!==void 0&&vs(e)&&r.includes(e)}i(Gr,"isAcceptedUploadType");var Rs=Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function Cs(e){return Gr(e,Xt)?Rs[e]:Rs["application/pdf"]}i(Cs,"recordsUploadFilename");var ks=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Es=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 Pu(e){let r=Object.prototype.hasOwnProperty.call(Es,e)?Es[e]:void 0;if(r!==void 0)return r;let t=e;return ks.has(t)?t:"parsing"}i(Pu,"normalizeStatus");function _s(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(_s,"normalizeOrigin");var Tu=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 gt(e){let r=Tu.safeParse(e);if(!r.success)return null;let t=r.data,o=Iu(t.simple_status),n=o==="requested"&&(t.status==="awaiting_upload"||t.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(t.simple_status_detail==="in_review"||t.simple_status_detail==="review_email_failed")?"in_review":o??Pu(t.status);return Object.freeze({id:t.request_id,petRef:t.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:t.simple_status_detail??null,statusLabel:t.status_label??"",dispatchStatus:t.dispatch_status??null,canRetrySend:t.can_retry_send===true,canRevoke:t.can_revoke===true,canConvertToUpload:t.can_convert_to_upload===true,canUpdateClinicEmail:t.can_update_clinic_email===true,reminderCount:t.reminder_count??0,lastReminderAt:t.last_reminder_at??null,waitingExpectation:t.waiting_expectation??null,documentCount:xs(t.document_count,0),heldItemCount:xs(t.held_item_count,0),receivedAt:t.received_at??null,parsingStartedAt:t.parsing_started_at??null,reviewStartedAt:t.review_started_at??null,createdAt:t.created_at??"",updatedAt:t.updated_at??"",wireStatus:t.status,source:t.source??null,actionNeededLabel:t.action_needed_label??null,failureReason:t.failure_reason??null,failureCode:t.failure_code??null,recoveryStage:t.recovery_stage??null,showClinicPhone:t.show_clinic_phone===true,clinicName:t.clinic_name??null,clinicEmail:t.clinic_email??null,clinicPhone:t.clinic_phone??null,convertedToUploadAt:t.converted_to_upload_at??null,requestGroupId:t.request_group_id??null})}i(gt,"mapRequestView");var Du=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 Ps(e){let r=Du.safeParse(e);if(!r.success)return null;let t=r.data,o=bi(t.members);return o.some(n=>n.petRef!==t.pet_ref)?null:Object.freeze({requestGroupId:t.request_group_id,petRef:t.pet_ref,total:t.total,responded:t.responded,pending:t.pending,members:o})}i(Ps,"mapRequestGroup");function Iu(e){return !e||e==="awaiting_upload"||e==="in_review"?null:ks.has(e)?e:null}i(Iu,"normalizeSimpleStatus");function bi(e){let r=Array.isArray(e)?e:[],t=[];for(let o of r){let n=gt(o);n!==null&&t.push(n);}return Object.freeze(t)}i(bi,"mapRequestList");var Ou=zod.z.object({source_doc_id:zod.z.string().min(1),request_id:zod.z.string().min(1)});function Ts(e){let r=Ou.safeParse(e);return r.success?Object.freeze({documentId:r.data.source_doc_id,requestId:r.data.request_id,status:"received"}):null}i(Ts,"mapUploadedDocument");var Au=zod.z.object({label:zod.z.string(),value:zod.z.string()}),hi=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()}),Fu=zod.z.object({at:zod.z.string(),value:zod.z.number().nullish(),display:zod.z.string().nullish(),origin:zod.z.string().nullish()}),qu=zod.z.object({key:zod.z.string(),label:zod.z.string().optional(),points:zod.z.array(Fu).optional()}),Nu=zod.z.object({title:zod.z.string(),detail:zod.z.string().nullish(),due_at:zod.z.string().nullish()}),Ri=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 vi(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:_s(e.origin),canonicalKey:e.canonical_key??null})}i(vi,"mapEntityRow");function Ci(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Ci,"mapDocumentRow");var Lu=zod.z.object({identity:zod.z.array(Au).optional(),entities:zod.z.array(hi).optional(),entity_series:zod.z.array(qu).optional(),forward_looking:zod.z.array(Nu).optional(),documents:zod.z.array(Ri).optional()});function Ds(e,r){let t=Mu(r)?r:{},o=ws(t.schema_version,"epdf/1.0"),n=ws(t.disclaimer,""),s=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return Ss(s,o,n);let a=Lu.safeParse(t);if(!a.success)return Ss(s,o,n);let c=a.data,l=(c.identity??[]).map(g=>Object.freeze({label:g.label,value:g.value})),d=(c.entities??[]).map(vi),u=(c.entity_series??[]).map(g=>Object.freeze({key:g.key,label:g.label??g.key,points:Object.freeze((g.points??[]).map(f=>Object.freeze({at:f.at,value:f.value??null,display:f.display??null,origin:_s(f.origin)})))})),p=(c.forward_looking??[]).map(g=>Object.freeze({title:g.title,detail:g.detail??null,dueAt:g.due_at??null})),m={};for(let g of c.documents??[])m[g.doc_id]=Ci(g);let y=t.is_empty===true||l.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(m).length===0;return Object.freeze({petRef:s,schemaVersion:o,isEmpty:y,withheld:false,generatedAt:$u(t.generated_at),identity:Object.freeze(l),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(m),disclaimer:n})}i(Ds,"mapRecordView");function Ss(e,r,t){return Object.freeze({petRef:e,schemaVersion:r,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:t})}i(Ss,"withheldView");var zu=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 lo(e,r){let t=zu.safeParse(r),o=t.success?t.data:{};return Object.freeze({petRef:typeof o.pet_ref=="string"&&o.pet_ref.length>0?o.pet_ref:e,granted:o.granted===true,version:o.version??null,grantedAt:o.granted_at??null})}i(lo,"mapConsent");function Mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Mu,"isObject");function xs(e,r){return typeof e=="number"&&Number.isFinite(e)?e:r}i(xs,"numberOr");function ws(e,r){return typeof e=="string"&&e.length>0?e:r}i(ws,"strOr");function $u(e){return typeof e=="string"&&e.length>0?e:null}i($u,"strOrNull");var Is=Object.freeze(["published","failed","revoked"]);function Jt(e){return Is.includes(e)}i(Jt,"isTerminalStatus");function bt(e){if(e===null)return null;let r=e.recordsReason;return r==="consent_required"||r==="session_required"||r==="entitlement"||r==="pet_not_found"?r:null}i(bt,"recordsDenialReasonOf");var Uu="records_consent_required";function Bu(e){let r=e.raw;if(r===null||typeof r!="object")return null;let t=r,o=typeof t.error=="object"&&t.error!==null?t.error.code:t.code;return typeof o=="string"&&o.length>0?o:null}i(Bu,"recordsWireCodeOf");function Yr(e){return e===null||e.httpStatus!==409?false:Bu(e)===Uu}i(Yr,"isRecordsConsentRequired");var Hu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function co(e){return e!==Hu}i(co,"isUploadTransportAvailable");var Os=Object.freeze({record(){}}),Kr=25*1024*1024,As=64,wn=128,lr=128,Fs="application/pdf",qs=9e4;function Ls(e){return new Ei(e)}i(Ls,"createRecordsController");var Si=class Si{constructor(r){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.features=kr;this.repository=r.repository,this.uploads=r.uploads,this.telemetry=r.telemetry??Os,this.newIdempotencyKey=r.newIdempotencyKey??Yu(),this.timers=r.timers??Wu,this.uploadDeadlineMs=r.uploadDeadlineMs??qs;}async createUploadRequest(r){let t=await this.repository.createRequest({pet_ref:r.petRef,idempotency_key:r.idempotencyKey});if(!t.ok)return this.onRequestError(t.error);let o=gt(t.value);return o===null?J(uo()):(this.observeRequest(o),Te(o))}async getRequest(r){let t=await this.repository.getRequest(r);if(!t.ok)return this.onRequestError(t.error);let o=gt(t.value);return o===null?J(uo()):(this.observeRequest(o),Te(o))}async listRequests(){let r=await this.repository.listRequests();if(!r.ok)return this.onRequestError(r.error);let t=bi(r.value);for(let o of t)this.observeRequest(o);return Te(t)}async readFeatures(){let r=this.repository.getFeatures;if(r===void 0)return this.features=kr;let t=kr;try{let o=await r.call(this.repository);o.ok&&(t=so(o.value));}catch{}return this.features=t,t}async uploadDocument(r){let{requestId:t,file:o}=r,n=ju(o,this.features.uploadContentTypes);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),J(Ns(`upload rejected: ${n}`));let s=await this.repository.initiateUpload(t,{content_type:o.mimeType,file_size:o.sizeBytes});if(!s.ok)return this.onRequestError(s.error);let a=await this.postToS3(s.value,o,r);if(!a.ok)return this.telemetry.record("records.upload.failed",{reason:a.reason}),J(Ns(a.reason));let c=await this.repository.completeUpload(t,{upload_id:s.value.upload_id});if(!c.ok)return c.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:Vu(c.error)??"corrupt"}),this.onRequestError(c.error);let l=Ts(c.value);return l===null?J(uo()):Te(l)}async postToS3(r,t,o){let n=new AbortController,s=Gu(n.signal,o.signal),a=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let c={signal:s};return o.onProgress&&(c.onProgress=o.onProgress),await this.uploads.postMultipart(r,t,c),{ok:!0}}catch{return {ok:false,reason:n.signal.aborted&&o.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(a);}}async getRecord(r){let t=this.consentEpoch.get(r)??0,o=await this.repository.getRecord(r);if(t!==(this.consentEpoch.get(r)??0))return J(Object.freeze({...H("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let s=bt(o.error);return s==="consent_required"?(this.recordCache.delete(r),this.telemetry.record("records.consent.denied",{pet_ref:r})):s==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:r}),J(o.error)}let n=Ds(r,o.value);return n.petRef!==r?J(uo()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:r}),this.recordCache.delete(r),Te(n)):(this.recordCache.set(r,n),Te(n))}peekCachedRecord(r){return this.recordCache.get(r)??null}async getConsent(r){let t=await this.repository.getConsent(r);return t.ok?Te(lo(r,t.value)):J(t.error)}async grantConsent(r){let t=await this.repository.putConsent(r.petRef,{consent_version:r.consentVersion,idempotency_key:r.idempotencyKey});return t.ok?Te(lo(r.petRef,t.value)):(bt(t.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:r.petRef}),J(t.error))}async revokeConsent(r){let t=await this.repository.deleteConsent(r);return t.ok?(this.consentEpoch.set(r,(this.consentEpoch.get(r)??0)+1),this.recordCache.delete(r),Te(lo(r,t.value))):J(t.error)}reportCapabilityDenied(r){this.telemetry.record("records.capability.denied",r?{pet_ref:r}:{});}observeRequest(r){r.reviewStartedAt!==null&&!this.reportedGaps.has(r.id)&&(this.reportedGaps.add(r.id),this.telemetry.record("records.parse.gap",{request_id:r.id}));}onRequestError(r){return bt(r)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),J(r)}};i(Si,"RecordsControllerImpl");var Ei=Si;function ju(e,r){if(!Gr(e.mimeType,r))return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>Kr?"oversize":null}i(ju,"validateFile");function Vu(e){let r=e.wireMessage;return r==="unsupported_format"||r==="oversize"||r==="corrupt"?r:null}i(Vu,"reasonFromWire");function Ns(e){return H("mediaUploadFailed",{retryable:false,wireMessage:e})}i(Ns,"uploadFailed");function uo(){return H("internalError",{retryable:true})}i(uo,"internal");var Wu={setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Gu(e,r){if(!r)return e;let t=new AbortController;if(e.aborted||r.aborted)return t.abort(),t.signal;let o=i(()=>t.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true}),t.signal}i(Gu,"mergeSignals");function Yu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Yu,"defaultIdempotencyFactory");function Nr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Nr,"assertNever");function zs(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(zs,"errorFrame");function Xu(e){let r={};return e.mode==="personalized"?r.authorization=`Bearer ${e.token}`:r["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(r["x-everfur-user-ref"]=e.userRef),e.sessionId&&(r["x-everfur-session-id"]=e.sessionId),r}i(Xu,"authHeaders");function kn(e,r){return {...e,headers:{...Ju(e.headers),...Xu(r)}}}i(kn,"withAuthHeaders");function Ju(e){if(!e)return {};let r={};for(let[t,o]of Object.entries(e)){let n=t.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(r[t]=o);}return r}i(Ju,"stripAuthHeaders");async function Ms(e,r){if(r.mode==="anonymous")return r.transport.request(kn(e,{mode:"anonymous",publishableKey:r.publishableKey,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));let t;try{t=await r.identity.currentToken();}catch{return J(xi())}let o=await r.transport.request(kn(e,{mode:"personalized",token:t,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await r.identity.currentToken({forceRefresh:!0});}catch{return J(xi())}let s=await r.transport.request(kn(e,{mode:"personalized",token:n,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?J(xi(s.error.httpStatus)):s}i(Ms,"authedSend");function xi(e){return H("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(xi,"authRejectedError");function $s(e){return H("internalError",{retryable:true,wireMessage:Zu(e)})}i($s,"networkError");function Zu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Zu,"describeCause");var ep=3e4,rp=ui*2,tp="idempotency-key",np=new Set(["POST","PUT","PATCH","DELETE"]),op=Object.freeze({onEvent(){}}),ip=Object.freeze({setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ap(e){let r=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return r.length===0?null:`efs_${r}`.slice(0,128)}i(ap,"seededIdempotencyKey");function ht(e){let r=e.observer??op,t=e.timers??ip,o=e.rng??Math.random,n=e.sleep??((m,y)=>Rp(m,t,y)),s=e.maxAttempts??cs,a=e.unaryTimeoutMs??ep,c=e.newIdempotencyKey??it(),l=i(m=>{try{r.onEvent(m);}catch{}},"emit");async function d(m,y,g){let f=g?.maxAttempts,v=Math.max(1,f??s),b=g?.idempotent??np.has(y.method),R=g?.idempotencyKey===void 0?null:ap(g.idempotencyKey),h=b?R??c():null,E=sp(y,h),S=0;for(;;){let C=i(N=>Object.freeze({call:m,method:y.method,path:y.path,attempt:S,...h?{idempotencyKey:h}:{},...N}),"stamp");l(C({phase:"attempt"}));let k=bp(a,t),M=hp(k.signal,y.signal),T;try{T=await Ms({...E,signal:M.signal},e.auth);}catch(N){T=J($s(N));}finally{M.dispose(),k.cancel();}if(T.ok)return l(C({phase:"settled",ok:true,reason:"ok"})),T;let O=T.error,z=dp(O,S,{maxAttempts:v,rng:o,now:t.now(),aborted:y.signal?.aborted===true,...f!==void 0?{perCallMaxAttempts:f}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),q={ok:false,code:O.code,reason:z.reason,...O.httpStatus!==void 0?{httpStatus:O.httpStatus}:{},...O.requestId!==void 0?{requestId:O.requestId}:{}};if(!z.retry)return l(C({phase:"settled",...q})),J(O);if(l(C({phase:"retry",...q,delayMs:z.delayMs})),await n(z.delayMs,y.signal),y.signal?.aborted===true)return l(C({phase:"settled",...q,reason:"aborted"})),J(O);S+=1;}}i(d,"send");async function u(m){return kn(m,await gp(e.auth))}i(u,"authorize");async function*p(m,y,g){l(Object.freeze({call:m,phase:"stream.open",method:y.method,path:y.path,attempt:0}));try{yield*e.auth.transport.stream(y,g);}catch{yield zs({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:u,stream:p})}i(ht,"createRequestFunnel");function sp(e,r){let t={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==tp&&(t[o]=n);return r!==null&&(t["Idempotency-Key"]=r),{...e,headers:t}}i(sp,"assembleHeaders");function it(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(it,"defaultIdempotencyKeyFactory");var lp=10;function dp(e,r,t){if(t.aborted)return {retry:false,reason:"aborted"};let o=cp(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!ci(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(t.policy===void 0)return false;try{return !t.policy.shouldRetry(e.code,r)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(t.policy===void 0)return null;let d;try{d=t.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(lp,Math.floor(d)))},"policyCeiling"),c=t.perCallMaxAttempts??a()??t.maxAttempts;if(r+1>=c)return {retry:false,reason:"attempts-exhausted"};let l=up(e,t.now);return l!==null?l>rp?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:l}:{retry:true,reason:n,delayMs:us(r,t.rng)}}i(dp,"decideRetry");function cp(e){let r=e.code==="unknown"?ls(yp(e.raw)):e.code;return r==="quotaExceeded"?"quota":r==="rateLimited"||e.httpStatus===429?"burst":null}i(cp,"throttleKind");function up(e,r){let t=mp(e.raw);if(t!==null){let n=t-r;return n>0?n:0}let o=pp(e.raw);return o===null?null:Math.round(o*1e3)}i(up,"retryOverrideMs");function pp(e){for(let r of wi(e)){let t=r.retry_after_seconds;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return t}return null}i(pp,"findRetryAfterSeconds");function mp(e){for(let r of wi(e)){let t=r.resets_at,o=fp(t);if(o!==null)return o}return null}i(mp,"findResetsAt");function wi(e){if(!Us(e))return [];let r=[e];for(let t of ["error","detail"]){let o=e[t];Us(o)&&r.push(o);}return r}i(wi,"candidateScopes");function fp(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 r=Date.parse(e);return Number.isFinite(r)?r:null}return null}i(fp,"parseInstantMs");function yp(e){for(let r of wi(e)){let t=r.code;if(typeof t=="string"&&t.length>0)return t}return null}i(yp,"rawWireCode");function Us(e){return typeof e=="object"&&e!==null}i(Us,"isRecord");async function gp(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(gp,"resolveDeviceAuth");function bp(e,r){let t=new AbortController,o=r.setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>r.clearTimeout(o),"cancel")}}i(bp,"boundedSignal");function hp(e,r){let t=i(()=>{},"noop");if(!r)return {signal:e,dispose:t};let o=new AbortController;if(e.aborted||r.aborted)return o.abort(),{signal:o.signal,dispose:t};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),r.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),r.removeEventListener("abort",n);},"dispose")}}i(hp,"mergeSignals");function Rp(e,r,t){return e<=0||t?.aborted===true?Promise.resolve():new Promise(o=>{let n=r.setTimeout(()=>{t?.removeEventListener("abort",s),o();},e),s=i(()=>{r.clearTimeout(n),o();},"onAbort");t?.addEventListener("abort",s,{once:true});})}i(Rp,"delayAbortable");function at(e){for(let r=0;r<e.length;r+=1){let t=e.charCodeAt(r);if(t>=55296&&t<=56319){let o=e.charCodeAt(r+1);if(!(o>=56320&&o<=57343))return true;r+=1;}else if(t>=56320&&t<=57343)return true}return false}i(at,"hasLoneSurrogate");var Qr="/widget/v1/records";function Hs(e){let{auth:r}=e,t=r.mode,o=e.funnel??ht({auth:r,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(l,d,u)=>{let p=await o.send(l,d);return p.ok?p:J(Ep(p.error,t,u))},"send"),s=i((l,d)=>typeof d!="string"||d.length===0?H("validationFailed",{retryable:false,wireMessage:`${l} is required and must be a non-empty string`}):at(d)?H("validationFailed",{retryable:false,wireMessage:`${l} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),a=i((l,d,u)=>{let p=s(l,d);if(p!==null)return p;let y=[...d].length;return y>u?H("validationFailed",{retryable:false,wireMessage:`${l} is ${y} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...l)=>l.find(d=>d!==null)??null,"firstError");return {createRequest:i(l=>{let d=c(a("idempotency_key",l.idempotency_key,wn),a("pet_ref",l.pet_ref,lr));return d?Promise.resolve(J(d)):n("records.createRequest",ki(`${Qr}/requests`,l),"request")},"createRequest"),initiateUpload:i((l,d)=>{let u=s("request_id",l);return u?Promise.resolve(J(u)):n("records.initiateUpload",ki(`${Qr}/requests/${encodeURIComponent(l)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((l,d)=>{let u=s("request_id",l);return u?Promise.resolve(J(u)):n("records.completeUpload",ki(`${Qr}/requests/${encodeURIComponent(l)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(l=>{let d=s("request_id",l);return d?Promise.resolve(J(d)):n("records.getRequest",_n(`${Qr}/requests/${encodeURIComponent(l)}`),"request")},"getRequest"),listRequests:i(async()=>{let l=await n("records.listRequests",_n(`${Qr}/requests`),"request");if(!l.ok)return l;let d=l.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(l=>{let d=a("pet_ref",l,lr);return d?Promise.resolve(J(d)):n("records.getRecord",_n(`${Qr}/pets/${encodeURIComponent(l)}/record`),"content")},"getRecord"),getConsent:i(l=>{let d=a("pet_ref",l,lr);return d?Promise.resolve(J(d)):n("records.getConsent",_n(`${Qr}/pets/${encodeURIComponent(l)}/consent`),"consent")},"getConsent"),putConsent:i((l,d)=>{let u=c(a("consent_version",d.consent_version,As),a("idempotency_key",d.idempotency_key,wn),a("pet_ref",l,lr));return u?Promise.resolve(J(u)):n("records.putConsent",Sp(`${Qr}/pets/${encodeURIComponent(l)}/consent`,d),"consent")},"putConsent"),getFeatures:i(()=>n("records.getFeatures",_n(`${Qr}/features`),"request"),"getFeatures"),deleteConsent:i(l=>{let d=a("pet_ref",l,lr);return d?Promise.resolve(J(d)):n("records.deleteConsent",xp(`${Qr}/pets/${encodeURIComponent(l)}/consent`),"consent")},"deleteConsent")}}i(Hs,"createHttpRecordsRepository");function Bs(e,r){let t={...e,recordsReason:r};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(t,o,n);}return Object.freeze(t)}i(Bs,"withReason");var vp="pet_not_registered";function Cp(e){return e.httpStatus!==404?null:e.reasonCode===vp?"pet_not_found":"entitlement"}i(Cp,"recordsErrorReasonFor");function Ep(e,r,t){let o=Cp(e);return o!==null?Bs(e,o):e.code!=="accessDenied"?e:Bs(e,r==="anonymous"?"session_required":t==="content"?"consent_required":"entitlement")}i(Ep,"tagReason");function _n(e){return {method:"GET",path:e}}i(_n,"get");function ki(e,r){return {method:"POST",path:e,body:r}}i(ki,"post");function Sp(e,r){return {method:"PUT",path:e,body:r}}i(Sp,"put");function xp(e){return {method:"DELETE",path:e}}i(xp,"del");var js=Symbol.for("@everfur/sdk#EverfurContext@v1"),Vs=globalThis,Ws=Vs[js]??(Vs[js]=react.createContext(null));Ws.displayName??="EverfurContext";function se(){let e=react.useContext(Ws);if(e===null)throw new Sn("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(se,"useEverfurContext");var _i=new Map,Pi=new Set;function Gs(e){_i.set(e,(_i.get(e)??0)+1);for(let r of [...Pi])r();}i(Gs,"notifyRecordsConsentWithdrawn");function Tp(e){return _i.get(e)??0}i(Tp,"recordsConsentEpochOf");function Dp(e){return Pi.add(e),()=>{Pi.delete(e);}}i(Dp,"subscribe");function po(e){let r=react.useCallback(()=>Tp(e),[e]);return react.useSyncExternalStore(Dp,r,r)}i(po,"useRecordsConsentEpoch");var Di={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:kr.uploadContentTypes},Ks=4e3,Op=30;function er(e){let{petRef:r}=e,t=react.useRef(e.uploadTransport);t.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:s,scopeEpoch:a}=se(),c=react.useMemo(()=>({}),[n,s,r,a,e.controller]),l=react.useRef(c),[d,u]=react.useState({scope:c,controller:e.controller??null}),p=e.controller??(d.scope===c?d.controller:null),[m,y]=react.useState({scope:c,value:Di}),g=m.scope===c?m.value:Di,f=react.useCallback(I=>{y(w=>w.scope===c?{scope:c,value:I(w.value)}:w);},[c]),v=react.useRef(0);react.useEffect(()=>(l.current=c,y({scope:c,value:Di}),()=>{l.current=null,v.current+=1;}),[c]),react.useEffect(()=>{if(e.controller)return;let{services:I}=n.registry,w={record:i((_,Y)=>I.telemetry.track(_,Y),"record")},A=n.registry.acquire("records",`${s??""}|${r}${o?"|own-upload":""}`,()=>Ls({repository:Hs({auth:I.authFor(s),...I.errorPolicy?{errorPolicy:I.errorPolicy}:{}}),uploads:o?{postMultipart:i((_,Y,me)=>(t.current??I.uploadTransport).postMultipart(_,Y,me),"postMultipart")}:I.uploadTransport,telemetry:w}),()=>{});return u({scope:c,controller:A}),()=>{n.registry.release(A);}},[n,s,r,e.controller,a,c,o]);let b=react.useCallback(I=>{f(w=>({...w,...I}));},[f]),R=react.useCallback(async()=>{if(!p||l.current!==c)return;let I=v.current+=1;k.current=0,O(),b({loading:true,error:null,denialReason:null,withheld:false});let[w,A]=await Promise.all([p.getConsent(r),p.listRequests()]);if(I!==v.current)return;let _=w.ok?w.value:null,Y=A.ok?A.value.filter(Ne=>Ne.petRef===r):[],me=A.ok?null:A.error;if(_&&_.granted){let Ne=await p.getRecord(r);if(I!==v.current)return;if(Ne.ok){b({consent:_,requests:Y,record:Ne.value,withheld:Ne.value.withheld,error:Ne.value.withheld?Np():me,denialReason:null,loading:false});return}b({consent:_,requests:Y,record:null,error:Ne.error,denialReason:bt(Ne.error),withheld:false,loading:false});return}b({consent:_,requests:Y,record:null,error:w.ok?me:w.error,denialReason:_?"consent_required":qp(w),withheld:false,loading:false});},[p,r,b,c]);react.useEffect(()=>(R(),()=>{v.current+=1;}),[R]);let h=e.readUploadFeatures===true;react.useEffect(()=>{if(!h||!p?.readFeatures)return;let I=true;return p.readFeatures().then(w=>{I&&l.current===c&&b({uploadContentTypes:w.uploadContentTypes});}),()=>{I=false;}},[p,h,b,c]);let E=react.useMemo(()=>Fp(g.requests),[g.requests]),S=E?.id??null,C=E?.status??null,k=react.useRef(0),M=react.useRef(null),[T,O]=react.useReducer(I=>I+1,0);react.useEffect(()=>{if(!p||S===null||C===null||Jt(C)||C==="in_review")return;M.current!==String(S)&&(M.current=String(S),k.current=0);let I=false,w=i(async()=>{if(I||k.current>=Op)return;k.current+=1;let _=await p.getRequest(S);if(!I){if(_.ok&&_.value.petRef===r){if(f(Y=>({...Y,requests:mo(Y.requests,_.value)})),Jt(_.value.status)){_.value.status==="published"&&R();return}if(_.value.status==="in_review")return}A=setTimeout(()=>{w();},Ks);}},"tick"),A=setTimeout(()=>{w();},Ks);return ()=>{I=true,clearTimeout(A);}},[p,S,C,R,T,r,f]);let z=react.useCallback(async I=>{if(!p||l.current!==c)return fo();let w=await p.createUploadRequest({petRef:r,idempotencyKey:I});return l.current===c&&w.ok&&w.value.petRef===r&&f(A=>({...A,requests:mo(A.requests,w.value)})),w},[p,r,c,f]),q=react.useCallback((I,w)=>{f(A=>({...A,uploadQueue:A.uploadQueue.map(_=>_.key===I?w(_):_)}));},[f]),N=react.useCallback(async(I,w)=>{let A=Date.now().toString(36),_=w.map((me,Ne)=>{let re=Qs(me,g.uploadContentTypes);return {key:`${A}-${Ne}`,name:me.name??null,status:re===null?"queued":"skipped",progress:0,skipReason:re,error:null}}),Y=[..._];if(!p||l.current!==c)return Object.freeze(Y);f(me=>({...me,uploadQueue:_,isUploading:true,uploadProgress:0}));for(let[me,Ne]of w.entries()){let re=_[me];if(re.status==="skipped")continue;if(l.current!==c)break;q(re.key,Pe=>({...Pe,status:"uploading",progress:0})),b({uploadProgress:0});let oe=await p.uploadDocument({requestId:I,file:Ne,onProgress:i(Pe=>{if(l.current!==c)return;let Ge=Math.min(1,Math.max(0,Pe));q(re.key,xe=>({...xe,progress:Math.max(xe.progress,Ge)})),b({uploadProgress:Ge});},"onProgress")});if(l.current!==c)break;let Se=oe.ok?{...re,status:"done",progress:1}:{...re,status:"failed",error:oe.error};if(Y[me]=Se,q(re.key,()=>Se),oe.ok){let Pe=await p.getRequest(I);l.current===c&&Pe.ok&&Pe.value.petRef===r&&f(Ge=>({...Ge,requests:mo(Ge.requests,Pe.value)}));}}return l.current===c&&b({isUploading:false,uploadProgress:null}),Object.freeze(Y)},[p,b,q,r,c,f,g.uploadContentTypes]),B=react.useCallback(async(I,w)=>{if(!p||l.current!==c)return fo();let A=`${Date.now().toString(36)}-0`;f(Y=>({...Y,isUploading:true,uploadProgress:0,uploadQueue:[{key:A,name:w.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let _=await p.uploadDocument({requestId:I,file:w,onProgress:i(Y=>{l.current===c&&(b({uploadProgress:Y}),q(A,me=>({...me,progress:Math.max(me.progress,Math.min(1,Y))})));},"onProgress")});if(l.current!==c)return _;if(b({isUploading:false,uploadProgress:null}),q(A,Y=>_.ok?{...Y,status:"done",progress:1}:{...Y,status:"failed",error:_.error}),_.ok){let Y=await p.getRequest(I);l.current===c&&Y.ok&&Y.value.petRef===r&&f(me=>({...me,requests:mo(me.requests,Y.value)}));}return _},[p,b,q,r,c,f]),x=react.useCallback(async(I,w)=>{if(!p||l.current!==c)return fo();let A=await p.grantConsent({petRef:r,consentVersion:I,idempotencyKey:w});return A.ok&&l.current===c&&R(),A},[p,r,R,c]),L=react.useCallback(async()=>{if(!p||l.current!==c)return fo();let I=await p.revokeConsent(r);return I.ok&&Gs(r),I.ok&&l.current===c&&(v.current+=1,b({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:I.value})),I},[p,r,b,c]),F=react.useCallback(()=>R(),[R]),W=Ap(g,p!==null);return react.useMemo(()=>({status:W,record:g.record,requests:g.requests,activeRequest:E,consent:g.consent,error:g.error,denialReason:g.denialReason,withheld:g.withheld,isUploading:g.isUploading,uploadProgress:g.uploadProgress,uploadQueue:g.uploadQueue,uploadContentTypes:g.uploadContentTypes,createRequest:z,uploadDocument:B,uploadDocuments:N,grantConsent:x,revokeConsent:L,refresh:F}),[W,g,E,z,B,N,x,L,F])}i(er,"useEverfurRecords");function Qs(e,r){if(!Gr(e.mimeType,r))return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>Kr?"too_large":null}i(Qs,"skipReasonFor");function Xs(e,r){let t=[],o=[];for(let n of e){let s=Qs(n,r);s===null?t.push(n):o.push({name:n.name??null,reason:s});}return {uploadable:t,skipped:o}}i(Xs,"classifyPick");function Ap(e,r){return e.loading||!r?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(Ap,"selectStatus");function Fp(e){if(e.length===0)return null;let r=e[0];for(let t of e)t.updatedAt>r.updatedAt&&(r=t);return r}i(Fp,"newestRequest");function mo(e,r){let t=e.filter(o=>o.id!==r.id);return [r,...t]}i(mo,"replaceRequest");function qp(e){return e.ok?"consent_required":bt(e.error)??"consent_required"}i(qp,"consentDenial");function Np(){return H("internalError",{retryable:false})}i(Np,"withheldSentinel");function fo(){return {ok:false,error:H("internalError",{retryable:true})}}i(fo,"notReady");function Ii(e){let r=globalThis.console;try{r?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Ii,"reportHostFailure");function Lp(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Lp,"isThenable");function zp(e,...r){if(typeof e=="function")try{let t=e(...r);return Lp(t)&&Promise.resolve(t).then(void 0,Ii),t}catch(t){Ii(t);return}}i(zp,"callHost");var Js=new WeakMap;function Dn(e){if(typeof e!="function")return;let r=Js.get(e);if(r!==void 0)return r;let t=i((...o)=>{zp(e,...o);},"guarded");return Js.set(e,t),t}i(Dn,"guardHost");function Ie(e,r){let t=null;for(let o of r){let n=e[o];typeof n=="function"&&(t??={...e},t[o]=Dn(n));}return t??e}i(Ie,"guardHostProps");function It(e,...r){let t;try{t=e(...r);}catch(o){return Ii(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(t).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(It,"callHostAsync");var Mp="your pet";function Re(e){let r=e?.trim()??"";return r.length>0?r:Mp}i(Re,"petNameOr");var yr=Object.freeze({title:"Health records",titleWeb:i(e=>{let r=e?.trim()??"";return r.length>0?`${r}\u2019s Records`:"Health records"},"titleWeb"),titleNative:i(e=>{let r=e?.trim()??"";return r.length>0?r:"Health records"},"titleNative"),openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${Re(e)}\u2019s lab trends`,"lead"),retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:i(e=>`Important: ${e}`,"important")}),_r=Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet\u2019s biomarkers",ask:"Ask about these markers",askA11y:"Ask Everfur about these markers",a11y:i((e,r,t,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${r} in range, ${t} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),Oi=Object.freeze({counter:i((e,r)=>`${e+1} of ${r}`,"counter"),a11y:i((e,r,t)=>e!==null?`${e}, marker ${r+1} of ${t}. Swipe left or right to see more markers.`:`Marker ${r+1} of ${t}`,"a11y")}),st=Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we\u2019ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:i(e=>{let r=e?.trim()??"";return r.length>0?`Ask about ${r}`:"Ask about this marker"},"askNamed"),askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),status:i(e=>`Status: ${e}`,"status"),latestA11y:i((e,r,t)=>`Latest reading ${e}, ${r}, collected ${t}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),gr=Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn\u2019t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading",askA11y:"Ask Everfur about this reading"}),lt=Object.freeze({title:i(e=>`${Re(e)}\u2019s records are on the way`,"title"),anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:i(e=>`We\u2019re requesting ${Re(e)}\u2019s records from your vet. This usually takes a few days; we\u2019ll show lab trends here as soon as they arrive.`,"body"),a11y:i(e=>`Records request in progress for ${Re(e)}.`,"a11y"),openA11y:i((e,r)=>`Open ${Re(e)}\u2019s records request. ${r}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),Jr=Object.freeze({title:i(e=>`Add ${Re(e)}\u2019s records`,"title"),firstRecordTitle:i(e=>`Add ${Re(e)}\u2019s first record`,"firstRecordTitle"),body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",requestFromClinicA11y:i(e=>`Request ${Re(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${Re(e)}\u2019s records`,"uploadDocumentA11y")});var _e=Object.freeze({title:"Medical records",titleFor:i(e=>{let r=e?.trim()??"";return r.length>0?`${r}\u2019s Records`:"Medical records"},"titleFor"),lead:"Follow your records requests and add records you already have.",viewRecord:"Visits & records",viewTimeline:"Timeline",viewLabs:"Labs & bloodwork",viewScreenings:"Screenings",requestsFor:i(e=>`Requests for ${Re(e)}`,"requestsFor"),uploadPromptTitle:i(e=>`Do you already have ${Re(e)}'s records?`,"uploadPromptTitle"),uploadPromptBody:"Upload PDF records you already have, up to 25 MB each. You can pick several at once. We'll read them and add the results to your records.",uploadAction:"Upload records I already have",uploadStarting:"Starting upload\u2026",noPet:"Add your pet in Chat before starting a records request.",requestRecords:"Request records",requestTimeline:"Request timeline",requestTimelineA11y:i(e=>`Request timeline, ${e}`,"requestTimelineA11y"),ownerProvided:"Records you provided",askA11y:i(e=>`Ask Everfur about ${Re(e)}'s medical records`,"askA11y")});function Zs(e){return `I'm looking at ${e?.trim()||"my pet"}'s medical records. What do these records tell me about their health and what should I keep on top of?`}i(Zs,"buildRecordsPageAskPrompt");function yo(e){if(e.convertedToUploadAt)return _e.ownerProvided;let r=e.clinicName?.trim()??"";return r.length>0?r:_e.ownerProvided}i(yo,"consumerRequestSource");var X=Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),el="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";function rl(e){return !Jt(e.status)}i(rl,"isRecordsInProgress");function go(e,r){if(r===null)return null;let t=e.filter(s=>s.petRef===r);if(t.length===0)return null;let o=t.find(s=>s.status==="published");return o!==void 0?o:t.filter(rl).sort((s,a)=>a.updatedAt.localeCompare(s.updatedAt))[0]??null}i(go,"pickPetRecordsRequest");function Ai(e){if(e.hasMarkers)return "published";let r=go(e.requests,e.petRef);return r===null?"none":r.status==="published"||rl(r)?"in_progress":"none"}i(Ai,"deriveRecordsDashboardState");function $p(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i($p,"selectDashboardLoading");function Fi(e){return $p(e)?"loading":e.hasFullRecord?"record":e.markersError||e.recordError&&!e.hasMarkers?"error":e.dashboardState==="in_progress"&&e.drivingRequest!==null?"in_progress":e.dashboardState==="none"?"none":"labs_only"}i(Fi,"selectDashboardView");function nr(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(nr,"recordsEmptyVariantForError");var tl=Object.freeze({name:"dashboard"});function Zt(e=tl){return Object.freeze({stack:Object.freeze([e])})}i(Zt,"initialRecordsNav");function bo(e){return e.stack[e.stack.length-1]??tl}i(bo,"currentRecordsScreen");function qi(e,r){return Object.freeze({stack:Object.freeze([...e.stack,r])})}i(qi,"pushRecordsNav");function Ni(e,r){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),r])})}i(Ni,"replaceRecordsNav");function Li(e){return Zt(e)}i(Li,"resetRecordsNav");function ho(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(ho,"popRecordsNav");function nl(e,r){return r.name==="dashboard"?Li(r):bo(e).name==="upload"&&r.name==="request"?Ni(e,r):qi(e,r)}i(nl,"transitionRecordsNav");function In(e,r){switch(r.type){case "push":return qi(e,r.screen);case "pop":return ho(e).state;case "replace":return Ni(e,r.screen);case "reset":return Li(r.screen);case "navigate":return nl(e,r.screen);default:return e}}i(In,"recordsNavReducer");function Zr(e,r){return e??r?.version??""}i(Zr,"resolveConsentVersion");function dt(e,r){return Zr(e,r).length>0}i(dt,"canGrantConsent");function et(e,r){return e.denialReason==="consent_required"?r?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:H("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:H("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(et,"selectErrorView");function Ro(e){let r=e.clinicName?.trim()??"";return r.length>0?r:e.source==="owner_provided"?ol.ownerUpload:ol.clinicRequest}i(Ro,"selectRequestTitle");var ol=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function zi(e,r){return r===null||r.status!=="awaiting_upload"?null:r}i(zi,"selectResumableUploadRequest");function Mi(e){return `${e} ${X.beingReviewed}`}i(Mi,"heldItemsLabel");function $i(e){let r=[...e].sort((t,o)=>t.updatedAt!==o.updatedAt?t.updatedAt>o.updatedAt?-1:1:t.createdAt!==o.createdAt?t.createdAt>o.createdAt?-1:1:0);return Object.freeze(r)}i($i,"selectRequestList");function On(e){let r=e.actionNeededLabel?.trim()??"";return r.length>0?r:e.statusLabel}i(On,"selectPrimaryLabel");function vo(e){if(e.showClinicPhone!==true)return null;let r=e.clinicPhone?.trim()??"";return r.length===0?null:{phone:r,dial:`tel:${r.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(vo,"selectClinicCall");function il(e){switch(e.wireStatus??e.status){case "published":return "positive";case "failed":case "clinic_declined":return "critical";case "revoked":return "neutral";case "clinic_responded_no_records":case "awaiting_upload":case "records_received":case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return "warning";default:return "info"}}i(il,"selectRequestStatusTone");var Hi=class Hi extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(t,o){return Object.is(t.resetKey,o.key)?null:{failed:false,key:t.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(Hi,"HostRenderBoundary");var Ui=Hi;function Bp({render:e}){return e()}i(Bp,"RenderHost");function Bi({render:e,fallback:r,resetKey:t}){return react.createElement(Ui,{fallback:r,resetKey:t,children:react.createElement(Bp,{render:e})})}i(Bi,"HostRender");function Vi(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let r of Object.keys(e))Vi(e[r]);}return e}i(Vi,"deepFreeze");var Hp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),ll={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},dl={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},sl={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},jp={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Vp={regular:"400",medium:"500",bold:"700"},Wp={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Gp=0,Co="System",Eo="monospace",Yp=["content","heading","control","compact","badge"];function Kp(e){let r={};for(let t of Yp)r[t]=e;return r}i(Kp,"authoredTierSizes");function cl(){return {family:Co,mono:Eo,fontUrl:null,families:{regular:Co,medium:Co,bold:Co,mono:Eo,monoMedium:Eo,monoBold:Eo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:sl,tierSizes:Kp(sl),lineHeight:jp,weight:Vp,letterSpacing:Wp,scale:1,maxScale:Gp,scaleCaps:Hp}}i(cl,"baseType");var ul={},ji=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function An(e){return `cubic-bezier(${e.join(", ")})`}i(An,"cssCubicBezier");var pl={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:An(ji.standard),emphasized:An(ji.emphasized),exit:An(ji.exit)},reducedMotion:false},Qp={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},ml=Vi({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Qp,space:ll,radius:dl,type:cl(),motion:pl,slots:ul}),Xp={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};Vi({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Xp,space:ll,radius:dl,type:cl(),motion:pl,slots:ul});var fl=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),yl=globalThis,Wi=yl[fl]??(yl[fl]=react.createContext(ml));Wi.displayName??="EverfurThemeContext";function ye(){return react.useContext(Wi)}i(ye,"useEverfurTheme");var gl=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var bl='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',em="System";function rm(e){let r=e.trim();return r.length===0||r===em?bl:`${hl(r)}, ${bl}`}i(rm,"cssFontFamily");function tm(e){let r=e.trim();return r.length===0||r==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${hl(r)}, ui-monospace, Menlo, Consolas, monospace`}i(tm,"cssMonoFamily");function hl(e){return `"${e.replace(/[\\"]/g,"\\$&")}"`}i(hl,"quote");function D(e,r){let t=e.type,o=t.families[r];return {fontFamily:r==="mono"||r==="monoMedium"||r==="monoBold"?tm(o):rm(o),fontWeight:t.namedFaces[r]?t.weight.regular:t.weight[gl[r]]}}i(D,"faceCss");var Rt=Object.freeze({textAlign:"start"});var nm=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 om(e){return nm[e]}i(om,"requires");function Rl(e,r,t){let o=om(e),n=new Map;for(let c of r)n.set(c.resource,c);if(t?.isPending===true&&o.some(c=>!n.has(c)))return Gi({name:e,enabled:false,isPending:true,limits:{}});let s=im(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?Gi({name:e,enabled:true,isPending:false,limits:s}):Gi({name:e,enabled:false,isPending:false,limits:s,disabled:am(o,n)})}i(Rl,"decideCapability");function im(e,r){let t={};for(let o of e){let n=r.get(o)?.limits;if(n)for(let[s,a]of Object.entries(n)){let c=t[s];t[s]=c===void 0?a:Math.min(c,a);}}return t}i(im,"mergeLimits");function am(e,r){for(let t of e){let o=r.get(t)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:pi("accessDenied"),level:"user_entitlement",recoverable:false})}i(am,"disabledFor");function Gi(e){let r={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(r.disabled=e.disabled),Object.freeze(r)}i(Gi,"freezeDecision");function Ot(e){let{runtime:r}=se(),t=r.entitlements,o=react.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot);return react.useMemo(()=>Rl(e,o.decisions,{isPending:o.isPending}),[e,o])}i(Ot,"useCapability");var dm=48;function cm(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(cm,"selectView");function Oe(e){let{capability:r,children:t,renderDisabled:o,renderPending:n,style:s,className:a}=e,c=Ot(r),l=react.useMemo(()=>cm(c),[c]);switch(l){case "enabled":return t;case "pending":return n?jsxRuntime.jsx(Bi,{render:n,fallback:jsxRuntime.jsx(vl,{capability:r,style:s,className:a})}):jsxRuntime.jsx(vl,{capability:r,style:s,className:a});case "disabled":return o?jsxRuntime.jsx(Bi,{render:()=>o(c),fallback:jsxRuntime.jsx(Cl,{decision:c,style:s,className:a}),resetKey:c}):jsxRuntime.jsx(Cl,{decision:c,style:s,className:a});default:return Nr(l)}}i(Oe,"CapabilityGate");function vl({capability:e,style:r,className:t}){let o=ye(),n=react.useMemo(()=>El(o),[o]);return jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${e}`,className:t,style:{...n.offstate,...r},children:jsxRuntime.jsx("div",{style:n.skeletonBar})})}i(vl,"PendingSkeleton");function Cl({decision:e,style:r,className:t}){let o=ye(),n=react.useMemo(()=>El(o),[o]),s=e.disabled?.reason??"";return jsxRuntime.jsx("div",{className:t,style:{...n.offstate,...r},children:s.length>0?jsxRuntime.jsx("p",{style:n.offstateText,children:s}):null})}i(Cl,"OffState");function El(e){let{color:r,space:t,radius:o,type:n}=e;return {offstate:{...Rt,boxSizing:"border-box",minHeight:dm,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${t.md}px ${t.lg}px`,backgroundColor:r.surfaceCream,borderRadius:o.md,border:`1px solid ${r.brandBorder}`},offstateText:{margin:0,...D(e,"regular"),fontSize:n.size.body,lineHeight:`${Math.round(n.size.body*n.lineHeight.normal)}px`,color:r.text.muted},skeletonBar:{height:t.md,borderRadius:o.xs,backgroundColor:r.brandSofter}}}i(El,"makeStyles");var So=2;function Sl(e){return typeof e!="number"||!Number.isInteger(e)?So:e<1?1:e>6?6:e}i(Sl,"headingLevel");function Ki(e){return e>=6?6:e+1}i(Ki,"nextHeadingLevel");function xo(e){return `h${String(e)}`}i(xo,"headingTag");var pm=Ki(So);react.createContext(pm);function Ae(e){let r=ye(),t=react.useMemo(()=>fm(r),[r]);return jsxRuntime.jsx("p",{role:"note",className:e.className,style:{...t,...e.style},"data-testid":"records-footnote",children:el})}i(Ae,"RecordsFootnote");function fm(e){let{color:r,space:t,type:o}=e;return {...Rt,boxSizing:"border-box",margin:0,padding:`${t.md}px ${t.lg}px ${t.lg}px`,textAlign:"center",...D(e,"regular"),fontSize:o.size.caption,lineHeight:`${Math.round(o.size.caption*o.lineHeight.normal)}px`,color:r.text.muted,backgroundColor:r.background}}i(fm,"footnoteStyle");var te=Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you\u2019re authorizing",send:"Send request",sending:"Sending\u2026",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can\u2019t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:i(e=>`Typed signature: ${e}`,"typedSignatureA11y"),missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"}),xl=100;var we=Object.freeze({title:te.title,titleFor:i(e=>{let r=e?.trim()??"";return r.length>0?`Request ${r}\u2019s records`:te.title},"titleFor"),leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:i(e=>[{title:"We send a secure request",body:"With your permission, straight to the clinic\u2019s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${e}\u2019s records.`}],"howSteps"),placeholder:te.placeholder,searchA11y:te.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload\u2026",uploadOwnA11y:"Upload records you already have",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:te.recentlyUsed,noMatch:i(e=>`No clinics match \u201C${e}\u201D. You can still request records using the option above.`,"noMatch"),loadingMore:"Loading more\u2026",loadMoreFailed:"Couldn\u2019t load more. Tap to retry.",loadMoreRetryA11y:"Retry loading more clinics",selectA11y:i(e=>`Request records from ${e}`,"selectA11y"),fallback:Object.freeze({title:"Can\u2019t find your clinic?",subtitle:"Add it by email and we\u2019ll request your records.",expandA11y:"Can't find your clinic? Add it by email to request records.",collapseA11y:"Hide the request-by-email form",nameLabel:"Clinic name",namePlaceholder:"Your clinic\u2019s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue",submitA11y:"Request records by email"})});function wl(e){switch(e){case "verified":return {label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case "unverified":return {label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return {label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}i(wl,"clinicEmailStatusBadge");var gm=1.609344;function kl(e){return e===null||!Number.isFinite(e)?null:(e/gm).toFixed(1)}i(kl,"milesLabel");function _l(e){let r=kl(e);return r===null?"":`${r} mi`}i(_l,"formatClinicDistanceLabel");function Pl(e){let r=kl(e);return r===null?"":`${r} ${r==="1.0"?"mile":"miles"} away`}i(Pl,"formatClinicDistanceForA11y");var Tl=300,Qi=2;var le=Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:i((e,r)=>`${e} has the request. We\u2019ll let you know when ${r}\u2019s file arrives.`,"sentLeadWeb"),sentLeadNative:i(e=>`We\u2019ll let you know when ${e}\u2019s file arrives.`,"sentLeadNative"),whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there\u2019s no reply by day 14.",waitingBanner:i(e=>`It\u2019s been ${e} ${e===1?"day":"days"}. Some clinics take a little longer; we\u2019ve been following up automatically and are still on it. If there\u2019s no reply by day 14, we\u2019ll let you know.`,"waitingBanner"),viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",tryAnotherClinicA11y:"Request records from a different clinic",convert:"Upload my own records instead",converting:"Switching\u2026",convertHint:"We\u2019ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we\u2019ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting\u2026",cancel:"Cancel request",cancelling:"Cancelling\u2026",cancelA11y:"Cancel this records request",cancellingA11y:"Cancelling, please wait",resend:"Resend email",resending:"Resending\u2026",resendA11y:"Resend the authorization email to the clinic",resendingA11y:"Resending the email, please wait",errors:Object.freeze({cancel:"We couldn\u2019t cancel this request. Please try again.",retry:"We couldn\u2019t retry this request. Please try again.",email:"We couldn\u2019t update the clinic email. Please try again.",convert:"We couldn\u2019t switch this to an upload. Please try again.",start:"We couldn\u2019t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function bm(e){if(e.wireStatus==="clinic_declined")return "The clinic declined to release the records.";if(e.wireStatus==="clinic_responded_no_records")return "The clinic replied but didn\u2019t include your records.";switch(e.failureCode){case "no_response":return "The clinic didn\u2019t reply after several reminders over 14 days.";case "parse_timeout":case "parse_error":return "We received the records but couldn\u2019t read them. Uploading a clean copy usually fixes this.";case "hard_bounce":case "dispatch_failed":return "We couldn\u2019t deliver the email to the clinic.";default:return "This request didn\u2019t go through."}}i(bm,"fallbackFailureTitle");function Dl(e){let r=e.failureReason?.trim()??"";return r.length>0?r:bm(e)}i(Dl,"failureTitle");var hm=1440*60*1e3;function Xi(e,r){if(!e.createdAt)return 0;let t=Date.parse(e.createdAt);if(Number.isNaN(t))return 0;let o=r-t;return o<=0?0:Math.floor(o/hm)}i(Xi,"requestElapsedDays");var Rm=7;function Il(e,r){return e.wireStatus!=="awaiting_response"?false:Xi(e,r)>=Rm}i(Il,"requestWaitingTooLong");function Ji(e){return e.status==="failed"}i(Ji,"isTerminalFailure");function Ol(e){return Ji(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(Ol,"shouldOfferRecovery");function ql(e,r){let[t,o]=react.useState(""),[n,s]=react.useState(""),[a,c]=react.useState([]),[l,d]=react.useState(null),[u,p]=react.useState([]),[m,y]=react.useState(true),[g,f]=react.useState(false),[v,b]=react.useState(false),[R,h]=react.useState(null),[E,S]=react.useState(null),[C,k]=react.useState(0),M=react.useRef(0),T=react.useRef(true),O=r?.latitude,z=r?.longitude,q=react.useMemo(()=>O!==void 0&&z!==void 0?{latitude:O,longitude:z}:void 0,[O,z]);react.useEffect(()=>(T.current=true,()=>{T.current=false,M.current+=1;}),[e]),react.useEffect(()=>{let F=true;return y(true),e.recentClinics({limit:5}).then(W=>{F&&(W.ok&&p(W.value.clinics),y(false));}).catch(()=>{F&&y(false);}),()=>{F=false;}},[e]),react.useEffect(()=>{let F=t.trim();if(F.length<Qi){s("");return}let W=setTimeout(()=>s(F),Tl);return ()=>clearTimeout(W)},[t]);let N=n.length>=Qi;react.useEffect(()=>{let F=M.current+=1;if(c([]),d(null),h(null),S(null),!N){f(false);return}f(true),e.searchClinics({query:n,limit:25,...q?{location:q}:{}}).then(W=>{!T.current||F!==M.current||(W.ok?(c(W.value.clinics),d(W.value.nextCursor)):h(W.error),f(false));}).catch(()=>{T.current&&F===M.current&&f(false);});},[e,n,N,q,C]);let B=react.useCallback(()=>{if(!N||l===null||v)return;let F=M.current;b(true),S(null),e.searchClinics({query:n,limit:25,cursor:l,...q?{location:q}:{}}).then(W=>{!T.current||F!==M.current||(W.ok?(c(I=>[...I,...W.value.clinics]),d(W.value.nextCursor)):S(W.error),b(false));}).catch(()=>{T.current&&F===M.current&&b(false);});},[e,l,n,N,v,q]),x=react.useCallback(F=>o(F),[]),L=react.useCallback(()=>k(F=>F+1),[]);return react.useMemo(()=>({query:t,debouncedQuery:n,isSearchActive:N,clinics:a,recent:u,recentLoading:m,initialLoading:g,loadingMore:v,hasNextPage:l!==null,error:R,pageError:E,setQuery:x,loadMore:B,retry:L}),[t,n,N,a,u,m,g,v,l,R,E,x,B,L])}i(ql,"useClinicPicker");function ea(e,r,t,o){return Object.freeze({key:e?.id??`free:${r??""}`,clinic:e,freeText:r,email:t,idempotencyKey:o})}i(ea,"clinicDraftFor");var en=10,ko=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),Fn=i((e,r=1)=>zod.z.string().refine(t=>!at(t)&&[...t].length>=r&&[...t].length<=e),"text"),Ll=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),vm=zod.z.object({clinicId:ko.optional(),clinicFreeText:Fn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Fn(320,3).refine(e=>!Ll(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:ko.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)),Cm=zod.z.object({petRef:Fn(128),ownerName:Fn(200).refine(e=>e.trim().length>0&&!Ll(e)),authorizationVersion:Fn(64),clinics:zod.z.array(vm).min(1).max(en)}).strict(),Em=zod.z.object({request_group_id:ko,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:ko.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 zl(e){let r=e.funnel??ht({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(t){if(!Cm.safeParse(t).success)return J(H("validationFailed",{retryable:false}));let o=await r.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:t.petRef,owner_name:t.ownerName,authorization_version:t.authorizationVersion,clinics:t.clinics.map(a=>({...a.clinicId!==void 0?{clinic_id:a.clinicId}:{clinic_free_text:a.clinicFreeText},...a.clinicEmail!==void 0?{clinic_email:a.clinicEmail}:{},...a.signatureId!==void 0?{signature_id:a.signatureId}:{signature_png_base64:a.signaturePngBase64},idempotency_key:a.idempotencyKey}))}});if(!o.ok)return o;let n=Em.safeParse(o.value);if(!n.success||n.data.pet_ref!==t.petRef)return Nl();let s=[];for(let a of n.data.results){let c=a.request===void 0||a.request===null?null:gt(a.request);if(a.created!==(c!==null))return Nl();s.push(Object.freeze({idempotencyKey:a.idempotency_key,clinicId:a.clinic_id??null,clinicFreeText:a.clinic_free_text??null,created:a.created,request:c,failureCode:a.failure_code??null,failureReason:a.failure_reason??null}));}return Te(Object.freeze({requestGroupId:n.data.request_group_id,petRef:n.data.pet_ref,results:Object.freeze(s),createdCount:n.data.created_count,failedCount:n.data.failed_count}))}}}i(zl,"createRecordsClinicBatchClient");function Nl(){return J(H("internalError",{retryable:false}))}i(Nl,"malformed");var Ml=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),Sm=zod.z.object({clinics:zod.z.array(zod.z.object({clinic_id:Ml,name:zod.z.string().min(1),address:zod.z.string().nullable(),phone:zod.z.string().nullable(),email_status:zod.z.string(),distance_km:zod.z.number().finite().nonnegative().nullable()})),next_cursor:zod.z.string().nullable().optional()}),xm=zod.z.object({authorization_version:zod.z.string().min(1),scope_template:zod.z.string().min(1),authorization_template:zod.z.string().min(1)}),wm=zod.z.object({upload_id:zod.z.string().min(1),upload_url:zod.z.string().url().refine(e=>e.startsWith("https://")),upload_fields:zod.z.record(zod.z.string())});function $l(e){let{repository:r}=e,t=i(async n=>{let s=await n;if(!s.ok)return s;let a=gt(s.value);return a===null?At():Te(a)},"request"),o=i(async n=>{let s=await n;if(!s.ok)return s;let a=Sm.safeParse(s.value);return a.success?Te(Object.freeze({clinics:Object.freeze(a.data.clinics.map(c=>Object.freeze({id:c.clinic_id,name:c.name,address:c.address,phone:c.phone,emailStatus:c.email_status,distanceKm:c.distance_km}))),nextCursor:a.data.next_cursor??null})):At()},"page");return {searchClinics:i((n={})=>o(r.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(r.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let s=await r.getRequestGroup(n);if(!s.ok)return s;let a=Ps(s.value);return a===null?At():Te(a)},async getAuthorizationCopy(){let n=await r.getAuthorizationCopy();if(!n.ok)return n;let s=xm.safeParse(n.value);return s.success?Te(Object.freeze({authorizationVersion:s.data.authorization_version,scopeTemplate:s.data.scope_template,authorizationTemplate:s.data.authorization_template})):At()},async createClinicRequest(n){let s=await t(r.createClinicRequest(n));return s.ok&&s.value.petRef!==n.petRef?At():s},retryRequest:i(n=>t(r.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>t(r.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,s)=>t(r.updateClinicEmail(n,s)),"updateClinicEmail"),convertToUpload:i(n=>t(r.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let s=await r.initiateSignatureUpload(n);if(!s.ok)return s;let a=wm.safeParse(s.value);return a.success?Te(Object.freeze({uploadId:a.data.upload_id,uploadUrl:a.data.upload_url,uploadFields:Object.freeze(a.data.upload_fields)})):At()},async completeSignatureUpload(n){let s=await r.completeSignatureUpload(n);if(!s.ok)return s;let a=zod.z.object({signature_id:Ml}).safeParse(s.value);return a.success?Te(a.data.signature_id):At()}}}i($l,"createRecordsClinicController");function At(){return J(H("internalError",{retryable:false}))}i(At,"malformed");var vt="/widget/v1/records",Ul=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),Et=i((e,r=1)=>zod.z.string().refine(t=>!at(t)&&[...t].length>=r&&[...t].length<=e),"text"),Hl=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),jl=Et(320,3).refine(e=>!Hl(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),Bl=Et(64),km=zod.z.object({limit:zod.z.number().int().min(1).max(25).optional()}).strict(),_m=zod.z.object({query:Et(200,0).optional(),location:zod.z.object({latitude:zod.z.number().finite().min(-90).max(90),longitude:zod.z.number().finite().min(-180).max(180)}).strict().optional(),limit:zod.z.number().int().min(1).max(100).optional(),cursor:Et(512,0).optional()}).strict(),Pm=zod.z.object({petRef:Et(128),ownerName:Et(200).refine(e=>e.trim().length>0&&!Hl(e)),authorizationVersion:Et(64),clinicId:Ul.optional(),clinicFreeText:Et(200).refine(e=>e.trim().length>0).optional(),clinicEmail:jl.optional(),signatureId:Ul.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));function Vl(e){let r=e.funnel??ht({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),t=i((n,s,a=false)=>r.send(`records.clinic.${n}`,s,s.method==="GET"||a?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,s,a)=>Bl.safeParse(n).success?t(s,{method:"POST",path:`${vt}/requests/${encodeURIComponent(n)}/${s}`,...a?{body:a}:{}}):Ct(),"recover");return {searchClinics(n){return _m.safeParse(n).success?t("search",{method:"GET",path:`${vt}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):Ct()},recentClinics(n){return km.safeParse(n).success?t("recent",{method:"GET",path:`${vt}/clinics/recent`,query:{limit:n.limit}}):Ct()},getRequestGroup(n){return Bl.safeParse(n).success?t("requestGroup",{method:"GET",path:`${vt}/request-groups/${encodeURIComponent(n)}`}):Ct()},getAuthorizationCopy:i(()=>t("authorizationCopy",{method:"GET",path:`${vt}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Pm.safeParse(n).success?t("create",{method:"POST",path:`${vt}/clinic-requests`,body:{pet_ref:n.petRef,owner_name:n.ownerName,authorization_version:n.authorizationVersion,idempotency_key:n.idempotencyKey,...n.clinicId!==void 0?{clinic_id:n.clinicId}:{clinic_free_text:n.clinicFreeText},...n.clinicEmail!==void 0?{clinic_email:n.clinicEmail}:{},...n.signatureId!==void 0?{signature_id:n.signatureId}:{signature_png_base64:n.signaturePngBase64}}},true):Ct()},retryRequest:i(n=>o(n,"retry"),"retryRequest"),revokeRequest:i(n=>o(n,"revoke"),"revokeRequest"),convertToUpload:i(n=>o(n,"convert-to-upload"),"convertToUpload"),updateClinicEmail(n,s){return jl.safeParse(s).success?o(n,"clinic-email",{clinic_email:s}):Ct()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?Ct():t("signatureInitiate",{method:"POST",path:`${vt}/signatures/initiate`,body:{content_type:"image/png",file_size:n}})},completeSignatureUpload(n){return /^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?t("signatureComplete",{method:"POST",path:`${vt}/signatures/complete`,body:{upload_id:n}}):Ct()}}}i(Vl,"createHttpRecordsClinicRepository");function Ct(){return Promise.resolve(J(H("validationFailed",{retryable:false})))}i(Ct,"invalid");function zr(){let{runtime:e,userRef:r,scopeEpoch:t}=se(),o=react.useMemo(()=>{let{services:s}=e.registry;return $l({repository:Vl({auth:s.authFor(r),...s.errorPolicy?{errorPolicy:s.errorPolicy}:{}})})},[e,r,t]),n=react.useRef(o);return react.useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),react.useMemo(()=>{let s=i(async a=>{if(r===null||n.current!==o)return J(H("accessDenied"));let c=await a();return n.current===o?c:J(H("accessDenied"))},"run");return {searchClinics:i(a=>s(()=>o.searchClinics(a)),"searchClinics"),recentClinics:i(a=>s(()=>o.recentClinics(a)),"recentClinics"),getRequestGroup:i(a=>s(()=>o.getRequestGroup(a)),"getRequestGroup"),getAuthorizationCopy:i(()=>s(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(a=>s(()=>o.createClinicRequest(a)),"createClinicRequest"),retryRequest:i(a=>s(()=>o.retryRequest(a)),"retryRequest"),revokeRequest:i(a=>s(()=>o.revokeRequest(a)),"revokeRequest"),updateClinicEmail:i((a,c)=>s(()=>o.updateClinicEmail(a,c)),"updateClinicEmail"),convertToUpload:i(a=>s(()=>o.convertToUpload(a)),"convertToUpload"),initiateSignatureUpload:i(a=>s(()=>o.initiateSignatureUpload(a)),"initiateSignatureUpload"),completeSignatureUpload:i(a=>s(()=>o.completeSignatureUpload(a)),"completeSignatureUpload")}},[o,r])}i(zr,"useEverfurRecordsClinic");function ra(){let{runtime:e,userRef:r,scopeEpoch:t}=se(),o=react.useMemo(()=>{let{services:s}=e.registry;return zl({auth:s.authFor(r),...s.errorPolicy?{errorPolicy:s.errorPolicy}:{}})},[e,r,t]),n=react.useRef(o);return react.useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),react.useMemo(()=>({async createClinicRequestBatch(s){if(r===null||n.current!==o)return J(H("accessDenied"));let a=await o.createClinicRequestBatch(s);return n.current===o?a:J(H("accessDenied"))}}),[o,r])}i(ra,"useEverfurRecordsClinicBatch");var Tm=120,Dm=44;function Im({reason:e,onExit:r,exitLabel:t,style:o,className:n}){let{color:s,space:a,radius:c,type:l}=ye();return jsxRuntime.jsxs("div",{className:n,"data-testid":"records-gate-off",style:{boxSizing:"border-box",minHeight:Tm,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"flex-start",gap:a.md,padding:a.lg,borderRadius:c.md,border:`1px solid ${s.brandBorder}`,backgroundColor:s.surfaceCream,color:s.text.primary,...o},children:[e.length>0?jsxRuntime.jsx("p",{style:{margin:0,fontSize:l.size.bodyTight,color:s.text.muted},children:e}):null,jsxRuntime.jsx("button",{type:"button",onClick:r,"data-testid":"records-gate-off-exit",style:{minHeight:Dm,padding:`0 ${a.lg}px`,borderRadius:c.pill,border:`1.5px solid ${s.brandInk}`,backgroundColor:"transparent",color:s.brandInk,font:"inherit",fontSize:l.size.body,cursor:"pointer"},children:t})]})}i(Im,"RecordsGateOffState");function Fe(e,r){return e===void 0?{}:{renderDisabled:i(t=>jsxRuntime.jsx(Im,{reason:t.disabled?.reason??"",onExit:e,exitLabel:r}),"renderDisabled")}}i(Fe,"recordsGateExit");function Am(e,r){if(e===void 0)return {};let t={};return e.backgroundColor!==void 0&&(t.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(t.borderColor=e.borderColor,t.borderWidth=r??1),e.borderRadius!==void 0&&(t.borderRadius=e.borderRadius),t}i(Am,"slotBox");function tt(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(tt,"slotText");function Mr(e,r){let t=Am(e,r),o={};return t.backgroundColor!==void 0&&(o.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(o.border=`${t.borderWidth??1}px solid ${t.borderColor}`),t.borderRadius!==void 0&&(o.borderRadius=t.borderRadius),o}i(Mr,"slotBoxCss");var Yl=Object.freeze([.23,1,.32,1]),St=Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var oa=An(Yl);function Ql(e=false){let r=ye(),[t,o]=react.useState(false),n=r.motion.reducedMotion||e,s=react.useCallback(()=>o(true),[]),a=react.useCallback(()=>o(false),[]);return {style:n?{}:{transform:t?`scale(${St.pressScale})`:"none",transition:`transform ${St.pressMs}ms ${oa}`},handlers:{onPointerDown:s,onPointerUp:a,onPointerLeave:a,onPointerCancel:a}}}i(Ql,"usePressScale");function xt(){let r=ye().motion.reducedMotion,t=react.useRef(false),o=react.useRef([]);return react.useEffect(()=>()=>{for(let n of o.current)n.cancel();},[]),react.useCallback(n=>{n===null||t.current||r||(t.current=true,Array.from(n.children).forEach((s,a)=>{if(typeof s.animate!="function")return;let c=Math.min(a,St.maxSteps-1)*St.staggerMs;try{o.current.push(s.animate([{transform:`translateY(${St.riseWebPx}px)`},{transform:"none"}],{duration:St.moveMs,delay:c,easing:oa,fill:"backwards"}),s.animate([{opacity:0},{opacity:1}],{duration:St.fadeMs,delay:c,easing:oa,fill:"backwards"}));}catch{}}));},[r])}i(xt,"useSectionRise");var Ft="data-ef-screen-heading";function Jl(e){return e.focus(),document.activeElement===e}i(Jl,"focusTook");function Lm(e){let r=e.querySelector(`[${Ft}]`);if(r!==null&&(r.textContent??"").trim().length>0&&Jl(r)||Jl(e))return;let t=e.firstElementChild;t instanceof HTMLElement&&(t.hasAttribute("tabindex")||(t.setAttribute("tabindex","-1"),t.style.outline="none"),t.focus());}i(Lm,"focusScreen");function rn(e){let r=react.useRef(null),t=react.useRef(e);return react.useEffect(()=>{if(Object.is(t.current,e))return;t.current=e;let o=r.current;o!==null&&Lm(o);},[e]),r}i(rn,"useFocusScreenOnChange");var Mm=120,qt=44,$m=52,Me="Back";function V(){let e=ye(),r=react.useMemo(()=>Bm(e),[e]);return {theme:e,styles:r}}i(V,"useScreenStyles");function Ke({title:e,onBack:r,right:t,testID:o,variant:n="brand"}){let{styles:s}=V();return jsxRuntime.jsxs("header",{style:s.headerRow,"data-testid":o,children:[r?jsxRuntime.jsx("button",{type:"button",onClick:r,"aria-label":Me,style:s.iconButton,"data-testid":o?`${o}-back`:void 0,children:jsxRuntime.jsx("span",{"aria-hidden":"true",style:s.backChevron})}):jsxRuntime.jsx("span",{style:s.iconButton}),e.trim().length>0?jsxRuntime.jsx("h2",{tabIndex:-1,[Ft]:"",style:n==="document"?s.documentTitle:s.headerTitle,children:e}):jsxRuntime.jsx("span",{"aria-hidden":"true",style:s.headerTitle,"data-testid":o?`${o}-spacer`:void 0}),jsxRuntime.jsx("div",{style:s.headerRight,children:t??jsxRuntime.jsx("span",{style:s.iconButton})})]})}i(Ke,"ScreenHeader");function wt({disclaimer:e,style:r}){let{styles:t}=V();return e.trim().length===0?null:jsxRuntime.jsxs("p",{role:"note","aria-label":yr.important(e),style:{...t.band,...r},"data-testid":"records-disclaimer-band",children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:t.infoGlyph,children:"i"}),jsxRuntime.jsx("span",{style:t.bandText,children:e})]})}i(wt,"DisclaimerBand");function j({label:e,onClick:r,kind:t="primary",disabled:o=false,busy:n=false,ariaLabel:s,ariaDescribedBy:a,testID:c,style:l}){let{styles:d}=V(),u=Ql(o||n),p=t==="primary"?d.pillPrimary:t==="outline"?d.pillOutline:t==="danger"?d.pillDanger:t==="ask"?d.pillAsk:d.pillLink;return jsxRuntime.jsx("button",{type:"button",onClick:r,disabled:o||n,"aria-busy":n,"aria-label":s,"aria-describedby":a,...u.handlers,style:{...d.pill,...p,...o?d.pillDisabled:{},...u.style,...l},"data-testid":c,children:e})}i(j,"Pill");function br({label:e,tone:r="neutral",testID:t}){let{styles:o}=V(),n=e.length>Um;return jsxRuntime.jsx("span",{style:{...o.chip,...n?o.chipSentence:{},...o.chipTones[r]},"data-testid":t,children:e})}i(br,"Chip");var Um=24;function $r({title:e,count:r}){let{styles:t}=V();return jsxRuntime.jsxs("div",{style:t.sectionHeader,children:[jsxRuntime.jsx("h3",{style:t.sectionTitle,children:e}),r!==void 0?jsxRuntime.jsx("span",{style:t.sectionCount,children:r}):null]})}i($r,"SectionHeader");function ia({name:e,color:r}){return jsxRuntime.jsx("svg",{"aria-hidden":"true",focusable:"false",width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:r,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0},"data-glyph":e,children:e==="send"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),jsxRuntime.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("circle",{cx:"18",cy:"5",r:"3"}),jsxRuntime.jsx("circle",{cx:"6",cy:"12",r:"3"}),jsxRuntime.jsx("circle",{cx:"18",cy:"19",r:"3"}),jsxRuntime.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),jsxRuntime.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]})})}i(ia,"HeaderGlyph");function kt({direction:e="right"}){let{styles:r}=V(),t=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...r.chevron,transform:`rotate(${t})`}})}i(kt,"Chevron");function Bm(e){let{color:r,space:t,radius:o,type:n,slots:s}=e,a=i((g,f)=>`${Math.round(g*f)}px`,"lh"),c=i((g,f,v,b="regular")=>({margin:0,...D(e,b),fontSize:g,lineHeight:a(g,f),color:v}),"text"),l=tt(s.recordCard),d=e.brightness==="dark"?r.errorRed:r.danger,u=i((g,f)=>({backgroundColor:g,color:f,border:"1.5px solid transparent"}),"tone"),p=i((g,f)=>({backgroundColor:r.surface,color:f,border:`1.5px solid ${g}`}),"edge"),m=`1px solid ${r.borderRingCream}`,y={boxSizing:"border-box",minHeight:$m,minWidth:qt,padding:`${t.md}px ${t.lg+t.xs/2}px`,borderRadius:o.pill,...D(e,"bold"),fontSize:n.size.body,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:t.sm,textDecoration:"none"};return {chipTones:{neutral:p(r.brandBorderStrong,r.text.primary),info:u(r.brandSoft,r.brandInk),warning:p(r.cautionAccent,r.text.primary),critical:p(r.danger,r.danger),positive:p(r.success,r.brandInk)},root:{...Rt,boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:Mm,height:"100%",backgroundColor:r.background,color:r.text.primary,...D(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},content:{display:"flex",flexDirection:"column",gap:t.lg,padding:`0 ${t.lg}px ${t.xxl}px`},contentTight:{display:"flex",flexDirection:"column",gap:t.lg,padding:`0 ${t.sm}px ${t.xxl}px`},inset:{padding:`0 ${t.sm}px`},headerRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:t.sm,padding:`${t.xs}px ${t.lg}px ${t.md}px`},iconButton:{boxSizing:"border-box",width:qt,height:qt,display:"inline-flex",alignItems:"center",justifyContent:"center",border:0,background:"transparent",cursor:"pointer",padding:0,color:r.brandInk,flexShrink:0},backChevron:{display:"block",width:t.md,height:t.md,borderLeft:`2px solid ${r.brandInk}`,borderBottom:`2px solid ${r.brandInk}`,transform:"rotate(45deg)",marginLeft:t.xs},headerTitle:{...c(n.size.heading,n.lineHeight.tight,r.brandInk,"bold"),flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},documentTitle:{...c(n.size.subtitle,n.lineHeight.snug,r.text.primary,"bold"),flex:1,textAlign:"center"},headerRight:{display:"flex",alignItems:"center",gap:t.sm+t.xs/2},section:{display:"flex",flexDirection:"column",gap:t.sm+t.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:t.sm,padding:`0 ${t.xs}px`},sectionTitle:{...c(n.size.subtitle,n.lineHeight.snug,r.text.primary,"bold"),letterSpacing:"-0.02em"},sectionCount:{...c(n.size.bodyTight,n.lineHeight.snug,r.text.muted,"medium")},card:{boxSizing:"border-box",borderRadius:o.lg,border:m,backgroundColor:r.surface,padding:`${t.xs}px ${t.lg}px`,margin:0,listStyle:"none",...Mr(s.recordCard,1)},creamCard:{boxSizing:"border-box",borderRadius:o.lg,border:m,backgroundColor:r.surfaceCream,padding:t.lg,display:"flex",flexDirection:"column",gap:t.md,...Mr(s.recordCard,1)},row:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:t.md,padding:`${t.md}px 0`},rowDivider:{borderTop:`1px solid ${r.borderHairlineGreen}`},rowMain:{flex:1,minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:t.xs+t.xs/2},rowTitle:{...c(n.size.body,n.lineHeight.snug,r.text.primary,"medium"),...l},rowDetail:{...c(n.size.caption,n.lineHeight.normal,r.text.secondary),marginTop:t.xs/2,...l},rowValue:{...c(n.size.body+1,n.lineHeight.snug,r.text.primary,"bold"),marginTop:t.xs/2,...l},rowMuted:{...c(n.size.caption,n.lineHeight.normal,r.text.muted),...l},chip:{boxSizing:"border-box",display:"inline-flex",alignItems:"center",minHeight:24,borderRadius:o.pill,padding:`0 ${t.sm+t.xs/2}px`,...D(e,"monoBold"),fontSize:n.size.tiny+1,lineHeight:a(n.size.tiny+1,n.lineHeight.snug),letterSpacing:"0.06em",textTransform:"uppercase",whiteSpace:"nowrap"},pill:y,pillPrimary:{border:0,backgroundColor:r.brand,color:r.onPrimary,...Mr(s.primaryButton),...tt(s.primaryButton)},pillOutline:{border:`1.5px solid ${r.brandInk}`,backgroundColor:"transparent",color:r.brandInk},pillDanger:{border:`1.4px solid ${r.danger}`,backgroundColor:r.surface,color:r.danger,fontSize:n.size.bodyTight},pillAsk:{border:`1px solid ${r.borderRingCream}`,backgroundColor:r.surface,color:r.text.primary},pillLink:{minHeight:qt,border:0,backgroundColor:"transparent",color:r.linkInk,padding:`${t.sm}px`},pillDisabled:{opacity:.5,cursor:"default"},infoNote:{display:"flex",gap:t.sm,borderRadius:o.md-t.xs/2,backgroundColor:r.brandSoft,padding:`${t.sm+t.xs/2}px ${t.md}px`,...c(n.size.bodyTight,n.lineHeight.normal,r.text.primary)},cautionNote:{display:"flex",gap:t.sm,borderRadius:o.md-t.xs/2,backgroundColor:r.badgeBgCaution,padding:`${t.sm+t.xs/2}px ${t.md}px`,...c(n.size.bodyTight,n.lineHeight.normal,r.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:r.brandSoft,padding:t.md+t.xs/2,...c(n.size.bodyTight,n.lineHeight.relaxed,r.text.primary)},errorBanner:{display:"flex",gap:t.sm,borderRadius:o.md-t.xs/2,backgroundColor:r.badgeBgCritical,padding:t.md,...c(n.size.bodyTight,n.lineHeight.normal,d)},errorText:c(n.size.bodyTight,n.lineHeight.normal,d),band:{display:"flex",alignItems:"flex-start",gap:t.sm,borderRadius:o.md-t.xs/2,padding:t.md,backgroundColor:r.brandSoft,margin:0},bandText:{flex:1,...c(n.size.caption,n.lineHeight.normal,r.text.secondary)},infoGlyph:{boxSizing:"border-box",flexShrink:0,width:t.md+t.xs/2,height:t.md+t.xs/2,borderRadius:o.pill,border:`1px solid ${r.text.secondary}`,display:"inline-flex",alignItems:"center",justifyContent:"center",...D(e,"bold"),fontSize:n.size.small,color:r.text.secondary},chevron:{display:"inline-block",width:t.sm,height:t.sm,borderTop:`2px solid ${r.text.muted}`,borderRight:`2px solid ${r.text.muted}`,flexShrink:0},chipSentence:{...D(e,"medium"),fontSize:n.size.caption,lineHeight:a(n.size.caption,n.lineHeight.normal),letterSpacing:"normal",textTransform:"none",whiteSpace:"normal",borderRadius:o.md,padding:`${t.xs}px ${t.sm+t.xs/2}px`},lead:{...c(n.size.body+1,n.lineHeight.snug,r.text.primary,"bold"),padding:`0 ${t.sm}px`},subLead:{...c(n.size.body,n.lineHeight.normal,r.text.muted),padding:`0 ${t.lg}px ${t.md}px`},field:{boxSizing:"border-box",display:"block",width:"100%",minHeight:qt,padding:`${t.sm}px ${t.md}px`,border:`1px solid ${r.borderHairlineGreen}`,borderRadius:o.sm,color:r.text.primary,backgroundColor:r.surface,...D(e,"regular"),fontSize:n.size.body},fieldLabel:{...c(n.size.bodyTight,n.lineHeight.normal,r.text.secondary,"medium"),display:"block",marginBottom:t.xs},muted:c(n.size.caption,n.lineHeight.normal,r.text.muted),bodyText:c(n.size.body,n.lineHeight.normal,r.text.primary),mono:D(e,"mono"),plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},dialogFrame:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",margin:0,padding:0,border:0,backgroundColor:"transparent",overflow:"hidden"},dialogScrim:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",padding:t.lg,backgroundColor:"rgba(0,0,0,0.4)"},dialogScrimSide:{boxSizing:"border-box",display:"flex",alignItems:"stretch",justifyContent:"flex-end",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.4)"},dialogPanel:{boxSizing:"border-box",width:"100%",maxWidth:560,maxHeight:"100%",overflowY:"auto",backgroundColor:r.surface,borderRadius:o.xl-1,padding:`${t.lg}px ${t.lg+t.xs+t.xs/2}px`,display:"flex",flexDirection:"column",gap:t.md,...D(e,"regular"),color:r.text.primary},dialogPanelSide:{boxSizing:"border-box",width:"min(100vw, 480px)",height:"100%",maxHeight:"100%",overflowY:"auto",backgroundColor:r.surface,padding:`${t.lg}px ${t.lg+t.xs+t.xs/2}px`,display:"flex",flexDirection:"column",gap:t.md,...D(e,"regular"),color:r.text.primary},sheetHeader:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:t.sm},sheetTitle:{...c(n.size.heading,n.lineHeight.snug,r.text.primary,"bold")},sheetHelper:c(n.size.bodyTight,n.lineHeight.normal,r.text.muted),closeGlyph:{fontSize:n.size.verdict,lineHeight:1,color:r.text.primary}}}i(Bm,"makeScreenStyles");function tn(e,r){return e===null?"":r?`${e} ${r}`:e}i(tn,"formatEntityValue");function aa(e){if(e===null||e.length===0)return "";let r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(r!==null){let n=r[1]??"",s=r[2]??"",a=r[3]??"";return `${Number(s)}/${Number(a)}/${n.slice(2)}`}let t=Date.parse(e);if(Number.isNaN(t))return e;let o=new Date(t);return `${o.getUTCMonth()+1}/${o.getUTCDate()}/${String(o.getUTCFullYear()).slice(2)}`}i(aa,"formatShortDate");var ed=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ee(e){if(!e)return "-";let r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(r!==null){let n=ed[Number(r[2])-1];return n===void 0?"-":`${n} ${Number(r[3])}, ${r[1]}`}let t=Date.parse(e);if(Number.isNaN(t))return "-";let o=new Date(t);return `${ed[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(ee,"formatRecordsDate");function rd(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let r=ee(e),t=Number(e.slice(8,10));return r==="-"||t<1||t>31?e:r}i(rd,"formatIdentityValue");var ge=Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:i(e=>`Measured ${e}`,"measured"),uploadedDocument:"Uploaded document",kind:Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:i(e=>`Dr. ${e}`,"doctor"),lot:i(e=>`Lot ${e}`,"lot"),expires:i(e=>`Expires ${e}`,"expires")});function nt(e){switch(e){case "above":return {label:"Above range",outOfRange:true};case "below":return {label:"Below range",outOfRange:true};case "in_range":return {label:"In range",outOfRange:false};default:return {label:"No range on file",outOfRange:false}}}i(nt,"markerStatusLabel");function nn(e,r){return r<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${r} visits`}i(nn,"trajectoryLabel");function ot(e){let r=e.replace(/_/g," ").trim();return r.length===0?e:r.charAt(0).toUpperCase()+r.slice(1)}i(ot,"humanize");var td=Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function on(e){return Object.prototype.hasOwnProperty.call(td,e)?td[e]:ot(e)}i(on,"bodySystemLabel");var nd=Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function an(e){return Object.prototype.hasOwnProperty.call(nd,e)?nd[e]:ot(e)}i(an,"soapSectionLabel");function od(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(od,"formatWeightKg");function hr(e,r,t){if((e===null||!Number.isFinite(e))&&t)return t;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return r?`${o} ${r}`:o}i(hr,"formatMarkerReading");function sa(e,r,t){let o=nn(r,t);return e?`${ge.measured(ee(e))}${o?` \xB7 ${o}`:""}`:o}i(sa,"labDetailLine");var Po=Object.freeze({idle:Object.freeze({title:"Find your pet\u2019s clinic",body:"Search for the clinic that holds your pet\u2019s records. We\u2019ll request them on your behalf once you sign the authorization.",action:null}),no_requests:Object.freeze({title:"No record requests yet",body:"When you request records from a clinic, you\u2019ll be able to track every step here.",action:null}),no_records:Object.freeze({title:"Nothing to show just yet",body:"Once your pet\u2019s records arrive and our team reviews them, lab trends and visits will appear here.",action:null}),rate_limited:Object.freeze({title:"Slow down a moment",body:"You\u2019ve made a lot of requests just now. You can try again shortly.",action:"Try again"}),service_unavailable:Object.freeze({title:"Records search is temporarily down",body:"We\u2019re working on it. Please try again in a few minutes.",action:"Try again"}),error:Object.freeze({title:"Couldn\u2019t reach Everfur",body:"Check your connection and try again.",action:"Try again"})}),la=60;function id(e){return `Try again in ${e}s`}i(id,"coolingActionLabel");var ad="Try again, available shortly";var K=Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,r)=>`${ee(e)} to ${ee(r)}`,"dateRange"),documents:"Sources on file",uploadedDocument:ge.uploadedDocument,documentRowA11y:i(e=>`View what ${e} contributed to this record`,"documentRowA11y"),documentMeta:i((e,r)=>{let t=r?ee(r):null,n=[e!==null&&Number.isInteger(e)&&e>0?`${e} ${e===1?"page":"pages"}`:null,t].filter(s=>s!==null);return n.length>0?n.join(" \xB7 "):null},"documentMeta"),identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:i(e=>`Last done ${e}`,"lastDone"),overdue:"Overdue",due:i(e=>`Due ${e}`,"due"),askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:ge.labResults,visits:ge.visits,physicalExams:ge.physicalExams,visitNotes:ge.visitNotes,document:Object.freeze({title:"Health Record",titleFor:i(e=>{let r=e?.trim()??"";return r.length>0?`${r}\u2019s health record`:"Health Record"},"titleFor"),download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:i(e=>`Generated ${ee(e)}`,"generated"),identity:"Identity",labs:"Blood & Lab Work",ref:i(e=>`Ref ${e}`,"ref"),noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),sd=Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function ct(e){return Object.prototype.hasOwnProperty.call(sd,e)?sd[e]:ot(e)}i(ct,"entityTypeLabel");var To=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function Do(e){let r=To.filter(o=>e.includes(o)),t=e.filter(o=>!To.includes(o));return [...r,...t]}i(Do,"orderEntityTypes");function Io(e){switch(e){case "identity_risk":return {label:"Identity mismatch",rank:0,tone:"critical"};case "benign":return {label:"Minor difference",rank:2,tone:"neutral"};default:return {label:"Needs review",rank:1,tone:"warning"}}}i(Io,"conflictSeverityMeta");function Nn(e,r){if(!e)return null;let t=Date.parse(e);if(Number.isNaN(t))return null;let o=t<r-1440*60*1e3;return {label:o?K.overdue:K.due(ee(e)),overdue:o}}i(Nn,"dueBadge");function ld(e){return e===null?null:e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}`:e.refLow!==null?`\u2265 ${e.refLow}`:e.refHigh!==null?`\u2264 ${e.refHigh}`:null}i(ld,"formatReferenceBand");var Q=Object.freeze({openA11y:"Share medical record",openA11yFor:i(e=>{let r=e?.trim()??"";return r.length>0?`Share ${r}\u2019s record`:"Share medical record"},"openA11yFor"),title:"Share medical record",titleFor:i(e=>{let r=e?.trim()??"";return r.length>0?`Send ${r}\u2019s record`:"Share medical record"},"titleFor"),helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it\u2019s for; we include the right pages.",leadWebFor:i(e=>{let r=e?.trim()??"";return r.length>0?`Share a snapshot of what ${r}\u2019s vets recorded. Pick who it\u2019s for and we include the right pages.`:"Pick who it\u2019s for; we include the right pages."},"leadWebFor"),audienceLabel:"Who it\u2019s for",audiences:Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What\u2019s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com\u2026",send:"Send",sending:"Sending\u2026",addEmailFor:i(e=>{let r=e?.trim()??"";return r.length>0?`Add an email to send ${r}\u2019s record.`:"Add an email to send the record."},"addEmailFor"),emailInvalid:"That email doesn\u2019t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn\u2019t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",copyLinkA11y:i(e=>`Copy share link, ${e}`,"copyLinkA11y"),turnOff:"Turn off",turnOffA11y:i(e=>`Turn off share link, ${e}`,"turnOffA11y"),turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:i(e=>`View this medical record: ${e}`,"shareMessage"),consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:i(e=>`Couldn\u2019t copy. The link is ${e}`,"copyFailedNative"),turnedOff:"Link turned off.",sentTo:i(e=>`Sent to ${e}. The link works for 7 days.`,"sentTo")})}),Hm=Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),jm=Object.freeze([["encounters","encounters",ge.visits],["lab_results","markers",ge.labResults],["physical_exams","physical_exams",ge.physicalExams]]);function dd(e,r){let t=[];e.sections.includes("entities")&&(e.entityTypes===null?t.push(...Hm):t.push(...Do(e.entityTypes).map(ct)));for(let[o,n,s]of jm)e.sections.includes(o)&&r[n]===true&&t.push(s);return e.sections.includes("forward_looking")&&t.push(K.upcomingCare),Object.freeze(t)}i(dd,"shareIncludedLines");function Vm(e,r){if(!e)return false;let t=Date.parse(e);return Number.isNaN(t)?false:t<=r}i(Vm,"isShareExpired");function Wm(e,r){let t=ee(e);return t==="-"?r?"Expired":"No expiry date":r?`Expired ${t}`:`Expires ${t}`}i(Wm,"formatShareExpiry");function cd(e,r,t){let o=e.map(n=>{let s=Vm(n.expiresAt,t),a=Wm(n.expiresAt,s),c=ee(n.createdAt),l=s?"Expired":"Active",d=a.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return {shareId:n.shareId,shareUrl:r[n.shareId]??null,active:!s,statusLabel:l,expiryLabel:a,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${l}. ${a}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(cd,"buildShareRows");function _t(e,r){let t=e?.httpStatus;if(Yr(e)){if(r==="create"||r==="email")return "Records access for this pet is off, so a new link cannot be created.";if(r==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(t===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(r==="revoke"&&(t===404||t===409||t===410))return "That link was already turned off.";if(t===401||t===403)return "You need to be signed in as this pet's owner to do that.";if(r==="email"&&(t===400||t===422||e?.code==="validationFailed"))return Q.emailInvalid;switch(r){case "create":return "Could not create a share link. Please try again.";case "revoke":return "Could not turn off that link. Please try again.";case "email":return Q.emailFailed;default:return "Could not download the record PDF. Please try again."}}i(_t,"shareErrorMessage");function ve({width:e,height:r,radius:t,style:o}){let{color:n,radius:s}=ye();return jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:e,height:r,borderRadius:t??s.xs,backgroundColor:n.skeleton,flexShrink:0,...o}})}i(ve,"SkeletonBlock");var da=180,pd=44,ca=62;function sn({testID:e}){let r=ln(),t=i(o=>jsxRuntime.jsxs("div",{style:r.actionRow,children:[jsxRuntime.jsxs("div",{style:r.actionLeft,children:[jsxRuntime.jsx(ve,{width:18,height:18,radius:9}),jsxRuntime.jsx(ve,{width:"55%",height:14,radius:7})]}),jsxRuntime.jsx(ve,{width:18,height:18,radius:9})]},o),"action");return jsxRuntime.jsxs("div",{role:"progressbar","aria-label":yr.loading,"aria-busy":"true",style:r.dashboard,"data-testid":e,children:[jsxRuntime.jsx("div",{style:r.inset,children:jsxRuntime.jsxs("div",{style:r.summaryCard,children:[jsxRuntime.jsx(ve,{width:da,height:da,radius:da/2}),jsxRuntime.jsxs("div",{style:r.badges,children:[jsxRuntime.jsx(ve,{width:70,height:22,radius:11}),jsxRuntime.jsx(ve,{width:70,height:22,radius:11})]})]})}),jsxRuntime.jsx("div",{style:r.inset,children:jsxRuntime.jsx(ve,{width:150,height:16,radius:8})}),jsxRuntime.jsx("div",{style:r.carouselCard,children:jsxRuntime.jsx(ve,{width:"100%",height:300,radius:14})}),jsxRuntime.jsxs("div",{style:r.dots,children:[jsxRuntime.jsx(ve,{width:6,height:6,radius:3}),jsxRuntime.jsx(ve,{width:18,height:6,radius:3}),jsxRuntime.jsx(ve,{width:6,height:6,radius:3})]}),jsxRuntime.jsx("div",{style:r.centered,children:jsxRuntime.jsx(ve,{width:46,height:12,radius:6})}),jsxRuntime.jsx("div",{style:r.inset,children:jsxRuntime.jsx(ve,{width:"100%",height:pd,radius:12})}),jsxRuntime.jsxs("div",{style:{...r.inset,...r.actions},children:[t("a"),t("b")]})]})}i(sn,"DashboardSkeleton");function Oo({testID:e}){let r=ln();return jsxRuntime.jsxs("div",{role:"progressbar","aria-label":le.loading,"aria-busy":"true",style:r.request,"data-testid":e,children:[jsxRuntime.jsx("div",{children:[0,1,2,3].map(t=>jsxRuntime.jsxs("div",{style:r.railRow,children:[jsxRuntime.jsxs("div",{style:r.railColumn,children:[jsxRuntime.jsx(ve,{width:24,height:24,radius:12}),t<3?jsxRuntime.jsx(ve,{width:2,height:20,radius:1}):null]}),jsxRuntime.jsxs("div",{style:r.railBody,children:[jsxRuntime.jsx(ve,{width:"55%",height:14,radius:7}),jsxRuntime.jsx(ve,{width:"75%",height:11,radius:6})]})]},t))}),jsxRuntime.jsxs("div",{style:r.statusCard,children:[jsxRuntime.jsx(ve,{width:"90%",height:13,radius:6}),jsxRuntime.jsx(ve,{width:"60%",height:13,radius:6})]}),jsxRuntime.jsx(ve,{width:"100%",height:50,radius:25})]})}i(Oo,"RequestSkeleton");function md({testID:e}){let r=ln();return jsxRuntime.jsxs("div",{role:"progressbar","aria-label":ge.loadingTimeline,"aria-busy":"true",style:r.timeline,"data-testid":e,children:[jsxRuntime.jsx("div",{style:r.timelineDisclaimer,children:jsxRuntime.jsx(ve,{width:"100%",height:pd,radius:12})}),Array.from({length:6},(t,o)=>jsxRuntime.jsxs("div",{children:[o>0?jsxRuntime.jsx("div",{style:r.timelineSeparator}):null,jsxRuntime.jsxs("div",{style:r.timelineRow,children:[jsxRuntime.jsx(ve,{width:34,height:34,radius:17}),jsxRuntime.jsxs("div",{style:r.timelineBody,children:[jsxRuntime.jsxs("div",{style:r.timelineTop,children:[jsxRuntime.jsx(ve,{width:44,height:10,radius:5}),jsxRuntime.jsx(ve,{width:56,height:12,radius:6})]}),jsxRuntime.jsx(ve,{width:"70%",height:14,radius:7}),o%2===0?jsxRuntime.jsx(ve,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(md,"TimelineSkeleton");function fd({testID:e}){let r=ln();return jsxRuntime.jsx("div",{role:"progressbar","aria-label":we.loading,"aria-busy":"true",style:r.clinics,"data-testid":e,children:Array.from({length:5},(t,o)=>jsxRuntime.jsxs("div",{style:r.clinicRow,children:[jsxRuntime.jsx(ve,{width:"65%",height:14,radius:7}),jsxRuntime.jsx(ve,{width:"40%",height:11,radius:6})]},o))})}i(fd,"ClinicsSkeleton");function yd({testID:e}){let r=ln();return jsxRuntime.jsx("div",{role:"progressbar","aria-label":Q.loadingLinks,"aria-busy":"true",style:r.shares,"data-testid":e,children:[0,1].map(t=>jsxRuntime.jsxs("div",{style:r.shareRow,children:[jsxRuntime.jsx(ve,{width:"55%",height:13}),jsxRuntime.jsx(ve,{width:"40%",height:11})]},t))})}i(yd,"SharesSkeleton");function He({variant:e,onAction:r,message:t,testID:o}){let n=ln(),s=Po[e],[a,c]=react.useState(e==="rate_limited"?la:0);react.useEffect(()=>{e==="rate_limited"&&c(la);},[e]),react.useEffect(()=>{if(a<=0)return;let u=setTimeout(()=>c(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[a]);let l=e==="rate_limited"&&a>0,d=l?id(a):s.action;return jsxRuntime.jsxs("section",{role:"status",style:n.empty,"data-testid":o,children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:n.emptyGlyph}),jsxRuntime.jsx("h3",{style:n.emptyTitle,children:s.title}),jsxRuntime.jsx("p",{style:n.emptyBody,children:t??s.body}),d!==null&&r?jsxRuntime.jsx("button",{type:"button",onClick:r,disabled:l,"aria-label":l?ad:d,style:{...n.emptyAction,...l?n.emptyActionDisabled:{}},"data-testid":o?`${o}-action`:`records-empty-${e}-action`,children:d}):null]})}i(He,"RecordsEmptyState");function ln(){let e=ye();return react.useMemo(()=>Km(e),[e])}i(ln,"useStyles");function Km(e){let{color:r,space:t,radius:o,type:n}=e,s=`1px solid ${r.brandBorder}`;return {dashboard:{display:"flex",flexDirection:"column",gap:t.lg,padding:`${t.xs}px ${t.sm}px 0`,backgroundColor:r.background},inset:{padding:`0 ${t.sm}px`},summaryCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.md+t.xs/2,borderRadius:o.lg-t.xs,border:s,backgroundColor:r.surface,padding:`${t.lg+t.xs}px ${t.lg}px`},badges:{display:"flex",gap:t.md},carouselCard:{borderRadius:o.lg-t.xs,border:s,backgroundColor:r.surface,padding:t.lg},dots:{display:"flex",alignItems:"center",justifyContent:"center",gap:t.xs+t.xs/2},centered:{display:"flex",justifyContent:"center"},actions:{display:"flex",flexDirection:"column",gap:t.sm+t.xs/2},actionRow:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,border:s,backgroundColor:r.surface,padding:t.lg},actionLeft:{flex:1,display:"flex",alignItems:"center",gap:t.md},request:{display:"flex",flexDirection:"column",gap:t.lg+t.xs/2,padding:`${t.xs}px ${t.lg}px 0`},railRow:{display:"flex",alignItems:"flex-start",gap:t.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.xs/2,width:24},railBody:{flex:1,display:"flex",flexDirection:"column",gap:t.xs+t.xs/2,paddingBottom:t.lg+t.xs/2},statusCard:{display:"flex",flexDirection:"column",gap:t.sm,borderRadius:o.md,backgroundColor:r.brandSoft,padding:t.md+t.xs/2},timeline:{backgroundColor:r.background},timelineDisclaimer:{padding:`${t.xs}px ${t.lg}px ${t.md}px`},timelineRow:{display:"flex",gap:t.md,padding:`${t.md+t.xs/2}px ${t.lg}px`},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:t.xs-1},timelineTop:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:t.sm},timelineSeparator:{height:1,backgroundColor:r.brandBorder,marginLeft:ca},clinics:{display:"flex",flexDirection:"column",gap:t.md},clinicRow:{display:"flex",flexDirection:"column",gap:t.sm,borderRadius:o.lg-t.xs/2,border:s,backgroundColor:r.surface,padding:`${t.md+t.xs/2}px`},shares:{display:"flex",flexDirection:"column",gap:t.md,padding:t.md,borderRadius:o.md,backgroundColor:r.surfaceCream,border:s},shareRow:{display:"flex",flexDirection:"column",gap:t.xs+t.xs/2},empty:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.sm+t.xs/2,padding:`${t.xxl}px ${t.xl}px`,textAlign:"center"},emptyGlyph:{boxSizing:"border-box",width:22,height:22,borderRadius:11,backgroundColor:r.brandSoft,border:s,marginBottom:t.xs},emptyTitle:{margin:0,...D(e,"bold"),fontSize:n.size.subtitle,lineHeight:`${Math.round(n.size.subtitle*n.lineHeight.snug)-1}px`,color:r.brandInk},emptyBody:{margin:0,...D(e,"regular"),fontSize:n.size.bodyTight,lineHeight:`${Math.round(n.size.bodyTight*n.lineHeight.normal)}px`,color:r.text.muted,maxWidth:320},emptyAction:{boxSizing:"border-box",marginTop:t.sm,minHeight:40,borderRadius:o.pill,padding:`0 ${t.lg+t.xs/2}px`,backgroundColor:r.brand,color:r.onPrimary,border:0,cursor:"pointer",...D(e,"bold"),fontSize:n.size.bodyTight},emptyActionDisabled:{opacity:.5,cursor:"default"}}}i(Km,"makeStyles");var Jm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Ln(e){let{userRef:r,scopeEpoch:t}=se();return jsxRuntime.jsx(Oe,{capability:"recordsClinic",style:e.style,className:e.className,...Fe(e.onBack,Me),children:r===null?jsxRuntime.jsx("p",{role:"alert",children:X.sessionRequired}):jsxRuntime.jsx(Zm,{...Ie(e,["onNavigate","onBack"])},JSON.stringify([r,t,e.petRef]))})}i(Ln,"EverfurClinicPicker");function Zm({petRef:e,petName:r,controller:t,recordsController:o,location:n,onNavigate:s,onBack:a,style:c,className:l}){let{theme:d,styles:u}=V(),p=zr(),m=ql(t??p,n),y=er(o?{petRef:e,controller:o}:{petRef:e}),g=react.useRef(it()),[f,v]=react.useState(false),[b,R]=react.useState(null),[h,E]=react.useState(false),[S,C]=react.useState(""),[k,M]=react.useState(false),[T,O]=react.useState(""),[z,q]=react.useState(false),N=react.useCallback(_=>{s?.({name:"consent",clinic:ea(_,null,"",g.current())});},[s]),B=i(()=>{f||(v(true),R(null),y.createRequest(`records-upload-${Date.now().toString(36)}`).then(_=>{if(v(false),!_.ok){R(le.errors.start);return}s?.({name:"request",requestId:_.value.id});}));},"startUpload"),x=k?S:m.query,L=Jm.test(T.trim()),F=x.trim().length>0&&L,W=m.isSearchActive?m.clinics:m.recent,I=m.isSearchActive?m.error?nr(m.error):!m.initialLoading&&m.clinics.length===0?"idle":null:m.recent.length>0||m.recentLoading?null:"idle",w={display:"flex",flexDirection:"column",gap:d.space.sm},A=i(_=>{let Y=_.currentTarget;Y.scrollTop+Y.clientHeight>=Y.scrollHeight-Y.clientHeight*.6&&m.loadMore();},"onScroll");return jsxRuntime.jsxs("div",{className:l,style:{...u.root,...c},"data-testid":"records-clinic-picker",children:[jsxRuntime.jsx(Ke,{title:we.titleFor(r),onBack:a,testID:"records-clinic-header"}),jsxRuntime.jsx("p",{style:u.subLead,"data-testid":"records-clinic-lead",children:we.leadWeb}),jsxRuntime.jsx("label",{htmlFor:"records-clinic-search",style:{...u.fieldLabel,padding:`0 ${d.space.lg}px`},children:we.searchLabelWeb}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:d.space.sm,margin:`0 ${d.space.lg}px ${d.space.sm}px`,padding:`0 ${d.space.md+d.space.xs/2}px`,height:44,borderRadius:22,backgroundColor:d.color.surfaceSubtle,border:`1px solid ${d.color.borderHairlineGreen}`},children:[jsxRuntime.jsx("input",{id:"records-clinic-search",type:"search",value:m.query,onChange:_=>m.setQuery(_.target.value),placeholder:we.placeholder,maxLength:200,autoComplete:"off",style:{flex:1,border:0,background:"transparent",font:"inherit",fontSize:d.type.size.body,color:d.color.text.primary,outline:"none"},"data-testid":"records-clinic-search-input"}),m.query.length>0?jsxRuntime.jsx("button",{type:"button",onClick:()=>m.setQuery(""),"aria-label":we.clearSearch,style:{...u.iconButton,width:32,height:32},"data-testid":"records-clinic-search-clear",children:jsxRuntime.jsx("span",{"aria-hidden":"true",style:u.closeGlyph,children:"\xD7"})}):null]}),s?jsxRuntime.jsxs("div",{style:{...w,padding:`0 ${d.space.lg}px ${d.space.md}px`},children:[b?jsxRuntime.jsx("p",{role:"alert",style:u.errorBanner,children:b}):null,jsxRuntime.jsx(j,{label:f?we.uploadOwnStarting:we.uploadOwn,kind:"outline",ariaLabel:we.uploadOwnA11y,busy:f,onClick:B,testID:"records-clinic-upload-own"})]}):null,jsxRuntime.jsxs("div",{style:{...u.body,...u.content,gap:d.space.md},onScroll:m.isSearchActive?A:void 0,"data-testid":"records-clinic-results",children:[m.isSearchActive?jsxRuntime.jsxs("section",{style:{...u.creamCard,borderStyle:"dashed",padding:`${d.space.md}px ${d.space.md+d.space.xs/2}px`},"data-testid":"records-clinic-fallback-card",children:[jsxRuntime.jsxs("button",{type:"button",onClick:()=>E(_=>!_),"aria-expanded":h,"aria-label":h?we.fallback.collapseA11y:we.fallback.expandA11y,style:{display:"flex",alignItems:"center",gap:d.space.md,width:"100%",minHeight:44,background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},"data-testid":"records-clinic-fallback",children:[jsxRuntime.jsxs("span",{style:{flex:1,display:"flex",flexDirection:"column",gap:d.space.xs/2},children:[jsxRuntime.jsx("span",{style:{...u.rowTitle,...D(d,"bold")},children:we.fallback.title}),jsxRuntime.jsx("span",{style:u.muted,children:we.fallback.subtitle})]}),jsxRuntime.jsx(kt,{direction:h?"up":"down"})]}),h?jsxRuntime.jsxs("div",{style:w,children:[jsxRuntime.jsx("label",{htmlFor:"records-clinic-fallback-name",style:u.fieldLabel,children:we.fallback.nameLabel}),jsxRuntime.jsx("input",{id:"records-clinic-fallback-name",style:u.field,value:x,onChange:_=>{C(_.target.value),M(true);},placeholder:we.fallback.namePlaceholder,maxLength:200,autoComplete:"off","data-testid":"records-clinic-fallback-name"}),jsxRuntime.jsx("label",{htmlFor:"records-clinic-fallback-email",style:u.fieldLabel,children:we.fallback.emailLabel}),jsxRuntime.jsx("input",{id:"records-clinic-fallback-email",type:"email",style:u.field,value:T,onChange:_=>{O(_.target.value),q(false);},onBlur:()=>q(true),placeholder:we.fallback.emailPlaceholder,maxLength:320,autoComplete:"off","data-testid":"records-clinic-fallback-email"}),z&&T.trim().length>0&&!L?jsxRuntime.jsx("p",{role:"alert",style:u.errorText,children:le.errors.invalidEmail}):null,jsxRuntime.jsx("p",{style:u.muted,children:we.fallback.reviewNote}),jsxRuntime.jsx(j,{label:we.fallback.submit,ariaLabel:we.fallback.submitA11y,disabled:!F||!s,onClick:()=>s?.({name:"consent",clinic:ea(null,x.trim(),T.trim().toLowerCase(),g.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):m.recent.length>0?jsxRuntime.jsx("h3",{style:{...u.fieldLabel,...D(d,"bold"),textTransform:"uppercase",marginBottom:0},"data-testid":"records-clinic-recent-label",children:we.recentlyUsed}):null,m.isSearchActive&&m.initialLoading?jsxRuntime.jsx(fd,{testID:"records-clinic-page-loading"}):null,jsxRuntime.jsx("ul",{style:{...u.plainList,gap:d.space.md},children:W.map(_=>{let Y=wl(_.emailStatus),me=_l(_.distanceKm),Ne=[_.name,_.address,_.phone?`phone ${_.phone}`:null,me?Pl(_.distanceKm):null,Y.a11y].filter(Boolean).join(", "),re=Y.tone==="positive"?{backgroundColor:d.color.badgeBgPositive,color:d.color.success}:Y.tone==="caution"?{backgroundColor:d.color.badgeBgCaution,color:d.color.cautionAccent}:{backgroundColor:d.color.badgeBgNeutral,color:d.color.text.muted};return jsxRuntime.jsx("li",{children:jsxRuntime.jsxs("button",{type:"button",onClick:()=>N(_),"aria-label":we.selectA11y(Ne),style:{...u.creamCard,backgroundColor:d.color.surface,width:"100%",textAlign:"left",cursor:"pointer",gap:d.space.sm,padding:`${d.space.md}px ${d.space.md+d.space.xs/2}px`,font:"inherit",color:"inherit"},"data-testid":`records-clinic-${_.id}`,children:[jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:d.space.sm},children:[jsxRuntime.jsx("span",{style:{...u.rowTitle,...D(d,"bold"),color:d.color.brandInk},children:_.name}),me?jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...u.muted,...u.mono},children:me}):null]}),_.address?jsxRuntime.jsx("span",{style:u.rowDetail,children:_.address}):null,_.phone?jsxRuntime.jsx("span",{"aria-hidden":"true",style:u.rowMuted,children:_.phone}):null,jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...u.chip,...re,...D(d,"bold"),fontSize:d.type.size.micro,alignSelf:"flex-start"},children:Y.label})]})},_.id)})}),I&&!m.initialLoading?jsxRuntime.jsx(He,{variant:I,message:m.isSearchActive&&I==="idle"?we.noMatch(m.debouncedQuery):m.error?.displayMessage,onAction:m.error?.retryable===true?m.retry:void 0,testID:"records-clinic-empty"}):null,jsxRuntime.jsxs("div",{style:w,children:[m.loadingMore?jsxRuntime.jsx("p",{role:"status",style:{...u.muted,textAlign:"center"},"data-testid":"records-clinic-loading-more",children:we.loadingMore}):null,m.pageError?jsxRuntime.jsx("button",{type:"button",onClick:m.loadMore,"aria-label":we.loadMoreRetryA11y,style:{...u.pill,...u.pillLink},"data-testid":"records-clinic-page-error-retry",children:we.loadMoreFailed}):null]}),jsxRuntime.jsx(ef,{petName:r})]}),jsxRuntime.jsx(Ae,{})]})}i(Zm,"PickerBody");function ef({petName:e}){let{theme:r,styles:t}=V();return jsxRuntime.jsxs("section",{style:{...t.creamCard,backgroundColor:r.color.surfaceSubtle,border:0},"aria-label":we.howItWorks,"data-testid":"records-clinic-how",children:[jsxRuntime.jsx("h3",{style:t.sectionTitle,children:we.howItWorks}),jsxRuntime.jsx("ol",{style:{...t.plainList,gap:r.space.md},children:we.howSteps(Re(e)).map((o,n)=>jsxRuntime.jsxs("li",{style:{display:"flex",gap:r.space.md},children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...t.mono,...D(r,"monoBold"),fontSize:r.type.size.caption,color:r.color.brandInk,minWidth:r.space.xl},children:String(n+1).padStart(2,"0")}),jsxRuntime.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:r.space.xs/2},children:[jsxRuntime.jsx("span",{style:{...t.rowTitle,...D(r,"bold")},children:o.title}),jsxRuntime.jsx("span",{style:t.rowDetail,children:o.body})]})]},o.title))})]})}i(ef,"HowItWorks");var je=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${en} clinics`,sendA11y:i(e=>e===1?"Send 1 records request":`Send ${e} records requests`,"sendA11y"),send:i(e=>`Send ${e} ${e===1?"request":"requests"}`,"send"),sending:"Sending\u2026",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:i(e=>`Remove ${e}`,"remove"),emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn\u2019t send any of these requests. See the details below and try again.",partial:i((e,r,t)=>`${e} of ${r} requests sent. ${t} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,r)=>`${e} of ${r} ${r===1?"clinic":"clinics"} responded`,"responded")});var Fo=25,Ao=5;function qo(e){let[r,t]=react.useState({list:e,shown:Ao}),o=r.list===e?r.shown:Ao,n=react.useCallback(()=>{t(s=>({list:e,shown:(s.list===e?s.shown:Ao)+Ao}));},[e]);return {visible:e.slice(0,o),hasMore:e.length>o,showMore:n}}i(qo,"useVisibleClinics");function zn(e,r,t,o){let n={owner_name:r,pet_name:t,clinic_name:o},s=false,a=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,l)=>Object.prototype.hasOwnProperty.call(n,l)?n[l]??"":(s=true,""));return s||/[{}]/.test(a)?null:a}i(zn,"renderClinicScope");function Mn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(Mn,"clinicNeedsEmail");function gd(e,r,t){let[o,n]=react.useState(e.ownerName),[s,a]=react.useState(""),[c,l]=react.useState(null),[d,u]=react.useState(""),[p,m]=react.useState([]),[y,g]=react.useState([]),[f,v]=react.useState(null),[b,R]=react.useState(null),[h,E]=react.useState(false),[S,C]=react.useState(false),[k,M]=react.useState(null),[T,O]=react.useState(0),z=react.useRef(false),q=react.useRef(false),N=react.useRef(0),B=react.useRef(it()),x=react.useRef(null),L=react.useRef(null),F=react.useRef(0);react.useEffect(()=>(z.current=true,q.current=false,E(false),()=>{z.current=false,F.current+=1,N.current+=1,x.current=null,L.current?.abort();}),[r]),react.useEffect(()=>{let re=true;return v(null),x.current=null,r.getAuthorizationCopy().then(oe=>{re&&(oe.ok?(v(oe.value),R(null)):R(oe.error));}).catch(()=>{re&&R(H("internalError"));}),()=>{re=false;}},[r,T]),react.useEffect(()=>{let re=true;return g([]),r.recentClinics({limit:5}).then(oe=>{re&&oe.ok&&g(oe.value.clinics);}).catch(()=>{}),()=>{re=false;}},[r]);let W=i(()=>{x.current=null,R(null);},"invalidate"),I=c?.name??s.trim(),w=f?zn(f,o.trim(),e.petName,I):null,A=Mn(c),_=qo(p),Y=!!(f&&w&&o.trim()&&e.petName.trim()&&I&&(!A||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&t),me=i(async()=>{if(q.current)return;let re=++N.current;C(true);try{let oe=await r.searchClinics({query:s.trim(),limit:Fo});if(!z.current||re!==N.current)return;oe.ok?(m(oe.value.clinics),R(null)):R(oe.error);}catch{z.current&&re===N.current&&R(H("internalError"));}finally{z.current&&re===N.current&&C(false);}},"search"),Ne=i(async()=>{if(q.current||k||!Y||!f||!w||!t)return;q.current=true;let re=F.current,oe=i(()=>z.current&&F.current===re,"current");E(true),R(null);try{if(!x.current){L.current=new AbortController;let Pe=await t({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:I,authorizationVersion:f.authorizationVersion,scopeText:w,signal:L.current.signal});if(!oe()||Pe===null)return;let Ge=c&&(!A||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:I};x.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:f.authorizationVersion,...Ge,...A?{clinicEmail:d.trim().toLowerCase()}:{},...Pe.signatureId!==void 0?{signatureId:Pe.signatureId}:{signaturePngBase64:Pe.signaturePngBase64},idempotencyKey:B.current()};}if(!oe())return;let Se=await r.createClinicRequest(x.current);if(!oe())return;if(!Se.ok){R(Se.error);return}if(Se.value.petRef!==e.petRef){R(H("internalError"));return}M(Se.value),x.current=null,e.onCreated?.(Se.value);}catch{oe()&&R(H("internalError"));}finally{q.current=false,oe()&&E(false);}},"submit");return {ownerName:o,query:s,clinic:c,email:d,clinics:p,copy:f,scope:w,error:b,busy:h,searching:S,created:k,ready:Y,needsEmail:A,visibleClinics:_.visible,hasMoreClinics:_.hasMore,showMoreClinics:_.showMore,recent:p.length===0&&c===null?y:[],setOwnerName(re){q.current||(W(),n(re));},setQuery(re){q.current||(W(),N.current+=1,C(false),m([]),l(null),u(""),a(re));},setEmail(re){q.current||(W(),u(re));},selectClinic(re){q.current||(W(),N.current+=1,C(false),m([]),l(re),a(re.name),u(""));},invalidate:W,search:me,submit:Ne,retryCopy(){R(null),O(re=>re+1);}}}i(gd,"useClinicRequestForm");var nf=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function cn(e){return e.clinic?.name??e.freeText??""}i(cn,"draftName");function dn(e){return Mn(e.clinic)}i(dn,"draftNeedsEmail");function bd(e,r,t,o,n){let[s,a]=react.useState(e.ownerName),[c,l]=react.useState(""),[d,u]=react.useState([]),[p,m]=react.useState([]),[y,g]=react.useState([]),[f,v]=react.useState(null),[b,R]=react.useState(null),[h,E]=react.useState(false),[S,C]=react.useState(false),[k,M]=react.useState(null),[T,O]=react.useState(null),[z,q]=react.useState(0),N=react.useRef(false),B=react.useRef(false),x=react.useRef(0),L=react.useRef(0),F=react.useRef(it()),W=react.useRef(null),I=react.useRef(null);react.useEffect(()=>(N.current=true,B.current=false,E(false),()=>{N.current=false,L.current+=1,x.current+=1,W.current=null,I.current?.abort();}),[r,t]),react.useEffect(()=>{let ie=true;return v(null),W.current=null,r.getAuthorizationCopy().then(ke=>{ie&&(ke.ok?(v(ke.value),R(null)):R(ke.error));}).catch(()=>{ie&&R(H("internalError"));}),()=>{ie=false;}},[r,z]),react.useEffect(()=>{let ie=true;return m([]),r.recentClinics({limit:5}).then(ke=>{ie&&ke.ok&&m(ke.value.clinics);}).catch(()=>{}),()=>{ie=false;}},[r]);let w=qo(d),A=i(()=>{W.current=null,R(null);},"invalidate"),_=y.map(cn),Y=f?_.map(ie=>zn(f,s.trim(),e.petName,ie)):[],me=Y.every(ie=>ie!==null)?Y.join(`
|
|
2
|
-
|
|
3
|
-
`):null,Ne=y.length>0&&y.every(ie=>!dn(ie)||nf.test(ie.email.trim())),re=y.length>=en,oe=!!(f&&me&&s.trim()&&e.petName.trim()&&Ne&&o)&&k===null,Se=i(async()=>{if(B.current)return;let ie=++x.current;C(true);try{let ke=await r.searchClinics({query:c.trim(),limit:Fo});if(!N.current||ie!==x.current)return;ke.ok?(u(ke.value.clinics),R(null)):R(ke.error);}catch{N.current&&ie===x.current&&R(H("internalError"));}finally{N.current&&ie===x.current&&C(false);}},"search"),Pe=i(ie=>{B.current||re||k!==null||ie.clinic!==null&&y.some(ke=>ke.clinic?.id===ie.clinic?.id)||(A(),g(ke=>[...ke,{...ie,key:F.current(),idempotencyKey:F.current()}]),u([]),l(""));},"add"),Ge=i(async()=>{if(B.current||k!==null||!oe||!f||!me||!o)return;B.current=true;let ie=L.current,ke=i(()=>N.current&&L.current===ie,"current");E(true),R(null);try{if(W.current===null){I.current=new AbortController;let fr=await o({petRef:e.petRef,petName:e.petName,ownerName:s.trim(),clinicName:_.join(", "),authorizationVersion:f.authorizationVersion,scopeText:me,signal:I.current.signal});if(!ke()||fr===null)return;if(W.current=fr,fr.signaturePngBase64!==void 0&&n!==void 0){let lu=await n(fr.signaturePngBase64,I.current.signal);if(!ke())return;W.current={signatureId:lu.signatureId};}}let qr=W.current,Cn=y.map(fr=>({...fr.clinic!==null&&(!dn(fr)||fr.clinic.emailStatus==="none")?{clinicId:fr.clinic.id}:{clinicFreeText:cn(fr)},...dn(fr)?{clinicEmail:fr.email.trim().toLowerCase()}:{},...qr.signatureId!==void 0?{signatureId:qr.signatureId}:{signaturePngBase64:qr.signaturePngBase64},idempotencyKey:fr.idempotencyKey})),En=await t.createClinicRequestBatch({petRef:e.petRef,ownerName:s.trim(),authorizationVersion:f.authorizationVersion,clinics:Cn});if(!ke())return;if(!En.ok){R(En.error);return}M(En.value),e.onCreated?.(En.value),xe(En.value.requestGroupId,ie);}catch{ke()&&R(H("internalError"));}finally{B.current=false,ke()&&E(false);}},"submit"),xe=i(async(ie,ke)=>{try{let qr=await r.getRequestGroup(ie);if(!N.current||L.current!==ke)return;qr.ok&&qr.value.petRef===e.petRef&&O(qr.value);}catch{}},"loadGroup"),ur=i(async()=>{k===null||B.current||await xe(k.requestGroupId,L.current);},"refreshGroup");return {ownerName:s,query:c,clinics:d,copy:f,scopeText:me,error:b,busy:h,searching:S,drafts:y,outcome:k,group:T,ready:oe,atCap:re,visibleClinics:w.visible,hasMoreClinics:w.hasMore,showMoreClinics:w.showMore,recent:d.length===0?p.filter(ie=>!y.some(ke=>ke.clinic?.id===ie.id)):[],setOwnerName(ie){B.current||(A(),a(ie));},setQuery(ie){B.current||(x.current+=1,C(false),u([]),l(ie));},search:Se,addClinic(ie){Pe({clinic:ie,freeText:null,email:""});},addFreeText(){let ie=c.trim();ie.length!==0&&Pe({clinic:null,freeText:ie,email:""});},setDraftEmail(ie,ke){B.current||(A(),g(qr=>qr.map(Cn=>Cn.key===ie?{...Cn,email:ke}:Cn)));},removeDraft(ie){B.current||k!==null||(A(),g(ke=>ke.filter(qr=>qr.key!==ie)));},submit:Ge,refreshGroup:ur,retryCopy(){R(null),q(ie=>ie+1);}}}i(bd,"useClinicBatchForm");function hd(e){try{let r=new URL(e);if(r.protocol!=="https:"||r.username||r.password||r.port&&r.port!=="443")return !1;let t=r.hostname.toLowerCase();return t==="s3.amazonaws.com"||t.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(t)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(t)||t==="s3-accelerate.amazonaws.com"||t.endsWith(".s3-accelerate.amazonaws.com")||t==="s3-accelerate.dualstack.amazonaws.com"||t.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(hd,"trustedSignatureUploadUrl");function Rd(e,r,t,o){e.clearRect(0,0,t,o);let n=r.trim();if(!n)return;let s=Math.max(1,t-32),a=Math.min(44,Math.max(16,Math.round(o*.34))),c=i(()=>{e.font=`italic 700 ${a}px Georgia, "Times New Roman", serif`;},"font");for(c();a>12&&e.measureText(n).width>s;)a-=2,c();e.textAlign="center",e.textBaseline="middle",e.fillText(n,t/2,o/2,s);}i(Rd,"paintClinicTypedSignature");function vd(e,r,t,o){e.clearRect(0,0,t,o);for(let n of r){let s=n[0];if(s!==void 0){e.beginPath(),e.moveTo(s[0],s[1]),n.length===1&&e.lineTo(s[0],s[1]);for(let a=1;a<n.length;a+=1){let c=n[a];c!==void 0&&e.lineTo(c[0],c[1]);}e.stroke();}}}i(vd,"paintSignatureStrokes");async function Cd(e,r,t,o=fetch){let n=i(()=>new Error("Signature upload failed"),"fail"),s=await new Promise(m=>e.toBlob(m,"image/png"));if(!s||!s.size||s.size>2*1024*1024||t.aborted)throw n();let a=await r.initiateSignatureUpload(s.size);if(!a.ok||t.aborted||!hd(a.value.uploadUrl))throw n();let c=new FormData;for(let[m,y]of Object.entries(a.value.uploadFields))c.append(m,y);c.append("file",s,"signature.png");let l=new AbortController,d=i(()=>l.abort(),"onAbort");t.addEventListener("abort",d,{once:true});let u=setTimeout(d,9e4);try{if(!(await o(a.value.uploadUrl,{method:"POST",body:c,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:l.signal})).ok||t.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),t.removeEventListener("abort",d);}let p=await r.completeSignatureUpload(a.value.uploadId);if(!p.ok||t.aborted)throw n();return {signatureId:p.value}}i(Cd,"registerClinicSignature");var af=8,sf=480,lf=160;function Mt(e){let r=react.useRef(null),t=react.useRef(false),o=react.useRef([]),[n,s]=react.useState("draw"),[a,c]=react.useState(""),[l,d]=react.useState(false),u=react.useRef(a);u.current=a;let p=react.useCallback(()=>{let f=r.current,v=f?.getContext("2d");if(!f||!v)return;let b=typeof window<"u"&&window.devicePixelRatio||1;v.setTransform(b,0,0,b,0,0);let R=f.width/b,h=f.height/b;if(u.current.trim().length>0){v.fillStyle="#111",Rd(v,u.current,R,h);return}v.lineWidth=2,v.lineCap="round",v.lineJoin="round",v.strokeStyle="#111",vd(v,o.current,R,h);},[]);react.useEffect(()=>{let f=r.current;if(!f)return;let v=i(()=>{let R=f.getBoundingClientRect(),h=typeof window<"u"&&window.devicePixelRatio||1,E=Math.max(1,Math.round((R.width||f.clientWidth||sf)*h)),S=Math.max(1,Math.round((R.height||f.clientHeight||lf)*h));f.width!==E&&(f.width=E),f.height!==S&&(f.height=S),p();},"resize");if(v(),typeof ResizeObserver>"u")return;let b=new ResizeObserver(v);return b.observe(f),()=>b.disconnect()},[p]);let m=react.useCallback(()=>{e?.(),o.current=[],d(false),c(""),u.current="",p();},[e,p]),y=i(f=>{let v=f.currentTarget.getBoundingClientRect();return [f.clientX-v.left,f.clientY-v.top]},"point"),g=i(()=>o.current.reduce((f,v)=>f+v.length,0),"countPoints");return {canvas:r,mode:n,typed:a,signed:l,clear:m,setTyped(f){e?.(),c(f),u.current=f,d(!!f.trim()),p();},toggle(){m(),s(f=>f==="draw"?"type":"draw");},onPointerDown(f){n==="draw"&&(e?.(),t.current=true,f.currentTarget.setPointerCapture(f.pointerId),o.current=[...o.current,[y(f)]],p());},onPointerMove(f){if(!t.current||n!=="draw")return;let v=o.current[o.current.length-1];v!==void 0&&(o.current=[...o.current.slice(0,-1),[...v,y(f)]],p(),d(g()>=af));},onPointerUp(){t.current=false;},register(f,v){return !r.current||!l?Promise.reject(new Error("Signature upload failed")):Cd(r.current,f,v)}}}i(Mt,"useSignatureCanvas");function $t({pad:e,disabled:r}){let t=ye(),o=e.mode==="type"?e.typed.trim():"",n={minHeight:44,padding:t.space.sm,border:`1px solid ${t.color.borderHairlineGreen}`,borderRadius:t.radius.sm,background:t.color.surface,color:t.color.text.primary,font:"inherit"},s={...n,cursor:"pointer"};return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("p",{style:{margin:`0 0 ${t.space.sm}px`},children:e.mode==="draw"?te.draw:te.type}),jsxRuntime.jsx("button",{type:"button",style:{...s,alignSelf:"flex-start",marginBottom:t.space.sm,textDecoration:"underline"},disabled:r,onClick:e.toggle,"data-testid":"records-consent-sign-mode-toggle",children:e.mode==="draw"?te.toType:te.toDraw}),e.mode==="type"&&jsxRuntime.jsx("input",{"aria-label":te.type,style:{...n,display:"block",width:"100%",boxSizing:"border-box"},maxLength:xl,value:e.typed,disabled:r,autoComplete:"off",onChange:a=>e.setTyped(a.target.value)}),jsxRuntime.jsx("canvas",{ref:e.canvas,role:"img","aria-label":o.length>0?te.typedSignatureA11y(o):te.sign,style:{display:"block",width:"100%",height:160,maxWidth:"100%",boxSizing:"border-box",touchAction:"none",background:"#fff",border:`1px solid ${t.color.borderHairlineGreen}`,...r?{opacity:.6,pointerEvents:"none"}:{},...e.mode==="type"?{pointerEvents:"none"}:{}},onPointerDown:a=>{r||e.onPointerDown(a);},onPointerMove:a=>{r||e.onPointerMove(a);},onPointerUp:e.onPointerUp,onPointerCancel:e.onPointerUp}),jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:t.space.sm,marginTop:t.space.sm},children:[jsxRuntime.jsx("p",{style:{margin:0,fontSize:t.type.size.tiny,color:t.color.text.muted},"data-testid":"records-signature-hint",children:e.signed||e.mode==="type"?"\xA0":te.drawHint}),e.mode==="type"?null:jsxRuntime.jsx("button",{type:"button",style:s,disabled:r,onClick:e.clear,"aria-label":te.clearA11y,"data-testid":"records-signature-clear",children:te.clear})]})]})}i($t,"SignatureCanvas");function $n(e){let{userRef:r,scopeEpoch:t}=se();return jsxRuntime.jsx(Oe,{capability:"recordsClinic",...Fe(e.onClose,te.cancel),children:r===null?jsxRuntime.jsx("p",{role:"alert",children:X.sessionRequired}):jsxRuntime.jsx(df,{...Ie(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i($n,"EverfurClinicRequestBatch");function df(e){let r=zr(),t=ra(),o=e.controller??r,n=ye(),s=Mt(),a=bd(e,o,e.batchClient??t,e.onCaptureSignature??(async f=>s.signed?s.register(o,f.signal):null)),c=e.onCaptureSignature!==void 0||s.signed,l={minHeight:44,padding:n.space.sm,border:`1px solid ${n.color.borderHairlineGreen}`,borderRadius:n.radius.sm,background:n.color.surface,color:n.color.text.primary,font:"inherit"},d={...l,display:"block",width:"100%",boxSizing:"border-box"},u={...l,cursor:"pointer"},p={margin:0,color:n.color.text.muted,fontSize:n.type.size.bodyTight},m=i(f=>[f.name,f.address,f.phone].filter(Boolean).join(", "),"clinicLabel"),y=a.busy?je.sending:a.drafts.length===0?je.addToContinue:a.error?je.tryAgain:je.send(a.drafts.length),g=a.outcome?je.resultTitle:je.title;return jsxRuntime.jsxs("section",{className:e.className,"aria-label":g,style:{...Rt,background:n.color.surface,color:n.color.text.primary,padding:n.space.lg,borderRadius:n.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...e.style},children:[jsxRuntime.jsx("h2",{style:{margin:0,fontSize:n.type.size.heading},children:g}),jsxRuntime.jsx("p",{style:{margin:`${n.space.sm}px 0 ${n.space.lg}px`},children:e.petName}),a.outcome?jsxRuntime.jsxs("div",{style:{display:"grid",gap:n.space.sm},"data-testid":"records-batch-result",children:[jsxRuntime.jsx("p",{role:"status",style:{margin:0},children:a.outcome.createdCount===0?je.allFailed:a.outcome.failedCount>0?je.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):je.allSent(a.outcome.createdCount)}),jsxRuntime.jsx("h3",{style:{margin:0,fontSize:n.type.size.subtitle},children:je.perClinic}),jsxRuntime.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:n.space.sm},children:a.outcome.results.map((f,v)=>{let b=f.request?.clinicName??a.drafts[v]?.clinic?.name??f.clinicFreeText??"";return jsxRuntime.jsxs("li",{"data-testid":`records-batch-row-${f.created?"created":"failed"}`,children:[jsxRuntime.jsx("span",{children:b})," ",jsxRuntime.jsx("span",{style:p,children:f.created?je.sent:je.notSent}),f.created&&f.request?.statusLabel?jsxRuntime.jsx("p",{style:p,children:f.request.statusLabel}):null,!f.created&&f.failureReason?jsxRuntime.jsx("p",{style:p,children:f.failureReason}):null]},f.idempotencyKey)})}),a.group?jsxRuntime.jsx("p",{"aria-live":"polite",style:{margin:0},children:je.responded(a.group.responded,a.group.total)}):null,a.group?.members.map(f=>f.statusLabel?jsxRuntime.jsx("p",{style:p,children:[f.clinicName,f.statusLabel].filter(Boolean).join(": ")},f.id):null)]}):jsxRuntime.jsxs("div",{style:{display:"grid",gap:n.space.md},children:[jsxRuntime.jsxs("label",{children:[te.ownerName,jsxRuntime.jsx("input",{style:d,maxLength:200,value:a.ownerName,disabled:a.busy,autoComplete:"name",onChange:f=>{s.clear(),a.setOwnerName(f.target.value);}})]}),a.drafts.length>0&&jsxRuntime.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:n.space.sm},children:a.drafts.map(f=>jsxRuntime.jsxs("li",{"data-testid":`records-batch-draft-${f.key}`,style:{display:"grid",gap:n.space.xs},children:[jsxRuntime.jsx("span",{children:cn(f)}),dn(f)?jsxRuntime.jsxs("label",{children:[te.email,jsxRuntime.jsx("input",{style:d,type:"email",placeholder:te.emailPlaceholder,maxLength:320,autoComplete:"off",value:f.email,disabled:a.busy,onChange:v=>{s.clear(),a.setDraftEmail(f.key,v.target.value);}})]}):null,dn(f)&&!f.email.trim()?jsxRuntime.jsx("p",{style:p,children:je.emailToAdd}):null,jsxRuntime.jsx("button",{type:"button",style:u,disabled:a.busy,"aria-label":je.remove(cn(f)),onClick:()=>{s.clear(),a.removeDraft(f.key);},children:je.remove(cn(f))})]},f.key))}),jsxRuntime.jsx("p",{style:{margin:0},children:a.atCap?je.atCap:je.addClinic}),!a.atCap&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("label",{children:[te.clinic,jsxRuntime.jsx("input",{style:d,placeholder:te.placeholder,maxLength:200,value:a.query,disabled:a.busy,autoComplete:"off",onChange:f=>a.setQuery(f.target.value)})]}),jsxRuntime.jsx("button",{type:"button",style:u,disabled:a.busy||a.searching||a.query.trim().length<2,onClick:()=>{a.search();},children:te.search}),a.query.trim().length>0&&a.clinics.length===0&&!a.searching&&jsxRuntime.jsx("button",{type:"button",style:u,disabled:a.busy,onClick:()=>{s.clear(),a.addFreeText();},children:je.addClinic}),a.searching&&jsxRuntime.jsx("p",{role:"status",children:X.loading}),a.recent.length>0&&jsxRuntime.jsx("h3",{style:{margin:0,fontSize:n.type.size.subtitle},children:te.recentlyUsed}),a.recent.map(f=>jsxRuntime.jsx("button",{type:"button",style:u,disabled:a.busy,onClick:()=>{s.clear(),a.addClinic(f);},children:m(f)},`recent-${f.id}`)),a.visibleClinics.map(f=>jsxRuntime.jsx("button",{type:"button",style:u,disabled:a.busy,onClick:()=>{s.clear(),a.addClinic(f);},children:m(f)},f.id)),a.hasMoreClinics&&jsxRuntime.jsx("button",{type:"button",style:u,disabled:a.busy,onClick:a.showMoreClinics,"data-testid":"records-clinic-results-more",children:te.moreClinics})]}),jsxRuntime.jsx("h3",{style:{margin:`${n.space.sm}px 0 0`,fontSize:n.type.size.subtitle},children:te.scopeHeading}),a.copy?jsxRuntime.jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??H("internalError").displayMessage:X.consentRequired}):!a.error&&jsxRuntime.jsx("p",{role:"status",children:X.loading}),!e.onCaptureSignature&&jsxRuntime.jsx($t,{pad:s,disabled:a.busy}),!c&&a.ready&&jsxRuntime.jsx("p",{role:"alert","data-testid":"records-batch-missing-signature",children:te.missingSignature}),a.error&&jsxRuntime.jsx("p",{role:"alert",children:a.error.displayMessage}),!a.copy&&a.error&&jsxRuntime.jsx("button",{type:"button",style:u,onClick:a.retryCopy,children:X.retry}),jsxRuntime.jsx("button",{type:"button","aria-label":je.sendA11y(a.drafts.length),style:{...u,background:n.color.primary,color:n.color.onPrimary,opacity:a.busy||!a.ready||!c?.5:1},disabled:a.busy||!a.ready||!c,onClick:()=>{a.submit();},children:y})]}),e.onClose&&jsxRuntime.jsx("button",{type:"button",style:u,disabled:a.busy,onClick:e.onClose,children:te.cancel}),jsxRuntime.jsx(Ae,{})]})}i(df,"BatchBody");var be=Object.freeze({scopeHeading:"What we ask for",scopeBody:"You\u2019re asking your pet\u2019s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:i(e=>`I\u2019m ${Re(e)}\u2019s owner. I authorize Everfur to request these records on my behalf.`,"authorizeLabel"),missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We\u2019ll email this clinic directly to request your pet\u2019s medical records. Clinics usually reply within a week.",titleFreeText:"Check and send",titleDirectory:"Check and send",leadWeb:i(e=>`The clinic gets a secure request, with your permission to release ${Re(e)}\u2019s records to Everfur.`,"leadWeb"),leadNative:"The clinic gets a secure request, with your permission.",whatHappensNext:"What happens next",whatHappensNextBody:"Most clinics respond within 3 to 5 business days. We follow up automatically, and you can cancel any time before the records arrive.",noEmailNote:i((e,r)=>`We don\u2019t have an email on file for ${r}. Add it so we can request ${Re(e)}\u2019s records.`,"noEmailNote"),emailLabel:"Clinic email for records",emailPlaceholder:"records@clinic.com",emailRequired:"Add the clinic\u2019s records email to send the request.",emailInvalid:"That email doesn\u2019t look right. Check it and try again.",reuseSignature:"Reuse a previous signature",reuseHint:"\u2026or sign again below",reuseTileA11y:"Use this earlier signature",reuseTileSelectedA11y:"Earlier signature, selected",signType:"Type your name to sign",signDraw:"Sign with your finger",clear:"Clear",clearA11y:"Clear signature",fullName:"Your full name",fullNamePlaceholder:"Jane Doe",toType:"Can\u2019t draw? Type your name instead",toTypeA11y:"Can\u2019t draw? Type your name to sign instead",toDraw:"Draw your signature instead",signatureHint:i(e=>`Your signature is added to the authorization sent to ${e}.`,"signatureHint"),submit:"Send request",submitting:"Sending\u2026",submitA11y:"Send request"});var uf="value_text",xd=64,wd=512;function kd(e){return e!==null&&e.httpStatus===409&&!Yr(e)}i(kd,"isFactReviewerLocked");var Un=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:uf}),_d=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Pd=/^\d{4}-\d{2}-\d{2}$/;function Td(e){if(e==null)return "text";let r=e.trim();return _d.test(r)?"num":Pd.test(r)&&!Number.isNaN(Date.parse(r))?"date":r==="true"||r==="false"?"bool":"text"}i(Td,"inferFactValueKind");function fa(e,r){let t=r.trim(),o=Td(e);if(o==="num"&&_d.test(t)){let n=Number(t);if(Number.isFinite(n))return Object.freeze({[Un.num]:n})}return o==="date"&&Pd.test(t)&&!Number.isNaN(Date.parse(t))?Object.freeze({[Un.date]:t}):Object.freeze(o==="bool"&&(t==="true"||t==="false")?{[Un.bool]:t==="true"}:{[Un.text]:t})}i(fa,"factCorrectionFor");var qe=zod.z.string().nullish(),Lo=zod.z.number().nullish(),pf=zod.z.object({collected_at:qe,at:qe,value:Lo,unit:qe,qualitative_result:qe,ref_low:Lo,ref_high:Lo,status:qe,source_clinic:qe,source_doc_id:qe,doc_id:qe,reviewed:zod.z.boolean().nullish()}),mf=zod.z.object({collected_at:qe,at:qe,value:Lo,unit:qe,qualitative_result:qe,status:qe}),ff=zod.z.object({marker_id:zod.z.string().min(1),canonical_name:qe,name:qe,loinc_code:qe,canonical_unit:qe,unit:qe,panel_name:qe,panel:qe,meaning_text:qe,meaning:qe,latest:mf.nullish(),trajectory:qe,points:zod.z.array(pf).optional()}),yf=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()}),gf=zod.z.object({markers:zod.z.array(ff).optional(),summary:yf.nullish(),disclaimer:zod.z.string().optional(),featured_marker_id:qe});function bf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(bf,"isObject");function Dd(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Dd,"withheldMarkers");function Id(e,r){let t=bf(r)?r:{},o=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return Dd(o);let n=gf.safeParse(t);if(!n.success)return Dd(o);let s=n.data,a=i(l=>Object.freeze({at:l.collected_at??l.at??null,value:l.value??null,unit:l.unit??null,qualitativeResult:l.qualitative_result??null,refLow:l.ref_low??null,refHigh:l.ref_high??null,status:l.status??null,sourceClinic:l.source_clinic??null,docId:l.source_doc_id??l.doc_id??null,reviewed:l.reviewed===true}),"point"),c=(s.markers??[]).map(l=>Object.freeze({markerId:l.marker_id,name:l.canonical_name??l.name??l.marker_id,loincCode:l.loinc_code??null,unit:l.canonical_unit??l.unit??null,panel:l.panel_name??l.panel??null,meaning:l.meaning_text??l.meaning??null,latest:l.latest?Object.freeze({at:l.latest.collected_at??l.latest.at??null,value:l.latest.value??null,unit:l.latest.unit??null,qualitativeResult:l.latest.qualitative_result??null,status:l.latest.status??null}):null,trajectory:l.trajectory??null,points:Object.freeze((l.points??[]).map(a))}));return Object.freeze({petRef:o,withheld:false,markers:Object.freeze(c),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(Id,"mapRecordMarkers");var hf=zod.z.string().min(1).refine(e=>e.startsWith("https://")),Rf=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:hf,expires_in_seconds:zod.z.number().int().nonnegative().nullish()}),vf=zod.z.object({items:zod.z.array(zod.z.unknown()).optional()});function Od(e){let r=vf.safeParse(e);if(!r.success)return null;let t=[];for(let o of r.data.items??[]){let n=Rf.safeParse(o);n.success&&t.push(Object.freeze({sourceDocId:n.data.source_doc_id,fileName:n.data.file_name??null,docFormat:n.data.doc_format??null,byteSize:n.data.byte_size??null,receivedAt:n.data.received_at??null,downloadUrl:n.data.download_url,expiresInSeconds:n.data.expires_in_seconds??0}));}return Object.freeze(t)}i(Od,"mapRequestDocuments");var Cf=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 Ad(e){let r=Cf.safeParse(e);return r.success?Object.freeze((r.data.signatures??[]).map(t=>Object.freeze({signatureId:t.signature_id,previewUrl:t.preview_url,createdAt:t.created_at??null}))):null}i(Ad,"mapSignatureSuggestions");var G=zod.z.string().nullish(),Bn=zod.z.number().nullish(),Ef=zod.z.object({at:G,value:Bn,unit:G,qualitative_result:G,ref_low:Bn,ref_high:Bn,status:G,doc_id:G}),Sf=zod.z.object({marker_id:zod.z.string(),name:zod.z.string(),loinc_code:G,unit:G,panel:G,meaning:G,latest:zod.z.object({at:G,value:Bn,unit:G,qualitative_result:G,status:G}).nullish(),trajectory:G,points:zod.z.array(Ef).optional()}),xf=zod.z.object({encounter_id:zod.z.string(),date:G,type:G,clinic_name:G,veterinarian:G,doc_id:G}),wf=zod.z.object({note_id:zod.z.string(),encounter_id:G,observed_on:G,sections:zod.z.array(zod.z.object({section:zod.z.string(),text:zod.z.string()})).optional()}),kf=zod.z.object({exam_id:zod.z.string(),encounter_id:G,observed_on:G,doc_id:G,systems:zod.z.record(zod.z.object({finding_status:G,finding:G})).optional()}),_f=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:G,latest_record_at:G,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()}),Pf=zod.z.object({conflict_id:zod.z.string(),entity_type:zod.z.string(),field:G,severity:G,candidates:zod.z.array(zod.z.object({value:zod.z.string(),source_doc_id:G,doc_id:G,collected_at:G})).optional()}),Tf=zod.z.object({lab_results:zod.z.array(Sf).optional(),encounters:zod.z.array(xf).optional(),clinician_notes:zod.z.array(wf).optional(),physical_exams:zod.z.array(kf).optional(),completeness:_f.nullish(),conflicts:zod.z.array(Pf).optional()}),Df=zod.z.object({visits:zod.z.array(zod.z.object({visit_id:zod.z.string(),visit_date:G,veterinarian:G,summary:G,doc_id:G})),vaccines:zod.z.array(zod.z.object({vaccine_id:zod.z.string(),product:G,lot:G,administered_on:G,expires_on:G,doc_id:G})),weights:zod.z.array(zod.z.object({weight_id:zod.z.string(),observed_on:G,weight_kg:Bn,doc_id:G})),medications:zod.z.array(zod.z.object({medication_id:zod.z.string(),drug_name:G,dose:G,route:G,frequency:G,sig:G,rx_number:G,started_on:G,stopped_on:G,doc_id:G})),disclaimer:zod.z.string().optional()}),If=zod.z.object({document:Ri,contributions:zod.z.array(hi),contribution_count:zod.z.number().int().nonnegative().optional()});function ga(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ga,"isObject");function ba(e,r){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:r}i(ba,"petOf");function ya(e,r){return Object.freeze({petRef:e,available:false,withheld:r,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(ya,"emptyDepth");function Of(e,r){let t=ga(r)?r:{},o=ba(t,e);if(t.withheld===true)return ya(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(l=>l in t))return ya(o,false);let s=Tf.safeParse(t);if(!s.success)return ya(o,true);let a=s.data,c=i(l=>Object.freeze({at:l.at??null,value:l.value??null,unit:l.unit??null,qualitativeResult:l.qualitative_result??null,refLow:l.ref_low??null,refHigh:l.ref_high??null,status:l.status??null,docId:l.doc_id??null}),"point");return Object.freeze({petRef:o,available:true,withheld:false,labResults:Object.freeze((a.lab_results??[]).map(l=>Object.freeze({markerId:l.marker_id,name:l.name,loincCode:l.loinc_code??null,unit:l.unit??null,panel:l.panel??null,meaning:l.meaning??null,latest:Object.freeze({at:l.latest?.at??null,value:l.latest?.value??null,unit:l.latest?.unit??null,qualitativeResult:l.latest?.qualitative_result??null,status:l.latest?.status??null}),trajectory:l.trajectory??null,points:Object.freeze((l.points??[]).map(c))}))),encounters:Object.freeze((a.encounters??[]).map(l=>Object.freeze({encounterId:l.encounter_id,date:l.date??null,type:l.type??null,clinicName:l.clinic_name??null,veterinarian:l.veterinarian??null,docId:l.doc_id??null}))),clinicianNotes:Object.freeze((a.clinician_notes??[]).map(l=>Object.freeze({noteId:l.note_id,encounterId:l.encounter_id??null,observedOn:l.observed_on??null,sections:Object.freeze((l.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((a.physical_exams??[]).map(l=>Object.freeze({examId:l.exam_id,encounterId:l.encounter_id??null,observedOn:l.observed_on??null,docId:l.doc_id??null,systems:Object.freeze(Object.entries(l.systems??{}).map(([d,u])=>Object.freeze({system:d,findingStatus:u.finding_status??null,finding:u.finding??null})))}))),completeness:a.completeness?Object.freeze({hasLabHistory:a.completeness.has_lab_history===true,hasVaccinationHistory:a.completeness.has_vaccination_history===true,hasWeightHistory:a.completeness.has_weight_history===true,hasVitalsHistory:a.completeness.has_vitals_history===true,hasPhysicalExamHistory:a.completeness.has_physical_exam_history===true,hasProcedureHistory:a.completeness.has_procedure_history===true,hasGeneticHistory:a.completeness.has_genetic_history===true,hasReproductiveHistory:a.completeness.has_reproductive_history===true,hasParasitePreventionHistory:a.completeness.has_parasite_prevention_history===true,earliestRecordAt:a.completeness.earliest_record_at??null,latestRecordAt:a.completeness.latest_record_at??null,documentsIngested:a.completeness.documents_ingested??0,documentsInReview:a.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...a.completeness.entities_pending_review??{}}),heldTotal:a.completeness.held_total??0}):null,conflicts:Object.freeze((a.conflicts??[]).map(l=>Object.freeze({conflictId:l.conflict_id,entityType:l.entity_type,field:l.field??null,severity:l.severity??"needs_review",candidates:Object.freeze((l.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(Of,"mapRecordDepth");function Fd(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Fd,"withheldTimeline");function Af(e,r){let t=ga(r)?r:{},o=ba(t,e);if(t.withheld===true)return Fd(o);let n=Df.safeParse(t);if(!n.success)return Fd(o);let s=n.data,a=s.visits.map(u=>Object.freeze({visitId:u.visit_id,visitDate:u.visit_date??null,veterinarian:u.veterinarian??null,summary:u.summary??null,docId:u.doc_id??null})),c=s.vaccines.map(u=>Object.freeze({vaccineId:u.vaccine_id,product:u.product??null,lot:u.lot??null,administeredOn:u.administered_on??null,expiresOn:u.expires_on??null,docId:u.doc_id??null})),l=s.weights.map(u=>Object.freeze({weightId:u.weight_id,observedOn:u.observed_on??null,weightKg:u.weight_kg??null,docId:u.doc_id??null})),d=s.medications.map(u=>Object.freeze({medicationId:u.medication_id,drugName:u.drug_name??null,dose:u.dose??null,route:u.route??null,frequency:u.frequency??null,sig:u.sig??null,rxNumber:u.rx_number??null,startedOn:u.started_on??null,stoppedOn:u.stopped_on??null,docId:u.doc_id??null}));return Object.freeze({petRef:o,withheld:false,isEmpty:a.length===0&&c.length===0&&l.length===0&&d.length===0,visits:Object.freeze(a),vaccines:Object.freeze(c),weights:Object.freeze(l),medications:Object.freeze(d),disclaimer:s.disclaimer??""})}i(Af,"mapRecordsTimeline");function Ff(e,r){let t=ga(r)?r:{},o=ba(t,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(t.withheld===true)return n();let s=If.safeParse(t);if(!s.success)return n();let a=Object.freeze(s.data.contributions.map(vi));return Object.freeze({petRef:o,withheld:false,document:Ci(s.data.document),contributions:a,contributionCount:s.data.contribution_count??a.length})}i(Ff,"mapDocumentContributions");var qf="/widget/v1/records/pets";function qd(e){let r=e.funnel??ht({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),t=i((l,d)=>typeof l=="string"&&l.length>0&&!at(l)&&[...l].length<=d,"segment"),o=i(async(l,d,u,p)=>{if(!t(d,lr))return Br();let m=await r.send(l,{method:"GET",path:u});if(!m.ok)return m;let y=p(m.value);return y.petRef===d?Te(y):J(H("internalError",{retryable:false}))},"read"),n=i(l=>`${qf}/${encodeURIComponent(l)}`,"pet"),s=i(l=>`${n(l)}/everfur_record`,"record"),a=i(async(l,d,u)=>{let p=await r.send(l,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let m=u(p.value);return m===null?J(H("internalError",{retryable:false})):Te(m)},"parsed"),c=i((l,d)=>!t(l.entityType,xd)||!t(l.canonicalKey,wd)||l.idempotencyKey!==void 0&&!t(l.idempotencyKey,wn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:l.entityType,canonical_key:l.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...l.idempotencyKey!==void 0?{idempotency_key:l.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(l=>o("records.depth.record",l,`${n(l)}/record`,d=>Of(l,d)),"getRecordDepth"),getTimeline:i(l=>o("records.depth.timeline",l,`${n(l)}/timeline`,d=>Af(l,d)),"getTimeline"),getDocumentContributions(l,d){return t(d,64)?o("records.depth.contributions",l,`${n(l)}/documents/${encodeURIComponent(d)}/contributions`,u=>Ff(l,u)):Br()},getMarkers:i(l=>o("records.depth.markers",l,`${n(l)}/markers`,d=>Id(l,d)),"getMarkers"),createShare(l,d){if(!t(l,lr))return Br();let u=d?.audience;return u!==void 0&&!Kt.includes(u)?Br():a("records.share.create",{method:"POST",path:`${s(l)}/share`,...u!==void 0?{body:{audience:u}}:{}},p=>ys(p,e.apiBaseUrl))},emailShare(l,d){let u=d.recipientKind,p=typeof d.recipientEmail=="string"?d.recipientEmail.trim():"",m=u==="other"||Kt.includes(u);return !t(l,lr)||!m||!ao(p)||at(p)?Br():a("records.share.email",{method:"POST",path:`${s(l)}/share/email`,body:{recipient_email:p,recipient_kind:u}},bs)},async readFeatures(){try{let l=await r.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return l.ok?so(l.value):kr}catch{return kr}},listShares(l){return t(l,lr)?a("records.share.list",{method:"GET",path:`${s(l)}/shares`},gs):Br()},async revokeShare(l,d){if(!t(l,lr)||!t(d,64))return Br();let u=await r.send("records.share.revoke",{method:"DELETE",path:`${s(l)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?Te(void 0):u},getPdfLink(l){return t(l,lr)?a("records.pdf.link",{method:"GET",path:`${s(l)}/pdf-link`},hs):Br()},async editFact(l,d){let u=t(l,lr)?c(d,d.correctedFields):null;if(u===null)return Br();let p=await r.send("records.fact.edit",{method:"POST",path:`${s(l)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?Te(void 0):p},async removeFact(l,d){let u=t(l,lr)?c(d):null;if(u===null)return Br();let p=await r.send("records.fact.remove",{method:"POST",path:`${s(l)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?Te(void 0):p},listRequestDocuments(l){return t(l,64)?a("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(l)}/documents`},Od):Br()},listAuthorizationSignatures:i(()=>a("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Ad),"listAuthorizationSignatures")}}i(qd,"createRecordsDepthClient");function Br(){return Promise.resolve(J(H("validationFailed",{retryable:false})))}i(Br,"invalid");function Rr(){let{runtime:e,userRef:r,scopeEpoch:t}=se();return react.useMemo(()=>{let{services:o}=e.registry;return qd({auth:o.authFor(r),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,r,t])}i(Rr,"useEverfurRecordsDepthClient");function Hr(e,r,t,o=""){let n=Rr(),{userRef:s}=se(),a=po(e),c=react.useMemo(()=>({}),[n,e,o,a]),[l,d]=react.useState({scope:c,value:null,error:null,loading:true}),u=react.useRef(0),p=react.useCallback(async()=>{let b=u.current+=1;if(d({scope:c,value:null,error:null,loading:true}),s===null){d({scope:c,value:null,error:null,loading:false});return}let R=await r(n,e);b===u.current&&(R.ok?d({scope:c,value:R.value,error:null,loading:false}):d({scope:c,value:null,error:R.error,loading:false}));},[n,e,r,c,s]);react.useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let m=l.scope===c?l:{value:null,error:null,loading:true},y=react.useCallback(()=>{p();},[p]),g=m.error===null||m.error.httpStatus!==404,f=g?m.error:null,v=m.loading?"loading":f!==null?"error":m.value===null?"empty":m.value.withheld?"populated":t(m.value)?"empty":"populated";return react.useMemo(()=>({status:v,value:m.value,error:f,available:g,refresh:y}),[v,m.value,f,g,y])}i(Hr,"useRecordsDepthRead");function pt(e){return e!==null&&e.httpStatus===404}i(pt,"isDarkRouteError");var $f=i((e,r)=>e.getMarkers(r),"readMarkers"),Uf=i(e=>e.markers.length===0,"markersEmpty");function Ra(e){let r=Hr(e,$f,Uf);return react.useMemo(()=>{let t=r.available&&r.value!==null&&!r.value.withheld?r.value:null;return {status:r.status,markers:t,available:r.available,error:r.error,refresh:r.refresh}},[r])}i(Ra,"useRecordsMarkers");var Bf=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function zd(e){let{clinic:r,controller:t,depthClient:o,capture:n,onCreated:s}=e,a=r.clinic?.name??r.freeText??"",c=r.clinic===null,[l,d]=react.useState(false),[u,p]=react.useState(e.ownerName),[m,y]=react.useState(r.email),[g,f]=react.useState(false),[v,b]=react.useState(null),[R,h]=react.useState(null),[E,S]=react.useState(0),[C,k]=react.useState(null),[M,T]=react.useState(false),[O,z]=react.useState(null),[q,N]=react.useState([]),[B,x]=react.useState(null),[L,F]=react.useState(false),W=react.useRef(false),I=react.useRef(true),w=react.useRef(it()),A=react.useRef(null);react.useEffect(()=>(I.current=true,()=>{I.current=false,A.current=null;}),[t]),react.useEffect(()=>{let xe=true;return b(null),A.current=null,t.getAuthorizationCopy().then(ur=>{xe&&(ur.ok?(b(ur.value),h(null)):h(ur.error));}).catch(()=>{xe&&h(H("internalError"));}),()=>{xe=false;}},[t,E]),react.useEffect(()=>{if(o===void 0)return;let xe=true;return o.listAuthorizationSignatures().then(ur=>{xe&&(ur.ok?N(ur.value):pt(ur.error)||N([]));}).catch(()=>{}),()=>{xe=false;}},[o]);let _=Mn(r.clinic),Y=m.trim().toLowerCase(),me=Bf.test(Y),Ne=_&&(g||Y.length>0)&&!me?Y.length>0?be.emailInvalid:be.emailRequired:null,re=v?zn(v,u.trim(),Re(e.petName),a):null,oe=e.hostCapture===true||L||B!==null,Se=!!(l&&v&&re&&u.trim()&&a&&oe&&(!_||me)),Pe=react.useCallback(async()=>{if(!(W.current||O!==null||!v||!re)){if(!a){k(be.missingDraftError);return}if(_&&!me){f(true),k(Y.length>0?be.emailInvalid:be.emailRequired);return}if(!(!l||!u.trim())){W.current=true,T(true),k(null);try{if(A.current===null){let ur=B!==null?{signatureId:B}:await n();if(!I.current)return;if(ur===null){k(be.missingSignatureError);return}let ie=r.clinic&&(!_||r.clinic.emailStatus==="none")?{clinicId:r.clinic.id}:{clinicFreeText:a};A.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:v.authorizationVersion,...ie,..._?{clinicEmail:Y}:{},...ur.signatureId!==void 0?{signatureId:ur.signatureId}:{signaturePngBase64:ur.signaturePngBase64},idempotencyKey:w.current()};}let xe=await t.createClinicRequest(A.current);if(!I.current)return;if(!xe.ok){k(xe.error.displayMessage);return}if(xe.value.petRef!==e.petRef){k(H("internalError").displayMessage);return}z(xe.value),A.current=null,s?.(xe.value);}catch{I.current&&k(H("internalError").displayMessage);}finally{W.current=false,I.current&&T(false);}}}},[l,n,r.clinic,a,t,v,O,e.petRef,_,Y,s,u,B,re,me]),Ge=react.useCallback(()=>{A.current=null,k(null);},[]);return {title:c?be.titleFreeText:be.titleDirectory,clinicName:a,isFreeText:c,authorized:l,ownerName:u,email:m,emailError:Ne,needsEmail:_,directoryClinicNoEmail:_&&r.clinic!==null,copy:v,copyError:R,scope:re,error:C,busy:M,created:O,ready:Se,signatures:q,reuseSignatureId:B,hasSignature:oe,setAuthorized(xe){W.current||(Ge(),d(xe));},setOwnerName(xe){W.current||(Ge(),p(xe));},setEmail(xe){W.current||(Ge(),f(false),y(xe));},setSigned(xe){W.current||(Ge(),F(xe),xe&&x(null));},pickReuseSignature(xe){W.current||(Ge(),x(xe));},retryCopy(){h(null),S(xe=>xe+1);},submit:Pe}}i(zd,"useRecordsConsentForm");function Hn(e){let{userRef:r,scopeEpoch:t}=se();return jsxRuntime.jsx(Oe,{capability:"recordsClinic",style:e.style,className:e.className,...Fe(e.onBack,Me),children:r===null?jsxRuntime.jsx("p",{role:"alert",children:X.sessionRequired}):jsxRuntime.jsx(Vf,{...Ie(e,["onCreated","onNavigate","onBack"])},JSON.stringify([r,t,e.petRef,e.clinic.key]))})}i(Hn,"EverfurRecordsConsent");function Vf({petRef:e,petName:r,clinic:t,ownerName:o,onCaptureSignature:n,onCreated:s,controller:a,onNavigate:c,onBack:l,style:d,className:u}){let{theme:p,styles:m}=V(),y=zr(),g=a??y,f=Rr(),v=Mt(),b=xt(),R=zd({petRef:e,petName:r,ownerName:o??"",clinic:t,controller:g,depthClient:f,capture:n?()=>n({petRef:e,petName:Re(r),ownerName:R.ownerName,clinicName:R.clinicName,authorizationVersion:R.copy?.authorizationVersion??"",scopeText:R.scope??"",signal:new AbortController().signal}):async()=>v.signed?v.register(g,new AbortController().signal):null,hostCapture:n!==void 0,onCreated:i(T=>{s?.(T),c?.({name:"dashboard"});},"onCreated")}),h=v.signed,E=react.useRef(R);E.current=R,react.useEffect(()=>{E.current.setSigned(h);},[h]);let S=R.busy,C={display:"flex",flexDirection:"column",gap:p.space.sm},k="records-consent-owner-name",M="records-consent-clinic-email";return jsxRuntime.jsxs("div",{className:u,style:{...m.root,...d},"data-testid":"records-consent-screen",children:[jsxRuntime.jsx(Ke,{title:R.title,onBack:l,testID:"records-consent-header"}),jsxRuntime.jsx("p",{style:m.subLead,"data-testid":"records-consent-lead",children:be.leadWeb(r)}),jsxRuntime.jsxs("div",{ref:b,style:{...m.body,...m.content,gap:p.space.lg+p.space.xs/2},"data-testid":"records-consent",children:[jsxRuntime.jsxs("section",{style:m.creamCard,"aria-label":be.scopeHeading,children:[jsxRuntime.jsx("h3",{style:{...m.sectionTitle,color:p.color.brandInk},children:be.scopeHeading}),jsxRuntime.jsx("p",{style:m.bodyText,children:be.scopeBody}),jsxRuntime.jsx("ul",{style:{...m.plainList,gap:p.space.sm},children:be.whatWeDo.map(T=>jsxRuntime.jsxs("li",{style:{...m.bodyText,display:"flex",gap:p.space.sm},children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:{color:p.color.brandInk,...D(p,"bold")},children:"\u2713"}),jsxRuntime.jsx("span",{children:T})]},T))}),jsxRuntime.jsx("p",{style:{...m.muted,paddingTop:p.space.xs,borderTop:`1px solid ${p.color.borderHairlineGreen}`},children:be.retentionNote}),R.copy&&R.scope?jsxRuntime.jsx("p",{style:{...m.rowDetail,whiteSpace:"pre-wrap"},"data-testid":"records-consent-scope",children:R.scope}):R.copyError?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("p",{role:"alert",style:m.errorText,children:R.copyError.displayMessage}),jsxRuntime.jsx(j,{label:X.retry,kind:"outline",onClick:R.retryCopy,testID:"records-consent-copy-retry"})]}):jsxRuntime.jsx("p",{role:"status",style:m.muted,children:X.loading})]}),jsxRuntime.jsxs("button",{type:"button",role:"checkbox","aria-checked":R.authorized,onClick:()=>R.setAuthorized(!R.authorized),style:{display:"flex",alignItems:"flex-start",gap:p.space.md,textAlign:"left",font:"inherit",cursor:"pointer",borderRadius:p.radius.lg-p.space.xs,border:`1px solid ${R.authorized?p.color.brand:p.color.brandBorder}`,backgroundColor:R.authorized?p.color.brandSoft:p.color.surface,padding:p.space.md+p.space.xs/2,color:p.color.text.primary},"data-testid":"records-authorize-toggle",children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:{boxSizing:"border-box",flexShrink:0,width:p.space.xl,height:p.space.xl,borderRadius:p.radius.xs+1,border:`1.6px solid ${p.color.brandInk}`,backgroundColor:R.authorized?p.color.brand:p.color.surface,color:p.color.onPrimary,display:"inline-flex",alignItems:"center",justifyContent:"center",...D(p,"bold")},children:R.authorized?"\u2713":""}),jsxRuntime.jsx("span",{style:{...m.rowTitle,...D(p,"bold"),fontSize:p.type.size.bodyTight},children:be.authorizeLabel(r)})]}),jsxRuntime.jsxs("div",{style:C,children:[jsxRuntime.jsx("label",{htmlFor:k,style:m.fieldLabel,children:be.fullName}),jsxRuntime.jsx("input",{id:k,style:m.field,value:R.ownerName,placeholder:be.fullNamePlaceholder,maxLength:200,disabled:S,autoComplete:"name",onChange:T=>R.setOwnerName(T.target.value),"data-testid":"records-consent-owner-name"})]}),R.needsEmail?jsxRuntime.jsxs("div",{style:C,"data-testid":"records-consent-email-block",children:[R.directoryClinicNoEmail?jsxRuntime.jsx("p",{style:m.cautionNote,"data-testid":"records-consent-no-email-note",children:be.noEmailNote(r,R.clinicName)}):null,jsxRuntime.jsx("label",{htmlFor:M,style:m.fieldLabel,children:be.emailLabel}),jsxRuntime.jsx("input",{id:M,type:"email",style:m.field,value:R.email,placeholder:be.emailPlaceholder,maxLength:320,disabled:S,autoComplete:"off",onChange:T=>R.setEmail(T.target.value),"data-testid":"records-consent-clinic-email"}),R.emailError?jsxRuntime.jsx("p",{role:"alert",style:m.errorText,children:R.emailError}):null,jsxRuntime.jsx("p",{style:m.muted,"data-testid":"records-consent-review-note",children:be.newClinicDirectSendNote})]}):null,n?null:jsxRuntime.jsxs("div",{style:C,children:[R.signatures.length>0?jsxRuntime.jsxs("div",{style:C,children:[jsxRuntime.jsx("span",{style:m.fieldLabel,children:be.reuseSignature}),jsxRuntime.jsx("div",{style:{display:"flex",gap:p.space.sm,overflowX:"auto",padding:`${p.space.xs}px 0`},children:R.signatures.map(T=>{let O=R.reuseSignatureId===T.signatureId;return jsxRuntime.jsx("button",{type:"button",onClick:()=>R.pickReuseSignature(O?null:T.signatureId),"aria-label":O?be.reuseTileSelectedA11y:be.reuseTileA11y,"aria-pressed":O,style:{flexShrink:0,width:112,height:56,borderRadius:p.radius.sm,border:O?`2px solid ${p.color.brandInk}`:`1px solid ${p.color.brandBorder}`,backgroundColor:p.color.surface,padding:0,overflow:"hidden",cursor:"pointer"},"data-testid":`records-consent-reuse-${T.signatureId}`,children:jsxRuntime.jsx("img",{src:T.previewUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"contain"}})},T.signatureId)})}),jsxRuntime.jsx("p",{style:m.muted,children:be.reuseHint})]}):null,jsxRuntime.jsx($t,{pad:v,disabled:S}),jsxRuntime.jsx("p",{style:m.muted,children:be.signatureHint(R.clinicName)}),!R.hasSignature&&R.clinicName.length>0?jsxRuntime.jsx("p",{style:m.muted,"data-testid":"records-consent-signature-required",children:be.missingSignatureError}):null]}),jsxRuntime.jsxs("section",{style:{...m.creamCard,backgroundColor:p.color.surfaceSubtle,border:0},"aria-label":be.whatHappensNext,"data-testid":"records-consent-next",children:[jsxRuntime.jsx("h3",{style:m.sectionTitle,children:be.whatHappensNext}),jsxRuntime.jsx("p",{style:m.bodyText,children:be.whatHappensNextBody})]}),R.error?jsxRuntime.jsx("p",{role:"alert","aria-live":"assertive",style:m.errorBanner,children:R.error}):null,R.created?jsxRuntime.jsx("p",{role:"status",style:m.bodyText,children:R.created.statusLabel||X.records}):null]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:p.space.sm,padding:`${p.space.md}px ${p.space.lg}px ${p.space.xxl}px`,borderTop:`1px solid ${p.color.borderHairlineGreen}`,backgroundColor:p.color.background},children:[l?jsxRuntime.jsx(j,{label:Me,kind:"link",disabled:S,onClick:l,style:{flex:"0 0 auto"},testID:"records-consent-cancel"}):null,jsxRuntime.jsx(j,{label:S?be.submitting:be.submit,ariaLabel:be.submitA11y,disabled:!R.ready,busy:S,onClick:()=>{R.submit();},style:{flex:"1 1 12rem",minWidth:0,minHeight:54},testID:"records-consent-submit"})]}),jsxRuntime.jsx(Ae,{})]})}i(Vf,"ConsentBody");var Mo=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function Md(e){if(!e)return null;let r=Date.parse(e);return Number.isNaN(r)?null:r}i(Md,"toMillis");function $d(e){let r=[...e.visits.map((t,o)=>({key:`visit-${o}-${t.visitId}`,kind:"visit",kindLabel:ge.kind.visit,at:t.visitDate,date:ee(t.visitDate),title:t.summary??ge.clinicVisit,detail:t.veterinarian?ge.doctor(t.veterinarian):null,docId:t.docId})),...e.vaccines.map((t,o)=>{let n=[];return t.lot&&n.push(ge.lot(t.lot)),t.expiresOn&&n.push(ge.expires(ee(t.expiresOn))),{key:`vaccine-${o}-${t.vaccineId}`,kind:"vaccine",kindLabel:ge.kind.vaccine,at:t.administeredOn,date:ee(t.administeredOn),title:t.product||ge.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:t.docId}}),...e.weights.map((t,o)=>({key:`weight-${o}-${t.weightId}`,kind:"weight",kindLabel:ge.kind.weight,at:t.observedOn,date:ee(t.observedOn),title:od(t.weightKg),detail:null,docId:t.docId})),...e.medications.map((t,o)=>{let n=[t.dose,t.route,t.frequency].filter(s=>!!s);return {key:`medication-${o}-${t.medicationId}`,kind:"medication",kindLabel:ge.kind.medication,at:t.startedOn,date:ee(t.startedOn),title:t.drugName||ge.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:t.docId}})];return Object.freeze(r.sort((t,o)=>{let n=Md(t.at),s=Md(o.at);return n===null&&s===null?Mo[t.kind]-Mo[o.kind]:n===null?1:s===null?-1:s!==n?s-n:Mo[t.kind]-Mo[o.kind]}))}i($d,"buildTimelineRows");var Xf=300,Ud=120,Bd=44,Jf=i((e,r)=>e.getTimeline(r),"readTimeline"),Zf=i(e=>e.isEmpty,"timelineEmpty");var ey=i(e=>e.contributions.length===0,"contributionsEmpty");function $o({petRef:e,style:r,className:t,onBack:o}){let n=Hr(e,Jf,Zf);return jsxRuntime.jsx(Hd,{state:n,style:r,className:t,onBack:o,header:jsxRuntime.jsx(Ke,{title:ge.timeline,onBack:Dn(o),testID:"timeline-header"}),loading:jsxRuntime.jsx(md,{testID:"timeline-loading"}),empty:jsxRuntime.jsx(He,{variant:"no_records",testID:"timeline-empty"}),render:s=>jsxRuntime.jsx(ny,{timeline:s})})}i($o,"EverfurRecordsTimeline");function Uo({petRef:e,docId:r,style:t,className:o,onBack:n}){let s=react.useCallback((l,d)=>l.getDocumentContributions(d,r),[r]),a=Hr(e,s,ey,r),c=a.value?.document?.title?.trim()||ge.uploadedDocument;return jsxRuntime.jsx(Hd,{state:a,style:t,className:o,onBack:n,header:jsxRuntime.jsx(Ke,{title:c,onBack:Dn(n),testID:"contributions-header"}),empty:jsxRuntime.jsx(He,{variant:"no_records",testID:"contributions-empty"}),render:l=>jsxRuntime.jsx(oy,{view:l})})}i(Uo,"EverfurDocumentContributions");function Hd({state:e,style:r,className:t,header:o,loading:n,empty:s,render:a,onBack:c}){let{styles:l}=Ca(),{userRef:d}=se();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...Fe(Dn(c),Me),children:jsxRuntime.jsxs("div",{className:t,style:{...l.container,...r},children:[o??null,jsxRuntime.jsx("div",{style:l.body,children:d===null?jsxRuntime.jsx("p",{role:"alert",style:l.alertText,children:X.sessionRequired}):ry(e,a,l,n,s)}),jsxRuntime.jsx(Ae,{})]})})}i(Hd,"DepthSurface");function ry(e,r,t,o,n){switch(e.status){case "loading":return o??jsxRuntime.jsx(ty,{styles:t});case "empty":return n??jsxRuntime.jsx("div",{style:t.centered,children:jsxRuntime.jsx("div",{role:"img","aria-label":X.empty,style:t.emptyGlyph})});case "error":return e.error?jsxRuntime.jsx(He,{variant:nr(e.error),message:e.error.displayMessage,onAction:e.error.retryable?e.refresh:void 0,testID:"depth-error"}):null;case "populated":return e.value===null||e.value.withheld?null:r(e.value);default:return null}}i(ry,"renderState");function ty({styles:e}){let[r,t]=react.useState(false);return react.useEffect(()=>{let o=setTimeout(()=>t(true),Xf);return ()=>clearTimeout(o)},[]),jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":X.loading,style:e.centered,children:r?jsxRuntime.jsx("div",{"aria-hidden":"true",style:e.spinner}):null})}i(ty,"LoadingState");function ny({timeline:e}){let{styles:r}=Ca(),t=$d(e);return jsxRuntime.jsxs("section",{"aria-label":ge.timeline,style:r.timelineList,children:[e.disclaimer.length>0?jsxRuntime.jsx("p",{role:"note","aria-label":yr.important(e.disclaimer),style:r.timelineBand,children:e.disclaimer}):null,jsxRuntime.jsx("ul",{style:r.plainList,children:t.map((o,n)=>jsxRuntime.jsx("li",{style:n>0?r.timelineSeparated:void 0,"data-testid":`records-timeline-row-${o.kind}`,children:jsxRuntime.jsxs("div",{style:r.timelineRow,"aria-label":[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:r.timelineBubble}),jsxRuntime.jsxs("div",{style:r.timelineBody,children:[jsxRuntime.jsxs("div",{style:r.topLine,children:[jsxRuntime.jsx("span",{style:r.timelineKind,children:o.kindLabel}),jsxRuntime.jsx("span",{style:r.date,children:o.date})]}),jsxRuntime.jsx("span",{style:r.timelineTitle,children:o.title}),o.detail?jsxRuntime.jsx("span",{style:r.rowDetail,children:o.detail}):null]})]})},o.key))})]})}i(ny,"TimelineBody");function oy({view:e}){let{styles:r}=Ca();return jsxRuntime.jsxs("section",{"aria-label":X.records,style:r.list,children:[e.document?.receivedAt?jsxRuntime.jsx("p",{style:r.rowDetail,children:ee(e.document.receivedAt)}):null,jsxRuntime.jsx("dl",{style:r.card,children:e.contributions.map(t=>jsxRuntime.jsxs("div",{style:r.row,children:[jsxRuntime.jsx("dt",{style:r.rowTitle,children:t.label}),jsxRuntime.jsx("dd",{style:r.rowValue,children:tn(t.value,t.unit)}),t.observedAt?jsxRuntime.jsx("dd",{style:r.rowDetail,children:ee(t.observedAt)}):null]},t.key))})]})}i(oy,"ContributionsBody");function Ca(){let e=ye(),r=react.useMemo(()=>iy(e),[e]);return {theme:e,styles:r}}i(Ca,"useDepthTheme");function iy(e){let{color:r,space:t,radius:o,type:n,slots:s}=e,a=i((m,y)=>`${Math.round(m*y)}px`,"lh"),c=i((m,y,g,f="regular")=>({margin:0,...D(e,f),fontSize:m,lineHeight:a(m,y),color:g}),"text"),l=tt(s.recordCard),d=i((m,y,g,f="regular")=>({...c(m,y,g,f),...l}),"inCard"),u=`1px solid ${r.brandBorder}`,p=e.brightness==="dark"?r.errorRed:r.danger;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:Ud,height:"100%",backgroundColor:r.background,color:r.text.primary,...D(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:Ud,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:t.lg,padding:t.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:24,height:24,borderRadius:o.pill,border:`3px solid ${r.brandSofter}`,borderTopColor:r.brandInk},emptyGlyph:{boxSizing:"border-box",width:40,height:40,borderRadius:o.lg,backgroundColor:r.brandSoft,border:u},alertText:c(n.size.subtitle,n.lineHeight.snug,r.text.secondary),errorText:c(n.size.subtitle,n.lineHeight.snug,p),primaryButton:{boxSizing:"border-box",minHeight:Bd,minWidth:Bd,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...D(e,"bold"),fontSize:n.size.body,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Mr(s.primaryButton),...tt(s.primaryButton)},list:{display:"flex",flexDirection:"column",gap:t.md,padding:t.lg},section:{display:"flex",flexDirection:"column",gap:t.sm},heading:{...c(n.size.heading,n.lineHeight.snug,r.text.primary,"bold")},card:{boxSizing:"border-box",listStyle:"none",display:"flex",flexDirection:"column",gap:t.sm,margin:0,padding:t.md,borderRadius:o.md,backgroundColor:r.surfaceCream,border:u,...Mr(s.recordCard,1)},plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:t.sm},row:{display:"flex",flexDirection:"column",gap:t.xs,padding:`${t.xs}px 0`,borderBottom:`1px solid ${r.borderHairlineGreen}`},topLine:{display:"flex",justifyContent:"space-between",gap:t.md},kindLabel:{...d(n.size.caption,n.lineHeight.normal,r.text.muted,"medium")},date:d(n.size.caption,n.lineHeight.normal,r.text.muted),rowTitle:{...d(n.size.body,n.lineHeight.normal,r.text.primary,"bold")},rowValue:{...d(n.size.body,n.lineHeight.normal,r.text.primary,"medium")},rowDetail:d(n.size.bodyTight,n.lineHeight.normal,r.text.muted),rowMuted:{...d(n.size.bodyTight,n.lineHeight.normal,r.text.muted),opacity:.7},chip:{...c(n.size.caption,n.lineHeight.normal,r.text.primary),alignSelf:"flex-start",padding:`${t.xs}px ${t.sm}px`,borderRadius:o.pill},chipNeutral:{backgroundColor:r.badgeBgNeutral},chipCaution:{backgroundColor:r.badgeBgCaution},chipCritical:{backgroundColor:r.badgeBgCritical},disclaimer:c(n.size.caption,n.lineHeight.normal,r.text.muted),timelineList:{display:"flex",flexDirection:"column",paddingBottom:t.xxl},timelineBand:{...c(n.size.caption,n.lineHeight.normal,r.text.secondary),borderRadius:o.md-t.xs/2,padding:t.md,backgroundColor:r.brandSoft,margin:`${t.xs}px ${t.lg}px ${t.md}px`},timelineSeparated:{borderTop:`1px solid ${r.brandBorder}`,marginLeft:ca,paddingLeft:0},timelineRow:{display:"flex",gap:t.md,padding:`${t.md+t.xs/2}px ${t.lg}px`},timelineBubble:{boxSizing:"border-box",flexShrink:0,width:34,height:34,borderRadius:o.pill,backgroundColor:r.brandSoft,border:u},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:t.xs-1,minWidth:0},timelineKind:{...D(e,"mono"),fontSize:n.size.micro,lineHeight:`${n.size.bodyTight}px`,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:r.text.secondary},timelineTitle:{...c(n.size.body,n.lineHeight.normal,r.text.primary,"medium")}}}i(iy,"makeStyles");function Ea(e,r={}){let t=Rr(),{userRef:o}=se(),n=r.now??Date.now,[s,a]=react.useState(null),[c,l]=react.useState(true),[d,u]=react.useState(null),[p,m]=react.useState(null),y=p===true,[g,f]=react.useState({}),[v,b]=react.useState(false),[R,h]=react.useState(null),[E,S]=react.useState(false),[C,k]=react.useState(false),[M,T]=react.useState(false),[O,z]=react.useState(null),q=O!==null&&O.client===t?O.value:kr,N=q.shareAudiences,B=po(e),x=react.useRef(0),L=react.useRef(true),F=react.useCallback(async()=>{let oe=x.current+=1;if(l(true),u(null),o===null){a(null),l(false);return}let Se=await t.listShares(e);oe!==x.current||!L.current||(Se.ok?(a(Se.value),m(true)):pt(Se.error)?(a(null),m(false)):(a(null),u(Se.error),jd(Se)&&m(true)),l(false));},[t,e,o]);react.useEffect(()=>(L.current=true,F(),()=>{L.current=false,x.current+=1;}),[F]),react.useEffect(()=>{if(o===null||t.readFeatures===void 0)return;let oe=true;return t.readFeatures().then(Se=>{oe&&z({client:t,value:Se});},()=>{}),()=>{oe=false;}},[t,o]);let W=react.useRef(B);react.useEffect(()=>{W.current!==B&&(W.current=B,f({}),k(true),F());},[B,F]);let I=react.useCallback(async oe=>{b(true);let Pe=await(oe!==void 0&&N.some(Ge=>Ge.audience===oe)?t.createShare(e,{audience:oe}):t.createShare(e));return L.current&&(b(false),Pe.ok?(f(Ge=>({...Ge,[Pe.value.shareId]:Pe.value.shareUrl})),F()):pt(Pe.error)?m(false):Yr(Pe.error)&&k(true)),Pe},[t,e,F,N]),w=react.useCallback(async oe=>{T(true);let Se=await t.emailShare(e,oe);return L.current&&(T(false),Se.ok?F():pt(Se.error)?m(false):Yr(Se.error)?k(true):Se.error.httpStatus===502&&F()),Se},[t,e,F]),A=react.useCallback(async oe=>{h(oe);let Se=await t.revokeShare(e,oe);return L.current&&(h(null),F()),Se},[t,e,F]),_=react.useCallback(async()=>{S(true);let oe=await t.getPdfLink(e);return L.current&&(S(false),!oe.ok&&Yr(oe.error)&&k(true)),oe},[t,e]),Y=react.useCallback(()=>{k(false),F();},[F]),me=react.useMemo(()=>cd(s??[],g,n()),[s,g,n]),Ne=c?"loading":d!==null?"error":me.length===0?"empty":"populated",re=q.features;return react.useMemo(()=>({status:Ne,rows:me,available:y,consentRequired:C,error:d,creating:v,revokingId:R,preparingPdf:E,shareAudiences:N,features:re,sending:M,createLink:I,sendEmail:w,revoke:A,pdfLink:_,refresh:Y}),[Ne,me,y,C,d,v,R,E,N,re,M,I,w,A,_,Y])}i(Ea,"useRecordShares");function jd(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(jd,"answeredBehindGate");function Vd(e){return e.available||e.status!=="empty"}i(Vd,"sharesListShown");function Sa(e){let r=Rr(),{userRef:t}=se(),o=react.useMemo(()=>({}),[r,e,t]),[n,s]=react.useState({scope:o,lit:null});react.useEffect(()=>{if(t===null)return;let c=true;return r.listShares(e).then(l=>{c&&(!l.ok&&pt(l.error)?s({scope:o,lit:false}):jd(l)&&s({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[r,e,t,o]);let a=n.scope===o?n.lit:null;return react.useMemo(()=>({lit:a}),[a])}i(Sa,"useRecordsDepthProbe");function xa(e){let r=Rr(),o=Sa(e).lit===true,[n,s]=react.useState(false),[a,c]=react.useState(null),l=react.useRef(true);react.useEffect(()=>(l.current=true,()=>{l.current=false;}),[]);let d=react.useCallback(async()=>{s(true),c(null);let u=await r.getPdfLink(e);return l.current&&(s(false),u.ok||c(u.error)),u},[r,e]);return react.useMemo(()=>({preparing:n,available:o,error:a,pdfLink:d}),[n,o,a,d])}i(xa,"useRecordPdfLink");var Wn=Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:i(e=>`Call the clinic at ${e}`,"callAt")});var ay=Math.round(Kr/(1024*1024)),Qe=Object.freeze({title:i(e=>`Upload ${Re(e)}\u2019s records`,"title"),screenTitle:"Upload a document",subtitle:i(e=>`Already have lab results, a vet summary, or test reports? Add them here and we\u2019ll read them and pull out ${Re(e)}\u2019s health markers.`,"subtitle"),noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${ay} MB each. You can pick several at once. We\u2019ll read them and add the results to your records.`,chooseFiles:"Choose a file",chooseFilesA11y:"Choose records to upload",uploading:i((e,r)=>`Uploading ${Math.min(e+1,r)} of ${r}\u2026`,"uploading"),cancel:"Cancel",cancelA11y:"Cancel these uploads",received:i(e=>`${e===1?"Record received.":`${e} records received.`} We\u2019ll read and review ${e===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,"received"),retryFailed:i(e=>`Retry ${e} that didn\u2019t upload`,"retryFailed"),retryFailedA11y:i(e=>`Retry ${e} failed upload${e>1?"s":""}`,"retryFailedA11y"),haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:Object.freeze({start:"We couldn\u2019t start that upload. Check your connection and try again.",startPlain:"We couldn\u2019t start that upload. Please try again.",upload:"We couldn\u2019t upload that record. Check your connection and try again."})}),Gn=Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can\u2019t read this kind of file. Upload a PDF or a photo of the record."});var wa=Math.round(Kr/(1024*1024)),Ht=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,r)=>`Uploading ${Math.min(e+1,r)} of ${r} records`,"uploading"),uploaded:i((e,r)=>`${e} of ${r} records uploaded`,"uploaded")});function Wd(e){let r=Math.round(e.progress*100);switch(e.status){case "done":return Ht.done;case "failed":return Ht.failed;case "uploading":return e.progress>=1?Ht.verifying:`${r}%`;case "queued":return Ht.queued;default:return null}}i(Wd,"uploadItemStatusLabel");function Ho(e,r=false){if(e.length===0)return null;let t=i(a=>{let c=a.map(l=>l.name??"");return c.length<=3?c.join(", "):`${c.slice(0,3).join(", ")} and ${c.length-3} more`},"nameList"),o=e.filter(a=>a.reason==="too_large"),n=e.filter(a=>a.reason==="unsupported");if(r){let a=[];return n.length>0&&a.push(Gn.unreadable),o.length>0&&a.push(`Didn\u2019t upload: ${t(o)} ${o.length>1?"are":"is"} over ${wa} MB.`),a.join(" ")}let s=[];return n.length>0&&s.push(`${t(n)} ${n.length>1?"are not PDFs":"is not a PDF"}`),o.length>0&&s.push(`${t(o)} ${o.length>1?"are":"is"} over ${wa} MB`),`Didn\u2019t upload: ${s.join("; ")}. We can only read PDFs up to ${wa} MB right now.`}i(Ho,"skippedFilesMessage");function Gd(e){let r=[];for(let t of e)t.status==="skipped"&&t.skipReason!==null&&r.push({name:t.name,reason:t.skipReason});return r}i(Gd,"skippedOf");var ka=[37,80,68,70,45],sy=[255,216,255],ly=[137,80,78,71,13,10,26,10],Yd=12,dy=Object.freeze({heic:"image/heic",heix:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif"}),Kd="application/pdf,.pdf",cy=Object.freeze({"image/jpeg":"image/jpeg,.jpg,.jpeg","image/png":"image/png,.png","image/heic":"image/heic,.heic","image/heif":"image/heif,.heif"});function jo(e){let r=Xt.filter(t=>Gr(t,e));return [Kd,...r.map(t=>cy[t])].join(",")}i(jo,"recordsDocumentAccept");var uy="application/octet-stream",py="file:web-document";async function Qd(e,r){let t=e.slice(0,r);try{return typeof t.arrayBuffer=="function"?new Uint8Array(await t.arrayBuffer()):await new Promise(o=>{let n=new FileReader;n.onload=()=>{o(n.result instanceof ArrayBuffer?new Uint8Array(n.result):new Uint8Array);},n.onerror=()=>o(new Uint8Array),n.readAsArrayBuffer(t);})}catch{return new Uint8Array}}i(Qd,"readHead");async function Xd(e){if(e.size<ka.length)return false;let r=await Qd(e,ka.length);return _a(r,ka)}i(Xd,"isPdfBlob");function _a(e,r,t=0){return e.length>=t+r.length&&r.every((o,n)=>e[t+n]===o)}i(_a,"startsWith");function my(e){return _a(e,sy)?"image/jpeg":_a(e,ly)?"image/png":e.length>=Yd&&String.fromCharCode(...e.slice(4,8))==="ftyp"?dy[String.fromCharCode(...e.slice(8,12))]??null:null}i(my,"photoTypeOf");async function fy(e,r){if(await Xd(e))return Fs;if(!Xt.some(o=>Gr(o,r)))return null;let t=my(await Qd(e,Yd));return t!==null&&Gr(t,r)?t:null}i(fy,"detectedType");async function Vo(e,r){let t=await fy(e,r),o=e.name,n=typeof o=="string"?o:void 0;return Object.freeze({uri:py,mimeType:t??uy,sizeBytes:e.size,blob:e,...n!==void 0?{name:n}:{}})}i(Vo,"fileToHandle");function yy(e,r){let t=e.sizeBytes;return Gr(e.mimeType,r)&&typeof t=="number"&&Number.isFinite(t)&&t>0&&t<=Kr}i(yy,"isUploadableHandle");function gy(e=document,r){return new Promise(t=>{let o=e.createElement("input");o.type="file",o.accept=jo(r),o.hidden=true;let n=i(()=>{o.remove();},"done");o.addEventListener("change",()=>{let s=o.files?.[0];if(n(),s===void 0){t(null);return}Vo(s,r).then(t);},{once:true}),o.addEventListener("cancel",()=>{n(),t(null);},{once:true}),e.body.appendChild(o),o.click();})}i(gy,"pickDocument");var jr=Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",updateEmailA11y:"Update clinic email and resend request",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We\u2019ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function Jd({request:e,onRecovered:r,canUpload:t=false},o){let[n,s]=react.useState(""),[a,c]=react.useState(false),[l,d]=react.useState(null),[u,p]=react.useState(false),[m,y]=react.useState(null),g=react.useRef(false),f=react.useRef(false),v=react.useRef(0);react.useEffect(()=>(f.current=true,()=>{f.current=false,v.current+=1;}),[o]);let b=m!==null&&m.before===e.updatedAt?{...m.value,canRetrySend:e.canRetrySend===true&&m.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&m.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&m.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&m.value.canConvertToUpload===true}:e,R=n.trim(),h=R.length<=320&&!Array.from(R).some(T=>T.charCodeAt(0)<=32||T.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(R),E=b.canUpdateClinicEmail===true&&R.length>0,S=b.canRetrySend===true&&!a&&!E,C=b.canUpdateClinicEmail===true&&!a&&h,k=b.canConvertToUpload===true&&t,M=i(async T=>{let O={retry:S,email:C,revoke:b.canRevoke===true&&u,convert:k};if(g.current||!f.current||!O[T])return;g.current=true,c(true),d(null);let z=v.current,q=i(()=>f.current&&z===v.current,"live");try{let N=T==="retry"?await o.retryRequest(e.id):T==="email"?await o.updateClinicEmail(e.id,R):T==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!q())return;if(!N.ok){d(N.error);return}if(N.value.id!==e.id||N.value.petRef!==e.petRef){d(H("internalError"));return}y({before:e.updatedAt,value:N.value}),s(""),p(!1),r();}catch{q()&&d(H("internalError"));}finally{g.current=false,q()&&c(false);}},"run");return {request:b,email:n,busy:a,error:l,canRetry:S,canUpdateEmail:C,canConvert:k,hasEmailEdit:E,confirmingRevoke:u&&b.canRevoke===true,emailInvalid:R.length>0&&!h,setEmail(T){g.current||(s(T),d(null));},retry:i(()=>M("retry"),"retry"),updateEmail:i(()=>M("email"),"updateEmail"),revoke:i(()=>M("revoke"),"revoke"),convert:i(()=>M("convert"),"convert"),askRevoke(){!g.current&&b.canRevoke===true&&p(true);},keepRequest(){g.current||p(false);}}}i(Jd,"useRecordsRecovery");var hy=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],Ry=["requested","awaiting_upload","records_received","processing","ready"],vy=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],mn=Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),Cy=Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records\u2026"}),Ta=Object.freeze({notified:i(e=>`A secure request went to ${e}.`,"notified"),received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:i(e=>`Added to ${e}\u2019s records`,"added")}),Cr=Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn\u2019t read this one automatically",manualReview:"Checking these by hand so nothing\u2019s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),Ey=Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),Sy=Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function xy(e){return e.wireStatus??Sy[e.status]??"sent"}i(xy,"wireStatusOf");function wy(e,r){return e!=="awaiting_response"||r<=0?null:`${r} ${r===1?"reminder":"reminders"} sent`}i(wy,"reminderProgressLabel");function ky(e){switch(e){case "submitted":case "sent":return 1;case "awaiting_response":return 2;case "records_received":return 3;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 4;case "published":return 5;default:return -1}}i(ky,"reachedRailIndex");function _y(e){switch(e.dispatchStatus){case "sent":return Cr.delivered;case "preparing":case "queued":case "sending":return Cr.emailing;case "failed":return Cr.bounced;default:return null}}i(_y,"deliveryDetail");function Py(e,r){return wy(r,e.reminderCount??0)??Cr.waiting}i(Py,"awaitingDetail");function jt(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(jt,"isOwnerSourcedRequest");function Ty(e,r,t){let o=jt(r);switch(e){case "sent_to_clinic":return _y(r);case "awaiting_clinic":return Py(r,t);case "awaiting_upload":return Cr.upload;case "records_received":return o?Cr.ownerAdded:Cr.clinicSent;case "processing":return Cr.preparing;case "ready":return Cr.ready;default:return null}}i(Ty,"railDetail");function Dy(e,r){return !!e.reviewStartedAt||r==="parsing_failed"||r==="review_email_failed"}i(Dy,"tookReviewBranch");function Iy(e,r,t){if(e.key!=="processing"||!Dy(r,t))return [e];let o=t==="parsing_failed",n=t==="published",s=n?"done":o?"current":"done",a=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:mn.parsing_failed,detail:Cr.parsingFailed,at:null,state:s},{key:"manual_review",title:mn.manual_review,detail:Cr.manualReview,at:r.reviewStartedAt??null,state:a}]}i(Iy,"expandProcessingPhase");function Oy(e){switch(e){case "awaiting_upload":return 3;case "records_received":return 4;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 5;case "published":return 6;default:return 3}}i(Oy,"convertedReachedIndex");function Zd(e){return {key:"awaiting_clinic",title:Cr.switchedTitle,detail:Cr.switched,at:e.convertedToUploadAt??null,state:"done"}}i(Zd,"convertedClinicSwitchEvent");function Ay(e){switch(e){case "submitted":case "sent":return 0;case "awaiting_upload":return 1;case "records_received":return 2;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 3;case "published":return 4;default:return -1}}i(Ay,"ownerReachedIndex");function Fy(e,r,t){switch(e){case "requested":return r.createdAt||null;case "awaiting_clinic":return r.lastReminderAt??null;case "processing":return r.parsingStartedAt??r.reviewStartedAt??null;case "ready":return t==="published"&&r.updatedAt||null;default:return null}}i(Fy,"railTimestamp");function ec(e,r,t,o){return {key:e,title:mn[e],detail:Ty(e,r,t),at:Fy(e,r,t),state:o}}i(ec,"railEvent");function mt(e,r){return {key:e,title:mn[e],detail:Ey[e]??null,at:r.updatedAt||null,state:"failed"}}i(mt,"terminalEvent");function Da(e,r,t,o,n){return e.map((s,a)=>{let c=n?.(s)??null;if(c!==null)return c;let l=o==="published"||a<r?"done":a===r?"current":"upcoming";return ec(s,t,o,l)}).flatMap(s=>Iy(s,t,o))}i(Da,"walkRail");function Ia(e,r={}){return qy(Ny(e),e,r.petName??null)}i(Ia,"buildRequestTimeline");function qy(e,r,t){let o=r.source!=="owner_provided"&&!e.some(s=>s.key==="delivery_failed"),n=r.clinicEmail?.trim()??"";return e.map(s=>{if(s.title!==mn[s.key])return s;if(s.key==="ready")return {...s,title:Ta.added(Re(t))};if(!o)return s;let a=Cy[s.key]??s.title;return s.key==="sent_to_clinic"&&r.dispatchStatus==="sent"&&n.length>0?{...s,title:a,detail:Ta.notified(n)}:s.key==="records_received"&&!jt(r)?{...s,title:a,detail:Ta.received}:{...s,title:a}})}i(qy,"inArtifactWords");function Ny(e){let r=xy(e),t=i(n=>ec(n,e,r,"done"),"done");if(r==="revoked")return [t("requested"),mt("revoked",e)];if(e.convertedToUploadAt)return r==="failed"?[t("requested"),t("sent_to_clinic"),Zd(e),t("awaiting_upload"),t("records_received"),mt("processing_failed",e)]:Da(vy,Oy(r),e,r,n=>n==="awaiting_clinic"?Zd(e):null);if(e.source==="owner_provided"){if(r==="failed"||r==="clinic_declined")return [t("requested"),t("awaiting_upload"),t("records_received"),mt("processing_failed",e)];let n=Ay(r);return Da(Ry,n<0?1:n,e,r)}if(r==="clinic_declined")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),mt("clinic_declined",e)];if(r==="clinic_responded_no_records")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),mt("clinic_no_records",e)];if(r==="failed"){let n=e.failureCode??null;return n==="no_response"?[t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),mt("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[t("requested"),mt("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),t("records_received"),mt("processing_failed",e)]:[t("requested"),mt("delivery_failed",e)]}let o=ky(r);return Da(hy,o<0?1:o,e,r)}i(Ny,"buildRailEvents");var zy=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),Wo=28,My="Now";function fn({request:e,petName:r}){let t=By(),o=Ia(e,{petName:r??null});return jsxRuntime.jsx("ol",{style:t.list,"aria-label":le.timelineA11y,"data-testid":"records-timeline",children:o.map((n,s)=>jsxRuntime.jsx($y,{event:n,isLast:s===o.length-1,styles:t},n.key))})}i(fn,"RequestTimeline");function $y({event:e,isLast:r,styles:t}){let o=e.at?ee(e.at):null,n={...t.title,...e.state==="current"?t.titleCurrent:{},...e.state==="failed"?t.titleFailed:{},...e.state==="upcoming"?t.titleUpcoming:{}};return jsxRuntime.jsxs("li",{style:t.row,"data-testid":`records-timeline-${e.key}`,children:[jsxRuntime.jsxs("div",{style:t.railColumn,"aria-hidden":"true",children:[jsxRuntime.jsx(Uy,{state:e.state,styles:t}),r?null:jsxRuntime.jsx("div",{style:{...t.connector,...e.state==="done"?t.connectorDone:{}}})]}),jsxRuntime.jsxs("div",{style:t.body,children:[jsxRuntime.jsxs("div",{style:t.titleRow,children:[jsxRuntime.jsxs("span",{style:n,children:[e.title,e.state==="current"?jsxRuntime.jsx("span",{"aria-hidden":"true",style:t.now,children:My}):null]}),o&&e.at?jsxRuntime.jsx("time",{dateTime:e.at,style:t.date,children:o}):null]}),e.detail?jsxRuntime.jsx("span",{style:{...t.detail,...e.state==="upcoming"?t.detailUpcoming:{}},children:e.detail}):null,jsxRuntime.jsx("span",{style:t.srOnly,children:zy[e.state]})]})]})}i($y,"TimelineRow");function Uy({state:e,styles:r}){return e==="done"?jsxRuntime.jsx("div",{style:{...r.dot,...r.dotDone},children:"\u2713"}):e==="failed"?jsxRuntime.jsx("div",{style:{...r.dot,...r.dotFailed},children:"!"}):e==="current"?jsxRuntime.jsx("div",{style:{...r.dot,...r.dotCurrent},children:jsxRuntime.jsx("div",{style:r.dotCurrentCore})}):jsxRuntime.jsx("div",{style:{...r.dot,...r.dotUpcoming}})}i(Uy,"Dot");function By(){let e=ye();return react.useMemo(()=>Hy(e),[e])}i(By,"useStyles");function Hy(e){let{color:r,space:t,type:o,radius:n}=e,s=i(c=>`${Math.round(c*o.lineHeight.snug)}px`,"lh"),a={boxSizing:"border-box",width:Wo,height:Wo,borderRadius:Wo/2,display:"flex",alignItems:"center",justifyContent:"center",...D(e,"bold"),fontSize:o.size.caption,lineHeight:s(o.size.caption)};return {list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},row:{display:"flex",alignItems:"flex-start",gap:t.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",alignSelf:"stretch",width:Wo,flexShrink:0},body:{flex:1,minWidth:0,paddingTop:t.xs/2,paddingBottom:t.lg+t.xs/2,display:"flex",flexDirection:"column",gap:t.xs/2},titleRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:t.sm},dot:a,dotDone:{backgroundColor:r.brand,color:r.onPrimary},dotFailed:{backgroundColor:r.danger,color:r.onDanger},dotCurrent:{border:`2px solid ${r.brandInk}`,backgroundColor:r.surface},dotCurrentCore:{width:10,height:10,borderRadius:5,backgroundColor:r.success},dotUpcoming:{border:`2px solid ${r.borderHairlineGreen}`,backgroundColor:r.surface},connector:{width:2,flex:1,minHeight:22,backgroundColor:r.borderHairlineGreen,margin:"2px 0"},connectorDone:{backgroundColor:r.brand},title:{flex:1,display:"flex",flexWrap:"wrap",alignItems:"center",gap:t.sm,...D(e,"bold"),fontSize:o.size.bodyTight,lineHeight:s(o.size.bodyTight),color:r.text.primary},titleCurrent:{color:r.brandInk},titleFailed:{color:r.danger},titleUpcoming:{color:r.text.muted,...D(e,"regular")},date:{...D(e,"regular"),fontSize:o.size.caption,lineHeight:s(o.size.caption),color:r.text.muted},detail:{...D(e,"regular"),fontSize:o.size.caption,lineHeight:`${Math.round(o.size.caption*o.lineHeight.normal)}px`,color:r.text.muted},now:{display:"inline-flex",alignItems:"center",minHeight:20,padding:`0 ${t.sm}px`,borderRadius:n.pill,backgroundColor:r.scanButtonPink,color:r.onBubbleVet,...D(e,"monoBold"),fontSize:o.size.tiny,lineHeight:s(o.size.tiny),letterSpacing:"0.06em",textTransform:"uppercase"},detailUpcoming:{opacity:.7},srOnly:{position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0}}}i(Hy,"makeStyles");function rc(e){return e.value!==null&&Number.isFinite(e.value)}i(rc,"isFinitePoint");function Go(e){return e.display!==null&&e.display.length>0?e.display:e.value!==null?String(e.value):""}i(Go,"pointDisplay");function tc(e){let r=e.find(C=>C.points.some(rc));if(r===void 0)return null;let t=r.points.filter(rc),o=t[0];if(o===void 0)return null;let n=t.map(C=>C.value),s=Math.min(...n),a=Math.max(...n);s===a&&(s-=1,a+=1);let c=(a-s)*.18,l=s-c,d=a+c,u=d-l,p=6,m=t.length,y=t.map((C,k)=>({xPct:m<=1?50:p+k/(m-1)*(100-2*p),yPct:(d-C.value)/u*100})),g=(d-a)/u*100,f=(d-s)/u*100,v=t.reduce((C,k)=>k.value<C.value?k:C,o),b=t.reduce((C,k)=>k.value>C.value?k:C,o),R=t[t.length-1]??o,h=r.points[r.points.length-1]??R,E=Go(h),S=E.length>0?E:Go(R);return {label:r.label,heroDisplay:S,minDisplay:Go(v),maxDisplay:Go(b),firstDate:aa(r.points[0]?.at??null),lastDate:aa(h.at),points:y,bandTopPct:g,bandBottomPct:f}}i(tc,"buildTrendModel");function jy(e){let r=e.indexOf(":");return r<=0?null:e.slice(0,r)}i(jy,"entityTypeOf");function nc(e,r,t){let o=new Map,n=[];for(let c of e){let l=jy(c.key)??"",d=o.get(l);d===void 0?(o.set(l,[c]),n.push(l)):d.push(c);}let s=r.filter(c=>o.has(c)),a=n.filter(c=>!s.includes(c));return Object.freeze([...s,...a].map(c=>Object.freeze({entityType:c.length>0?c:null,label:c.length>0?t(c):null,series:Object.freeze([...o.get(c)??[]])})))}i(nc,"groupSeriesByEntityType");function oc({series:e}){let r=ye(),t=react.useMemo(()=>Gy(r),[r]),o=react.useMemo(()=>nc(e,To,ct),[e]);return o.length===0?null:jsxRuntime.jsxs("section",{"aria-label":K.careTimeline,style:t.section,children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{style:t.sectionTitle,children:K.careTimeline}),jsxRuntime.jsx("p",{style:t.sectionSub,children:K.careTimelineSub})]}),o.map(n=>jsxRuntime.jsxs("div",{style:t.group,children:[n.label===null?null:jsxRuntime.jsx("p",{style:t.eyebrow,children:n.label}),n.series.map(s=>jsxRuntime.jsx(Vy,{series:s,styles:t},s.key))]},n.entityType??"_"))]})}i(oc,"TrendRangeCard");function Vy({series:e,styles:r}){let t=react.useMemo(()=>tc([e]),[e]);if(t===null){let n=e.points[e.points.length-1]?.display??null;return jsxRuntime.jsxs("div",{style:r.card,children:[jsxRuntime.jsx("p",{style:r.eyebrow,children:e.label}),n!==null&&n.length>0?jsxRuntime.jsx("p",{style:r.hero,children:n}):null]})}return jsxRuntime.jsx(Wy,{model:t,styles:r})}i(Vy,"SeriesChart");function Wy({model:e,styles:r}){let t=e.heroDisplay.length>0?`${e.label}, ${e.heroDisplay}`:e.label,o=Math.max(0,e.bandBottomPct-e.bandTopPct),n=e.points.length-1;return jsxRuntime.jsxs("div",{style:r.card,children:[jsxRuntime.jsxs("div",{role:"img","aria-label":t,children:[jsxRuntime.jsx("p",{style:r.eyebrow,children:e.label}),e.heroDisplay.length>0?jsxRuntime.jsx("p",{style:r.hero,children:e.heroDisplay}):null]}),jsxRuntime.jsxs("div",{"aria-hidden":"true",style:r.plot,children:[e.points.map((s,a)=>jsxRuntime.jsx("div",{style:{...r.guide,left:`${s.xPct}%`}},`g-${a}`)),jsxRuntime.jsx("div",{style:{...r.band,top:`${e.bandTopPct}%`,height:`${o}%`}}),e.points.map((s,a)=>jsxRuntime.jsx("div",{style:{...r.point,...a===n?r.pointLatest:null,left:`${s.xPct}%`,top:`${s.yPct}%`}},`pt-${a}`)),e.maxDisplay.length>0?jsxRuntime.jsx("span",{style:{...r.edgeLabel,top:`${e.bandTopPct}%`},children:e.maxDisplay}):null,e.minDisplay.length>0?jsxRuntime.jsx("span",{style:{...r.edgeLabel,top:`${e.bandBottomPct}%`},children:e.minDisplay}):null]}),e.firstDate.length>0||e.lastDate.length>0?jsxRuntime.jsxs("div",{"aria-hidden":"true",style:r.dates,children:[jsxRuntime.jsx("span",{children:e.firstDate}),jsxRuntime.jsx("span",{children:e.lastDate})]}):null]})}i(Wy,"TrendChart");function Gy(e){let{color:r,space:t,radius:o,type:n}=e,s=i((c,l)=>`${Math.round(c*l)}px`,"lh"),a=t.sm;return {section:{display:"flex",flexDirection:"column",gap:t.lg},sectionTitle:{margin:0,...D(e,"bold"),fontSize:n.size.subtitle,lineHeight:s(n.size.subtitle,n.lineHeight.snug),letterSpacing:"-0.02em",color:r.text.primary},sectionSub:{margin:`${t.xs}px 0 0`,...D(e,"regular"),fontSize:n.size.caption,lineHeight:s(n.size.caption,n.lineHeight.normal),color:r.text.muted},group:{display:"flex",flexDirection:"column",gap:t.sm},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.sm,padding:t.lg,borderRadius:o.lg,backgroundColor:r.surfaceCream,border:`1px solid ${r.borderRingCream}`},eyebrow:{margin:0,...D(e,"regular"),fontSize:n.size.caption,lineHeight:s(n.size.caption,n.lineHeight.normal),color:r.text.muted,letterSpacing:n.letterSpacing.eyebrow,textTransform:"uppercase",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},hero:{margin:0,...D(e,"bold"),fontSize:n.size.verdict,lineHeight:s(n.size.verdict,n.lineHeight.tight),color:r.text.primary,letterSpacing:n.letterSpacing.tight},plot:{position:"relative",height:t.xxl*3,marginTop:t.xs},guide:{position:"absolute",top:0,bottom:0,width:1,backgroundColor:r.borderHairlineGreen},band:{position:"absolute",left:t.xs,right:t.xs,borderRadius:o.sm,backgroundColor:r.brandSoft},point:{boxSizing:"border-box",position:"absolute",width:a,height:a,marginLeft:-(a/2),marginTop:-(a/2),borderRadius:o.pill,backgroundColor:r.brand,border:`1px solid ${r.surfaceCream}`},pointLatest:{backgroundColor:r.accent,borderColor:r.onAccent},edgeLabel:{position:"absolute",right:0,marginTop:-t.sm,...D(e,"medium"),fontSize:n.size.tiny,lineHeight:s(n.size.tiny,n.lineHeight.tight),color:r.text.muted,whiteSpace:"nowrap"},dates:{display:"flex",justifyContent:"space-between",...D(e,"regular"),fontSize:n.size.tiny,lineHeight:s(n.size.tiny,n.lineHeight.normal),color:r.text.muted}}}i(Gy,"makeStyles");var Xy=300,Jy=900,ac=120,sc=44,lc=40,dc=24,Zy=3;function Tt(e,r,t){let o=et(e,t);switch(o.kind){case "consent_required":return jsxRuntime.jsx(eg,{onGrant:r});case "consent_unavailable":return jsxRuntime.jsx(or,{label:X.consentRequired,glyph:"empty"});case "session_required":return jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"});case "withheld":return jsxRuntime.jsx(or,{label:X.recordUnavailable,glyph:"withheld"});case "pet_not_found":case "error":return jsxRuntime.jsx(rg,{error:o.error,onRetry:e.refresh});default:return Nr(o)}}i(Tt,"renderErrorFamily");function cc(){let{theme:e,styles:r}=gn(),[t,o]=react.useState(false),n=react.useRef(null);react.useEffect(()=>{let a=setTimeout(()=>o(true),Xy);return ()=>clearTimeout(a)},[]);let s=t&&!e.motion.reducedMotion;return react.useEffect(()=>{let a=n.current;if(!s||a===null||typeof a.animate!="function")return;let c=a.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:Jy,iterations:1/0});return ()=>c.cancel()},[s]),jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":X.loading,style:r.centered,children:t?jsxRuntime.jsx("div",{ref:n,"aria-hidden":"true",style:r.spinner}):null})}i(cc,"LoadingState");function uc({records:e}){let{styles:r}=gn(),t=e.uploadQueue;if(t.length===0)return null;let o=t.filter(a=>a.status!=="skipped"),n=o.filter(a=>a.status==="done").length,s=Ho(Gd(t));return jsxRuntime.jsxs("div",{style:r.card,"data-testid":"records-upload-queue",children:[s!==null?jsxRuntime.jsx("p",{role:"alert",style:r.errorText,children:s}):null,o.length>0?jsxRuntime.jsx("ul",{"aria-live":"polite","aria-label":e.isUploading?Ht.uploading(n,o.length):Ht.uploaded(n,o.length),style:{listStyle:"none",margin:0,padding:0},children:o.map(a=>{let c=Math.round(a.progress*100);return jsxRuntime.jsxs("li",{style:r.row,"data-testid":`records-upload-file-${a.status}`,children:[jsxRuntime.jsx("span",{style:r.rowLabel,children:a.name??""}),jsxRuntime.jsx("span",{style:r.rowValue,children:Wd(a)}),a.status==="uploading"?jsxRuntime.jsx("progress",{max:100,value:c,style:{width:"100%"}}):null,a.status==="failed"&&a.error?jsxRuntime.jsx("span",{style:r.timelineMeta,children:a.error.displayMessage}):null]},a.key)})}):null]})}i(uc,"UploadQueue");function eg({onGrant:e}){let{styles:r}=gn();return jsxRuntime.jsxs("div",{role:"alert","aria-live":"assertive",style:r.centered,children:[jsxRuntime.jsx("p",{style:r.alertText,children:X.consentRequired}),jsxRuntime.jsx("button",{type:"button",onClick:e,style:r.primaryButton,children:X.allow})]})}i(eg,"ConsentRequiredState");function or({label:e,glyph:r}){let{styles:t}=gn();return jsxRuntime.jsxs("div",{role:"alert","aria-live":"assertive",style:t.centered,children:[jsxRuntime.jsx("div",{"aria-hidden":"true",style:r==="withheld"?t.withheldGlyph:t.emptyGlyph}),jsxRuntime.jsx("p",{style:t.alertText,children:e})]})}i(or,"AlertState");function rg({error:e,onRetry:r}){let{styles:t}=gn();return jsxRuntime.jsxs("div",{role:"alert","aria-live":"assertive",style:t.centered,children:[jsxRuntime.jsx("p",{style:t.errorText,children:e.displayMessage}),e.retryable?jsxRuntime.jsx("button",{type:"button",onClick:r,style:t.primaryButton,children:X.retry}):null]})}i(rg,"ErrorState");function pc({call:e,prompt:r}){let{styles:t}=gn(),o=r.trim().length>0?r:Wn.fallbackPrompt;return jsxRuntime.jsxs("div",{style:t.callCard,children:[jsxRuntime.jsx("p",{style:t.timelineLabel,children:Wn.heading}),jsxRuntime.jsx("p",{style:t.timelineMeta,children:o}),jsxRuntime.jsx("a",{href:e.dial,"aria-label":Wn.callAt(e.phone),style:t.linkButton,"data-testid":"records-call-clinic",children:Wn.call})]})}i(pc,"ClinicCallCard");function gn(){let e=ye(),r=react.useMemo(()=>tg(e),[e]);return {theme:e,styles:r}}i(gn,"useRecordsTheme");function tg(e){let{color:r,space:t,radius:o,type:n,slots:s}=e,a=i((f,v)=>`${Math.round(f*v)}px`,"lh"),c=`1px solid ${r.brandBorder}`,l=Mr(s.recordCard,1),d=tt(s.recordCard),u=i((f,v,b,R="regular")=>({margin:0,...D(e,R),fontSize:f,lineHeight:a(f,v),color:b}),"text"),p=i((f,v,b,R="regular")=>({...u(f,v,b,R),...d}),"inCard"),m={boxSizing:"border-box",minHeight:sc,minWidth:sc,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...D(e,"bold"),fontSize:n.size.body,letterSpacing:n.letterSpacing.tight},y={boxSizing:"border-box",width:lc,height:lc},g=e.brightness==="dark"?r.errorRed:r.danger;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:ac,height:"100%",backgroundColor:r.background,color:r.text.primary,...D(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:ac,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:t.lg,padding:t.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:dc,height:dc,borderRadius:o.pill,border:`${Zy}px solid ${r.brandSofter}`,borderTopColor:r.brandInk},emptyGlyph:{...y,borderRadius:o.lg,backgroundColor:r.brandSoft,border:c},withheldGlyph:{...y,borderRadius:o.sm,backgroundColor:r.badgeBgCaution,border:`1px solid ${r.cautionAccent}`},alertText:u(n.size.subtitle,n.lineHeight.snug,r.text.secondary),errorText:u(n.size.subtitle,n.lineHeight.snug,g),primaryButton:{...m,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Mr(s.primaryButton),...tt(s.primaryButton)},disabledButton:{...m,border:c,cursor:"default",backgroundColor:r.surfaceSubtle,color:r.text.muted},list:{display:"flex",flexDirection:"column",gap:t.md,padding:t.lg},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.xs,padding:`${t.md}px ${t.lg}px`,borderRadius:o.md,backgroundColor:r.surfaceCream,border:c,...l},cardTitle:{...p(n.size.heading,n.lineHeight.snug,r.text.primary,"bold"),letterSpacing:n.letterSpacing.tight},callCard:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.sm,padding:t.md,borderRadius:o.md,backgroundColor:r.surfaceCream,border:c,...l},linkButton:{...m,display:"inline-flex",alignItems:"center",justifyContent:"center",alignSelf:"flex-start",textDecoration:"none",border:0,backgroundColor:r.primary,color:r.onPrimary,...Mr(s.primaryButton),...tt(s.primaryButton)},timelineLabel:{...p(n.size.subtitle,n.lineHeight.snug,r.text.secondary,"bold")},timelineMeta:p(n.size.bodyTight,n.lineHeight.normal,r.text.muted),row:{display:"flex",justifyContent:"space-between",gap:t.md,padding:`${t.xs}px 0`,borderBottom:`1px solid ${r.borderHairlineGreen}`},rowLabel:p(n.size.body,n.lineHeight.normal,r.text.muted),rowValue:{...p(n.size.body,n.lineHeight.normal,r.text.primary,"medium"),textAlign:"right"},disclaimer:u(n.size.caption,n.lineHeight.normal,r.text.muted)}}i(tg,"makeStyles");var Yo="everfur-record.pdf";function Ko(e){return typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("clipboard unavailable")):navigator.clipboard.writeText(e)}i(Ko,"copyText");function ng(e){return typeof e=="object"&&e!==null&&e.name==="AbortError"}i(ng,"isAbort");async function fc(e,r=Ko){let t=typeof navigator>"u"?void 0:navigator;if(t!==void 0&&typeof t.share=="function")try{return await t.share({url:e}),"shared"}catch(o){if(ng(o))return "dismissed"}return await r(e),"copied"}i(fc,"shareLinkInPlace");function og(e,r){let t;try{t=new URL(e,r);}catch{return null}if(t.protocol==="blob:"||t.protocol==="data:")return "download";if(r!==void 0)try{if(new URL(r).origin===t.origin)return "download"}catch{}let o=t.searchParams.get("response-content-disposition");return o!==null&&/^\s*attachment\b/i.test(o)?"attachment":null}i(og,"inPlaceRoute");function ig(){return typeof location>"u"?void 0:location.href}i(ig,"locationHref");function ag(e=typeof window>"u"?void 0:window){if(e===void 0)return false;try{return e.self!==e.top}catch{return true}}i(ag,"isFramedDocument");function mc(e,r){let t=document.createElement("a");t.href=e,t.download=r,t.rel="noopener",t.style.display="none",document.body.appendChild(t);try{t.click();}finally{t.remove();}}i(mc,"clickDownload");var sg=6e4;function lg(e){let r=document.createElement("iframe");r.setAttribute("sandbox","allow-downloads"),r.setAttribute("aria-hidden","true"),r.tabIndex=-1,r.style.display="none",r.src=e,document.body.appendChild(r),setTimeout(()=>r.remove(),sg);}i(lg,"saveThroughNestedFrame");async function bn(e,r,t=ag()){if(typeof document>"u")return false;let o=og(e,ig());if(o==="attachment"&&t)return lg(e),true;if(o!==null)return mc(e,r),true;let n;try{let a=await fetch(e,{credentials:"omit"});if(!a.ok)return !1;n=await a.blob();}catch{return false}let s=URL.createObjectURL(n);try{mc(s,r);}finally{setTimeout(()=>URL.revokeObjectURL(s),1e4);}return true}i(bn,"downloadInPlace");var Sr=K.document,yc=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),cg=i((e,r)=>e.getRecordDepth(r),"readDepth"),ug=i(e=>!e.available,"depthEmpty");function pg(e,r){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(r===null||r.labResults.length===0&&r.physicalExams.length===0&&r.clinicianNotes.length===0)}i(pg,"documentIsEmpty");function Qn(e){let{style:r,className:t,renderPending:o,...n}=Ie(e,["onBack"]),{userRef:s}=se(),{theme:a,styles:c}=V();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Fe(n.onBack,Me),children:jsxRuntime.jsxs("div",{className:t,style:{...c.root,backgroundColor:a.color.surface,...r},"data-testid":"record-document-screen",children:[s===null?jsxRuntime.jsx("div",{style:c.body,children:jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"})}):jsxRuntime.jsx(mg,{...n}),jsxRuntime.jsx(Ae,{})]})})}i(Qn,"EverfurRecordDocument");function mg({petRef:e,petName:r,controller:t,consentVersion:o,onBack:n,onOpenUrl:s}){let{theme:a,styles:c}=V(),l=gc(),d=react.useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),u=er(d),p=Hr(e,cg,ug),m=xa(e),y=dt(o,u.consent),g=i(()=>{let C=Zr(o,u.consent);C.length!==0&&u.grantConsent(C,`records-consent-${Date.now().toString(36)}`);},"onGrant"),f=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,v=u.record,[b,R]=react.useState(false),h=i(()=>{R(false),m.pdfLink().then(C=>{C.ok&&(s?It(s,C.value.downloadUrl,"record_pdf"):bn(C.value.downloadUrl,Yo).then(k=>R(!k)));});},"download"),E,S=false;if(u.status==="loading"||p.status==="loading"&&v!==null)E=jsxRuntime.jsx("div",{"data-testid":"record-document-loading",children:jsxRuntime.jsx(cc,{})});else if(u.status==="error"){let C=et(u,y);E=C.kind==="error"||C.kind==="pet_not_found"?jsxRuntime.jsx(He,{variant:nr(C.error),message:C.error.displayMessage,onAction:C.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):Tt(u,g,y);}else v===null||pg(v,f)?E=jsxRuntime.jsx("p",{style:l.empty,"data-testid":"record-document-empty",children:Sr.empty}):(S=true,E=jsxRuntime.jsx(fg,{record:v,depth:f,petName:r,wordmark:a.meta.displayName}));return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ke,{title:Sr.titleFor(r),variant:"document",onBack:n,testID:"record-document-header",right:m.available&&S?jsxRuntime.jsx("button",{type:"button",onClick:h,disabled:m.preparing,"aria-busy":m.preparing,"aria-label":Sr.download,style:c.iconButton,"data-testid":"record-document-download",children:jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:12,height:12,borderLeft:`2px solid ${a.color.brandInk}`,borderBottom:`2px solid ${a.color.brandInk}`,transform:"rotate(-45deg)"}})}):void 0}),m.error?jsxRuntime.jsx("p",{role:"alert",style:{...c.errorText,padding:`0 ${a.space.lg}px`},children:m.error.displayMessage}):b?jsxRuntime.jsx("p",{role:"alert",style:{...c.errorText,padding:`0 ${a.space.lg}px`},"data-testid":"record-document-save-failed",children:_t(null,"download")}):null,jsxRuntime.jsx("div",{style:c.body,children:E})]})}i(mg,"DocumentBody");function fg({record:e,depth:r,petName:t,wordmark:o}){let n=gc(),s=react.useMemo(()=>{let d=[],u=new Map;for(let y of e.entities){let g=y.category.trim();if(g.length===0)continue;let f=u.get(g);f===void 0?(d.push(g),u.set(g,[y])):f.push(y);}let p=yc.filter(y=>d.includes(y)),m=d.filter(y=>!yc.includes(y));return [...p,...m].map(y=>({type:y,rows:u.get(y)??[]}))},[e.entities]),a=Date.now(),c=i((d,u,p)=>jsxRuntime.jsxs("section",{style:n.section,"data-testid":p,children:[jsxRuntime.jsxs("div",{style:n.sectionHeader,children:[jsxRuntime.jsx("h3",{style:n.sectionTitle,children:d}),jsxRuntime.jsx("span",{style:n.rule})]}),jsxRuntime.jsx("div",{children:u})]},p),"section"),l=i((d,u)=>({...n.row,...d>0?n.rowDivider:{},...u}),"row");return jsxRuntime.jsxs("article",{style:n.page,"data-testid":"record-document",children:[jsxRuntime.jsxs("header",{style:n.letterhead,children:[jsxRuntime.jsx("span",{style:n.wordmark,children:o}),jsxRuntime.jsx("span",{style:n.docTitle,children:Sr.docTitle}),jsxRuntime.jsx("span",{style:n.petName,children:t?.trim()||Sr.namelessPet}),jsxRuntime.jsx("span",{style:n.generated,children:Sr.generated(e.generatedAt)})]}),e.identity.length>0?c(Sr.identity,e.identity.map((d,u)=>jsxRuntime.jsxs("div",{style:l(u),children:[jsxRuntime.jsx("span",{style:n.rowLabel,children:d.label}),jsxRuntime.jsx("span",{style:n.rowValue,children:d.value})]},`${u}:${d.label}`)),"record-document-identity"):null,r&&r.labResults.length>0?c(Sr.labs,r.labResults.map((d,u)=>{let p=nt(d.latest.status),m=ld(d.points[d.points.length-1]??null),y=hr(d.latest.value,d.latest.unit??d.unit,d.latest.qualitativeResult);return jsxRuntime.jsxs("div",{style:l(u,p.outOfRange?n.rowFlag:void 0),children:[jsxRuntime.jsxs("span",{style:n.rowMain,children:[jsxRuntime.jsx("span",{style:n.rowLabel,children:d.name}),jsxRuntime.jsxs("span",{style:n.rowMeta,children:[m?Sr.ref(m):Sr.noRange,d.latest.at?` \xB7 ${ee(d.latest.at)}`:""]})]}),jsxRuntime.jsxs("span",{style:n.rowRight,children:[y!=="-"?jsxRuntime.jsx("span",{style:{...n.rowValue,...p.outOfRange?n.alert:{}},children:y}):null,jsxRuntime.jsx("span",{style:{...n.markerStatus,...p.outOfRange?n.alert:{}},children:p.label})]})]},d.markerId)}),"record-document-labs"):null,s.map(({type:d,rows:u})=>c(ct(d),u.map((p,m)=>{let y=[tn(p.value,p.unit),p.observedAt?ee(p.observedAt):null].filter(g=>g&&g.length>0).join(" \xB7 ");return jsxRuntime.jsx("div",{style:l(m),children:jsxRuntime.jsxs("span",{style:n.rowMain,children:[jsxRuntime.jsx("span",{style:n.rowLabel,children:p.label}),y?jsxRuntime.jsx("span",{style:n.rowMeta,children:y}):null]})},p.key)}),`record-document-${d}`)),e.forwardLooking.length>0?c(Sr.upcomingCare,e.forwardLooking.map((d,u)=>{let p=Nn(d.dueAt,a);return jsxRuntime.jsxs("div",{style:l(u),children:[jsxRuntime.jsxs("span",{style:n.rowMain,children:[jsxRuntime.jsx("span",{style:n.rowLabel,children:d.title}),d.detail?jsxRuntime.jsx("span",{style:n.rowMeta,children:d.detail}):null]}),p?jsxRuntime.jsx("span",{style:{...n.rowValue,...p.overdue?n.alert:{}},children:p.label}):null]},`${d.title}-${u}`)}),"record-document-upcoming"):null,r&&r.physicalExams.length>0?c(Sr.physicalExams,r.physicalExams.map((d,u)=>jsxRuntime.jsxs("div",{style:{...n.block,...u>0?n.rowDivider:{}},children:[d.observedOn?jsxRuntime.jsx("span",{style:n.blockDate,children:ee(d.observedOn)}):null,d.systems.filter(p=>p.finding).map(p=>jsxRuntime.jsxs("div",{style:n.fieldRow,children:[jsxRuntime.jsx("span",{style:n.fieldLabel,children:on(p.system)}),jsxRuntime.jsx("span",{style:n.fieldValue,children:p.finding})]},p.system))]},d.examId)),"record-document-exams"):null,r&&r.clinicianNotes.length>0?c(Sr.clinicianNotes,r.clinicianNotes.map((d,u)=>jsxRuntime.jsxs("div",{style:{...n.block,...u>0?n.rowDivider:{}},children:[d.observedOn?jsxRuntime.jsx("span",{style:n.blockDate,children:ee(d.observedOn)}):null,d.sections.filter(p=>p.text).map((p,m)=>jsxRuntime.jsxs("div",{style:n.noteSection,children:[jsxRuntime.jsx("span",{style:n.noteLabel,children:an(p.section)}),jsxRuntime.jsx("p",{style:n.noteBody,children:p.text})]},`${p.section}-${m}`))]},d.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsxRuntime.jsx("p",{style:n.disclaimer,children:e.disclaimer}):null]})}i(fg,"RecordDocument");function gc(){let e=ye();return react.useMemo(()=>yg(e),[e])}i(gc,"useDocStyles");function yg(e){let{color:r,space:t,radius:o,type:n}=e,s=i((l,d,u,p="regular")=>({margin:0,...D(e,p),fontSize:l,lineHeight:`${Math.round(l*d)}px`,color:u}),"text"),a=i((l,d)=>({margin:0,...D(e,"mono"),fontSize:l,lineHeight:`${l+t.xs-1}px`,color:d,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"monoText"),c=`1px solid ${r.borderHairlineGreen}`;return {empty:{...s(n.size.body,n.lineHeight.normal,r.text.muted,"medium"),textAlign:"center",padding:`${t.xxl}px ${t.xxl}px`},page:{padding:`0 ${t.lg+t.xs}px ${t.xxl+t.lg}px`,...D(e,"regular")},letterhead:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.xs+t.xs/2,padding:`${t.md}px 0 ${t.lg+t.xs+t.xs/2}px`,borderBottom:`2px solid ${r.brandInk}`,marginBottom:t.sm},wordmark:{...s(n.size.heading,n.lineHeight.snug,r.brandInk,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...a(n.size.caption,r.brandInk),marginTop:t.sm+t.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:s(n.size.verdict+t.xs/2,n.lineHeight.tight,r.text.primary),generated:{...a(n.size.tiny,r.text.muted),textTransform:"none"},section:{marginTop:t.lg+t.xs+t.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:t.sm+t.xs/2,marginBottom:t.sm},sectionTitle:a(n.size.tiny,r.brandInk),rule:{flex:1,height:1,backgroundColor:r.borderHairlineGreen},row:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:t.md+t.xs/2,padding:`${t.sm+1}px 0`},rowDivider:{borderTop:c},rowFlag:{backgroundColor:r.badgeBgCritical,margin:`0 -${t.sm}px`,padding:`${t.sm+1}px ${t.sm}px`,borderRadius:o.xs},rowMain:{display:"flex",flexDirection:"column",minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:t.xs/2},rowLabel:{...s(n.size.body,n.lineHeight.normal,r.text.primary,"medium")},rowValue:{...s(n.size.body,n.lineHeight.normal,r.text.primary,"bold"),textAlign:"right"},alert:{color:r.danger},rowMeta:{marginTop:t.xs/2,...D(e,"mono"),fontSize:n.size.tiny,lineHeight:`${n.size.body}px`,color:r.text.muted},markerStatus:a(n.size.micro,r.text.muted),block:{padding:`${t.sm+t.xs/2}px 0`},blockDate:{...a(n.size.tiny,r.text.muted),display:"block",marginBottom:t.xs+t.xs/2},fieldRow:{display:"flex",alignItems:"flex-start",gap:t.md+t.xs/2,padding:`${t.xs-1}px 0`},fieldLabel:{width:120,flexShrink:0,...s(n.size.bodyTight,n.lineHeight.normal,r.text.muted,"medium")},fieldValue:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,r.text.primary,"medium")},noteSection:{marginTop:t.sm},noteLabel:{...a(n.size.tiny,r.brandInk),display:"block",marginBottom:t.xs/2},noteBody:s(n.size.bodyTight,n.lineHeight.relaxed,r.text.primary),disclaimer:{...s(n.size.tiny,n.lineHeight.relaxed,r.text.muted),marginTop:o.xl,paddingTop:t.md+t.xs/2,borderTop:c}}}i(yg,"makeDocStyles");var sr=Object.freeze({editA11y:i(e=>`Edit ${e}. Correct or remove this record detail.`,"editA11y"),title:i(e=>`Edit ${e}`,"title"),helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",removeA11y:i(e=>`Remove ${e}`,"removeA11y"),confirmRemove:"Remove this detail from your record? This can't be undone.",removeConfirm:"Remove",removing:"Removing...",keep:"Keep",noChange:"Change a value before saving.",saved:"Saved.",removed:"Removed.",detail:"record detail"});function bc(e,r){return Yr(e)?r==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":kd(e)?r==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":r==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(bc,"factEditErrorMessage");var bg=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function Fa(e,r){if(Object.keys(r.edits).length===0&&r.removed.length===0)return e;let t=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&r.removed.includes(n))continue;let s=n!==null?r.edits[n]:void 0;t.push(s===void 0?o:Object.freeze({...o,value:s}));}return Object.freeze(t)}i(Fa,"applyFactOverlay");function qa(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(qa,"isFactEditable");function hg(){return `records-fact-${Date.now().toString(36)}`}i(hg,"defaultFactKey");function Na(e,r={}){let t=Rr(),{userRef:o}=se(),[n,s]=react.useState(bg),[a,c]=react.useState(false),[l,d]=react.useState(null),u=react.useMemo(()=>({}),[t,e,o]),[p,m]=react.useState(null),y=react.useCallback(()=>m(u),[u]),g=o!==null&&p!==u,f=react.useRef(false),v=react.useRef(r.newIdempotencyKey);v.current=r.newIdempotencyKey;let b=react.useCallback(()=>(v.current??hg)(),[]),R=react.useCallback((C,k,M)=>{if(c(false),!C.ok){if(k(),pt(C.error)){y();return}d(bc(C.error,M));}},[y]),h=react.useCallback(async(C,k)=>{let M=C.canonicalKey??"",T=k.trim();if(f.current||M.length===0||T.length===0)return J(H("validationFailed",{retryable:false}));f.current=true,c(true),d(null);let O=n;s(q=>({...q,edits:{...q.edits,[M]:T}}));let z=await t.editFact(e,{entityType:C.category,canonicalKey:M,correctedFields:fa(C.value,T),idempotencyKey:b()});return f.current=false,R(z,()=>s(O),"edit"),z},[t,e,n,R,b]),E=react.useCallback(async C=>{let k=C.canonicalKey??"";if(f.current||k.length===0)return J(H("validationFailed",{retryable:false}));f.current=true,c(true),d(null);let M=n;s(O=>({...O,removed:[...O.removed,k]}));let T=await t.removeFact(e,{entityType:C.category,canonicalKey:k,idempotencyKey:b()});return f.current=false,R(T,()=>s(M),"remove"),T},[t,e,n,R,b]),S=react.useCallback(()=>d(null),[]);return react.useMemo(()=>({overlay:n,busy:a,error:l,available:g,edit:h,remove:E,clearError:S}),[n,a,l,g,h,E,S])}i(Na,"useRecordFactEdit");var Rg=Object.freeze({vaccination:"Vaccination",medication:"Medication",problem:"Problem",body_weight:"Weight",allergy:"Allergy",vital:"Vital",lab_result:"Lab result",parasite_prevention:"Preventive"}),vg="Given",Cg=/^\d{4}-\d{2}-\d{2}/,Eg=" \xB7 ";function ft(e){let r=e.filter(t=>t!==null&&t.trim().length>0);return r.length>0?r.join(Eg):null}i(ft,"joinDetail");function Sg(e,r){let t=e.label.trim();if(t.length>0)return t;let o=Rg[e.category];return o!==void 0?o:r(e.category)}i(Sg,"rowTitle");function vc(e,r){let t=Sg(e,r.humanize),o=r.formatEntityValue(e.value,e.unit),n=o.trim().length>0?o:null,s=e.observedAt!==null&&e.observedAt.trim().length>0?r.formatRecordsDate(e.observedAt):null,a=s!==null&&s!=="-"?s:null;switch(e.category){case "vaccination":{let c=e.value!==null&&Cg.test(e.value.trim()),l=c?r.formatRecordsDate(e.value):a;return l!==null&&l!=="-"?{title:t,detail:ft([`${vg} ${l}`,c?null:n])}:{title:t,detail:ft([n])}}case "medication":return {title:t,detail:ft([a])};case "problem":return {title:t,detail:ft([a])};case "body_weight":return {title:t,detail:ft([a])};case "allergy":return {title:t,detail:ft([a])};case "vital":return {title:t,detail:ft([n,a])};case "lab_result":return {title:t,detail:ft([n,a])};default:return {title:t,detail:ft([n,a])}}}i(vc,"entityRowSummary");function Xo(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(Xo,"markerStatusTone");function xg(e){switch(e){case "above":return "above the reference range";case "below":return "below the reference range";case "in_range":return "within range";default:return "no reference range on file"}}i(xg,"markerStatusSpoken");function wg(e){return e.refLow!==null&&e.refHigh!==null?`, reference range ${e.refLow} to ${e.refHigh}`:e.refLow!==null?`, reference range at least ${e.refLow}`:e.refHigh!==null?`, reference range up to ${e.refHigh}`:""}i(wg,"rangePhrase");function Jo(e,r){let t=r?` ${r}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${t}`:e.refLow!==null?`\u2265 ${e.refLow}${t}`:e.refHigh!==null?`\u2264 ${e.refHigh}${t}`:"-"}i(Jo,"formatReferenceRange");function La(e,r){let t=r.reviewed?", reviewed by our team":"",o=r.sourceClinic?`, from ${r.sourceClinic}`:"";return `${ee(r.at)}: ${hr(r.value,e.unit,r.qualitativeResult)}, ${xg(r.status)}${wg(r)}${o}${t}`}i(La,"markerPointSpoken");function Xe(e){return e?.trim()||"my pet"}i(Xe,"lead");function Cc(e){let r=e.trim();return /[.!?]$/.test(r)?r:`${r}.`}i(Cc,"clause");function Ec(e,r){let t=r.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Xe(e)}'s ${t}`],n=[r.latestValueText?.trim(),r.statusText?.trim(),r.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",r.meaningText?.trim()&&o.push(Cc(r.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Xe(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:r.markerId,payload:{marker:t,...r.statusText?.trim()?{status:r.statusText.trim()}:{}}}}}i(Ec,"buildMarkerAskPrompt");function Sc(e,r,t){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:s,unknownCount:a}=r;if(o===0)return {prompt:`I'm looking at ${Xe(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Xe(e)}?`,entityRef:{type:"marker_summary",id:t,payload:{total:0}}};let c=a>0?`, ${a} without a reference range`:"";return {prompt:`I'm looking at ${Xe(e)}'s lab markers: ${o} total, ${n} in range, ${s} out of range${c}. What should I focus on?`,entityRef:{type:"marker_summary",id:t,payload:{total:o,inRange:n,outOfRange:s,unknown:a}}}}i(Sc,"buildMarkerSummaryAskPrompt");function xc(e,r){let t=r.canonicalName.trim()||"a lab marker",o=[`${t}: ${r.valueText.trim()}`];r.collectedAt?.trim()&&o.push(`collected ${r.collectedAt.trim()}`),r.sourceClinic?.trim()&&o.push(`from ${r.sourceClinic.trim()}`),r.referenceText?.trim()&&o.push(`reference range ${r.referenceText.trim()}`),r.flagged&&o.push(`flagged ${r.flagged}`);let n={marker:t};return r.flagged&&(n.status=r.flagged),r.reviewed!==void 0&&(n.reviewed=r.reviewed),{prompt:`I'm looking at ${Xe(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:r.entityId,payload:n}}}i(xc,"buildMarkerReadingAskPrompt");function wc(e,r,t){let o=r.clinicName?.trim(),n=r.heldItemCount??0,s=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${Xe(e)}'s records request${o?` to ${o}`:""}, status: ${r.statusLabel.trim()}${s}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:t,payload:{status:r.status,held:n,...o?{clinic:o}:{}}}}}i(wc,"buildRecordsRequestAskPrompt");var kg=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function kc(e,r,t,o){let n=r.entityTypeLabel.trim()||"record",s=r.title.trim()||n,a=r.detail?.trim();return {prompt:`I'm looking at ${Xe(e)}'s ${n.toLowerCase()}: ${s}${a?`, ${a}`:""}. What does this mean, and what should I keep on top of for ${Xe(e)}?`,entityRef:{type:kg[t]??t,id:o,payload:{kind:n,title:s,...a?{detail:a}:{}}}}}i(kc,"buildEntityRowAskPrompt");function _c(e,r,t){let o=r.filter(a=>a.label.trim()),n={type:"upcoming_care",id:t};if(o.length===0)return {prompt:`I'm looking at ${Xe(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Xe(e)} be on?`,entityRef:n};let s=[...o].sort((a,c)=>(a.tone==="overdue"?0:1)-(c.tone==="overdue"?0:1)).slice(0,4).map(a=>a.relativeText.trim()?`${a.label.trim()} (${a.relativeText.trim().toLowerCase()})`:a.label.trim());return {prompt:`I'm looking at ${Xe(e)}'s upcoming care: ${s.join(", ")}. What should I prioritize for ${Xe(e)}, and how do I stay on top of these?`,entityRef:n}}i(_c,"buildUpcomingCareAskPrompt");function Pc(e,r,t){let o=[`I'm looking at ${Xe(e)}'s physical exam${r.observedOn?.trim()?` from ${r.observedOn.trim()}`:""}.`],n=r.abnormal.filter(s=>s.system.trim());return n.length>0?(o.push(`Abnormal: ${n.slice(0,6).map(s=>`${s.system.trim()}: ${s.finding.trim()}`).join("; ")}.`),o.push(`What do these findings mean, and what should I follow up on for ${Xe(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Xe(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:t}}}i(Pc,"buildPhysicalExamAskPrompt");function Tc(e,r,t){let o=[`I'm looking at ${Xe(e)}'s visit notes${r.observedOn?.trim()?` from ${r.observedOn.trim()}`:""}.`];for(let n of r.sections.filter(s=>s.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${Cc(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Xe(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:t}}}i(Tc,"buildVisitNoteAskPrompt");function Dc(e,r,t){let o=r.scopeLabel.trim()||"a detail",n=r.candidates.filter(a=>a.value.trim()),s=n.slice(0,3).map(a=>`"${a.value.trim()}"${a.clinicName?.trim()?` (${a.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${Xe(e)}'s documents disagree on ${o}: ${s}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:t,payload:{field:o,severity:r.severity,values:n.map(a=>a.value.trim()).join(" | ")}}}}i(Dc,"buildConflictAskPrompt");var Ic='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function $a(e){return e.tagName==="DIALOG"}i($a,"isDialogElement");function _g(e,r){if(r.isDefaultPrevented()||r.nativeEvent.isComposing)return false;let t=r.target;return !(t instanceof Element)||t.closest("dialog")===e}i(_g,"ownsEscape");function Oc(e,r,t,o){let n=o?.escapeAtKeyDown===true,s=react.useRef(null),a=react.useRef(false),c=react.useRef(null),l=react.useRef(t);l.current=t;let d=react.useCallback(()=>{if(!a.current)return;a.current=false;let m=l.current===void 0?c.current:l.current.current;m&&m.isConnected&&m.focus(),(!m||!m.isConnected||document.activeElement===m)&&(c.current=null);},[]);react.useEffect(()=>{if(!e){d();return}let m=s.current;if(!a.current){let g=typeof document>"u"?null:document.activeElement;g!==null&&m!==null&&m.contains(g)||(c.current=g instanceof HTMLElement?g:null);}if(a.current=true,m===null)return;if(!$a(m)){m.contains(document.activeElement)||(m.querySelector(Ic)??m).focus();return}let y=m;typeof y.showModal=="function"?y.open||y.showModal():y.setAttribute("open","");},[e,d]),react.useEffect(()=>d,[d]),react.useEffect(()=>{let m=s.current;if(!e||m===null||!$a(m))return;let y=m;if(typeof y.showModal!="function")return;let g=null,f=i(b=>{b.target instanceof HTMLElement&&(g=b.target);},"onFocusIn"),v=i(()=>{if(!y.isConnected||y.open)return;let b=g;y.showModal(),b!==null&&b.isConnected&&y.contains(b)&&document.activeElement!==b&&b.focus();},"onNativeClose");return y.addEventListener("focusin",f),y.addEventListener("close",v),()=>{y.removeEventListener("focusin",f),y.removeEventListener("close",v);}},[e]);let u=react.useCallback(m=>{let y=s.current;if(y===null)return;if(m.key==="Escape"&&!$a(y)){m.preventDefault(),m.stopPropagation(),r();return}if(m.key==="Escape"&&n&&_g(y,m)){m.preventDefault(),r();return}if(m.key!=="Tab")return;let g=Array.from(y.querySelectorAll(Ic)),f=g[0],v=g[g.length-1];if(!f||!v){m.preventDefault();return}let b=document.activeElement;m.shiftKey&&(b===f||!y.contains(b))?(m.preventDefault(),v.focus()):!m.shiftKey&&(b===v||!y.contains(b))&&(m.preventDefault(),f.focus());},[r,n]),p=react.useCallback(m=>{m.target===m.currentTarget&&(m.preventDefault(),r());},[r]);return {dialogRef:s,onKeyDown:u,onCancel:p}}i(Oc,"useModalDialog");var Tg='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function Dt({label:e,onClose:r,shape:t="modal",returnFocusTo:o,panelStyle:n,testID:s,children:a}){let{styles:c}=V(),l=Oc(true,r,o);react.useEffect(()=>{let u=l.dialogRef.current;u===null||u.contains(document.activeElement)||(u.querySelector(Tg)??u).focus();},[l.dialogRef]);let d=t==="side";return jsxRuntime.jsx("dialog",{ref:l.dialogRef,"aria-label":e,"aria-modal":"true",onCancel:l.onCancel,onKeyDown:l.onKeyDown,style:c.dialogFrame,"data-testid":s,children:jsxRuntime.jsx("div",{style:d?c.dialogScrimSide:c.dialogScrim,onClick:u=>{u.target===u.currentTarget&&r();},"data-testid":s?`${s}-scrim`:void 0,children:jsxRuntime.jsx("div",{style:{...d?c.dialogPanelSide:c.dialogPanel,...n},children:a})})})}i(Dt,"RecordsDialog");function Ac({entity:e,factEdit:r,children:t}){let{theme:o,styles:n}=V(),[s,a]=react.useState(false),c=react.useRef(null),l=e.label.trim()||sr.detail;return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:o.space.sm},children:[jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:t}),jsxRuntime.jsx("button",{ref:c,type:"button",onClick:()=>a(true),"aria-label":sr.editA11y(l),style:n.iconButton,"data-testid":`fact-edit-open-${e.canonicalKey??e.key}`,children:jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:o.space.md+o.space.xs/2,height:2,backgroundColor:o.color.brand,borderRadius:o.radius.pill,transform:"rotate(-45deg)"}})}),s?jsxRuntime.jsx(Og,{entity:e,title:l,factEdit:r,onClose:()=>a(false),returnFocusTo:c}):null]})}i(Ac,"FactEditAffordance");function Og({entity:e,title:r,factEdit:t,onClose:o,returnFocusTo:n}){let{theme:s,styles:a}=V(),[c,l]=react.useState(e.value??""),[d,u]=react.useState(null),[p,m]=react.useState(false);react.useEffect(()=>{t.clearError();},[t]);let y=c.trim().length>0&&c.trim()!==(e.value??"").trim(),g=d??t.error,f=t.busy,v=i(()=>{if(!y){u(sr.noChange);return}u(null),t.edit(e,c).then(h=>{h.ok&&o();});},"submitEdit"),b=i(()=>{u(null),t.remove(e).then(h=>{h.ok?o():m(false);});},"submitRemove"),R=`fact-edit-${e.key}`;return jsxRuntime.jsxs(Dt,{label:sr.title(r),onClose:o,returnFocusTo:n,testID:"fact-edit-sheet",children:[jsxRuntime.jsxs("div",{style:a.sheetHeader,children:[jsxRuntime.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:s.space.xs},children:[jsxRuntime.jsx("h3",{style:a.sheetTitle,children:sr.title(r)}),jsxRuntime.jsx("p",{role:"status","aria-live":"polite",style:{...a.sheetHelper,...g?a.errorText:{}},children:g??sr.helper})]}),jsxRuntime.jsx("button",{type:"button",onClick:o,"aria-label":sr.close,style:a.iconButton,"data-testid":"fact-edit-close",children:jsxRuntime.jsx("span",{style:a.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsxRuntime.jsx("label",{htmlFor:R,style:a.fieldLabel,children:e.label}),jsxRuntime.jsx("input",{id:R,style:a.field,value:c,onChange:h=>{l(h.target.value),u(null);},disabled:f,maxLength:512,"data-testid":"fact-edit-field"}),p?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:s.space.sm,padding:s.space.md,borderRadius:s.radius.md,backgroundColor:s.color.badgeBgCritical},"data-testid":"fact-edit-confirm-remove",children:[jsxRuntime.jsx("p",{style:a.bodyText,children:sr.confirmRemove}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:s.space.sm},children:[jsxRuntime.jsx(j,{label:f?sr.removing:sr.removeConfirm,kind:"danger",busy:f,onClick:b,style:{flex:1},testID:"fact-edit-remove-confirm"}),jsxRuntime.jsx(j,{label:sr.keep,kind:"outline",disabled:f,onClick:()=>m(false),style:{flex:1},testID:"fact-edit-remove-cancel"})]})]}):jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:s.space.sm},children:[jsxRuntime.jsx(j,{label:f?sr.saving:sr.save,busy:f,disabled:!y,onClick:v,testID:"fact-edit-save"}),jsxRuntime.jsx("button",{type:"button","aria-label":sr.removeA11y(r),disabled:f,onClick:()=>{u(null),m(true);},style:{...a.pill,...a.pillLink,color:s.color.danger,...f?a.pillDisabled:{}},"data-testid":"fact-edit-remove",children:sr.remove})]})]})}i(Og,"FactEditSheet");function ri({record:e,depth:r,petName:t,showLabs:o=true,onNavigate:n,onAsk:s,factEdit:a,nowMs:c}){let{theme:l,styles:d}=V(),u=c??Date.now(),p=react.useMemo(()=>a?Fa(e.entities,a.overlay):e.entities,[e.entities,a]),m=react.useMemo(()=>{let h=[],E=new Map;for(let S of p){let C=S.category.trim();if(C.length===0)continue;let k=E.get(C);k===void 0?(h.push(C),E.set(C,[S])):k.push(S);}return {order:Do(h),groups:E}},[p]),y=Object.values(e.documents),g=a!==void 0&&a.available,f=i((h,E,S)=>s?jsxRuntime.jsx("button",{type:"button",onClick:()=>{let C=h();s(C.prompt,C.entityRef);},"aria-label":E,style:{...d.pill,...d.pillAsk,marginTop:l.space.lg,alignSelf:"flex-start"},"data-testid":S,children:E}):null,"ask"),v={display:"flex",flexDirection:"column",gap:l.space.lg+l.space.xs},b=i(h=>({...d.row,...h>0?d.rowDivider:{}}),"rowStyle"),R={...d.card,padding:`${l.space.md}px ${l.space.lg}px`,display:"flex",flexDirection:"column"};return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{style:v,children:[r&&r.conflicts.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-conflicts",children:[jsxRuntime.jsx($r,{title:K.needsAttention,count:r.conflicts.length}),[...r.conflicts].sort((h,E)=>Io(h.severity).rank-Io(E.severity).rank).map(h=>{let E=Io(h.severity),S=ot(h.field??h.entityType);return jsxRuntime.jsxs("div",{style:{...R,borderColor:d.chipTones[E.tone].color,gap:l.space.sm},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.space.sm},children:[jsxRuntime.jsx("span",{style:{...d.rowTitle,...D(l,"bold"),flex:1},children:E.label}),jsxRuntime.jsx(br,{label:S,tone:E.tone})]}),jsxRuntime.jsx("p",{style:d.rowDetail,children:K.conflictSub}),h.candidates.map((C,k)=>jsxRuntime.jsxs("div",{style:{borderTop:`1px solid ${l.color.borderHairlineGreen}`,paddingTop:l.space.sm},children:[jsxRuntime.jsx("p",{style:d.rowTitle,children:C.value}),jsxRuntime.jsx("p",{style:d.rowMuted,children:[C.docId?e.documents[C.docId]?.title??K.uploadedDocument:K.uploadedDocument,C.collectedAt?ee(C.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},k)),f(()=>Dc(t,{scopeLabel:S,severity:h.severity,candidates:h.candidates.map(C=>({value:C.value,clinicName:C.docId?e.documents[C.docId]?.title??null:null}))},h.conflictId),K.askConflict,`records-ask-conflict-${h.conflictId}`)]},h.conflictId)})]}):null,r?.completeness?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-completeness",children:[jsxRuntime.jsx($r,{title:K.whatsOnFile}),jsxRuntime.jsxs("div",{style:d.card,children:[jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:l.space.sm,padding:`${l.space.md}px 0`},children:[[K.coverage.labs,r.completeness.hasLabHistory],[K.coverage.vaccines,r.completeness.hasVaccinationHistory],[K.coverage.weight,r.completeness.hasWeightHistory],[K.coverage.vitals,r.completeness.hasVitalsHistory],[K.coverage.exams,r.completeness.hasPhysicalExamHistory],[K.coverage.procedures,r.completeness.hasProcedureHistory],[K.coverage.genetics,r.completeness.hasGeneticHistory],[K.coverage.parasite,r.completeness.hasParasitePreventionHistory],[K.coverage.reproductive,r.completeness.hasReproductiveHistory]].map(([h,E])=>jsxRuntime.jsx("span",{"aria-label":`${h}: ${E?K.onFile:K.noneOnFile}`,style:{...d.chip,...E?d.chipTones.positive:{backgroundColor:l.color.badgeBgNeutral,color:l.color.text.muted},fontSize:l.type.size.caption},children:h},h))}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.space.sm,paddingBottom:l.space.md},children:[jsxRuntime.jsx("span",{style:{...d.rowDetail,flex:1,marginTop:0},children:K.documentsOnFile(r.completeness.documentsIngested)}),r.completeness.documentsInReview>0?jsxRuntime.jsx(br,{label:K.inReviewChip(r.completeness.documentsInReview),tone:"warning"}):null,Ba(r.completeness.heldTotal,r.completeness.entitiesPendingReview)>0?jsxRuntime.jsx("span",{"aria-label":K.beingVerifiedA11y(Ba(r.completeness.heldTotal,r.completeness.entitiesPendingReview)),children:jsxRuntime.jsx(br,{label:K.beingVerified(Ba(r.completeness.heldTotal,r.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),r.completeness.earliestRecordAt||r.completeness.latestRecordAt?jsxRuntime.jsx("p",{style:{...d.rowDetail,paddingBottom:l.space.md},children:K.dateRange(r.completeness.earliestRecordAt,r.completeness.latestRecordAt)}):null,Object.entries(r.completeness.entitiesPendingReview).filter(([,h])=>h>0).length>0?jsxRuntime.jsxs("p",{style:{...d.rowMuted,paddingBottom:l.space.md},children:[K.pendingReview,Object.entries(r.completeness.entitiesPendingReview).filter(([,h])=>h>0).map(([h,E])=>`${ct(h)} (${E})`).join(", ")]}):null]})]}):null,y.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-documents",children:[jsxRuntime.jsx($r,{title:K.documents,count:y.length}),jsxRuntime.jsx("ul",{style:d.card,children:y.map((h,E)=>{let S=h.title?.trim()||K.uploadedDocument,C=K.documentMeta(h.pageCount,h.receivedAt),k=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("span",{style:d.rowMain,children:[jsxRuntime.jsx("span",{style:d.rowTitle,children:S}),C?jsxRuntime.jsx("span",{style:{...d.rowDetail,display:"block"},children:C}):null]}),n?jsxRuntime.jsx(kt,{}):null]});return jsxRuntime.jsx("li",{style:b(E),children:n?jsxRuntime.jsx("button",{type:"button",onClick:()=>n({name:"contributions",docId:h.docId}),"aria-label":K.documentRowA11y(S),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:l.space.md,width:"100%",background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},"data-testid":`records-document-row-${h.docId}`,children:k}):k},h.docId)})})]}):null,e.identity.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-identity",children:[jsxRuntime.jsx($r,{title:K.identity}),jsxRuntime.jsx("dl",{style:d.card,children:e.identity.map((h,E)=>jsxRuntime.jsxs("div",{style:b(E),children:[jsxRuntime.jsx("dt",{style:{...d.rowDetail,...D(l,"medium"),marginTop:0},children:h.label}),jsxRuntime.jsx("dd",{style:{...d.rowTitle,margin:0,textAlign:"right"},children:rd(h.value)})]},`${E}:${h.label}`))})]}):null,jsxRuntime.jsx(oc,{series:e.entitySeries}),e.forwardLooking.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-upcoming",children:[jsxRuntime.jsx($r,{title:K.upcomingCare,count:e.forwardLooking.length}),jsxRuntime.jsx("ul",{style:d.card,children:e.forwardLooking.map((h,E)=>{let S=Nn(h.dueAt,u);return jsxRuntime.jsxs("li",{style:b(E),children:[jsxRuntime.jsxs("span",{style:d.rowMain,children:[jsxRuntime.jsx("span",{style:d.rowTitle,children:h.title}),h.detail?jsxRuntime.jsx("span",{style:{...d.rowDetail,display:"block"},children:h.detail}):null]}),S?jsxRuntime.jsx(br,{label:S.label,tone:S.overdue?"critical":"info"}):null]},`${h.title}-${E}`)})}),f(()=>_c(t,e.forwardLooking.map(h=>{let E=Nn(h.dueAt,u);return {label:h.title,relativeText:E?.label??"",tone:E?.overdue?"overdue":"upcoming"}}),e.petRef),K.askUpcomingCare,"records-ask-upcoming-care")]}):null,m.order.map(h=>{let E=m.groups.get(h)??[];if(E.length===0)return null;let S=ct(h);return jsxRuntime.jsxs("section",{style:d.section,"data-testid":`record-section-${h}`,children:[jsxRuntime.jsx($r,{title:S,count:E.length}),jsxRuntime.jsx("ul",{style:d.card,children:E.map((C,k)=>{let M=vc(C,{formatEntityValue:tn,formatRecordsDate:ee,humanize:ot}),T=M.detail,O=jsxRuntime.jsxs("div",{style:b(k),children:[jsxRuntime.jsxs("div",{style:{...d.rowMain,display:"flex",flexDirection:"column"},children:[jsxRuntime.jsx("span",{style:d.rowTitle,children:M.title}),T?jsxRuntime.jsx("span",{style:d.rowDetail,children:T}):null,f(()=>kc(t,{entityTypeLabel:S,title:M.title,detail:T},h,C.key),K.askEverfur,`records-ask-entity-${C.key}`)]}),C.status?jsxRuntime.jsx(br,{label:ot(C.status)}):null]});return jsxRuntime.jsx("li",{children:g&&qa(C)&&a?jsxRuntime.jsx(Ac,{entity:C,factEdit:a,children:O}):O},C.key)})})]},h)}),r&&r.physicalExams.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-exams",children:[jsxRuntime.jsx($r,{title:K.physicalExams,count:r.physicalExams.length}),r.physicalExams.map(h=>jsxRuntime.jsxs("div",{style:R,children:[jsxRuntime.jsx("h4",{style:{...d.rowTitle,paddingTop:l.space.sm},children:h.observedOn?ee(h.observedOn):ge.exam}),jsxRuntime.jsx("ul",{style:d.plainList,children:h.systems.map((E,S)=>{let C=E.findingStatus==="abnormal",k=C?ge.abnormal:E.findingStatus==="not_examined"?ge.notExamined:ge.normal;return jsxRuntime.jsxs("li",{style:b(S),children:[jsxRuntime.jsxs("span",{style:d.rowMain,children:[jsxRuntime.jsx("span",{style:d.rowTitle,children:on(E.system)}),C&&E.finding?jsxRuntime.jsx("span",{style:{...d.rowDetail,display:"block"},children:E.finding}):null]}),jsxRuntime.jsx(br,{label:k,tone:C?"warning":E.findingStatus==="not_examined"?"neutral":"positive"})]},E.system)})}),f(()=>Pc(t,{observedOn:h.observedOn?ee(h.observedOn):null,abnormal:h.systems.filter(E=>E.findingStatus==="abnormal").map(E=>({system:on(E.system),finding:E.finding??""}))},h.examId),K.askExam,`records-ask-exam-${h.examId}`)]},h.examId))]}):null,r&&r.clinicianNotes.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-notes",children:[jsxRuntime.jsx($r,{title:K.visitNotes,count:r.clinicianNotes.length}),r.clinicianNotes.map(h=>jsxRuntime.jsxs("div",{style:R,children:[jsxRuntime.jsx("h4",{style:{...d.rowTitle,paddingTop:l.space.sm},children:h.observedOn?ee(h.observedOn):ge.visitNote}),jsxRuntime.jsx("dl",{style:d.plainList,children:h.sections.map((E,S)=>jsxRuntime.jsxs("div",{style:{padding:`${l.space.md}px 0`,...S>0?d.rowDivider:{}},children:[jsxRuntime.jsx("dt",{style:{...d.rowDetail,...D(l,"bold"),marginTop:0,textTransform:"uppercase"},children:an(E.section)}),jsxRuntime.jsx("dd",{style:{...d.bodyText,marginLeft:0,...E.text?{}:{color:l.color.text.muted,fontStyle:"italic"}},children:E.text||ge.notRecorded})]},`${E.section}:${S}`))}),f(()=>Tc(t,{observedOn:h.observedOn?ee(h.observedOn):null,sections:h.sections.map(E=>({label:an(E.section),text:E.text}))},h.noteId),K.askVisit,`records-ask-note-${h.noteId}`)]},h.noteId))]}):null,o&&r&&r.labResults.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-labs",children:[jsxRuntime.jsx($r,{title:K.labResults,count:r.labResults.length}),jsxRuntime.jsx("ul",{style:d.card,children:r.labResults.map((h,E)=>{let S=nt(h.latest.status),C=sa(h.latest.at,h.trajectory,h.points.length);return jsxRuntime.jsxs("li",{style:b(E),children:[jsxRuntime.jsxs("span",{style:{...d.rowMain,display:"flex",flexDirection:"column"},children:[jsxRuntime.jsx("span",{style:d.rowTitle,children:h.name}),jsxRuntime.jsx("span",{style:d.rowValue,children:hr(h.latest.value,h.latest.unit,h.latest.qualitativeResult)}),C?jsxRuntime.jsx("span",{style:d.rowDetail,children:C}):null]}),jsxRuntime.jsx(br,{label:S.label,tone:Xo(h.latest.status)})]},h.markerId)})})]}):null,r&&r.encounters.length>0?jsxRuntime.jsxs("section",{style:d.section,"data-testid":"record-section-visits",children:[jsxRuntime.jsx($r,{title:K.visits,count:r.encounters.length}),jsxRuntime.jsx("ul",{style:d.card,children:r.encounters.map((h,E)=>{let S=[h.date?ee(h.date):null,h.clinicName,h.veterinarian].filter(C=>C&&C!=="-").join(" \xB7 ");return jsxRuntime.jsx("li",{style:b(E),children:jsxRuntime.jsxs("span",{style:d.rowMain,children:[jsxRuntime.jsx("span",{style:d.rowTitle,children:h.type?ot(h.type):ge.visit}),S?jsxRuntime.jsx("span",{style:{...d.rowDetail,display:"block"},children:S}):null]})},h.encounterId)})})]}):null]}),jsxRuntime.jsx(wt,{disclaimer:e.disclaimer})]})}i(ri,"RecordSections");function Ba(e,r){return e>0?e:Object.values(r).reduce((t,o)=>t+o,0)}i(Ba,"heldCount");function Nc({petRef:e,petName:r,onClose:t,onNavigate:o,onOpenUrl:n,onCopy:s,returnFocusTo:a}){let{theme:c,styles:l}=V(),d=Ea(e),[u,p]=react.useState(null),[m,y]=react.useState(null),[g,f]=react.useState("vet"),[v,b]=react.useState(""),R=react.useId(),h=d.available&&!d.consentRequired,E=d.shareAudiences.length>0,S=d.shareAudiences.find(x=>x.audience===g)??null,C=S!==null?dd(S,d.features):[],k=i((x,L)=>{if(n){It(n,x,L).then(F=>{F.ok||p(Q.toasts.shareSheet);});return}if(L==="share_link"){fc(x,s??Ko).then(F=>{F==="copied"&&p(Q.toasts.copied);},()=>p(Q.toasts.shareSheet));return}bn(x,Yo).then(F=>{F||p(_t(null,"download"));});},"open"),M=i(()=>{p(null),d.createLink(E?g:void 0).then(x=>{x.ok?k(x.value.shareUrl,"share_link"):p(_t(x.error,"create"));});},"onCreateLink"),T=i(x=>{if(x?.preventDefault(),d.sending)return;p(null);let L=v.trim();if(L.length===0){p(Q.addEmailFor(r));return}if(!ao(L)){p(Q.emailInvalid);return}d.sendEmail({recipientEmail:L,recipientKind:g}).then(F=>{F.ok?(b(""),p(Q.toasts.sentTo(L))):p(_t(F.error,"email"));});},"onSend"),O=i(()=>{p(null),d.pdfLink().then(x=>{x.ok?k(x.value.downloadUrl,"record_pdf"):p(_t(x.error,"download"));});},"onDownload"),z=i(x=>{x.shareUrl!==null&&It(s??Ko,x.shareUrl).then(L=>p(L.ok?Q.toasts.copied:Q.toasts.copyFailed));},"onCopyRow"),q=i(x=>{d.revoke(x).then(L=>{y(null),p(L.ok?Q.toasts.turnedOff:_t(L.error,"revoke"));});},"onConfirmRevoke"),N={display:"flex",flexDirection:"column",gap:c.space.sm,padding:c.space.md,borderRadius:c.radius.md,backgroundColor:c.color.surfaceCream,border:`1px solid ${c.color.brandBorder}`},B=i(x=>({boxSizing:"border-box",flex:"1 1 0",minWidth:0,minHeight:qt,display:"flex",alignItems:"center",gap:c.space.sm,padding:`${c.space.sm}px ${c.space.md}px`,borderRadius:c.radius.md,cursor:"pointer",border:x?`1.5px solid ${c.color.brandInk}`:`1px solid ${c.color.borderHairlineGreen}`,backgroundColor:x?c.color.brandSoft:c.color.surface,...l.rowTitle,...D(c,x?"bold":"medium")}),"choice");return jsxRuntime.jsxs(Dt,{label:Q.titleFor(r),onClose:t,shape:"side",returnFocusTo:a,testID:"share-record-sheet",children:[jsxRuntime.jsxs("div",{style:l.sheetHeader,children:[jsxRuntime.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:c.space.xs},children:[jsxRuntime.jsx("h3",{style:l.sheetTitle,children:Q.titleFor(r)}),jsxRuntime.jsx("p",{style:l.sheetHelper,children:E?Q.leadWebFor(r):Q.helper})]}),jsxRuntime.jsx("button",{type:"button",onClick:t,"aria-label":Q.close,style:l.iconButton,"data-testid":"share-record-close",children:jsxRuntime.jsx("span",{style:l.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:c.space.sm},children:[o?jsxRuntime.jsx(j,{label:Q.viewDocument,onClick:()=>{t(),o({name:"document"});},testID:"share-view-document"}):null,h?jsxRuntime.jsxs("form",{onSubmit:T,noValidate:true,style:{display:"flex",flexDirection:"column",gap:c.space.md,margin:0},"data-testid":"share-email-form",children:[jsxRuntime.jsxs("fieldset",{style:{border:0,margin:0,padding:0,minWidth:0},children:[jsxRuntime.jsx("legend",{style:{...l.fieldLabel,padding:0},children:Q.audienceLabel}),jsxRuntime.jsx("div",{style:{display:"flex",gap:c.space.sm},children:Kt.map(x=>jsxRuntime.jsxs("label",{style:B(g===x),children:[jsxRuntime.jsx("input",{type:"radio",name:R,value:x,checked:g===x,onChange:()=>f(x),style:{margin:0,accentColor:c.color.brandInk},"data-testid":`share-audience-${x}`}),Q.audiences[x]]},x))})]}),E&&C.length>0?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:c.space.xs},"data-testid":"share-included",children:[jsxRuntime.jsx("p",{style:{...l.fieldLabel,margin:0},children:Q.included}),jsxRuntime.jsx("ul",{style:{...l.bodyText,margin:0,paddingLeft:c.space.lg},children:C.map(x=>jsxRuntime.jsx("li",{children:x},x))})]}):null,jsxRuntime.jsxs("label",{style:{...l.fieldLabel,margin:0},children:[Q.sendTo,jsxRuntime.jsx("input",{type:"email",style:{...l.field,marginTop:c.space.xs},placeholder:Q.sendToPlaceholder,value:v,maxLength:fi,autoComplete:"email",disabled:d.sending,onChange:x=>b(x.target.value),"data-testid":"share-email-input"})]}),jsxRuntime.jsx(j,{label:d.sending?Q.sending:Q.send,busy:d.sending,onClick:()=>T(),testID:"share-email-send"})]}):null,h?jsxRuntime.jsx(j,{label:d.creating?Q.creatingLink:Q.createLink,kind:"outline",busy:d.creating,onClick:M,testID:"share-create-link"}):null,h?jsxRuntime.jsx(j,{label:d.preparingPdf?Q.preparingPdf:Q.downloadPdf,kind:"outline",busy:d.preparingPdf,onClick:O,testID:"share-download-pdf"}):null,h?jsxRuntime.jsx("p",{style:{...l.muted,textAlign:"center"},"data-testid":"share-link-terms",children:Q.linkTerms}):null]}),d.consentRequired?jsxRuntime.jsxs("div",{style:N,"data-testid":"share-consent-off",children:[jsxRuntime.jsx("p",{style:l.rowTitle,children:Q.consentOffTitle}),jsxRuntime.jsx("p",{style:l.muted,children:Q.consentOffBody}),jsxRuntime.jsx(j,{label:Q.retry,kind:"outline",onClick:d.refresh,testID:"share-consent-retry"})]}):null,u?jsxRuntime.jsx("p",{role:"status","aria-live":"polite",style:l.infoNote,"data-testid":"share-notice",children:u}):null,Vd(d)?jsxRuntime.jsxs("section",{"aria-label":Q.activeLinks,style:{display:"flex",flexDirection:"column",gap:c.space.sm},children:[jsxRuntime.jsx("h4",{style:{...l.fieldLabel,...D(c,"bold"),textTransform:"uppercase"},children:Q.activeLinks}),d.status==="loading"?jsxRuntime.jsx(yd,{testID:"share-record-loading"}):d.status==="error"?jsxRuntime.jsxs("div",{style:N,"data-testid":"share-record-error",children:[jsxRuntime.jsx("p",{style:l.rowTitle,children:Q.errorTitle}),jsxRuntime.jsx("p",{style:l.muted,children:Q.errorBody}),jsxRuntime.jsx(j,{label:Q.retry,kind:"outline",onClick:d.refresh,testID:"share-record-retry"})]}):d.rows.length===0?jsxRuntime.jsxs("div",{style:N,"data-testid":"share-record-empty",children:[jsxRuntime.jsx("p",{style:l.rowTitle,children:Q.emptyTitle}),jsxRuntime.jsx("p",{style:l.muted,children:Q.emptyBody})]}):jsxRuntime.jsx("ul",{style:{...l.plainList,gap:c.space.md},children:d.rows.map(x=>jsxRuntime.jsxs("li",{style:{...N},"data-testid":`share-row-${x.shareId}`,children:[jsxRuntime.jsxs("div",{"aria-label":x.a11yLabel,children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.space.sm},children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:c.space.sm,height:c.space.sm,borderRadius:c.space.xs,backgroundColor:x.active?c.color.success:c.color.text.muted}}),jsxRuntime.jsx("span",{style:{...l.rowTitle,...D(c,"bold")},children:x.statusLabel}),jsxRuntime.jsx("span",{style:l.muted,children:x.expiryLabel})]}),x.createdLabel?jsxRuntime.jsx("p",{style:l.muted,children:x.createdLabel}):null]}),m===x.shareId?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:c.space.sm},"data-testid":`share-revoke-confirm-${x.shareId}`,children:[jsxRuntime.jsx("p",{style:l.bodyText,children:Q.confirmTurnOff}),jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:c.space.sm},children:[jsxRuntime.jsx(j,{label:d.revokingId===x.shareId?Q.turningOff:Q.turnOff,kind:"danger",busy:d.revokingId===x.shareId,onClick:()=>q(x.shareId),testID:`share-revoke-do-${x.shareId}`}),jsxRuntime.jsx(j,{label:Q.keep,kind:"outline",disabled:d.revokingId===x.shareId,onClick:()=>y(null),testID:`share-revoke-cancel-${x.shareId}`})]})]}):jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:c.space.sm},children:[jsxRuntime.jsx(j,{label:Q.copyLink,kind:"outline",disabled:x.shareUrl===null,ariaLabel:Q.copyLinkA11y(x.actionContext),onClick:()=>z(x),testID:`share-copy-${x.shareId}`}),jsxRuntime.jsx(j,{label:Q.turnOff,kind:"danger",ariaLabel:Q.turnOffA11y(x.actionContext),onClick:()=>y(x.shareId),testID:`share-ask-revoke-${x.shareId}`})]})]},x.shareId))})]}):null]})}i(Nc,"ShareSheet");var Lg=i((e,r)=>e.getRecordDepth(r),"readDepth"),zg=i(e=>!e.available,"depthEmpty");function Xn(e){let{style:r,className:t,renderPending:o,...n}=Ie(e,["onNavigate","onBack","onAsk"]),{userRef:s}=se(),{styles:a}=V();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Fe(n.onBack,Me),children:jsxRuntime.jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"everfur-record-screen",children:[s===null?jsxRuntime.jsx("div",{style:a.body,children:jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"})}):jsxRuntime.jsx(Mg,{...n}),jsxRuntime.jsx(Ae,{})]})})}i(Xn,"EverfurRecordDetail");function Mg({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:s,onAsk:a,onOpenUrl:c,onCopy:l}){let{theme:d,styles:u}=V(),p=react.useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),m=er(p),y=Hr(e,Lg,zg),g=Na(e),f=Sa(e),[v,b]=react.useState(false),R=xt(),h=react.useRef(null),E=dt(o,m.consent),S=i(()=>{let z=Zr(o,m.consent);z.length!==0&&m.grantConsent(z,`records-consent-${Date.now().toString(36)}`);},"onGrant"),C=y.value!==null&&!y.value.withheld&&y.value.available?y.value:null,k=m.record,M=i(()=>{m.refresh(),y.refresh();},"retry"),T=n!==void 0||f.lit===true,O;if(m.status==="loading"||y.status==="loading"&&k!==null&&!k.isEmpty)O=jsxRuntime.jsx(sn,{testID:"everfur-record-loading"});else if(m.status==="error"){let z=et(m,E);O=z.kind==="error"||z.kind==="pet_not_found"?jsxRuntime.jsx(He,{variant:nr(z.error),message:z.error.displayMessage,onAction:z.error.retryable?M:void 0,testID:"everfur-record-error"}):Tt(m,S,E);}else if(k===null||k.isEmpty){let z=C?.completeness?.documentsInReview??0;O=jsxRuntime.jsxs("div",{style:u.content,"data-testid":"everfur-record-empty",children:[jsxRuntime.jsx(He,{variant:"no_records",message:z>0?K.inReview(z):void 0}),jsxRuntime.jsx(wt,{disclaimer:k?.disclaimer??""})]});}else O=jsxRuntime.jsx("div",{ref:R,style:{...u.content,gap:d.space.lg+d.space.xs,paddingBottom:d.space.xxl+d.space.sm},"data-testid":"everfur-record",children:jsxRuntime.jsx(ri,{record:k,depth:C,petName:r,onNavigate:n,onAsk:a,factEdit:g})});return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ke,{title:K.title,onBack:s,testID:"everfur-record-header",right:T||n?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[n?jsxRuntime.jsx("button",{type:"button",onClick:()=>n({name:"clinicBatch"}),"aria-label":K.requestClinicsA11y,style:u.iconButton,"data-testid":"everfur-record-request-clinics",children:jsxRuntime.jsx(ia,{name:"send",color:d.color.brandInk})}):null,T?jsxRuntime.jsx("button",{ref:h,type:"button",onClick:()=>b(true),"aria-label":Q.openA11yFor(r),style:u.iconButton,"data-testid":"everfur-record-share",children:jsxRuntime.jsx(ia,{name:"share2",color:d.color.brandInk})}):null]}):void 0}),jsxRuntime.jsx("div",{style:u.body,children:O}),v?jsxRuntime.jsx(Nc,{petRef:e,petName:r,onClose:()=>b(false),returnFocusTo:h,onNavigate:n,...c?{onOpenUrl:c}:{},...l?{onCopy:l}:{}}):null]})}i(Mg,"RecordBody");var oi=Object.freeze({download:"Download",downloadA11y:i(e=>`Download, ${e}`,"downloadA11y"),listA11y:"You added these records"});function $g(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i($g,"formatBytes");function Ug(e){let r=e?.trim();return r?r.toUpperCase():null}i(Ug,"formatLabel");function Ha(e){return Object.freeze(e.map(r=>{let t=Ug(r.docFormat),o=r.receivedAt?ee(r.receivedAt):null,n=r.fileName??t??o??r.sourceDocId,a=[r.fileName!==null&&t!==null&&r.fileName.toUpperCase().endsWith(`.${t}`)||n===t?null:t,r.byteSize!==null?$g(r.byteSize):null,n===o?null:o].filter(c=>!!c).join(" \xB7 ");return Object.freeze({key:r.sourceDocId,title:n,meta:a||null,downloadUrl:r.downloadUrl})}))}i(Ha,"requestDocumentRows");function zc(e){let r=e.fileName?.trim()||e.sourceDocId,t=e.docFormat?.trim().toLowerCase().replace(/^\./,"")??"";return t.length===0||r.toLowerCase().endsWith(`.${t}`)?r:`${r}.${t}`}i(zc,"requestDocumentFileName");function Va(e,r={}){let t=r.enabled??true,o=Rr(),{userRef:n}=se(),[s,a]=react.useState(null),[c,l]=react.useState(t),[d,u]=react.useState(null),p=react.useRef(0),m=react.useRef(true),y=react.useCallback(async()=>{let b=p.current+=1;if(!t||n===null){a(null),u(null),l(false);return}l(true),u(null);let R=await o.listRequestDocuments(e);b!==p.current||!m.current||(R.ok?a(R.value):(a(null),u(R.error)),l(false));},[o,t,e,n]);react.useEffect(()=>(m.current=true,y(),()=>{m.current=false,p.current+=1;}),[y]);let g=react.useMemo(()=>s===null?[]:Ha(s),[s]),f=react.useCallback(()=>{y();},[y]),v=c?"loading":d!==null?"error":g.length===0?"empty":"populated";return react.useMemo(()=>({status:v,rows:g,error:d,refresh:f}),[v,g,d,f])}i(Va,"useRequestDocuments");function Jn({requestId:e,open:r=true,onOpenUrl:t,testID:o="records-request-documents"}){let{theme:n,styles:s}=V(),a=Va(e,{enabled:r}),c=Rr(),[l,d]=react.useState(null),[u,p]=react.useState(null),m=react.useRef(true);react.useEffect(()=>(m.current=true,()=>{m.current=false;}),[]);let y=i(async g=>{d(g.key),p(null);let f=await c.listRequestDocuments(e),v=f.ok?f.value.find(R=>R.sourceDocId===g.key)??null:null,b=v===null;v!==null&&m.current&&(t?await It(t,v.downloadUrl,"request_document"):b=!await bn(v.downloadUrl,zc(v))),m.current&&(d(null),b&&p(g.key));},"save");return r?a.status==="loading"?jsxRuntime.jsx("div",{style:{paddingTop:n.space.sm},"aria-busy":"true","data-testid":`${o}-loading`,children:jsxRuntime.jsx(ve,{width:"100%",height:n.space.lg+n.space.md})}):a.status==="error"?jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:n.space.sm,paddingTop:n.space.sm},"data-testid":`${o}-error`,children:[jsxRuntime.jsx("p",{style:{...s.muted,margin:0},role:"alert",children:a.error?.displayMessage??""}),a.error?.retryable===true?jsxRuntime.jsx(j,{label:X.retry,kind:"outline",onClick:a.refresh,testID:`${o}-retry`}):null]}):a.status==="empty"?null:jsxRuntime.jsx("ul",{"aria-label":oi.listA11y,style:{...s.plainList,paddingTop:n.space.sm},"data-testid":o,children:a.rows.map((g,f)=>jsxRuntime.jsxs("li",{style:Vg(n.space.sm,f===0?null:n.color.brandBorder),children:[jsxRuntime.jsxs("div",{style:{minWidth:0},children:[jsxRuntime.jsx("p",{style:{...s.rowTitle,margin:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.title}),g.meta!==null?jsxRuntime.jsx("p",{style:{...s.muted,margin:0,fontVariantNumeric:"tabular-nums"},children:g.meta}):null]}),jsxRuntime.jsx(j,{label:oi.download,kind:"outline",ariaLabel:oi.downloadA11y(g.title),busy:l===g.key,onClick:()=>{y(g);},testID:`${o}-download-${g.key}`}),u===g.key?jsxRuntime.jsx("p",{role:"alert",style:{...s.errorText,flexBasis:"100%"},"data-testid":`${o}-save-failed-${g.key}`,children:Po.error.title}):null]},g.key))}):null}i(Jn,"RequestDocumentsList");function Vg(e,r){return {display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:e,paddingTop:e,paddingBottom:e,...r!==null?{borderTop:`1px solid ${r}`}:{}}}i(Vg,"rowStyle");function Zn(e){let{style:r,className:t,renderPending:o,...n}=Ie(e,["onNavigate","onBack"]),{userRef:s}=se(),{styles:a}=V();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Fe(n.onBack,Me),children:jsxRuntime.jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"upload-screen",children:[s===null?jsxRuntime.jsx("div",{style:a.body,children:jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"})}):jsxRuntime.jsx(Yg,{...n}),jsxRuntime.jsx(Ae,{})]})})}i(Zn,"EverfurRecordsUpload");function Yg({petRef:e,petName:r,controller:t,onNavigate:o,onBack:n}){let{theme:s,styles:a}=V(),{runtime:c}=se(),l=react.useMemo(()=>t?{petRef:e,controller:t,readUploadFeatures:true}:{petRef:e,readUploadFeatures:true},[e,t]),d=er(l),u=t!==void 0||co(c.registry.services.uploadTransport);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ke,{title:"",onBack:n,testID:"upload-header"}),jsxRuntime.jsxs("div",{style:{...a.body,...a.content,padding:s.space.lg+s.space.xs,gap:s.space.lg+s.space.xs},children:[jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:s.space.sm,textAlign:"center"},children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:52,height:52,borderRadius:s.radius.pill,backgroundColor:s.color.brandSoft,border:`1px solid ${s.color.brandBorder}`}}),jsxRuntime.jsx("h2",{tabIndex:-1,[Ft]:"",style:{...a.sectionTitle,fontSize:s.type.size.heading,color:s.color.brandInk},"data-testid":"upload-title",children:Qe.screenTitle}),jsxRuntime.jsx("p",{style:{...a.muted,fontSize:s.type.size.body,maxWidth:340},children:Qe.subtitle(r)})]}),jsxRuntime.jsx(Ka,{records:d,requestId:null,canUpload:u,onDone:o?p=>o({name:"request",requestId:p}):void 0})]})]})}i(Yg,"UploadBody");function Ka({records:e,requestId:r,canUpload:t,onDone:o}){let{theme:n,styles:s}=V(),a=react.useRef(null),c=`records-upload-format-hint-${r??"new"}`,[l,d]=react.useState(null),[u,p]=react.useState(0),[m,y]=react.useState(false),g=react.useRef(r),f=react.useRef([]),v=e.uploadQueue.filter(O=>O.status!=="skipped"),b=v.filter(O=>O.status==="done").length,R=v.filter(O=>O.status==="failed").length,h=!e.isUploading&&!m&&u>0,E=e.uploadContentTypes,S=xn(E),C=react.useCallback(async O=>{let{uploadable:z,skipped:q}=Xs(O,E),N=Ho(q,S);if(z.length===0){N!==null&&d(N);return}d(N),y(true);try{let B=g.current;if(B===null){let L=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!L.ok){d(Qe.errors.start);return}B=L.value.id,g.current=B;}p(L=>L+1);let x=await e.uploadDocuments(B,z);f.current=x.flatMap((L,F)=>L.status==="failed"&&z[F]!==void 0?[z[F]]:[]);}finally{y(false);}},[e,E,S]),k=i(O=>{let z=Array.from(O.currentTarget.files??[]);O.currentTarget.value="",!(z.length===0||!t)&&(async()=>{let q=[];for(let N of z)q.push(await Vo(N,E));await C(q);})();},"onChange"),M=i(()=>a.current?.click(),"pick"),T=e.isUploading||m;return jsxRuntime.jsxs("section",{style:{...s.creamCard,backgroundColor:n.color.surface},"data-testid":"records-upload-card",children:[jsxRuntime.jsx("h4",{style:{...s.rowTitle,...D(n,"bold"),fontSize:n.type.size.subtitle},children:Qe.cardTitle}),jsxRuntime.jsx("p",{id:c,style:s.muted,children:S?Gn.note:Qe.cardSubtitle}),jsxRuntime.jsx("input",{ref:a,type:"file",accept:jo(E),multiple:true,tabIndex:-1,"aria-hidden":"true",hidden:true,disabled:!t,onChange:k,"data-testid":"records-upload-input"}),l?jsxRuntime.jsx("p",{role:"alert",style:s.errorBanner,children:l}):null,jsxRuntime.jsx(uc,{records:e}),T?jsxRuntime.jsx("p",{style:s.muted,children:Qe.uploading(b,v.length)}):h?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:n.space.sm},children:[b>0?jsxRuntime.jsx("p",{role:"status",style:s.bodyText,children:Qe.received(b)}):null,R>0?jsxRuntime.jsx(j,{label:Qe.retryFailed(R),kind:"link",ariaLabel:Qe.retryFailedA11y(R),onClick:()=>{C(f.current);},testID:"records-upload-retry-failed"}):null,jsxRuntime.jsx("p",{style:{...s.rowTitle,...D(n,"bold"),marginTop:n.space.xs},children:Qe.haveMore}),S?jsxRuntime.jsx("p",{style:s.muted,children:Gn.haveMoreLead}):null,jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:n.space.sm},children:[jsxRuntime.jsx(j,{label:Qe.addMore,kind:"link",ariaLabel:Qe.addMoreA11y,ariaDescribedBy:c,disabled:!t,onClick:M,testID:"records-upload-another"}),o&&g.current!==null&&b>0?jsxRuntime.jsx(j,{label:Qe.done,ariaLabel:Qe.doneA11y,onClick:()=>o(g.current),testID:"records-upload-done"}):null]})]}):jsxRuntime.jsx(j,{label:Qe.chooseFiles,ariaLabel:Qe.chooseFilesA11y,ariaDescribedBy:c,disabled:!t,onClick:M,testID:"records-upload-choose"})]})}i(Ka,"UploadRecordCard");function eo(e){let{style:r,className:t,renderPending:o,...n}=Ie(e,["onNavigate","onBack"]),{userRef:s}=se(),{styles:a}=V();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Fe(n.onBack,Me),children:jsxRuntime.jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-request-screen",children:[s===null?jsxRuntime.jsx("div",{style:a.body,children:jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"})}):jsxRuntime.jsx(Jg,{...n}),jsxRuntime.jsx(Ae,{})]})})}i(eo,"EverfurRecordsRequest");function Jg({petRef:e,petName:r,requestId:t,controller:o,onNavigate:n,onBack:s,onOpenUrl:a,nowMs:c}){let{styles:l}=V(),{runtime:d,userRef:u,scopeEpoch:p}=se(),m=er(o?{petRef:e,controller:o,readUploadFeatures:true}:{petRef:e,readUploadFeatures:true}),y=m.requests.find(v=>v.id===t)??null,g=o!==void 0||co(d.registry.services.uploadTransport),f;return m.status==="loading"?f=jsxRuntime.jsx(Oo,{testID:"records-request-loading"}):m.status==="error"&&m.error?f=jsxRuntime.jsx(He,{variant:nr(m.error),message:m.error.displayMessage,onAction:m.error.retryable?m.refresh:void 0,testID:"records-request-error"}):y===null?f=jsxRuntime.jsx(He,{variant:"no_requests",testID:"records-request-missing"}):f=jsxRuntime.jsx(Zg,{petName:r,request:y,records:m,canUpload:g,onNavigate:n,onOpenUrl:a,nowMs:c},JSON.stringify([u,p,y.id])),jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ke,{title:y?Ro(y):"",onBack:s,testID:"records-request-header"}),jsxRuntime.jsx("div",{style:l.body,children:f})]})}i(Jg,"RequestBody");function Zg({petName:e,request:r,records:t,canUpload:o,onNavigate:n,onOpenUrl:s,nowMs:a}){let{theme:c,styles:l}=V(),d=Jd({request:r,onRecovered:t.refresh,canUpload:o},zr()),[u,p]=react.useState(null),[m,y]=react.useState(false),[g,f]=react.useState(null),v=react.useRef(true);react.useEffect(()=>(v.current=true,()=>{v.current=false;}),[]);let b=d.request,R=a??Date.now(),h=b.status==="published",E=b.status==="published"||b.status==="failed"||b.status==="revoked",S=Ji(b),C=b.wireStatus==="clinic_responded_no_records",k=Il(b,R),M=E?null:b.waitingExpectation?.trim()||null,T=vo(b),O=d.error!==null&&u!==null?u==="revoke"?le.errors.cancel:le.errors[u]:null,z=i((A,_)=>{p(A),_();},"run"),q=i(()=>{m||(y(true),f(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(A=>{if(v.current){if(y(false),!A.ok){f(le.errors.start);return}n?.({name:"request",requestId:A.value.id});}}));},"startFresh"),N={display:"flex",flexDirection:"column",gap:c.space.sm},B=i(A=>jsxRuntime.jsx("p",{role:"alert",style:l.errorBanner,children:A}),"errorBanner"),x=`records-failure-clinic-email-${b.id}`,L=xt(),F=b.clinicName?.trim()??"",W=!jt(b)&&F.length>0,I=W&&(b.status==="requested"||b.status==="awaiting_clinic"),w=ee(b.createdAt);return jsxRuntime.jsxs("div",{ref:L,style:{...l.content,gap:c.space.lg+c.space.xs/2},"data-testid":`records-request-${b.id}`,children:[I?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:c.space.xs},"data-testid":"records-request-sent",children:[jsxRuntime.jsx("h3",{style:{...l.sectionTitle,color:c.color.brandInk},children:le.sentTitle}),jsxRuntime.jsx("p",{style:l.bodyText,children:le.sentLeadWeb(F,Re(e))})]}):null,b.statusLabel.length>0||b.heldItemCount>0?jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:c.space.sm},"data-testid":"records-request-status-row",children:[b.statusLabel.length>0?jsxRuntime.jsx(br,{label:b.statusLabel,tone:il(b),testID:"records-request-status-chip"}):null,b.heldItemCount>0?jsxRuntime.jsx(br,{label:Mi(b.heldItemCount),tone:"neutral",testID:"records-request-held-count"}):null]}):null,b.status==="awaiting_upload"?jsxRuntime.jsx(Ka,{records:t,requestId:b.id,canUpload:o}):null,M&&!k?jsxRuntime.jsx("p",{style:l.infoNote,children:M}):b.wireStatus==="awaiting_response"&&!k?jsxRuntime.jsx("p",{style:l.infoNote,children:le.awaitingNote}):null,k?jsxRuntime.jsx("p",{style:l.cautionNote,"data-testid":"records-request-waiting-banner",children:le.waitingBanner(Xi(b,R))}):null,h&&n?jsxRuntime.jsx(j,{label:le.viewRecords,onClick:()=>n({name:"dashboard"}),testID:"records-request-view-dashboard"}):null,Ol(b)?jsxRuntime.jsxs("section",{style:{...N,gap:c.space.md,borderRadius:c.radius.lg-c.space.xs,padding:c.space.md+c.space.xs/2,backgroundColor:S?c.color.badgeBgCritical:c.color.badgeBgCaution},"data-testid":"records-failure-card",children:[jsxRuntime.jsx("p",{style:{...l.rowTitle,...D(c,"bold"),color:S?c.color.danger:c.color.warningStrong},children:Dl(b)}),b.canUpdateClinicEmail!==true&&b.canRetrySend!==true?jsxRuntime.jsx("p",{style:l.rowDetail,children:le.nextStep}):null,b.canUpdateClinicEmail===true?jsxRuntime.jsxs("div",{style:N,children:[jsxRuntime.jsx("label",{htmlFor:x,style:l.fieldLabel,children:jr.email}),jsxRuntime.jsx("input",{id:x,type:"email",style:l.field,placeholder:jr.emailPlaceholder,autoComplete:"off",maxLength:320,value:d.email,disabled:d.busy,onChange:A=>d.setEmail(A.target.value),"data-testid":"records-failure-clinic-email"}),d.emailInvalid?jsxRuntime.jsx("p",{role:"alert",style:l.errorText,children:le.errors.invalidEmail}):null,jsxRuntime.jsx(j,{label:jr.updateEmail,ariaLabel:jr.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&u==="email",onClick:()=>z("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,b.canRetrySend===true?jsxRuntime.jsx(j,{label:jr.retry,kind:"outline",ariaLabel:jr.retryA11y,disabled:!d.canRetry,busy:d.busy&&u==="retry",onClick:()=>z("retry",d.retry),testID:"records-failure-retry-send"}):null,b.canRetrySend===true&&d.hasEmailEdit?jsxRuntime.jsx("p",{style:l.rowDetail,children:jr.retryHint}):null,O&&(u==="email"||u==="retry")?B(O):null]}):null,(S||C)&&n?jsxRuntime.jsx(j,{label:le.tryAnotherClinic,kind:"outline",ariaLabel:le.tryAnotherClinicA11y,onClick:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,T!==null?jsxRuntime.jsxs("div",{style:N,children:[jsxRuntime.jsx(pc,{call:T,prompt:b.statusLabel}),b.canRetrySend===true?jsxRuntime.jsx(j,{label:d.busy&&u==="retry"?le.resending:le.resend,kind:"outline",ariaLabel:d.busy&&u==="retry"?le.resendingA11y:le.resendA11y,disabled:!d.canRetry,onClick:()=>z("retry",d.retry),testID:"records-resend-authorization"}):null]}):null,d.canConvert?jsxRuntime.jsxs("div",{style:N,children:[jsxRuntime.jsx(j,{label:d.busy&&u==="convert"?le.converting:le.convert,busy:d.busy&&u==="convert",onClick:()=>z("convert",d.convert),testID:"records-convert-upload"}),jsxRuntime.jsx("p",{style:l.muted,children:le.convertHint}),O&&u==="convert"?B(O):null]}):null,E&&!h?jsxRuntime.jsxs("div",{style:N,children:[jsxRuntime.jsx(j,{label:m?le.freshUploadStarting:le.freshUpload,kind:S||C?"outline":"primary",busy:m,onClick:q,testID:"records-upload-own-fresh"}),g?B(g):null]}):null,O&&u==="revoke"?B(O):null,b.canRevoke===true?d.confirmingRevoke?jsxRuntime.jsxs("div",{style:N,"data-testid":"records-revoke-confirm",children:[jsxRuntime.jsx("p",{style:{...l.rowTitle,...D(c,"bold"),fontSize:c.type.size.subtitle},children:jr.cancelQuestion}),jsxRuntime.jsx("p",{style:l.bodyText,children:jr.cancelConsequence}),jsxRuntime.jsx(j,{label:d.busy&&u==="revoke"?le.cancelling:le.cancel,kind:"danger",ariaLabel:d.busy&&u==="revoke"?le.cancellingA11y:le.cancelA11y,busy:d.busy&&u==="revoke",onClick:()=>z("revoke",d.revoke),testID:"records-revoke-do"}),jsxRuntime.jsx(j,{label:jr.keepRequest,kind:"outline",disabled:d.busy,onClick:d.keepRequest,testID:"records-revoke-keep"})]}):jsxRuntime.jsx(j,{label:le.cancel,kind:"danger",ariaLabel:le.cancelA11y,disabled:d.busy,onClick:d.askRevoke,testID:"records-revoke"}):null,jsxRuntime.jsxs("section",{style:{...l.creamCard,backgroundColor:c.color.surface},"aria-label":le.whereItStands,"data-testid":"records-request-where",children:[jsxRuntime.jsx("h3",{style:l.sectionTitle,children:le.whereItStands}),jsxRuntime.jsx(fn,{request:b,petName:e})]}),W?jsxRuntime.jsxs("section",{style:{...l.creamCard,backgroundColor:c.color.surface},"aria-label":le.details,"data-testid":"records-request-details",children:[jsxRuntime.jsx("h3",{style:l.sectionTitle,children:le.details}),jsxRuntime.jsxs("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"baseline",columnGap:c.space.lg,rowGap:c.space.sm},children:[jsxRuntime.jsx("dt",{style:l.muted,children:le.detailsClinic}),jsxRuntime.jsx("dd",{style:{...l.bodyText,margin:0},children:F}),w!=="-"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{style:l.muted,children:le.detailsSent}),jsxRuntime.jsx("dd",{style:{...l.bodyText,margin:0},children:jsxRuntime.jsx("time",{dateTime:b.createdAt,children:w})})]}):null]})]}):null,jt(b)?jsxRuntime.jsx(Jn,{requestId:b.id,...s?{onOpenUrl:s}:{}}):null]})}i(Zg,"RequestDetail");function to(e){return e.name==="request"||e.name==="clinicPicker"||e.name==="consent"||e.name==="clinicBatch"||e.name==="upload"}i(to,"isOverlayScreen");function jc(e,r){if(r.type!=="closeOverlay")return In(e,r);let t=e.stack.length;for(;t>1&&to(e.stack[t-1]);)t-=1;return t===e.stack.length?e:Object.freeze({stack:Object.freeze(e.stack.slice(0,t))})}i(jc,"recordsPageNavReducer");function Vc(e){let{stack:r}=e,t=r[r.length-1],o=to(t)?t:null,n=r.length-1;for(;n>0&&to(r[n]);)n-=1;let s=r[n],a=to(s)?{name:"dashboard"}:s,c=o===null?null:r[r.length-2];return Object.freeze({body:a,overlay:o,overlayCanStepBack:c!=null&&to(c),bodyCanGoBack:n>0})}i(Vc,"splitRecordsPageNav");function Wc(e){return {...e.petName!==void 0?{petName:e.petName}:{},...e.onOpenUrl?{onOpenUrl:e.onOpenUrl}:{},...e.onCopy?{onCopy:e.onCopy}:{},...e.onAsk?{onAsk:e.onAsk}:{},...e.location?{location:e.location}:{}}}i(Wc,"seamsOf");function Gc({screen:e,ctx:r,onBack:t}){let o={...Wc(r),onNavigate:r.navigate,onBack:t},n={...r.controller?{controller:r.controller}:{},...r.consentVersion!==void 0?{consentVersion:r.consentVersion}:{}},s=tb;switch(e.name){case "record":return jsxRuntime.jsx(Xn,{petRef:r.petRef,...o,...n,style:s});case "timeline":return jsxRuntime.jsx($o,{petRef:r.petRef,...o,style:s});case "document":return jsxRuntime.jsx(Qn,{petRef:r.petRef,...o,...n,style:s});case "contributions":return jsxRuntime.jsx(Uo,{petRef:r.petRef,docId:e.docId,...o,style:s});default:return Nr(e)}}i(Gc,"RecordsPageBodyScreenView");function Yc({screen:e,ctx:r,requests:t,onBack:o,onClose:n}){let s=rn(e),a=react.useMemo(()=>rb(e,t),[e,t]),c=r.onAsk,l=c?{onAsk:i((y,g)=>{n(),c(y,g);},"onAsk")}:{},d={...Wc(r),...l,onNavigate:r.navigate,onBack:o},u=r.clinicController?{controller:r.clinicController}:{},p=r.onCaptureSignature?{onCaptureSignature:r.onCaptureSignature}:{},m;switch(e.name){case "request":m=jsxRuntime.jsx(eo,{petRef:r.petRef,requestId:e.requestId,...d,...r.controller?{controller:r.controller}:{},style:ro});break;case "clinicPicker":m=jsxRuntime.jsx(Ln,{petRef:r.petRef,...d,...u,...r.controller?{recordsController:r.controller}:{},style:ro});break;case "consent":m=jsxRuntime.jsx(Hn,{petRef:r.petRef,clinic:e.clinic,...d,...r.ownerName!==void 0?{ownerName:r.ownerName}:{},...p,...u,style:ro});break;case "clinicBatch":m=jsxRuntime.jsx($n,{petRef:r.petRef,petName:r.petName??"",ownerName:r.ownerName??"",onClose:o,onCreated:()=>r.navigate({name:"dashboard"}),...p,...u,style:ro});break;case "upload":m=jsxRuntime.jsx(Zn,{petRef:r.petRef,...d,...r.controller?{controller:r.controller}:{},style:ro});break;default:m=Nr(e);}return jsxRuntime.jsx(Dt,{label:a,onClose:n,shape:"side",panelStyle:nb,testID:"everfur-records-page-sheet",children:jsxRuntime.jsx("div",{ref:s,tabIndex:-1,style:ob,children:m})})}i(Yc,"RecordsPageOverlay");function rb(e,r){if(e.name==="upload")return _e.uploadAction;if(e.name!=="request")return _e.requestRecords;let t=r.find(o=>o.id===e.requestId);return t?yo(t):_e.requestTimeline}i(rb,"overlayLabel");var tb=Object.freeze({height:"auto"}),nb=Object.freeze({padding:0,gap:0}),ob=Object.freeze({height:"100%",outline:"none"}),ro=Object.freeze({height:"100%"});function ii({requests:e,petName:r,level:t,headingId:o,onOpenRequest:n,onUpload:s,onOpenUrl:a}){let{theme:c,styles:l}=V(),d=xo(t),u=e.length>0;return jsxRuntime.jsxs("section",{"aria-labelledby":o,style:l.section,"data-testid":"everfur-records-page-requests",children:[jsxRuntime.jsxs("div",{style:l.sectionHeader,children:[jsxRuntime.jsx(d,{id:o,style:{...l.sectionTitle,color:c.color.brandInk},children:_e.requestsFor(r)}),u?jsxRuntime.jsx("span",{style:l.sectionCount,"data-testid":"everfur-records-page-requests-count",children:e.length}):null]}),u?jsxRuntime.jsx("ul",{style:{...l.plainList,gap:c.space.md},children:e.map(p=>{let m=yo(p),y=zi(null,p)!==null;return jsxRuntime.jsxs("li",{style:l.creamCard,"data-testid":`everfur-records-page-request-${p.id}`,children:[jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:c.space.sm},children:[jsxRuntime.jsx("span",{style:{...l.rowTitle,fontSize:c.type.size.subtitle},children:m}),n?jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:c.space.sm},children:[y?jsxRuntime.jsx(j,{label:Qe.cardTitle,onClick:()=>n(p),testID:`everfur-records-page-resume-upload-${p.id}`}):null,jsxRuntime.jsx(j,{label:_e.requestTimeline,kind:"outline",ariaLabel:_e.requestTimelineA11y(m),onClick:()=>n(p),testID:`everfur-records-page-open-${p.id}`})]}):null]}),jsxRuntime.jsx(fn,{request:p}),jt(p)?jsxRuntime.jsx(Jn,{requestId:p.id,...a?{onOpenUrl:a}:{}}):null]},p.id)})}):jsxRuntime.jsxs("div",{style:l.creamCard,"data-testid":"everfur-records-page-upload-prompt",children:[jsxRuntime.jsx("span",{style:{...l.rowTitle,fontSize:c.type.size.subtitle},children:_e.uploadPromptTitle(r)}),jsxRuntime.jsx("p",{style:l.bodyText,children:_e.uploadPromptBody}),s?jsxRuntime.jsx(j,{label:_e.uploadAction,onClick:s,testID:"everfur-records-page-upload"}):null]})]})}i(ii,"RecordsPageRequests");var ub=1248,pb=Object.freeze({height:"auto"}),ai=Object.freeze({overflowY:"visible",flex:"0 0 auto"});function mb(e){let{style:r,className:t,renderPending:o,...n}=Ie(e,["onNavigate","onBack","onAsk"]),{userRef:s}=se(),{styles:a}=V();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Fe(n.onBack,Me),children:jsxRuntime.jsxs("div",{className:t,style:{...a.root,...pb,...r},"data-testid":"everfur-records-page",children:[s===null?jsxRuntime.jsx("div",{style:{...a.body,...ai},children:jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"})}):jsxRuntime.jsx(fb,{...n}),jsxRuntime.jsx(Ae,{})]})})}i(mb,"EverfurRecordsPage");function fb(e){let{petRef:r,petName:t,controller:o,clinicController:n,consentVersion:s,ownerName:a,onCaptureSignature:c,onNavigate:l,onOpenUrl:d,onCopy:u,onAsk:p,location:m}=e,[y,g]=react.useReducer(jc,void 0,()=>Zt()),f=react.useCallback(z=>{l?l(z):g({type:"navigate",screen:z});},[l]),{body:v,overlay:b,overlayCanStepBack:R,bodyCanGoBack:h}=Vc(y),E=react.useMemo(()=>o?{petRef:r,controller:o}:{petRef:r},[r,o]),S=er(E),{refresh:C}=S,k=react.useRef(false);react.useEffect(()=>{b!==null?k.current=true:k.current&&(k.current=false,C());},[b,C]);let M=rn(v),T={petRef:r,petName:t,controller:o,clinicController:n,consentVersion:s,ownerName:a,onCaptureSignature:c,navigate:f,...d?{onOpenUrl:d}:{},...u?{onCopy:u}:{},...p?{onAsk:p}:{},...m?{location:m}:{}},O=v.name==="dashboard"||v.name==="requests";return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{ref:M,tabIndex:-1,style:yb,children:O?jsxRuntime.jsx(gb,{...e,records:S,navigate:f}):jsxRuntime.jsx(Gc,{screen:v,ctx:T,onBack:h?()=>g({type:"pop"}):()=>f({name:"dashboard"})})}),b!==null?jsxRuntime.jsx(Yc,{screen:b,ctx:T,requests:S.requests,onBack:R?()=>g({type:"pop"}):()=>g({type:"closeOverlay"}),onClose:()=>g({type:"closeOverlay"})}):null]})}i(fb,"RecordsPageBody");var yb=Object.freeze({outline:"none"});function gb({petRef:e,petName:r,consentVersion:t,onAsk:o,onOpenUrl:n,headingLevel:s,records:a,navigate:c}){let{theme:l,styles:d}=V(),u=Ot("recordsClinic"),p=u.enabled||u.isPending,m=Sl(s??So),y=xo(m),g=`${react.useId()}-requests-heading`,f=dt(t,a.consent),v=i(()=>{let R=Zr(t,a.consent);R.length!==0&&a.grantConsent(R,`records-consent-${Date.now().toString(36)}`);},"onGrant"),b={boxSizing:"border-box",width:"100%",maxWidth:ub,margin:"0 auto",display:"flex",flexDirection:"column",gap:l.space.lg+l.space.xs,padding:`${l.space.lg}px ${l.space.lg}px ${l.space.xxl}px`};if(a.status==="loading")return jsxRuntime.jsx("div",{style:{...d.body,...ai},children:jsxRuntime.jsx("div",{style:b,children:jsxRuntime.jsx(sn,{testID:"everfur-records-page-loading"})})});if(a.status==="error"){let R=et(a,f),h=R.kind==="error"||R.kind==="pet_not_found"?jsxRuntime.jsx(He,{variant:nr(R.error),message:R.error.displayMessage,onAction:R.error.retryable?()=>a.refresh():void 0,testID:"everfur-records-page-error"}):Tt(a,v,f);return jsxRuntime.jsx("div",{style:{...d.body,...ai},children:jsxRuntime.jsx("div",{style:b,children:h})})}return jsxRuntime.jsx("div",{style:{...d.body,...ai},children:jsxRuntime.jsxs("div",{style:b,"data-testid":"everfur-records-page-content",children:[jsxRuntime.jsxs("header",{style:{...d.creamCard,gap:l.space.md,padding:`${l.space.lg+l.space.xs}px ${l.space.lg+l.space.md}px`},"data-testid":"everfur-records-page-header",children:[jsxRuntime.jsx(y,{tabIndex:-1,[Ft]:"",style:{...d.headerTitle,whiteSpace:"normal",overflow:"visible"},children:_e.titleFor(r)}),jsxRuntime.jsx("p",{style:d.bodyText,children:_e.lead}),jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:l.space.sm},"data-testid":"everfur-records-page-actions",children:[p?jsxRuntime.jsx(j,{label:_e.requestRecords,onClick:()=>c({name:"clinicPicker"}),testID:"everfur-records-page-request-records"}):null,jsxRuntime.jsx(j,{label:_e.uploadAction,kind:"outline",onClick:()=>c({name:"upload"}),testID:"everfur-records-page-upload-action"}),o?jsxRuntime.jsx(j,{label:_e.askA11y(r),kind:"ask",ariaLabel:_e.askA11y(r),onClick:()=>o(Zs(r),{type:"marker_summary",id:e}),testID:"everfur-records-page-ask"}):null]}),jsxRuntime.jsxs("nav",{style:{display:"flex",flexWrap:"wrap",columnGap:l.space.lg,rowGap:l.space.xs},"data-testid":"everfur-records-page-links",children:[jsxRuntime.jsx(Kc,{label:_e.viewRecord,onClick:()=>c({name:"record"}),testID:"everfur-records-page-link-record"}),jsxRuntime.jsx(Kc,{label:_e.viewTimeline,onClick:()=>c({name:"timeline"}),testID:"everfur-records-page-link-timeline"})]})]}),jsxRuntime.jsx(ii,{requests:a.requests,petName:r,level:Ki(m),headingId:g,onOpenRequest:R=>c({name:"request",requestId:R.id}),onUpload:()=>c({name:"upload"}),...n?{onOpenUrl:n}:{}})]})})}i(gb,"RecordsPageContent");function Kc({label:e,onClick:r,testID:t}){let{theme:o,styles:n}=V();return jsxRuntime.jsx("button",{type:"button",onClick:r,style:{...n.pill,...n.pillLink,minHeight:44,padding:0,fontSize:o.type.size.bodyTight,textDecoration:"underline",textUnderlineOffset:4},"data-testid":t,children:e})}i(Kc,"PageLink");var xr=200,Xa=16,Ja=(xr-Xa)/2,Qc=2*Math.PI*Ja;function Jc({summary:e,onAsk:r,testID:t}){let o=hb(),{theme:n,styles:s}=V(),{totalMarkers:a,inRangeCount:c,outOfRangeCount:l,unknownCount:d}=e,u=c+l+d,p=react.useMemo(()=>{if(!(u>0))return [];let m=[{key:"in_range",color:n.color.success,count:c},{key:"out_of_range",color:n.color.danger,count:l},{key:"unknown",color:n.color.text.muted,count:d}],y=0;return m.filter(g=>g.count>0).map(g=>{let f=g.count/u*Qc,v=-y;return y+=f,{key:g.key,color:g.color,length:f,offset:v}})},[u,c,l,d,n]);return jsxRuntime.jsxs("section",{role:"group","aria-label":_r.title,style:o.card,"data-testid":t,children:[jsxRuntime.jsx("h3",{style:o.title,children:_r.title}),jsxRuntime.jsx("div",{style:o.ringRow,children:jsxRuntime.jsxs("div",{style:o.ringWrap,role:"img","aria-label":_r.a11y(a,c,l,d),children:[jsxRuntime.jsxs("svg",{width:xr,height:xr,viewBox:`0 0 ${xr} ${xr}`,"aria-hidden":"true",focusable:"false",children:[jsxRuntime.jsx("circle",{cx:xr/2,cy:xr/2,r:Ja,stroke:n.color.surfaceSubtle,strokeWidth:Xa,fill:"none"}),jsxRuntime.jsx("g",{transform:`rotate(-90 ${xr/2} ${xr/2})`,children:p.map(m=>jsxRuntime.jsx("circle",{cx:xr/2,cy:xr/2,r:Ja,stroke:m.color,strokeWidth:Xa,fill:"none",strokeDasharray:`${m.length} ${Qc}`,strokeDashoffset:m.offset,strokeLinecap:p.length>1?"round":"butt","data-testid":`marker-ring-${m.key}`},m.key))})]}),jsxRuntime.jsxs("div",{style:o.center,"aria-hidden":"true",children:[jsxRuntime.jsx("span",{style:o.centerCount,children:a}),jsxRuntime.jsx("span",{style:o.centerLabel,children:a===1?_r.marker:_r.markers})]})]})}),p.length>0?jsxRuntime.jsxs("div",{style:o.badges,children:[jsxRuntime.jsx("span",{style:{...o.badge,borderColor:n.color.danger,color:n.color.danger},children:`${l} ${_r.outOfRange}`}),jsxRuntime.jsx("span",{style:{...o.badge,borderColor:n.color.success,color:n.color.success},children:`${c} ${_r.inRange}`}),d>0?jsxRuntime.jsx("span",{style:{...o.badge,borderColor:n.color.text.muted,color:n.color.text.muted},children:`${d} ${_r.noRange}`}):null]}):null,jsxRuntime.jsx("p",{style:o.subtitle,children:_r.subtitle}),r?jsxRuntime.jsx("button",{type:"button",onClick:r,"aria-label":_r.askA11y,style:{...s.pill,...s.pillAsk},"data-testid":"marker-summary-ask",children:_r.ask}):null]})}i(Jc,"MarkerSummaryCard");function hb(){let e=ye();return react.useMemo(()=>Rb(e),[e])}i(hb,"useStyles");function Rb(e){let{color:r,space:t,radius:o,type:n}=e;return {card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.sm+t.xs/2,borderRadius:o.lg,backgroundColor:r.surfaceCream,border:`1px solid ${r.borderRingCream}`,padding:t.lg},title:{margin:0,...D(e,"bold"),fontSize:n.size.subtitle,color:r.brandInk,letterSpacing:"-0.02em"},ringRow:{display:"flex",justifyContent:"center"},ringWrap:{position:"relative",width:xr,height:xr},center:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},centerCount:{...D(e,"medium"),fontSize:n.size.verdict*2,lineHeight:1.1,color:r.text.primary},centerLabel:{...D(e,"medium"),fontSize:n.size.heading-1,lineHeight:1.2,color:r.text.primary},badges:{display:"flex",flexWrap:"wrap",justifyContent:"center",gap:t.sm},badge:{border:"1px solid",borderRadius:o.pill,padding:`${t.xs}px ${t.sm+t.xs/2}px`,...D(e,"mono"),fontSize:n.size.nano,lineHeight:`${n.size.tiny}px`,textTransform:"uppercase",letterSpacing:n.letterSpacing.headerBrand/2},subtitle:{margin:0,...D(e,"regular"),fontSize:n.size.caption,lineHeight:`${Math.round(n.size.caption*n.lineHeight.relaxed)}px`,color:r.text.primary}}}i(Rb,"makeStyles");function vb(e){return e.value!==null&&Number.isFinite(e.value)}i(vb,"numeric");function Zc(e){let r=e.points.filter(vb);if(r.length===0)return null;let t=e.points[e.points.length-1]??null,o=t?.refLow??null,n=t?.refHigh??null,s=r.map(b=>b.value),a=Math.min(...s,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...s,...o!==null?[o]:[],...n!==null?[n]:[]);a===c&&(a-=1,c+=1);let l=(c-a)*.18,d=a-l,u=c+l,p=u-d,m=i(b=>(u-b)/p*100,"y"),y=6,g=r.length,f=r.map((b,R)=>({index:R,xPct:g<=1?50:y+R/(g-1)*(100-2*y),yPct:m(b.value),status:b.status,point:b})),v=o!==null||n!==null?{topPct:n!==null?m(n):0,bottomPct:o!==null?m(o):100}:null;return {points:f,band:v,firstDate:r[0]?.at??null,lastDate:r[r.length-1]?.at??null}}i(Zc,"buildMarkerChart");var eu=100,si=44;function Eb({marker:e,onPointPress:r,onAsk:t}){let o=Za(),{theme:n,styles:s}=V(),a=nt(e.latest?.status??null),c=nn(e.trajectory,e.points.length),l=react.useMemo(()=>Zc(e),[e]),d=e.latest?hr(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsxRuntime.jsx("li",{style:o.page,"data-testid":`marker-card-${e.markerId}`,children:jsxRuntime.jsxs("article",{style:o.card,children:[jsxRuntime.jsxs("div",{style:o.headerRow,children:[jsxRuntime.jsxs("div",{style:o.nameColumn,children:[jsxRuntime.jsx("span",{style:o.markerName,children:e.name}),e.unit?jsxRuntime.jsx("span",{style:o.unit,children:e.unit}):null]}),jsxRuntime.jsx("span",{"aria-label":st.status(a.label),children:jsxRuntime.jsx(br,{label:a.label,tone:Xo(e.latest?.status??null)})})]}),e.latest&&d!==null?jsxRuntime.jsxs("div",{style:o.latestRow,children:[jsxRuntime.jsx("span",{style:{...o.latestValue,...a.outOfRange?o.latestValueDanger:{}},"aria-label":st.latestA11y(d,a.label,ee(e.latest.at)),children:d}),jsxRuntime.jsx("span",{style:o.latestDate,children:ee(e.latest.at)})]}):null,c?jsxRuntime.jsx("p",{style:o.trajectory,children:c}):null,l!==null?jsxRuntime.jsxs("div",{style:o.chartWrap,children:[jsxRuntime.jsxs("svg",{viewBox:`0 0 ${eu} ${si}`,preserveAspectRatio:"none",style:o.plot,"aria-hidden":"true",focusable:"false",children:[l.band?jsxRuntime.jsx("rect",{x:0,y:l.band.topPct/100*si,width:eu,height:Math.max(0,(l.band.bottomPct-l.band.topPct)/100*si),fill:n.color.badgeBgPositive}):null,l.points.length>1?jsxRuntime.jsx("polyline",{fill:"none",stroke:n.color.brandBorder,strokeWidth:.6,vectorEffect:"non-scaling-stroke",points:l.points.map(u=>`${u.xPct},${u.yPct/100*si}`).join(" ")}):null]}),jsxRuntime.jsx("div",{style:o.dotLayer,children:l.points.map(u=>jsxRuntime.jsx("button",{type:"button",onClick:()=>r(e,u.point),"aria-label":La(e,u.point),style:{...o.dot,...u.status==="above"||u.status==="below"?o.dotDanger:{},left:`${u.xPct}%`,top:`${u.yPct}%`},"data-testid":`marker-point-${e.markerId}-${u.index}`},u.index))}),jsxRuntime.jsx("ul",{"aria-label":st.readingsA11y(e.name),style:o.a11yTable,children:e.points.map((u,p)=>jsxRuntime.jsx("li",{children:La(e,u)},p))}),jsxRuntime.jsx("p",{style:e.points.length===1?o.singleHint:o.tapHint,children:e.points.length===1?st.singleHint:st.tapHint})]}):jsxRuntime.jsx("p",{style:o.emptyBody,children:st.empty}),t?jsxRuntime.jsx("button",{type:"button",onClick:()=>t(e),"aria-label":st.askA11y(e.name),style:{...s.pill,...s.pillAsk},"data-testid":`marker-ask-${e.markerId}`,children:st.askNamed(e.name)}):null]})})}i(Eb,"MarkerTrendCard");function tu({markers:e,onPointPress:r,onAsk:t}){let o=Za(),[n,s]=react.useState(0),a=i(l=>{let d=l.currentTarget;d.clientWidth<=0||s(Math.max(0,Math.min(Math.round(d.scrollLeft/d.clientWidth),e.length-1)));},"onScroll"),c=e[n]??null;return jsxRuntime.jsxs("div",{style:o.carousel,"data-testid":"marker-carousel",children:[jsxRuntime.jsx("ul",{style:o.track,onScroll:a,children:e.map(l=>jsxRuntime.jsx(Eb,{marker:l,onPointPress:r,onAsk:t},l.markerId))}),jsxRuntime.jsxs("div",{style:o.footer,"aria-label":Oi.a11y(c?.name??null,n,e.length),children:[jsxRuntime.jsx("div",{style:o.dots,"aria-hidden":"true",children:e.map((l,d)=>jsxRuntime.jsx("span",{style:{...o.dotIndicator,...d===n?o.dotActive:{}}},l.markerId))}),jsxRuntime.jsx("span",{style:o.counter,children:Oi.counter(n,e.length)})]})]})}i(tu,"MarkerTrendCarousel");function nu({marker:e,point:r,onClose:t,onAsk:o}){let n=Za(),{styles:s}=V();if(e===null||r===null)return null;let a=i((c,l)=>jsxRuntime.jsxs("div",{style:n.detailRow,children:[jsxRuntime.jsx("dt",{style:n.detailLabel,children:c}),jsxRuntime.jsx("dd",{style:n.detailValue,children:l})]},c),"row");return jsxRuntime.jsxs(Dt,{label:gr.title,onClose:t,panelStyle:n.sheetBg,testID:"marker-provenance-sheet",children:[jsxRuntime.jsxs("div",{style:s.sheetHeader,children:[jsxRuntime.jsx("h3",{style:s.sheetTitle,children:gr.title}),jsxRuntime.jsx("button",{type:"button",onClick:t,"aria-label":gr.close,style:s.iconButton,"data-testid":"marker-provenance-close",children:jsxRuntime.jsx("span",{style:s.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsxRuntime.jsxs("div",{style:n.valueRow,children:[jsxRuntime.jsx("span",{style:n.markerName,children:e.name}),jsxRuntime.jsx("span",{style:n.latestValue,children:hr(r.value,e.unit,r.qualitativeResult)})]}),r.reviewed?jsxRuntime.jsx("span",{style:n.reviewed,children:gr.reviewed}):null,jsxRuntime.jsxs("dl",{style:n.details,children:[a(gr.collected,ee(r.at)),r.sourceClinic?a(gr.clinic,r.sourceClinic):null,a(gr.referenceRange,r.refLow!==null||r.refHigh!==null?Jo(r,e.unit):gr.noRange),r.docId?a(gr.sourceDocument,r.docId):null]}),r.reviewed?null:jsxRuntime.jsx("p",{style:n.unverified,children:gr.unverified}),o?jsxRuntime.jsx("button",{type:"button",onClick:o,"aria-label":gr.askA11y,style:{...s.pill,...s.pillAsk},"data-testid":"marker-provenance-ask",children:gr.ask}):null]})}i(nu,"MarkerProvenanceDialog");function Za(){let e=ye();return react.useMemo(()=>Sb(e),[e])}i(Za,"useStyles");function Sb(e){let{color:r,space:t,radius:o,type:n}=e,s=i((c,l,d,u="regular")=>({margin:0,...D(e,u),fontSize:c,lineHeight:`${Math.round(c*l)}px`,color:d}),"text"),a=t.md;return {page:{flex:"0 0 100%",scrollSnapAlign:"start",boxSizing:"border-box",padding:`0 ${t.sm}px`,listStyle:"none"},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.md,borderRadius:o.lg,border:`1px solid ${r.borderRingCream}`,backgroundColor:r.surface,padding:t.lg},headerRow:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:t.sm+t.xs/2},nameColumn:{flex:1,display:"flex",flexDirection:"column",gap:t.xs/2,minWidth:0},markerName:{...s(n.size.subtitle,n.lineHeight.snug,r.text.primary,"bold")},unit:{...D(e,"mono"),fontSize:n.size.tiny,lineHeight:`${n.size.body}px`,color:r.text.muted},latestRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:t.md},latestValue:{...s(n.size.verdict+t.xs,n.lineHeight.tight,r.text.primary,"bold")},latestValueDanger:{color:r.danger},latestDate:s(n.size.caption,n.lineHeight.normal,r.text.muted),trajectory:s(n.size.bodyTight,n.lineHeight.normal,r.text.muted),chartWrap:{position:"relative",display:"flex",flexDirection:"column",gap:t.sm},plot:{display:"block",width:"100%",height:140,borderRadius:o.sm,backgroundColor:r.surfaceCream,border:`1px solid ${r.borderHairlineGreen}`},dotLayer:{position:"absolute",left:0,right:0,top:0,height:140},dot:{position:"absolute",boxSizing:"border-box",width:a,height:a,borderRadius:a/2,marginLeft:-a/2,marginTop:-a/2,backgroundColor:r.brand,border:`2px solid ${r.surface}`,padding:0,cursor:"pointer"},dotDanger:{backgroundColor:r.danger},a11yTable:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",margin:0,padding:0,listStyle:"none"},tapHint:{...s(n.size.tiny,n.lineHeight.normal,r.text.placeholder),textAlign:"center"},singleHint:{...s(n.size.caption,n.lineHeight.normal,r.text.muted),textAlign:"center"},emptyBody:{...s(n.size.bodyTight,n.lineHeight.normal,r.text.muted),textAlign:"center",padding:`${t.xxl+t.xs}px 0`},carousel:{display:"flex",flexDirection:"column"},track:{display:"flex",overflowX:"auto",scrollSnapType:"x mandatory",margin:0,padding:0,listStyle:"none"},footer:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.sm,paddingTop:t.md},dots:{display:"flex",gap:t.xs+t.xs/2},dotIndicator:{display:"block",width:t.xs+t.xs/2,height:t.xs+t.xs/2,borderRadius:t.xs-1,backgroundColor:r.borderHairlineGreen},dotActive:{width:t.lg+t.xs/2,backgroundColor:r.brand},counter:{...D(e,"mono"),fontSize:n.size.tiny,lineHeight:`${n.size.body}px`,letterSpacing:n.letterSpacing.eyebrow/3,color:r.text.muted},sheetBg:{backgroundColor:r.surfaceCream},valueRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:t.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,padding:`${t.xs}px ${t.sm+t.xs/2}px`,backgroundColor:r.badgeBgPositive,...s(n.size.tiny,n.lineHeight.normal,r.success,"medium")},details:{margin:0,display:"flex",flexDirection:"column",gap:t.md},detailRow:{display:"flex",flexDirection:"column",gap:t.xs/2},detailLabel:{...s(n.size.caption,n.lineHeight.normal,r.text.muted,"medium")},detailValue:{...s(n.size.body,n.lineHeight.normal,r.text.primary),marginLeft:0},unverified:s(n.size.caption,n.lineHeight.normal,r.text.muted)}}i(Sb,"makeStyles");var _b=i((e,r)=>e.getRecordDepth(r),"readDepth"),Pb=i(e=>!e.available,"depthEmpty");function rs(e){let{style:r,className:t,renderPending:o,...n}=Ie(e,["onNavigate","onBack","onAsk"]),{userRef:s}=se(),{styles:a}=V();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Fe(n.onBack,Me),children:jsxRuntime.jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-dashboard",children:[s===null?jsxRuntime.jsx("div",{style:a.body,children:jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"})}):jsxRuntime.jsx(Tb,{...n}),jsxRuntime.jsx(Ae,{})]})})}i(rs,"EverfurRecordsDashboard");function Tb({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:s,onAsk:a}){let{theme:c,styles:l}=V(),d=react.useMemo(()=>t?{petRef:e,controller:t,readUploadFeatures:true}:{petRef:e,readUploadFeatures:true},[e,t]),u=er(d),p=Ra(e),m=Hr(e,_b,Pb),[y,g]=react.useState(null),f=react.useCallback((w,A)=>g({marker:w,point:A}),[]),v=dt(o,u.consent),b=i(()=>{let w=Zr(o,u.consent);w.length!==0&&u.grantConsent(w,`records-consent-${Date.now().toString(36)}`);},"onGrant"),R=p.markers?.markers??[],h=R.length>0,E=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,S=go(u.requests,e),C=Ai({hasMarkers:h,requests:u.requests,petRef:e}),k=Fi({recordLoading:u.status==="loading",hasFullRecord:E,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:h,requestsLoading:u.status==="loading",dashboardState:C,drivingRequest:S}),M=p.markers?.disclaimer??u.record?.disclaimer??"",T=i(()=>{u.refresh(),p.refresh(),m.refresh();},"retryAll"),O=m.value!==null&&!m.value.withheld&&m.value.available?m.value:null,z=Re(r),q=xt(),N=a&&p.markers?.summary?()=>{let w=Sc(r,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);a(w.prompt,w.entityRef);}:void 0,B=a?w=>{let A=Ec(r,{canonicalName:w.name,markerId:w.markerId,latestValueText:w.latest?hr(w.latest.value,w.unit,w.latest.qualitativeResult):null,statusText:w.latest?nt(w.latest.status).label:null,trajectoryText:nn(w.trajectory,w.points.length),meaningText:w.meaning});a(A.prompt,A.entityRef);}:void 0,x=a&&y?()=>{let{marker:w,point:A}=y,_=xc(r,{canonicalName:w.name,valueText:hr(A.value,w.unit,A.qualitativeResult),collectedAt:ee(A.at),sourceClinic:A.sourceClinic,referenceText:A.refLow!==null||A.refHigh!==null?Jo(A,w.unit):null,flagged:A.status==="above"?"above":A.status==="below"?"below":null,reviewed:A.reviewed,entityId:A.docId??w.markerId});g(null),a(_.prompt,_.entityRef);}:void 0,L=i((w,A,_)=>jsxRuntime.jsxs("button",{type:"button",onClick:A,"aria-label":w,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",borderRadius:c.radius.lg,border:`1px solid ${c.color.borderRingCream}`,backgroundColor:c.color.surface,padding:c.space.lg,cursor:"pointer",font:"inherit",color:c.color.text.primary,textAlign:"left"},"data-testid":_,children:[jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:c.space.md},children:[jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:18,height:18,borderRadius:c.radius.xs,backgroundColor:c.color.brandSoft,border:`1px solid ${c.color.brandBorder}`}}),jsxRuntime.jsx("span",{style:{...l.rowTitle},children:w})]}),jsxRuntime.jsx(kt,{})]}),"actionRow"),F=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[p.markers?.summary?jsxRuntime.jsx("div",{style:l.inset,children:jsxRuntime.jsx(Jc,{summary:p.markers.summary,onAsk:N,testID:"dashboard-marker-summary"})}):null,jsxRuntime.jsx("p",{style:l.lead,children:yr.lead(r)}),jsxRuntime.jsx(tu,{markers:R,onPointPress:f,onAsk:B})]}),W=i(w=>n?jsxRuntime.jsxs("div",{style:{...l.inset,display:"flex",flexDirection:"column",gap:c.space.sm+c.space.xs/2},children:[w?L(yr.viewFullRecord,()=>n({name:"record"}),"dashboard-full-record-action"):null,L(yr.viewTimeline,()=>n({name:"timeline"}),"dashboard-timeline-action")]}):null,"actions"),I;if(u.status==="error"){let w=et(u,v);I=w.kind==="error"||w.kind==="pet_not_found"?jsxRuntime.jsx(He,{variant:nr(w.error),message:w.error.displayMessage,onAction:w.error.retryable?T:void 0,testID:"dashboard-error"}):Tt(u,b,v);}else switch(k){case "loading":I=jsxRuntime.jsx(sn,{testID:"dashboard-loading"});break;case "record":I=jsxRuntime.jsxs("div",{ref:q,style:l.contentTight,"data-testid":"dashboard-record",children:[h?F:p.status==="error"?jsxRuntime.jsx("div",{style:l.inset,children:L(yr.retryMarkers,T,"dashboard-markers-retry")}):null,jsxRuntime.jsx("div",{style:l.inset,children:u.record?jsxRuntime.jsx(ri,{record:u.record,depth:O,petName:r,showLabs:!h,onNavigate:n,onAsk:a}):null}),W(true)]});break;case "error":{let w=p.error??u.error;I=jsxRuntime.jsx(He,{variant:nr(w),message:w?.displayMessage,onAction:w?.retryable?T:void 0,testID:"dashboard-error"});break}case "in_progress":I=jsxRuntime.jsxs("div",{ref:q,style:l.content,"data-testid":"dashboard-in-progress",children:[S?jsxRuntime.jsx(Db,{request:S,petName:z,onOpen:n?()=>n({name:"request",requestId:S.id}):void 0,onAsk:a?()=>{let w=wc(r,{clinicName:S.clinicName??null,statusLabel:On(S),status:S.status,heldItemCount:S.heldItemCount},S.id);a(w.prompt,w.entityRef);}:void 0}):null,n?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:c.space.sm},"data-testid":"dashboard-ways",children:[jsxRuntime.jsx(ou,{title:lt.anotherClinic,sub:lt.anotherClinicSub,onClick:()=>n({name:"clinicPicker"}),testID:"dashboard-way-clinic"}),jsxRuntime.jsx(ou,{title:Jr.uploadDocument,...xn(u.uploadContentTypes)?{sub:lt.uploadDocumentPhotoSub}:{},ariaLabel:Jr.uploadDocumentA11y(r),dashed:true,onClick:()=>n({name:"upload"}),testID:"dashboard-way-upload"})]}):null,jsxRuntime.jsx(wt,{disclaimer:M})]});break;case "none":I=jsxRuntime.jsxs("div",{ref:q,style:l.content,"data-testid":"dashboard-request-prompt",children:[jsxRuntime.jsxs("section",{style:{...l.creamCard,gap:c.space.md},children:[jsxRuntime.jsx("h3",{style:{...l.sectionTitle,color:c.color.brandInk},children:Jr.firstRecordTitle(r)}),jsxRuntime.jsx("p",{style:l.bodyText,children:Jr.body}),n?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("p",{style:l.muted,children:Jr.requestFromClinicSub}),jsxRuntime.jsx(j,{label:Jr.requestFromClinic,ariaLabel:Jr.requestFromClinicA11y(r),onClick:()=>n({name:"clinicPicker"}),testID:"dashboard-request-prompt-clinic"}),jsxRuntime.jsx(j,{label:Jr.uploadDocument,kind:"outline",ariaLabel:Jr.uploadDocumentA11y(r),onClick:()=>n({name:"upload"}),testID:"dashboard-request-prompt-upload"})]}):null]}),jsxRuntime.jsx(wt,{disclaimer:M})]});break;case "labs_only":I=jsxRuntime.jsxs("div",{ref:q,style:l.contentTight,"data-testid":"dashboard-labs-only",children:[F,jsxRuntime.jsx("div",{style:l.inset,children:jsxRuntime.jsx(wt,{disclaimer:M})}),W(false)]});break;default:I=Nr(k);}return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ke,{title:yr.titleWeb(r),onBack:s,testID:"dashboard-header",right:n?jsxRuntime.jsx("button",{type:"button",onClick:()=>n({name:"timeline"}),"aria-label":yr.openTimeline,style:l.iconButton,"data-testid":"dashboard-timeline-link",children:jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:4},children:[0,1,2].map(w=>jsxRuntime.jsx("span",{style:{display:"block",width:18,height:2,borderRadius:2,backgroundColor:c.color.brand}},w))})}):void 0}),jsxRuntime.jsx("div",{style:l.body,children:I}),jsxRuntime.jsx(nu,{marker:y?.marker??null,point:y?.point??null,onClose:()=>g(null),onAsk:x})]})}i(Tb,"DashboardBody");function Db({request:e,petName:r,onOpen:t,onAsk:o}){let{theme:n,styles:s}=V(),a=lt.title(r),c=e.clinicName?.trim()??"",l=On(e),d=jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:n.space.lg},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.space.sm},children:[jsxRuntime.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:n.space.xs/2,minWidth:0},children:[jsxRuntime.jsx("span",{style:{...s.sectionTitle,color:n.color.brandInk},children:a}),c.length>0?jsxRuntime.jsx("span",{style:s.rowDetail,children:c}):null]}),t?jsxRuntime.jsx(kt,{}):null]}),jsxRuntime.jsx(fn,{request:e,petName:r}),l.length>0?jsxRuntime.jsx("p",{style:s.statusCard,children:l}):null]});return jsxRuntime.jsxs("section",{"aria-label":t?void 0:lt.a11y(r),style:{...s.creamCard,backgroundColor:n.color.surface,padding:n.space.lg+n.space.xs/2,gap:n.space.lg},"data-testid":"dashboard-in-progress-card",children:[t?jsxRuntime.jsx("button",{type:"button",onClick:t,"aria-label":lt.openA11y(r,l),style:{background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit",width:"100%"},"data-testid":"dashboard-in-progress-open",children:d}):d,o?jsxRuntime.jsx(j,{label:lt.ask,kind:"ask",ariaLabel:lt.askA11y,onClick:o,testID:"dashboard-in-progress-ask"}):null]})}i(Db,"InProgressCard");function ou({title:e,sub:r,ariaLabel:t,dashed:o=false,onClick:n,testID:s}){let{theme:a,styles:c}=V();return jsxRuntime.jsxs("button",{type:"button",onClick:n,"aria-label":t,style:{...c.creamCard,width:"100%",textAlign:"left",cursor:"pointer",font:"inherit",color:"inherit",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:a.space.md,...o?{borderStyle:"dashed",borderColor:a.color.brandBorderStrong}:{}},"data-testid":s,children:[jsxRuntime.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:a.space.xs/2},children:[jsxRuntime.jsx("span",{style:{...c.rowTitle,...D(a,"bold")},children:e}),r?jsxRuntime.jsx("span",{style:c.muted,children:r}):null]}),jsxRuntime.jsx(kt,{})]})}i(ou,"WayCard");function ts(e){let{style:r,className:t,renderPending:o,...n}=Ie(e,["onNavigate","onBack"]),{userRef:s}=se(),{styles:a}=V();return jsxRuntime.jsx(Oe,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Fe(n.onBack,Me),children:jsxRuntime.jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-requests-screen",children:[s===null?jsxRuntime.jsx("div",{style:a.body,children:jsxRuntime.jsx(or,{label:X.sessionRequired,glyph:"empty"})}):jsxRuntime.jsx(Ab,{...n}),jsxRuntime.jsx(Ae,{})]})})}i(ts,"EverfurRecordsRequests");function Ab({petRef:e,petName:r,controller:t,onNavigate:o,onBack:n,onOpenUrl:s}){let{theme:a,styles:c}=V(),l=er(t?{petRef:e,controller:t}:{petRef:e}),d=react.useMemo(()=>$i(l.requests.filter(y=>y.petRef===e)),[l.requests,e]),u=Ot("recordsClinic"),p=`${react.useId()}-requests-heading`,m;return l.status==="loading"&&d.length===0?m=jsxRuntime.jsx(Oo,{testID:"records-requests-loading"}):l.status==="error"&&l.error&&d.length===0?m=jsxRuntime.jsx(He,{variant:nr(l.error),message:l.error.displayMessage,onAction:l.error.retryable?l.refresh:void 0,testID:"records-requests-error"}):m=jsxRuntime.jsx(ii,{requests:d,petName:r,level:3,headingId:p,onOpenRequest:o?y=>o({name:"request",requestId:y.id}):void 0,onUpload:o?()=>o({name:"upload"}):void 0,...s?{onOpenUrl:s}:{}}),jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ke,{title:_e.title,onBack:n,testID:"records-requests-header"}),jsxRuntime.jsx("div",{style:c.body,children:jsxRuntime.jsxs("div",{style:{...c.content,gap:a.space.lg},children:[o?jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},"data-testid":"records-requests-actions",children:[u.enabled||u.isPending?jsxRuntime.jsx(j,{label:_e.requestRecords,onClick:()=>o({name:"clinicPicker"}),testID:"records-requests-request-records"}):null,jsxRuntime.jsx(j,{label:_e.uploadAction,kind:"outline",onClick:()=>o({name:"upload"}),testID:"records-requests-upload"})]}):null,m]})})]})}i(Ab,"RequestsBody");function au(e){let{petRef:r,petName:t,controller:o,clinicController:n,consentVersion:s,ownerName:a,onCaptureSignature:c,initialScreen:l,historyMode:d="memory",onExit:u,style:p,className:m,renderPending:y,onOpenUrl:g,onCopy:f,onAsk:v,location:b}=Ie(e,["onExit"]),[R,h]=react.useReducer(In,l,Zt),E=bo(R),S=R.stack.length,C=react.useRef(S);C.current=S;let k=react.useRef(S),M=react.useRef(false);react.useEffect(()=>{if(d!=="browser"||typeof window>"u")return;let F=i(W=>{let I=W.state;(typeof I?.efRecords=="number"?I.efRecords:1)<C.current&&(M.current=true,h({type:"pop"}));},"onPopState");return window.addEventListener("popstate",F),()=>window.removeEventListener("popstate",F)},[d]),react.useEffect(()=>{if(d!=="browser"||typeof window>"u")return;let F=k.current;S>F?window.history.pushState({efRecords:S},""):S<F&&!M.current&&window.history.go(S-F),M.current=false,k.current=S;},[d,S]);let T=react.useCallback(F=>h({type:"navigate",screen:F}),[]),O=react.useMemo(()=>ho(R).handled?()=>h({type:"pop"}):u,[R,u]),z=rn(E),q={onNavigate:T,...O?{onBack:O}:{},...t!==void 0?{petName:t}:{},...g?{onOpenUrl:g}:{},...f?{onCopy:f}:{},...v?{onAsk:v}:{},...b?{location:b}:{}},N={...o?{controller:o}:{},...s!==void 0?{consentVersion:s}:{}},B={...p?{style:p}:{},...m!==void 0?{className:m}:{}},x=y?{renderPending:y}:{},L;switch(E.name){case "dashboard":L=jsxRuntime.jsx(rs,{petRef:r,...q,...N,...x,...B});break;case "request":L=jsxRuntime.jsx(eo,{petRef:r,requestId:E.requestId,...q,...o?{controller:o}:{},...x,...B});break;case "timeline":L=jsxRuntime.jsx($o,{petRef:r,...q,...B});break;case "record":L=jsxRuntime.jsx(Xn,{petRef:r,...q,...N,...x,...B});break;case "document":L=jsxRuntime.jsx(Qn,{petRef:r,...q,...N,...x,...B});break;case "contributions":L=jsxRuntime.jsx(Uo,{petRef:r,docId:E.docId,...q,...B});break;case "clinicPicker":L=jsxRuntime.jsx(Ln,{petRef:r,...q,...n?{controller:n}:{},...o?{recordsController:o}:{},...B});break;case "clinicBatch":L=jsxRuntime.jsx($n,{petRef:r,petName:t??"",ownerName:a??"",...O?{onClose:O}:{},onCreated:()=>h({type:"navigate",screen:{name:"dashboard"}}),...c?{onCaptureSignature:c}:{},...n?{controller:n}:{},...B});break;case "consent":L=jsxRuntime.jsx(Hn,{petRef:r,clinic:E.clinic,...q,...a!==void 0?{ownerName:a}:{},...c?{onCaptureSignature:c}:{},...n?{controller:n}:{},...B});break;case "upload":L=jsxRuntime.jsx(Zn,{petRef:r,...q,...o?{controller:o}:{},...x,...B});break;case "requests":L=jsxRuntime.jsx(ts,{petRef:r,...q,...o?{controller:o}:{},...x,...B});break;default:L=Nr(E);}return jsxRuntime.jsx("div",{ref:z,style:zb,"data-testid":"everfur-records-flow",children:L})}i(au,"EverfurRecordsFlow");var zb=Object.freeze({display:"contents"}),Mb=au;function $b(e){let{userRef:r,scopeEpoch:t}=se();return jsxRuntime.jsx(Oe,{capability:"recordsClinic",...Fe(e.onClose,te.cancel),children:r===null?jsxRuntime.jsx("p",{role:"alert",children:X.sessionRequired}):jsxRuntime.jsx(Ub,{...Ie(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i($b,"EverfurClinicRequest");function Ub(e){let r=zr(),t=e.controller??r,o=ye(),n={current:null},s=Mt(()=>n.current?.invalidate()),a=gd(e,t,e.onCaptureSignature??(async u=>s.signed?s.register(t,u.signal):null));n.current=a;let c={minHeight:44,padding:o.space.sm,border:`1px solid ${o.color.borderHairlineGreen}`,borderRadius:o.radius.sm,background:o.color.surface,color:o.color.text.primary,font:"inherit"},l={...c,cursor:"pointer"},d=i(()=>{a.busy||s.clear();},"clear");return jsxRuntime.jsxs("section",{className:e.className,"aria-label":te.title,style:{background:o.color.surface,color:o.color.text.primary,padding:o.space.lg,borderRadius:o.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...e.style},children:[jsxRuntime.jsx("h2",{style:{margin:0,fontSize:o.type.size.heading},children:te.title}),jsxRuntime.jsx("p",{style:{margin:`${o.space.sm}px 0 ${o.space.lg}px`},children:e.petName}),a.created?jsxRuntime.jsx("p",{role:"status",children:a.created.statusLabel||X.records}):jsxRuntime.jsxs("div",{style:{display:"grid",gap:o.space.md},children:[jsxRuntime.jsxs("label",{children:[te.ownerName,jsxRuntime.jsx("input",{style:{...c,display:"block",width:"100%",boxSizing:"border-box"},maxLength:200,value:a.ownerName,disabled:a.busy,autoComplete:"name",onChange:u=>{d(),a.setOwnerName(u.target.value);}})]}),jsxRuntime.jsxs("label",{children:[te.clinic,jsxRuntime.jsx("input",{style:{...c,display:"block",width:"100%",boxSizing:"border-box"},placeholder:te.placeholder,maxLength:200,value:a.query,disabled:a.busy,autoComplete:"off",onChange:u=>{d(),a.setQuery(u.target.value);}})]}),jsxRuntime.jsx("button",{type:"button",style:l,disabled:a.busy||a.searching||a.query.trim().length<2,onClick:()=>{a.search();},children:te.search}),a.searching&&jsxRuntime.jsx("p",{role:"status",children:X.loading}),a.recent.length>0&&jsxRuntime.jsx("h3",{style:{margin:`${o.space.sm}px 0 0`,fontSize:o.type.size.subtitle},"data-testid":"records-clinic-recent-label",children:te.recentlyUsed}),a.recent.map(u=>jsxRuntime.jsxs("button",{type:"button",style:l,disabled:a.busy,onClick:()=>{d(),a.selectClinic(u);},children:[u.name,u.address?`, ${u.address}`:"",u.phone?`, ${u.phone}`:""]},`recent-${u.id}`)),a.visibleClinics.map(u=>jsxRuntime.jsxs("button",{type:"button",style:l,disabled:a.busy,onClick:()=>{d(),a.selectClinic(u);},children:[u.name,u.address?`, ${u.address}`:"",u.phone?`, ${u.phone}`:""]},u.id)),a.hasMoreClinics&&jsxRuntime.jsx("button",{type:"button",style:l,disabled:a.busy,onClick:a.showMoreClinics,"data-testid":"records-clinic-results-more",children:te.moreClinics}),a.needsEmail&&jsxRuntime.jsxs("label",{children:[te.email,jsxRuntime.jsx("input",{style:{...c,display:"block",width:"100%",boxSizing:"border-box"},type:"email",placeholder:te.emailPlaceholder,maxLength:320,autoComplete:"off",value:a.email,disabled:a.busy,onChange:u=>{d(),a.setEmail(u.target.value);}})]}),jsxRuntime.jsx("h3",{style:{margin:`${o.space.sm}px 0 0`,fontSize:o.type.size.subtitle},children:te.scopeHeading}),a.copy?jsxRuntime.jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:a.query.trim()&&a.ownerName.trim()?a.scope??H("internalError").displayMessage:X.consentRequired}):!a.error&&jsxRuntime.jsx("p",{role:"status",children:X.loading}),!e.onCaptureSignature&&jsxRuntime.jsx($t,{pad:s,disabled:a.busy}),a.error&&jsxRuntime.jsx("p",{role:"alert",children:a.error.displayMessage}),!a.copy&&a.error&&jsxRuntime.jsx("button",{type:"button",style:l,onClick:a.retryCopy,children:X.retry}),jsxRuntime.jsx("button",{type:"button",style:{...l,background:o.color.primary,color:o.color.onPrimary,opacity:a.busy||!a.ready||!e.onCaptureSignature&&!s.signed?.5:1},disabled:a.busy||!a.ready||!e.onCaptureSignature&&!s.signed,onClick:()=>{a.submit();},children:a.busy?te.sending:te.send})]}),e.onClose&&jsxRuntime.jsx("button",{type:"button",style:l,disabled:a.busy,onClick:e.onClose,children:te.cancel}),jsxRuntime.jsx(Ae,{})]})}i(Ub,"ClinicRequestBody");var Bb="file",Hb="records upload: the file handle carries no bytes",su="records upload failed";function jb(e={}){let r=e.xhr??(()=>new XMLHttpRequest);return Object.freeze({postMultipart(t,o,n){return new Promise((s,a)=>{let c=o.blob;if(c===void 0){a(new Error(Hb));return}let{signal:l,onProgress:d}=n;if(l?.aborted===true){a(new Error(su));return}let u=new FormData;for(let[f,v]of Object.entries(t.upload_fields))u.append(f,v);u.append(Bb,c,Cs(o.mimeType));let p=r(),m=false,y=i(f=>{m||(m=true,l?.removeEventListener("abort",g),f?s():a(new Error(su)));},"settle"),g=i(()=>{p.abort(),y(false);},"onAbort");p.open("POST",t.upload_url,true),p.withCredentials=false,d&&(p.upload.onprogress=f=>{!f.lengthComputable||f.total<=0||d(Math.min(1,Math.max(0,f.loaded/f.total)));}),p.onload=()=>y(p.status>=200&&p.status<300),p.onerror=()=>y(false),p.onabort=()=>y(false),p.ontimeout=()=>y(false),l?.addEventListener("abort",g,{once:true}),p.send(u);})}})}i(jb,"createWebRecordsUploadTransport");
|
|
4
|
-
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";var react=require("react"),zod=require("zod"),jsxRuntime=require("react/jsx-runtime");var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
3
|
+
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
4
|
+
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
5
|
+
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
6
|
+
/* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
7
|
+
/* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
8
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
9
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
10
|
+
/* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
11
|
+
/* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
|
|
12
|
+
/* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
|
|
13
|
+
/* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
|
|
14
|
+
/* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
15
|
+
/* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
16
|
+
/* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
17
|
+
/* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
18
|
+
/* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
19
|
+
/* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
20
|
+
/* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
21
|
+
/* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
22
|
+
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
23
|
+
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
24
|
+
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
25
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
26
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
27
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
28
|
+
/* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
29
|
+
/* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
30
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
31
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
32
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
33
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
34
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
35
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
36
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
37
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
38
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
39
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
40
|
+
/* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
41
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
42
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
|
|
43
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
44
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
45
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
46
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
47
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
48
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
49
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
50
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
51
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
52
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
53
|
+
/* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
54
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
55
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
56
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
57
|
+
/* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
|
|
58
|
+
/* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
59
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
60
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
61
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
62
|
+
/* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
63
|
+
/* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
64
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
65
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
66
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
67
|
+
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
68
|
+
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
69
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
70
|
+
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
72
|
+
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
73
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
74
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
75
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
76
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
77
|
+
/* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
78
|
+
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
79
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
80
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
81
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
82
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
84
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
85
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
86
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
87
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
88
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
89
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
90
|
+
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
91
|
+
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var RECORD_SHARE_AUDIENCES=/* @__PURE__ */Object.freeze(["vet","groomer","boarding"]),https=/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),str=/* @__PURE__ */zod.z.string().nullish(),audienceField=/* @__PURE__ */zod.z.unknown().optional(),linkSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),share_url:/* @__PURE__ */zod.z.string().min(1),expires_at:str,audience:audienceField}),listSchema=/* @__PURE__ */zod.z.object({shares:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str,created_at:str,view_count:/* @__PURE__ */zod.z.number().int().nonnegative().nullish(),last_viewed_at:str,audience:audienceField})).optional()}),pdfSchema=/* @__PURE__ */zod.z.object({download_url:https,expires_at:str}),emailSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str,audience:audienceField}),scopeSchema=/* @__PURE__ */zod.z.object({audience:/* @__PURE__ */zod.z.string().min(1),sections:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()),entity_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullable()}),SHARE_RECIPIENT_EMAIL_MAX=254;function isShareRecipientEmail(value){let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=SHARE_RECIPIENT_EMAIL_MAX&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)}var isAudience=value=>typeof value=="string"&&RECORD_SHARE_AUDIENCES.includes(value);function audienceOf(value){return isAudience(value)?value:null}function mapShareAudiences(wire){let parsed=zod.z.array(scopeSchema).safeParse(wire);if(!parsed.success)/* @__PURE__ */return Object.freeze([]);let seen=/* @__PURE__ */new Set,scopes=[];for(let scope of parsed.data)!isAudience(scope.audience)||seen.has(scope.audience)||(seen.add(scope.audience),scopes.push(/* @__PURE__ */Object.freeze({audience:scope.audience,sections:/* @__PURE__ */Object.freeze([...scope.sections]),entityTypes:scope.entity_types===null?null:/* @__PURE__ */Object.freeze([...scope.entity_types])}))/* @__PURE__ */);return Object.freeze(scopes)}function resolveShareUrl(shareUrl,apiBaseUrl){let trimmed=shareUrl.trim();if(trimmed.length===0)return null;try{let absolute=/^[a-z][a-z0-9+.-]*:/i.test(trimmed)?new URL(trimmed):apiBaseUrl!==void 0?new URL(trimmed,apiBaseUrl):null;return absolute===null||absolute.protocol!=="https:"?null:absolute.toString()}catch{return null}}function mapRecordShareLink(wire,apiBaseUrl){let parsed=linkSchema.safeParse(wire);if(!parsed.success)return null;let shareUrl=resolveShareUrl(parsed.data.share_url,apiBaseUrl);return shareUrl===null?null:/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,shareUrl:shareUrl,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)})}function mapRecordShareList(wire){let parsed=listSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.shares??[]).map(share=>/* @__PURE__ */Object.freeze({shareId:share.share_id,expiresAt:share.expires_at??null,createdAt:share.created_at??null,viewCount:share.view_count??0,lastViewedAt:share.last_viewed_at??null,audience:audienceOf(share.audience)}))):null}function mapRecordShareEmailReceipt(wire){let parsed=emailSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)}):null}function mapRecordPdfLink(wire){let parsed=pdfSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({downloadUrl:parsed.data.download_url,expiresAt:parsed.data.expires_at??null}):null}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var FILENAMES=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function recordsUploadFilename(type){return isAcceptedUploadType(type,RECORDS_PHOTO_CONTENT_TYPES)?FILENAMES[type]:FILENAMES["application/pdf"]}var RECORDS_FEATURES_PDF_ONLY=/* @__PURE__ */Object.freeze({features:/* @__PURE__ */Object.freeze({}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE]),shareAudiences:/* @__PURE__ */Object.freeze([])}),featuresSchema=/* @__PURE__ */zod.z.object({features:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.boolean()),upload_content_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullish(),share_audiences:/* @__PURE__ */zod.z.unknown().optional()});function mapRecordsFeatures(wire){let parsed=featuresSchema.safeParse(wire);if(!parsed.success)return RECORDS_FEATURES_PDF_ONLY;let listed=parsed.data.upload_content_types??[],photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>listed.includes(type));/* @__PURE__ */
|
|
92
|
+
return Object.freeze({features:/* @__PURE__ */Object.freeze({...parsed.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE,...photos]),shareAudiences:mapShareAudiences(parsed.data.share_audiences)})}function acceptsPhotos(types){return types!==void 0&&types.some(isPhotoType)}var KNOWN_STATUSES=/* @__PURE__ */new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),STATUS_ALIASES=/* @__PURE__ */Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function normalizeStatus(raw){let aliased=Object.prototype.hasOwnProperty.call(STATUS_ALIASES,raw)?STATUS_ALIASES[raw]:void 0;if(aliased!==void 0)return aliased;let value=raw;return KNOWN_STATUSES.has(value)?value:"parsing"}function normalizeOrigin(raw){return raw==="owner_reported"||raw==="clinic_document"?raw:null}var requestSchema=/* @__PURE__ */zod.z.object({request_id:/* @__PURE__ */zod.z.string().min(1),pet_ref:/* @__PURE__ */zod.z.string().min(1),status:/* @__PURE__ */zod.z.string(),simple_status:/* @__PURE__ */zod.z.string().nullish(),simple_status_detail:/* @__PURE__ */zod.z.string().nullish(),status_label:/* @__PURE__ */zod.z.string().optional(),dispatch_status:/* @__PURE__ */zod.z.string().nullish(),can_retry_send:/* @__PURE__ */zod.z.boolean().optional(),can_revoke:/* @__PURE__ */zod.z.boolean().optional(),can_convert_to_upload:/* @__PURE__ */zod.z.boolean().optional(),can_update_clinic_email:/* @__PURE__ */zod.z.boolean().optional(),reminder_count:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),last_reminder_at:/* @__PURE__ */zod.z.string().nullish(),waiting_expectation:/* @__PURE__ */zod.z.string().nullish(),document_count:/* @__PURE__ */zod.z.number().optional(),held_item_count:/* @__PURE__ */zod.z.number().optional(),received_at:/* @__PURE__ */zod.z.string().nullish(),parsing_started_at:/* @__PURE__ */zod.z.string().nullish(),review_started_at:/* @__PURE__ */zod.z.string().nullish(),created_at:/* @__PURE__ */zod.z.string().optional(),updated_at:/* @__PURE__ */zod.z.string().optional(),source:/* @__PURE__ */zod.z.string().nullish().catch(null),action_needed_label:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_reason:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_code:/* @__PURE__ */zod.z.string().nullish().catch(null),recovery_stage:/* @__PURE__ */zod.z.string().nullish().catch(null),show_clinic_phone:/* @__PURE__ */zod.z.boolean().optional().catch(void 0),clinic_name:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_email:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_phone:/* @__PURE__ */zod.z.string().nullish().catch(null),converted_to_upload_at:/* @__PURE__ */zod.z.string().nullish().catch(null),request_group_id:/* @__PURE__ */zod.z.string().nullish().catch(null)}).passthrough();function mapRequestView(wire){let parsed=requestSchema.safeParse(wire);if(!parsed.success)return null;let w=parsed.data,simpleStatus=normalizeSimpleStatus(w.simple_status),status=simpleStatus==="requested"&&(w.status==="awaiting_upload"||w.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":simpleStatus==="parsing"&&(w.simple_status_detail==="in_review"||w.simple_status_detail==="review_email_failed")?"in_review":simpleStatus??normalizeStatus(w.status);/* @__PURE__ */
|
|
93
|
+
return Object.freeze({id:w.request_id,petRef:w.pet_ref,status:status,simpleStatus:simpleStatus,simpleStatusDetail:w.simple_status_detail??null,statusLabel:w.status_label??"",dispatchStatus:w.dispatch_status??null,canRetrySend:w.can_retry_send===true,canRevoke:w.can_revoke===true,canConvertToUpload:w.can_convert_to_upload===true,canUpdateClinicEmail:w.can_update_clinic_email===true,reminderCount:w.reminder_count??0,lastReminderAt:w.last_reminder_at??null,waitingExpectation:w.waiting_expectation??null,documentCount:numberOr(w.document_count,0),heldItemCount:numberOr(w.held_item_count,0),receivedAt:w.received_at??null,parsingStartedAt:w.parsing_started_at??null,reviewStartedAt:w.review_started_at??null,createdAt:w.created_at??"",updatedAt:w.updated_at??"",wireStatus:w.status,source:w.source??null,actionNeededLabel:w.action_needed_label??null,failureReason:w.failure_reason??null,failureCode:w.failure_code??null,recoveryStage:w.recovery_stage??null,showClinicPhone:w.show_clinic_phone===true,clinicName:w.clinic_name??null,clinicEmail:w.clinic_email??null,clinicPhone:w.clinic_phone??null,convertedToUploadAt:w.converted_to_upload_at??null,requestGroupId:w.request_group_id??null})}var groupSchema=/* @__PURE__ */zod.z.object({request_group_id:/* @__PURE__ */zod.z.string().min(1),pet_ref:/* @__PURE__ */zod.z.string().min(1),total:/* @__PURE__ */zod.z.number().int().nonnegative(),responded:/* @__PURE__ */zod.z.number().int().nonnegative(),pending:/* @__PURE__ */zod.z.number().int().nonnegative(),members:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.unknown())});function mapRequestGroup(wire){let parsed=groupSchema.safeParse(wire);if(!parsed.success)return null;let g=parsed.data,members=mapRequestList(g.members);return members.some(member=>member.petRef!==g.pet_ref)?null:/* @__PURE__ */Object.freeze({requestGroupId:g.request_group_id,petRef:g.pet_ref,total:g.total,responded:g.responded,pending:g.pending,members:members})}function normalizeSimpleStatus(raw){return!raw||raw==="awaiting_upload"||raw==="in_review"?null:KNOWN_STATUSES.has(raw)?raw:null}function mapRequestList(wire){let list=Array.isArray(wire)?wire:[],out=[];for(let entry of list){let view=mapRequestView(entry);view!==null&&out.push(view)}/* @__PURE__ */
|
|
94
|
+
return Object.freeze(out)}var acceptedSchema=/* @__PURE__ */zod.z.object({source_doc_id:/* @__PURE__ */zod.z.string().min(1),request_id:/* @__PURE__ */zod.z.string().min(1)});function mapUploadedDocument(wire){let parsed=acceptedSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({documentId:parsed.data.source_doc_id,requestId:parsed.data.request_id,status:"received"}):null}var identitySchema=/* @__PURE__ */zod.z.object({label:/* @__PURE__ */zod.z.string(),value:/* @__PURE__ */zod.z.string()}),entitySchema=/* @__PURE__ */zod.z.object({key:/* @__PURE__ */zod.z.string(),category:/* @__PURE__ */zod.z.string().optional(),label:/* @__PURE__ */zod.z.string().optional(),value:/* @__PURE__ */zod.z.string().nullish(),unit:/* @__PURE__ */zod.z.string().nullish(),observed_at:/* @__PURE__ */zod.z.string().nullish(),status:/* @__PURE__ */zod.z.string().nullish(),origin:/* @__PURE__ */zod.z.string().nullish(),canonical_key:/* @__PURE__ */zod.z.string().nullish()}),seriesPointSchema=/* @__PURE__ */zod.z.object({at:/* @__PURE__ */zod.z.string(),value:/* @__PURE__ */zod.z.number().nullish(),display:/* @__PURE__ */zod.z.string().nullish(),origin:/* @__PURE__ */zod.z.string().nullish()}),seriesSchema=/* @__PURE__ */zod.z.object({key:/* @__PURE__ */zod.z.string(),label:/* @__PURE__ */zod.z.string().optional(),points:/* @__PURE__ */zod.z.array(seriesPointSchema).optional()}),forwardSchema=/* @__PURE__ */zod.z.object({title:/* @__PURE__ */zod.z.string(),detail:/* @__PURE__ */zod.z.string().nullish(),due_at:/* @__PURE__ */zod.z.string().nullish()}),documentSchema=/* @__PURE__ */zod.z.object({doc_id:/* @__PURE__ */zod.z.string(),title:/* @__PURE__ */zod.z.string().nullish(),page_count:/* @__PURE__ */zod.z.number().nullish(),received_at:/* @__PURE__ */zod.z.string().nullish()});function mapEntityRow(e){/* @__PURE__ */
|
|
95
|
+
return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:normalizeOrigin(e.origin),canonicalKey:e.canonical_key??null})}function mapDocumentRow(d){/* @__PURE__ */
|
|
96
|
+
return Object.freeze({docId:d.doc_id,title:d.title??null,pageCount:d.page_count??null,receivedAt:d.received_at??null})}var contentSchema=/* @__PURE__ */zod.z.object({identity:/* @__PURE__ */zod.z.array(identitySchema).optional(),entities:/* @__PURE__ */zod.z.array(entitySchema).optional(),entity_series:/* @__PURE__ */zod.z.array(seriesSchema).optional(),forward_looking:/* @__PURE__ */zod.z.array(forwardSchema).optional(),documents:/* @__PURE__ */zod.z.array(documentSchema).optional()});function mapRecordView(petRef,wire){let w=isObject(wire)?wire:{},schemaVersion=strOr(w.schema_version,"epdf/1.0"),disclaimer=strOr(w.disclaimer,""),pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldView(pet,schemaVersion,disclaimer);let content=contentSchema.safeParse(w);if(!content.success)return withheldView(pet,schemaVersion,disclaimer);let c=content.data,identity=(c.identity??[]).map(i=>/* @__PURE__ */Object.freeze({label:i.label,value:i.value})),entities=(c.entities??[]).map(mapEntityRow),entitySeries=(c.entity_series??[]).map(s=>/* @__PURE__ */Object.freeze({key:s.key,label:s.label??s.key,points:/* @__PURE__ */Object.freeze((s.points??[]).map(p=>/* @__PURE__ */Object.freeze({at:p.at,value:p.value??null,display:p.display??null,origin:normalizeOrigin(p.origin)})))})),forwardLooking=(c.forward_looking??[]).map(f=>/* @__PURE__ */Object.freeze({title:f.title,detail:f.detail??null,dueAt:f.due_at??null})),documents={};for(let d of c.documents??[])documents[d.doc_id]=mapDocumentRow(d);let isEmpty=w.is_empty===true||identity.length===0&&entities.length===0&&entitySeries.length===0&&forwardLooking.length===0&&Object.keys(documents).length===0;/* @__PURE__ */
|
|
97
|
+
return Object.freeze({petRef:pet,schemaVersion:schemaVersion,isEmpty:isEmpty,withheld:false,generatedAt:strOrNull(w.generated_at),identity:/* @__PURE__ */Object.freeze(identity),entities:/* @__PURE__ */Object.freeze(entities),entitySeries:/* @__PURE__ */Object.freeze(entitySeries),forwardLooking:/* @__PURE__ */Object.freeze(forwardLooking),documents:/* @__PURE__ */Object.freeze(documents),disclaimer:disclaimer})}function withheldView(petRef,schemaVersion,disclaimer){/* @__PURE__ */
|
|
98
|
+
return Object.freeze({petRef:petRef,schemaVersion:schemaVersion,isEmpty:false,withheld:true,generatedAt:null,identity:/* @__PURE__ */Object.freeze([]),entities:/* @__PURE__ */Object.freeze([]),entitySeries:/* @__PURE__ */Object.freeze([]),forwardLooking:/* @__PURE__ */Object.freeze([]),documents:/* @__PURE__ */Object.freeze({}),disclaimer:disclaimer})}var consentSchema=/* @__PURE__ */zod.z.object({pet_ref:/* @__PURE__ */zod.z.string().optional(),granted:/* @__PURE__ */zod.z.boolean().optional(),version:/* @__PURE__ */zod.z.string().nullish(),granted_at:/* @__PURE__ */zod.z.string().nullish()});function mapConsent(petRef,wire){let parsed=consentSchema.safeParse(wire),data=parsed.success?parsed.data:{};/* @__PURE__ */
|
|
99
|
+
return Object.freeze({petRef:typeof data.pet_ref=="string"&&data.pet_ref.length>0?data.pet_ref:petRef,granted:data.granted===true,version:data.version??null,grantedAt:data.granted_at??null})}function isObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function numberOr(v,fallback){return typeof v=="number"&&Number.isFinite(v)?v:fallback}function strOr(v,fallback){return typeof v=="string"&&v.length>0?v:fallback}function strOrNull(v){return typeof v=="string"&&v.length>0?v:null}var RECORDS_TERMINAL=/* @__PURE__ */Object.freeze(["published","failed","revoked"]);function isTerminalStatus(status){return RECORDS_TERMINAL.includes(status)}function recordsDenialReasonOf(error){if(error===null)return null;let reason=error.recordsReason;return reason==="consent_required"||reason==="session_required"||reason==="entitlement"||reason==="pet_not_found"?reason:null}var RECORDS_CONSENT_REQUIRED_WIRE_CODE="records_consent_required";function recordsWireCodeOf(error){let raw=error.raw;if(raw===null||typeof raw!="object")return null;let body=raw,code=typeof body.error=="object"&&body.error!==null?body.error.code:body.code;return typeof code=="string"&&code.length>0?code:null}function isRecordsConsentRequired(error){return error===null||error.httpStatus!==409?false:recordsWireCodeOf(error)===RECORDS_CONSENT_REQUIRED_WIRE_CODE}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var noopRecordsTelemetry=/* @__PURE__ */Object.freeze({record(){}}),MAX_UPLOAD_BYTES=25*1024*1024,CONSENT_VERSION_MAX=64,IDEMPOTENCY_KEY_MAX=128,PET_REF_MAX=128,RECORDS_UPLOAD_CONTENT_TYPE="application/pdf",UPLOAD_DEADLINE_MS=9e4;function createRecordsController(deps){return new RecordsControllerImpl(deps)}var RecordsControllerImpl=class{constructor(deps){this.recordCache=/* @__PURE__ */new Map;this.consentEpoch=/* @__PURE__ */new Map;this.reportedGaps=/* @__PURE__ */new Set;this.features=RECORDS_FEATURES_PDF_ONLY;this.repository=deps.repository,this.uploads=deps.uploads,this.telemetry=deps.telemetry??noopRecordsTelemetry,this.newIdempotencyKey=deps.newIdempotencyKey??defaultIdempotencyFactory(),this.timers=deps.timers??defaultTimers,this.uploadDeadlineMs=deps.uploadDeadlineMs??UPLOAD_DEADLINE_MS}async createUploadRequest(input){let res=await this.repository.createRequest({pet_ref:input.petRef,idempotency_key:input.idempotencyKey});if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async getRequest(id){let res=await this.repository.getRequest(id);if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async listRequests(){let res=await this.repository.listRequests();if(!res.ok)return this.onRequestError(res.error);let views=mapRequestList(res.value);for(let view of views)this.observeRequest(view);return ok(views)}async readFeatures(){let read=this.repository.getFeatures;if(read===void 0)return this.features=RECORDS_FEATURES_PDF_ONLY;let features=RECORDS_FEATURES_PDF_ONLY;try{let res=await read.call(this.repository);res.ok&&(features=mapRecordsFeatures(res.value))}catch{}return this.features=features,features}async uploadDocument(input){let{requestId:requestId2,file:file}=input,rejection=validateFile(file,this.features.uploadContentTypes);if(rejection!==null)return this.telemetry.record("records.upload.rejected",{reason:rejection}),err(uploadFailed(`upload rejected: ${rejection}`));let initiated=await this.repository.initiateUpload(requestId2,{content_type:file.mimeType,file_size:file.sizeBytes});if(!initiated.ok)return this.onRequestError(initiated.error);let s3=await this.postToS3(initiated.value,file,input);if(!s3.ok)return this.telemetry.record("records.upload.failed",{reason:s3.reason}),err(uploadFailed(s3.reason));let completed=await this.repository.completeUpload(requestId2,{upload_id:initiated.value.upload_id});if(!completed.ok)return completed.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:reasonFromWire(completed.error)??"corrupt"}),this.onRequestError(completed.error);let doc=mapUploadedDocument(completed.value);return doc===null?err(internal()):ok(doc)}async postToS3(policy,file,input){let deadline=new AbortController,signal=mergeSignals(deadline.signal,input.signal),handle=this.timers.setTimeout(()=>deadline.abort(),this.uploadDeadlineMs);try{let opts={signal:signal};return input.onProgress&&(opts.onProgress=input.onProgress),await this.uploads.postMultipart(policy,file,opts),{ok:!0}}catch{return{ok:false,reason:deadline.signal.aborted&&input.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(handle)}}async getRecord(pet){let epoch=this.consentEpoch.get(pet)??0,res=await this.repository.getRecord(pet);if(epoch!==(this.consentEpoch.get(pet)??0))return err(/* @__PURE__ */Object.freeze({...makeEverfurError("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!res.ok){let reason=recordsDenialReasonOf(res.error);return reason==="consent_required"?(this.recordCache.delete(pet),this.telemetry.record("records.consent.denied",{pet_ref:pet})):reason==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:pet}),err(res.error)}let view=mapRecordView(pet,res.value);return view.petRef!==pet?err(internal()):view.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:pet}),this.recordCache.delete(pet),ok(view)):(this.recordCache.set(pet,view),ok(view))}peekCachedRecord(pet){return this.recordCache.get(pet)??null}async getConsent(pet){let res=await this.repository.getConsent(pet);return res.ok?ok(mapConsent(pet,res.value)):err(res.error)}async grantConsent(input){let res=await this.repository.putConsent(input.petRef,{consent_version:input.consentVersion,idempotency_key:input.idempotencyKey});return res.ok?ok(mapConsent(input.petRef,res.value)):(recordsDenialReasonOf(res.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:input.petRef}),err(res.error))}async revokeConsent(pet){let res=await this.repository.deleteConsent(pet);return res.ok?(this.consentEpoch.set(pet,(this.consentEpoch.get(pet)??0)+1),this.recordCache.delete(pet),ok(mapConsent(pet,res.value))):err(res.error)}reportCapabilityDenied(pet){this.telemetry.record("records.capability.denied",pet?{pet_ref:pet}:{})}observeRequest(view){view.reviewStartedAt!==null&&!this.reportedGaps.has(view.id)&&(this.reportedGaps.add(view.id),this.telemetry.record("records.parse.gap",{request_id:view.id}))}onRequestError(error){return recordsDenialReasonOf(error)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),err(error)}};function validateFile(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported_format";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"oversize":null}function reasonFromWire(error){let raw=error.wireMessage;return raw==="unsupported_format"||raw==="oversize"||raw==="corrupt"?raw:null}function uploadFailed(wireMessage){return makeEverfurError("mediaUploadFailed",{retryable:false,wireMessage:wireMessage})}function internal(){return makeEverfurError("internalError",{retryable:true})}var defaultTimers={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle)};function mergeSignals(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}function defaultIdempotencyFactory(){let counter=0;return()=>`records-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
100
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals2(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
101
|
+
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
|
|
102
|
+
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals2(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}var BASE="/widget/v1/records";function createHttpRecordsRepository(deps){let{auth:auth}=deps,mode=auth.mode,funnel=deps.funnel??createRequestFunnel({auth:auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=async(call,req,kind)=>{let res=await funnel.send(call,req);return res.ok?res:err(tagReason(res.error,mode,kind))},segmentError=(field,value)=>typeof value!="string"||value.length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is required and must be a non-empty string`}):hasLoneSurrogate(value)?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} contains an unpaired surrogate and cannot be encoded`}):null,boundsError=(field,value,max)=>{let unusable=segmentError(field,value);if(unusable!==null)return unusable;let length=[...value].length;return length>max?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is ${length} characters; the server accepts at most ${max}`}):null},firstError=(...checks)=>checks.find(c=>c!==null)??null;return{createRequest:body=>{let invalid3=firstError(boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",body.pet_ref,PET_REF_MAX));return invalid3?Promise.resolve(err(invalid3)):send("records.createRequest",post(`${BASE}/requests`,body),"request")},initiateUpload:(requestId2,body)=>{let invalid3=segmentError("request_id",requestId2);return invalid3?Promise.resolve(err(invalid3)):send("records.initiateUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/initiate`,body),"request")},completeUpload:(requestId2,body)=>{let invalid3=segmentError("request_id",requestId2);return invalid3?Promise.resolve(err(invalid3)):send("records.completeUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/complete`,body),"request")},getRequest:requestId2=>{let invalid3=segmentError("request_id",requestId2);return invalid3?Promise.resolve(err(invalid3)):send("records.getRequest",get(`${BASE}/requests/${encodeURIComponent(requestId2)}`),"request")},listRequests:async()=>{let res=await send("records.listRequests",get(`${BASE}/requests`),"request");if(!res.ok)return res;let value=res.value;return{ok:true,value:Array.isArray(value)?value:value.items??[]}},getRecord:petRef=>{let invalid3=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid3?Promise.resolve(err(invalid3)):send("records.getRecord",get(`${BASE}/pets/${encodeURIComponent(petRef)}/record`),"content")},getConsent:petRef=>{let invalid3=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid3?Promise.resolve(err(invalid3)):send("records.getConsent",get(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")},putConsent:(petRef,body)=>{let invalid3=firstError(boundsError("consent_version",body.consent_version,CONSENT_VERSION_MAX),boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",petRef,PET_REF_MAX));return invalid3?Promise.resolve(err(invalid3)):send("records.putConsent",put(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`,body),"consent")},getFeatures:()=>send("records.getFeatures",get(`${BASE}/features`),"request"),deleteConsent:petRef=>{let invalid3=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid3?Promise.resolve(err(invalid3)):send("records.deleteConsent",del(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")}}}function withReason(error,reason){let tagged={...error,recordsReason:reason};for(let key of["wireMessage","raw"]){let descriptor=Object.getOwnPropertyDescriptor(error,key);descriptor!==void 0&&Object.defineProperty(tagged,key,descriptor)}/* @__PURE__ */
|
|
103
|
+
return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";function recordsErrorReasonFor(error){return error.httpStatus!==404?null:error.reasonCode===PET_NOT_REGISTERED?"pet_not_found":"entitlement"}function tagReason(error,mode,kind){let notFound=recordsErrorReasonFor(error);return notFound!==null?withReason(error,notFound):error.code!=="accessDenied"?error:withReason(error,mode==="anonymous"?"session_required":kind==="content"?"consent_required":"entitlement")}function get(path){return{method:"GET",path:path}}function post(path,body){return{method:"POST",path:path,body:body}}function put(path,body){return{method:"PUT",path:path,body:body}}function del(path){return{method:"DELETE",path:path}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var epochs=/* @__PURE__ */new Map,listeners=/* @__PURE__ */new Set;function notifyRecordsConsentWithdrawn(petRef){epochs.set(petRef,(epochs.get(petRef)??0)+1);for(let listener of[...listeners])listener()}function recordsConsentEpochOf(petRef){return epochs.get(petRef)??0}function subscribe(onStoreChange){return listeners.add(onStoreChange),()=>{listeners.delete(onStoreChange)}}function useRecordsConsentEpoch(petRef){let snapshot=react.useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return react.useSyncExternalStore(subscribe,snapshot,snapshot)}var INITIAL={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:RECORDS_FEATURES_PDF_ONLY.uploadContentTypes},POLL_INTERVAL_MS=4e3,MAX_POLLS=30;function useEverfurRecords(opts){let{petRef:petRef}=opts,ownTransport=react.useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=react.useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=react.useRef(scope),[binding,setBinding]=react.useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=react.useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=react.useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=react.useRef(0);react.useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),react.useEffect(()=>{if(opts.controller)return;let{services:services}=runtime.registry,telemetry={record:(event,props)=>services.telemetry.track(event,props)},acquired=runtime.registry.acquire("records",`${userRef??""}|${petRef}${hasOwnTransport?"|own-upload":""}`,()=>createRecordsController({repository:createHttpRecordsRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),uploads:hasOwnTransport?{postMultipart:(policy,file,o)=>(ownTransport.current??services.uploadTransport).postMultipart(policy,file,o)}:services.uploadTransport,telemetry:telemetry}),()=>{});return setBinding({scope:scope,controller:acquired}),()=>{runtime.registry.release(acquired)}},[runtime,userRef,petRef,opts.controller,scopeEpoch,scope,hasOwnTransport]);let patch=react.useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return;let gen=generation.current+=1;pollsRef.current=0,rearmPolls(),patch({loading:true,error:null,denialReason:null,withheld:false});let[consentRes,listRes]=await Promise.all([controller.getConsent(petRef),controller.listRequests()]);if(gen!==generation.current)return;let consent=consentRes.ok?consentRes.value:null,requests=listRes.ok?listRes.value.filter(request=>request.petRef===petRef):[],listError=listRes.ok?null:listRes.error;if(consent&&consent.granted){let recordRes=await controller.getRecord(petRef);if(gen!==generation.current)return;if(recordRes.ok){patch({consent:consent,requests:requests,record:recordRes.value,withheld:recordRes.value.withheld,error:recordRes.value.withheld?withheldSentinel():listError,denialReason:null,loading:false});return}patch({consent:consent,requests:requests,record:null,error:recordRes.error,denialReason:recordsDenialReasonOf(recordRes.error),withheld:false,loading:false});return}patch({consent:consent,requests:requests,record:null,error:consentRes.ok?listError:consentRes.error,denialReason:consent?"consent_required":consentDenial(consentRes),withheld:false,loading:false})},[controller,petRef,patch,scope]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;react.useEffect(()=>{if(!readUploadFeatures||!controller?.readFeatures)return;let live=true;return controller.readFeatures().then(features=>{live&&activeScope.current===scope&&patch({uploadContentTypes:features.uploadContentTypes})}),()=>{live=false}},[controller,readUploadFeatures,patch,scope]);let activeRequest=react.useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=react.useRef(0),polledIdRef=react.useRef(null),[pollEpoch,rearmPolls]=react.useReducer(n=>n+1,0);react.useEffect(()=>{if(!controller||activeId===null||activeStatus===null||isTerminalStatus(activeStatus)||activeStatus==="in_review")return;polledIdRef.current!==String(activeId)&&(polledIdRef.current=String(activeId),pollsRef.current=0);let cancelled=false,tick=async()=>{if(cancelled||pollsRef.current>=MAX_POLLS)return;pollsRef.current+=1;let res=await controller.getRequest(activeId);if(!cancelled){if(res.ok&&res.value.petRef===petRef){if(setSnap(current=>({...current,requests:replaceRequest(current.requests,res.value)})),isTerminalStatus(res.value.status)){res.value.status==="published"&&load();return}if(res.value.status==="in_review")return}handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS)}},handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS);return()=>{cancelled=true,clearTimeout(handle)}},[controller,activeId,activeStatus,load,pollEpoch,petRef,setSnap]);let createRequest=react.useCallback(async idempotencyKey=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.createUploadRequest({petRef:petRef,idempotencyKey:idempotencyKey});return activeScope.current===scope&&res.ok&&res.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,res.value)})),res},[controller,petRef,scope,setSnap]),patchItem=react.useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=react.useCallback(async(requestId2,files)=>{let batch=Date.now().toString(36),queue=files.map((file,index)=>{let skipReason=skipReasonFor(file,snap.uploadContentTypes);return{key:`${batch}-${index}`,name:file.name??null,status:skipReason===null?"queued":"skipped",progress:0,skipReason:skipReason,error:null}}),settled=[...queue];if(!controller||activeScope.current!==scope)/* @__PURE__ */return Object.freeze(settled);setSnap(c=>({...c,uploadQueue:queue,isUploading:true,uploadProgress:0}));for(let[index,file]of files.entries()){let item=queue[index];if(item.status==="skipped")continue;if(activeScope.current!==scope)break;patchItem(item.key,current=>({...current,status:"uploading",progress:0})),patch({uploadProgress:0});let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{if(activeScope.current!==scope)return;let bounded=Math.min(1,Math.max(0,fraction));patchItem(item.key,current=>({...current,progress:Math.max(current.progress,bounded)})),patch({uploadProgress:bounded})}});if(activeScope.current!==scope)break;let next=res.ok?{...item,status:"done",progress:1}:{...item,status:"failed",error:res.error};if(settled[index]=next,patchItem(item.key,()=>next),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}}return activeScope.current===scope&&patch({isUploading:false,uploadProgress:null}),/* @__PURE__ */Object.freeze(settled)},[controller,patch,patchItem,petRef,scope,setSnap,snap.uploadContentTypes]),uploadDocument=react.useCallback(async(requestId2,file)=>{if(!controller||activeScope.current!==scope)return notReady();let key=`${Date.now().toString(36)}-0`;setSnap(c=>({...c,isUploading:true,uploadProgress:0,uploadQueue:[{key:key,name:file.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{activeScope.current===scope&&(patch({uploadProgress:fraction}),patchItem(key,current=>({...current,progress:Math.max(current.progress,Math.min(1,fraction))})))}});if(activeScope.current!==scope)return res;if(patch({isUploading:false,uploadProgress:null}),patchItem(key,current=>res.ok?{...current,status:"done",progress:1}:{...current,status:"failed",error:res.error}),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}return res},[controller,patch,patchItem,petRef,scope,setSnap]),grantConsent=react.useCallback(async(consentVersion,idempotencyKey)=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.grantConsent({petRef:petRef,consentVersion:consentVersion,idempotencyKey:idempotencyKey});return res.ok&&activeScope.current===scope&&load(),res},[controller,petRef,load,scope]),revokeConsent=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.revokeConsent(petRef);return res.ok&¬ifyRecordsConsentWithdrawn(petRef),res.ok&&activeScope.current===scope&&(generation.current+=1,patch({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:res.value})),res},[controller,petRef,patch,scope]),refresh=react.useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return react.useMemo(()=>({status:status,record:snap.record,requests:snap.requests,activeRequest:activeRequest,consent:snap.consent,error:snap.error,denialReason:snap.denialReason,withheld:snap.withheld,isUploading:snap.isUploading,uploadProgress:snap.uploadProgress,uploadQueue:snap.uploadQueue,uploadContentTypes:snap.uploadContentTypes,createRequest:createRequest,uploadDocument:uploadDocument,uploadDocuments:uploadDocuments,grantConsent:grantConsent,revokeConsent:revokeConsent,refresh:refresh}),[status,snap,activeRequest,createRequest,uploadDocument,uploadDocuments,grantConsent,revokeConsent,refresh])}function skipReasonFor(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"too_large":null}function classifyPick(files,types){let uploadable=[],skipped=[];for(let file of files){let reason=skipReasonFor(file,types);reason===null?uploadable.push(file):skipped.push({name:file.name??null,reason:reason})}return{uploadable:uploadable,skipped:skipped}}function selectStatus(snap,hasController){return snap.loading||!hasController?"loading":snap.withheld||snap.denialReason!==null||snap.error!==null?"error":snap.record!==null&&!snap.record.isEmpty||snap.requests.length>0?"populated":"empty"}function newestRequest(requests){if(requests.length===0)return null;let newest=requests[0];for(let r of requests)r.updatedAt>newest.updatedAt&&(newest=r);return newest}function replaceRequest(requests,next){let filtered=requests.filter(r=>r.id!==next.id);return[next,...filtered]}function consentDenial(res){return res.ok?"consent_required":recordsDenialReasonOf(res.error)??"consent_required"}function withheldSentinel(){return makeEverfurError("internalError",{retryable:false})}function notReady(){return{ok:false,error:makeEverfurError("internalError",{retryable:true})}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date)=>`Latest reading ${reading}, ${status}, collected ${date}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});var CONSUMER_PAGE_COPY=/* @__PURE__ */Object.freeze({title:"Medical records",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Medical records"},lead:"Follow your records requests and add records you already have.",viewRecord:"Visits & records",viewTimeline:"Timeline",viewLabs:"Labs & bloodwork",viewScreenings:"Screenings",requestsFor:petName=>`Requests for ${petNameOr(petName)}`,uploadPromptTitle:petName=>`Do you already have ${petNameOr(petName)}'s records?`,uploadPromptBody:"Upload PDF records you already have, up to 25 MB each. You can pick several at once. We'll read them and add the results to your records.",uploadAction:"Upload records I already have",uploadStarting:"Starting upload…",noPet:"Add your pet in Chat before starting a records request.",requestRecords:"Request records",requestTimeline:"Request timeline",requestTimelineA11y:source=>`Request timeline, ${source}`,ownerProvided:"Records you provided",askA11y:petName=>`Ask Everfur about ${petNameOr(petName)}'s medical records`});function buildRecordsPageAskPrompt(petName){return`I'm looking at ${petName?.trim()||"my pet"}'s medical records. What do these records tell me about their health and what should I keep on top of?`}function consumerRequestSource(request){if(request.convertedToUploadAt)return CONSUMER_PAGE_COPY.ownerProvided;let clinic=request.clinicName?.trim()??"";return clinic.length>0?clinic:CONSUMER_PAGE_COPY.ownerProvided}var RECORDS_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
|
|
104
|
+
return Object.freeze({stack:/* @__PURE__ */Object.freeze([initial])})}function currentRecordsScreen(state){return state.stack[state.stack.length-1]??RECORDS_DASHBOARD}function pushRecordsNav(state,screen){/* @__PURE__ */
|
|
105
|
+
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
|
|
106
|
+
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}function resolveConsentVersion(consentVersion,consent){return consentVersion??consent?.version??""}function canGrantConsent(consentVersion,consent){return resolveConsentVersion(consentVersion,consent).length>0}function selectErrorView(state,canGrant){return state.denialReason==="consent_required"?canGrant?{kind:"consent_required"}:{kind:"consent_unavailable"}:state.denialReason==="pet_not_found"?{kind:"pet_not_found",error:makeEverfurError("petNotFound",{retryable:false})}:state.denialReason==="entitlement"?{kind:"error",error:makeEverfurError("accessDenied")}:state.denialReason==="session_required"?{kind:"session_required"}:state.withheld?{kind:"withheld"}:state.error===null?{kind:"withheld"}:{kind:"error",error:state.error}}function selectRequestTitle(request){let clinic=request.clinicName?.trim()??"";return clinic.length>0?clinic:request.source==="owner_provided"?REQUEST_TITLE_COPY.ownerUpload:REQUEST_TITLE_COPY.clinicRequest}var REQUEST_TITLE_COPY=/* @__PURE__ */Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function selectResumableUploadRequest(_record,activeRequest){return activeRequest===null||activeRequest.status!=="awaiting_upload"?null:activeRequest}function heldItemsLabel(count){return`${count} ${RECORDS_COPY.beingReviewed}`}function selectRequestList(requests){let sorted=[...requests].sort((a,b)=>a.updatedAt!==b.updatedAt?a.updatedAt>b.updatedAt?-1:1:a.createdAt!==b.createdAt?a.createdAt>b.createdAt?-1:1:0);/* @__PURE__ */
|
|
107
|
+
return Object.freeze(sorted)}function selectPrimaryLabel(request){let action=request.actionNeededLabel?.trim()??"";return action.length>0?action:request.statusLabel}function selectClinicCall(request){if(request.showClinicPhone!==true)return null;let phone=request.clinicPhone?.trim()??"";return phone.length===0?null:{phone:phone,dial:`tel:${phone.replace(/[^+\d]/g,"")}`,clinicName:request.clinicName?.trim()||null}}function selectRequestStatusTone(request){switch(request.wireStatus??request.status){case"published":return"positive";case"failed":case"clinic_declined":return"critical";case"revoked":return"neutral";case"clinic_responded_no_records":case"awaiting_upload":case"records_received":case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return"warning";default:return"info"}}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
108
|
+
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
109
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
110
|
+
return jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
111
|
+
return jsxRuntime.jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level>=6?6:level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);react.createContext(NESTED_HEADING_LEVEL_DEFAULT);var RecordsFootnoteDrawnAbove=react.createContext(false);function RecordsFootnote(props){let theme=useEverfurTheme(),style=react.useMemo(()=>footnoteStyle(theme),[theme]);return react.useContext(RecordsFootnoteDrawnAbove)?null:/* @__PURE__ */jsxRuntime.jsx("p",{role:"note",className:props.className,style:{...style,...props.style},"data-testid":"records-footnote",children:RECORDS_FOOTNOTE})}function footnoteStyle(theme){let{color:color,space:space,type:type}=theme;return{...SURFACE_ROOT_RESET,boxSizing:"border-box",margin:0,padding:`${space.md}px ${space.lg}px ${space.lg}px`,textAlign:"center",...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.normal)}px`,color:color.text.muted,backgroundColor:color.background}}var CLINIC_REQUEST_COPY=/* @__PURE__ */Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"}),TYPED_SIGNATURE_MAX_LENGTH=100;var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCountDraft:count=>`DRAFT COPY [[${String(count)} clinics found: the spoken count of search results]]`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){case"verified":return{label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case"unverified":return{label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return{label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location2){let[query,setQueryValue]=react.useState(""),[debouncedQuery,setDebounced]=react.useState(""),[clinics,setClinics]=react.useState([]),[cursor,setCursor]=react.useState(null),[recent,setRecent]=react.useState([]),[recentLoading,setRecentLoading]=react.useState(true),[initialLoading,setInitialLoading]=react.useState(false),[loadingMore,setLoadingMore]=react.useState(false),[error,setError]=react.useState(null),[pageError,setPageError]=react.useState(null),[attempt,setAttempt]=react.useState(0),generation=react.useRef(0),live=react.useRef(true),lat=location2?.latitude,lng=location2?.longitude,bias=react.useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);react.useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),react.useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),react.useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;react.useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=react.useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=react.useCallback(value=>setQueryValue(value),[]),retry=react.useCallback(()=>setAttempt(n=>n+1),[]);return react.useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
|
|
112
|
+
return Object.freeze({key:clinic?.id??`free:${freeText??""}`,clinic:clinic,freeText:freeText,email:email2,idempotencyKey:idempotencyKey})}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),clinicSchema=/* @__PURE__ */zod.z.object({clinicId:/* @__PURE__ */uuid.optional(),clinicFreeText:text(200).refine(value=>value.trim().length>0).optional(),clinicEmail:text(320,3).refine(value=>!hasControl(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())).optional(),signatureId:/* @__PURE__ */uuid.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0)),inputSchema=/* @__PURE__ */zod.z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */zod.z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */zod.z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */zod.z.string(),created_count:/* @__PURE__ */zod.z.number().int().nonnegative(),failed_count:/* @__PURE__ */zod.z.number().int().nonnegative(),results:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({idempotency_key:/* @__PURE__ */zod.z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */zod.z.string().nullable().optional(),created:/* @__PURE__ */zod.z.boolean(),request:/* @__PURE__ */zod.z.unknown().optional(),failure_code:/* @__PURE__ */zod.z.string().nullable().optional(),failure_reason:/* @__PURE__ */zod.z.string().nullable().optional()}))});function createRecordsClinicBatchClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async createClinicRequestBatch(input){if(!inputSchema.safeParse(input).success)return err(makeEverfurError("validationFailed",{retryable:false}));let result=await funnel.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,clinics:input.clinics.map(clinic=>({...clinic.clinicId!==void 0?{clinic_id:clinic.clinicId}:{clinic_free_text:clinic.clinicFreeText},...clinic.clinicEmail!==void 0?{clinic_email:clinic.clinicEmail}:{},...clinic.signatureId!==void 0?{signature_id:clinic.signatureId}:{signature_png_base64:clinic.signaturePngBase64},idempotency_key:clinic.idempotencyKey}))}});if(!result.ok)return result;let parsed=responseSchema.safeParse(result.value);if(!parsed.success||parsed.data.pet_ref!==input.petRef)return malformed();let results=[];for(let row of parsed.data.results){let request=row.request===void 0||row.request===null?null:mapRequestView(row.request);if(row.created!==(request!==null))return malformed();results.push(/* @__PURE__ */Object.freeze({idempotencyKey:row.idempotency_key,clinicId:row.clinic_id??null,clinicFreeText:row.clinic_free_text??null,created:row.created,request:request,failureCode:row.failure_code??null,failureReason:row.failure_reason??null}))}return ok(/* @__PURE__ */Object.freeze({requestGroupId:parsed.data.request_group_id,petRef:parsed.data.pet_ref,results:/* @__PURE__ */Object.freeze(results),createdCount:parsed.data.created_count,failedCount:parsed.data.failed_count}))}}}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}var uuid2=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),clinicPageSchema=/* @__PURE__ */zod.z.object({clinics:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({clinic_id:uuid2,name:/* @__PURE__ */zod.z.string().min(1),address:/* @__PURE__ */zod.z.string().nullable(),phone:/* @__PURE__ */zod.z.string().nullable(),email_status:/* @__PURE__ */zod.z.string(),distance_km:/* @__PURE__ */zod.z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */zod.z.string().nullable().optional()}),copySchema=/* @__PURE__ */zod.z.object({authorization_version:/* @__PURE__ */zod.z.string().min(1),scope_template:/* @__PURE__ */zod.z.string().min(1),authorization_template:/* @__PURE__ */zod.z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */zod.z.object({upload_id:/* @__PURE__ */zod.z.string().min(1),upload_url:/* @__PURE__ */zod.z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string())});function createRecordsClinicController(deps){let{repository:repository}=deps,request=async pending=>{let result=await pending;if(!result.ok)return result;let mapped=mapRequestView(result.value);return mapped===null?malformed2():ok(mapped)},page=async pending=>{let result=await pending;if(!result.ok)return result;let parsed=clinicPageSchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({clinics:/* @__PURE__ */Object.freeze(parsed.data.clinics.map(clinic=>/* @__PURE__ */Object.freeze({id:clinic.clinic_id,name:clinic.name,address:clinic.address,phone:clinic.phone,emailStatus:clinic.email_status,distanceKm:clinic.distance_km}))),nextCursor:parsed.data.next_cursor??null})):malformed2()};return{searchClinics:(input={})=>page(repository.searchClinics(input)),recentClinics:(input={})=>page(repository.recentClinics(input)),async getRequestGroup(requestGroupId){let result=await repository.getRequestGroup(requestGroupId);if(!result.ok)return result;let group=mapRequestGroup(result.value);return group===null?malformed2():ok(group)},async getAuthorizationCopy(){let result=await repository.getAuthorizationCopy();if(!result.ok)return result;let parsed=copySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({authorizationVersion:parsed.data.authorization_version,scopeTemplate:parsed.data.scope_template,authorizationTemplate:parsed.data.authorization_template})):malformed2()},async createClinicRequest(input){let result=await request(repository.createClinicRequest(input));return result.ok&&result.value.petRef!==input.petRef?malformed2():result},retryRequest:id=>request(repository.retryRequest(id)),revokeRequest:id=>request(repository.revokeRequest(id)),updateClinicEmail:(id,clinicEmail)=>request(repository.updateClinicEmail(id,clinicEmail)),convertToUpload:id=>request(repository.convertToUpload(id)),async initiateSignatureUpload(fileSize){let result=await repository.initiateSignatureUpload(fileSize);if(!result.ok)return result;let parsed=signaturePolicySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({uploadId:parsed.data.upload_id,uploadUrl:parsed.data.upload_url,uploadFields:/* @__PURE__ */Object.freeze(parsed.data.upload_fields)})):malformed2()},async completeSignatureUpload(uploadId){let result=await repository.completeSignatureUpload(uploadId);if(!result.ok)return result;let parsed=zod.z.object({signature_id:uuid2}).safeParse(result.value);return parsed.success?ok(parsed.data.signature_id):malformed2()}}}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}var BASE2="/widget/v1/records",uuid3=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text2=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl2=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),email=text2(320,3).refine(value=>!hasControl2(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())),requestId=text2(64),recentSchema=/* @__PURE__ */zod.z.object({limit:/* @__PURE__ */zod.z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */zod.z.object({query:text2(200,0).optional(),location:/* @__PURE__ */zod.z.object({latitude:/* @__PURE__ */zod.z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */zod.z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */zod.z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */zod.z.object({petRef:text2(128),ownerName:text2(200).refine(value=>value.trim().length>0&&!hasControl2(value)),authorizationVersion:text2(64),clinicId:/* @__PURE__ */uuid3.optional(),clinicFreeText:text2(200).refine(value=>value.trim().length>0).optional(),clinicEmail:email.optional(),signatureId:/* @__PURE__ */uuid3.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0));function createHttpRecordsClinicRepository(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=(call,request,deduplicated=false)=>funnel.send(`records.clinic.${call}`,request,request.method==="GET"||deduplicated?void 0:{idempotent:false,maxAttempts:1}),recover=(id,action,body)=>requestId.safeParse(id).success?send(action,{method:"POST",path:`${BASE2}/requests/${encodeURIComponent(id)}/${action}`,...body?{body:body}:{}}):invalid();return{searchClinics(input){return searchSchema.safeParse(input).success?send("search",{method:"GET",path:`${BASE2}/clinics/search`,query:{q:input.query??"",lat:input.location?.latitude,lng:input.location?.longitude,limit:input.limit,cursor:input.cursor}}):invalid()},recentClinics(input){return recentSchema.safeParse(input).success?send("recent",{method:"GET",path:`${BASE2}/clinics/recent`,query:{limit:input.limit}}):invalid()},getRequestGroup(requestGroupId){return requestId.safeParse(requestGroupId).success?send("requestGroup",{method:"GET",path:`${BASE2}/request-groups/${encodeURIComponent(requestGroupId)}`}):invalid()},getAuthorizationCopy:()=>send("authorizationCopy",{method:"GET",path:`${BASE2}/authorization-copy`}),createClinicRequest(input){return createSchema.safeParse(input).success?send("create",{method:"POST",path:`${BASE2}/clinic-requests`,body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,idempotency_key:input.idempotencyKey,...input.clinicId!==void 0?{clinic_id:input.clinicId}:{clinic_free_text:input.clinicFreeText},...input.clinicEmail!==void 0?{clinic_email:input.clinicEmail}:{},...input.signatureId!==void 0?{signature_id:input.signatureId}:{signature_png_base64:input.signaturePngBase64}}},true):invalid()},retryRequest:id=>recover(id,"retry"),revokeRequest:id=>recover(id,"revoke"),convertToUpload:id=>recover(id,"convert-to-upload"),updateClinicEmail(id,clinicEmail){return email.safeParse(clinicEmail).success?recover(id,"clinic-email",{clinic_email:clinicEmail}):invalid()},initiateSignatureUpload(fileSize){return!Number.isInteger(fileSize)||fileSize<=0||fileSize>2*1024*1024?invalid():send("signatureInitiate",{method:"POST",path:`${BASE2}/signatures/initiate`,body:{content_type:"image/png",file_size:fileSize}})},completeSignatureUpload(uploadId){return/^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uploadId)?send("signatureComplete",{method:"POST",path:`${BASE2}/signatures/complete`,body:{upload_id:uploadId}}):invalid()}}}function invalid(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsClinic(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),controller=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=react.useRef(controller);return react.useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),react.useMemo(()=>{let run=async operation=>{if(userRef===null||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation();return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{searchClinics:input=>run(()=>controller.searchClinics(input)),recentClinics:input=>run(()=>controller.recentClinics(input)),getRequestGroup:id=>run(()=>controller.getRequestGroup(id)),getAuthorizationCopy:()=>run(()=>controller.getAuthorizationCopy()),createClinicRequest:input=>run(()=>controller.createClinicRequest(input)),retryRequest:id=>run(()=>controller.retryRequest(id)),revokeRequest:id=>run(()=>controller.revokeRequest(id)),updateClinicEmail:(id,email2)=>run(()=>controller.updateClinicEmail(id,email2)),convertToUpload:id=>run(()=>controller.convertToUpload(id)),initiateSignatureUpload:size=>run(()=>controller.initiateSignatureUpload(size)),completeSignatureUpload:id=>run(()=>controller.completeSignatureUpload(id))}},[controller,userRef])}function useEverfurRecordsClinicBatch(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=react.useRef(client);return react.useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),react.useMemo(()=>({async createClinicRequestBatch(input){if(userRef===null||active.current!==client)return err(makeEverfurError("accessDenied"));let result=await client.createClinicRequestBatch(input);return active.current===client?result:err(makeEverfurError("accessDenied"))}}),[client,userRef])}var VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style,className:className}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
|
|
113
|
+
return jsxRuntime.jsxs("div",{className:className,"data-testid":"records-gate-off",style:{boxSizing:"border-box",minHeight:MIN_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"flex-start",gap:space.md,padding:space.lg,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`,backgroundColor:color.surfaceCream,color:color.text.primary,...style},children:[reason.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:{margin:0,fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
|
|
114
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onExit,"data-testid":"records-gate-off-exit",style:{minHeight:MIN_TARGET,padding:`0 ${space.lg}px`,borderRadius:radius.pill,border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk,font:"inherit",fontSize:type.size.body,cursor:"pointer"},children:exitLabel})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function slotBoxCss(slot,borderWidth){let box=slotBox(slot,borderWidth),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}var normalize=text3=>text3.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text3=normalize(disclaimer);return text3.length===0||text3===FOOTNOTE}var RECORDS_EASE_OUT=/* @__PURE__ */Object.freeze([.23,1,.32,1]),RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var EASE=cssCubicBezier(RECORDS_EASE_OUT);function usePressScale(disabled=false){let theme=useEverfurTheme(),[pressed,setPressed]=react.useState(false),still=theme.motion.reducedMotion||disabled,down=react.useCallback(()=>setPressed(true),[]),up=react.useCallback(()=>setPressed(false),[]);return{style:still?{}:{transform:pressed?`scale(${RECORDS_MOTION.pressScale})`:"none",transition:`transform ${RECORDS_MOTION.pressMs}ms ${EASE}`},handlers:{onPointerDown:down,onPointerUp:up,onPointerLeave:up,onPointerCancel:up}}}function useSectionRise(){let reduced=useEverfurTheme().motion.reducedMotion,ran=react.useRef(false),animations=react.useRef([]);return react.useEffect(()=>()=>{for(let animation of animations.current)animation.cancel()},[]),react.useCallback(node=>{node===null||ran.current||reduced||(ran.current=true,Array.from(node.children).forEach((child,index)=>{if(typeof child.animate!="function")return;let delay=Math.min(index,RECORDS_MOTION.maxSteps-1)*RECORDS_MOTION.staggerMs;try{animations.current.push(child.animate([{transform:`translateY(${RECORDS_MOTION.riseWebPx}px)`},{transform:"none"}],{duration:RECORDS_MOTION.moveMs,delay:delay,easing:EASE,fill:"backwards"}),child.animate([{opacity:0},{opacity:1}],{duration:RECORDS_MOTION.fadeMs,delay:delay,easing:EASE,fill:"backwards"}))}catch{}}))},[reduced])}var SCREEN_HEADING_ATTR="data-ef-screen-heading";function focusTook(el){return el.focus(),document.activeElement===el}function focusScreen(root){let heading=root.querySelector(`[${SCREEN_HEADING_ATTR}]`);if(heading!==null&&(heading.textContent??"").trim().length>0&&focusTook(heading)||focusTook(root))return;let screenRoot=root.firstElementChild;screenRoot instanceof HTMLElement&&(screenRoot.hasAttribute("tabindex")||(screenRoot.setAttribute("tabindex","-1"),screenRoot.style.outline="none"),screenRoot.focus())}var NOT_SEEN=/* @__PURE__ */Symbol("records.screenFocus.notSeen");function useFocusScreenOnChange(screen,onMount=false){let rootRef=react.useRef(null),seen=react.useRef(onMount?NOT_SEEN:screen);return react.useEffect(()=>{if(Object.is(seen.current,screen))return;seen.current=screen;let root=rootRef.current;root!==null&&focusScreen(root)},[screen]),rootRef}var MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET=44,BUTTON_HEIGHT=52,BACK_LABEL="Back";function useScreenStyles(){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeScreenStyles(theme),[theme]);return{theme:theme,styles:styles}}function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
115
|
+
return jsxRuntime.jsxs("header",{style:styles.headerRow,"data-testid":testID,children:[onBack?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onBack,"aria-label":BACK_LABEL,style:styles.iconButton,"data-testid":testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.backChevron})}):/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.iconButton}),title.trim().length>0?/* @__PURE__ */jsxRuntime.jsx("h2",{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:variant==="document"?styles.documentTitle:styles.headerTitle,children:title}):/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.headerTitle,"data-testid":testID?`${testID}-spacer`:void 0}),
|
|
116
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.headerRight,children:right??/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.iconButton})})]})}function DisclaimerBand({disclaimer:disclaimer,style:style}){let{styles:styles}=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxRuntime.jsxs("p",{role:"note","aria-label":DASHBOARD_COPY.important(disclaimer),style:{...styles.band,...style},"data-testid":"records-disclaimer-band",children:[
|
|
117
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.infoGlyph,children:"i"}),
|
|
118
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onClick:onClick,kind:kind="primary",disabled:disabled=false,busy:busy=false,ariaLabel:ariaLabel,ariaDescribedBy:ariaDescribedBy,testID:testID,style:style}){let{styles:styles}=useScreenStyles(),press=usePressScale(disabled||busy),box=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink;/* @__PURE__ */
|
|
119
|
+
return jsxRuntime.jsx("button",{type:"button",onClick:onClick,disabled:disabled||busy,"aria-busy":busy,"aria-label":ariaLabel,"aria-describedby":ariaDescribedBy,...press.handlers,style:{...styles.pill,...box,...disabled?styles.pillDisabled:{},...press.style,...style},"data-testid":testID,children:label})}function Chip({label:label,tone:tone="neutral",testID:testID}){let{styles:styles}=useScreenStyles(),sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
|
|
120
|
+
return jsxRuntime.jsx("span",{style:{...styles.chip,...sentence?styles.chipSentence:{},...styles.chipTones[tone]},"data-testid":testID,children:label})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
121
|
+
return jsxRuntime.jsxs("div",{style:styles.sectionHeader,children:[
|
|
122
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sectionTitle,children:title}),count!==void 0?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.sectionCount,children:count}):null]})}function HeaderGlyph({name:name,color:color}){/* @__PURE__ */
|
|
123
|
+
return jsxRuntime.jsx("svg",{"aria-hidden":"true",focusable:"false",width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:color,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0},"data-glyph":name,children:name==="send"?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
124
|
+
/* @__PURE__ */jsxRuntime.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),
|
|
125
|
+
/* @__PURE__ */jsxRuntime.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
126
|
+
/* @__PURE__ */jsxRuntime.jsx("circle",{cx:"18",cy:"5",r:"3"}),
|
|
127
|
+
/* @__PURE__ */jsxRuntime.jsx("circle",{cx:"6",cy:"12",r:"3"}),
|
|
128
|
+
/* @__PURE__ */jsxRuntime.jsx("circle",{cx:"18",cy:"19",r:"3"}),
|
|
129
|
+
/* @__PURE__ */jsxRuntime.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),
|
|
130
|
+
/* @__PURE__ */jsxRuntime.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]})})}function Chevron({direction:direction="right"}){let{styles:styles}=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
|
|
131
|
+
return jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...styles.chevron,transform:`rotate(${rotate})`}})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),cardText=slotText(slots.recordCard),errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({backgroundColor:bg,color:fg,border:"1.5px solid transparent"}),edge=(line,fg)=>({backgroundColor:color.surface,color:fg,border:`1.5px solid ${line}`}),cardEdge=`1px solid ${color.borderRingCream}`,button={boxSizing:"border-box",minHeight:BUTTON_HEIGHT,minWidth:MIN_TOUCH_TARGET,padding:`${space.md}px ${space.lg+space.xs/2}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:space.sm,textDecoration:"none"};return{chipTones:{neutral:edge(color.brandBorderStrong,color.text.primary),info:tone(color.brandSoft,color.brandInk),warning:edge(color.cautionAccent,color.text.primary),critical:edge(color.danger,color.danger),positive:edge(color.success,color.brandInk)},root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},content:{display:"flex",flexDirection:"column",gap:space.lg,padding:`0 ${space.lg}px ${space.xxl}px`},contentTight:{display:"flex",flexDirection:"column",gap:space.lg,padding:`0 ${space.sm}px ${space.xxl}px`},inset:{padding:`0 ${space.sm}px`},headerRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm,padding:`${space.xs}px ${space.lg}px ${space.md}px`},iconButton:{boxSizing:"border-box",width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,display:"inline-flex",alignItems:"center",justifyContent:"center",border:0,background:"transparent",cursor:"pointer",padding:0,color:color.brandInk,flexShrink:0},backChevron:{display:"block",width:space.md,height:space.md,borderLeft:`2px solid ${color.brandInk}`,borderBottom:`2px solid ${color.brandInk}`,transform:"rotate(45deg)",marginLeft:space.xs},headerTitle:{...text3(type.size.heading,type.lineHeight.tight,color.brandInk,"bold"),flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},documentTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),flex:1,textAlign:"center"},headerRight:{display:"flex",alignItems:"center",gap:space.sm+space.xs/2},section:{display:"flex",flexDirection:"column",gap:space.sm+space.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:space.sm,padding:`0 ${space.xs}px`},sectionTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),letterSpacing:"-0.02em"},sectionCount:{...text3(type.size.bodyTight,type.lineHeight.snug,color.text.muted,"medium")},card:{boxSizing:"border-box",borderRadius:radius.lg,border:cardEdge,backgroundColor:color.surface,padding:`${space.xs}px ${space.lg}px`,margin:0,listStyle:"none",...slotBoxCss(slots.recordCard,1)},creamCard:{boxSizing:"border-box",borderRadius:radius.lg,border:cardEdge,backgroundColor:color.surfaceCream,padding:space.lg,display:"flex",flexDirection:"column",gap:space.md,...slotBoxCss(slots.recordCard,1)},row:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.md,padding:`${space.md}px 0`},rowDivider:{borderTop:`1px solid ${color.borderHairlineGreen}`},rowMain:{flex:1,minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(type.size.body+1,type.lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},chip:{boxSizing:"border-box",display:"inline-flex",alignItems:"center",minHeight:24,borderRadius:radius.pill,padding:`0 ${space.sm+space.xs/2}px`,...faceCss(theme,"monoBold"),fontSize:type.size.tiny+1,lineHeight:lh(type.size.tiny+1,type.lineHeight.snug),letterSpacing:"0.06em",textTransform:"uppercase",whiteSpace:"nowrap"},pill:button,pillPrimary:{border:0,backgroundColor:color.brand,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},pillOutline:{border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk},pillDanger:{border:`1.4px solid ${color.danger}`,backgroundColor:color.surface,color:color.danger,fontSize:type.size.bodyTight},pillAsk:{border:`1px solid ${color.borderRingCream}`,backgroundColor:color.surface,color:color.text.primary},pillLink:{minHeight:MIN_TOUCH_TARGET,border:0,backgroundColor:"transparent",color:color.linkInk,padding:`${space.sm}px`},pillDisabled:{opacity:.5,cursor:"default"},infoNote:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,padding:`${space.sm+space.xs/2}px ${space.md}px`,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary)},cautionNote:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,padding:`${space.sm+space.xs/2}px ${space.md}px`,...text3(type.size.bodyTight,type.lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2,...text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary)},errorBanner:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md,...text3(type.size.bodyTight,type.lineHeight.normal,errorColor)},errorText:text3(type.size.bodyTight,type.lineHeight.normal,errorColor),band:{display:"flex",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,margin:0},bandText:{flex:1,...text3(type.size.caption,type.lineHeight.normal,color.text.secondary)},infoGlyph:{boxSizing:"border-box",flexShrink:0,width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,border:`1px solid ${color.text.secondary}`,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:type.size.small,color:color.text.secondary},chevron:{display:"inline-block",width:space.sm,height:space.sm,borderTop:`2px solid ${color.text.muted}`,borderRight:`2px solid ${color.text.muted}`,flexShrink:0},chipSentence:{...faceCss(theme,"medium"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),letterSpacing:"normal",textTransform:"none",whiteSpace:"normal",borderRadius:radius.md,padding:`${space.xs}px ${space.sm+space.xs/2}px`},lead:{...text3(type.size.body+1,type.lineHeight.snug,color.text.primary,"bold"),padding:`0 ${space.sm}px`},subLead:{...text3(type.size.body,type.lineHeight.normal,color.text.muted),padding:`0 ${space.lg}px ${space.md}px`},field:{boxSizing:"border-box",display:"block",width:"100%",minHeight:MIN_TOUCH_TARGET,padding:`${space.sm}px ${space.md}px`,border:`1px solid ${color.borderHairlineGreen}`,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...faceCss(theme,"regular"),fontSize:type.size.body},fieldLabel:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary,"medium"),display:"block",marginBottom:space.xs},muted:text3(type.size.caption,type.lineHeight.normal,color.text.muted),bodyText:text3(type.size.body,type.lineHeight.normal,color.text.primary),mono:faceCss(theme,"mono"),plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},dialogFrame:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",margin:0,padding:0,border:0,backgroundColor:"transparent",overflow:"hidden"},dialogScrim:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",padding:space.lg,backgroundColor:"rgba(0,0,0,0.4)"},dialogScrimSide:{boxSizing:"border-box",display:"flex",alignItems:"stretch",justifyContent:"flex-end",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.4)"},dialogPanel:{boxSizing:"border-box",width:"100%",maxWidth:560,maxHeight:"100%",overflowY:"auto",backgroundColor:color.surface,borderRadius:radius.xl-1,padding:`${space.lg}px ${space.lg+space.xs+space.xs/2}px`,display:"flex",flexDirection:"column",gap:space.md,...faceCss(theme,"regular"),color:color.text.primary},dialogPanelSide:{boxSizing:"border-box",width:"min(100vw, 480px)",height:"100%",maxHeight:"100%",overflowY:"auto",backgroundColor:color.surface,padding:`${space.lg}px ${space.lg+space.xs+space.xs/2}px`,display:"flex",flexDirection:"column",gap:space.md,...faceCss(theme,"regular"),color:color.text.primary},sheetHeader:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},sheetTitle:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},sheetHelper:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),closeGlyph:{fontSize:type.size.verdict,lineHeight:1,color:color.text.primary}}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}function formatShortDate(at){if(at===null||at.length===0)return"";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){let year=iso[1]??"",month=iso[2]??"",day=iso[3]??"";return`${Number(month)}/${Number(day)}/${year.slice(2)}`}let ms=Date.parse(at);if(Number.isNaN(ms))return at;let date=new Date(ms);return`${date.getUTCMonth()+1}/${date.getUTCDate()}/${String(date.getUTCFullYear()).slice(2)}`}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){let month=MONTHS[Number(iso[2])-1];return month===void 0?"-":`${month} ${Number(iso[3])}, ${iso[1]}`}let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date=new Date(ms);return`${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}`}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}var DEPTH_COPY=/* @__PURE__ */Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:date=>`Measured ${date}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date=>`Expires ${date}`});function markerStatusLabel(status){switch(status){case"above":return{label:"Above range",outOfRange:true};case"below":return{label:"Below range",outOfRange:true};case"in_range":return{label:"In range",outOfRange:false};default:return{label:"No range on file",outOfRange:false}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num3=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num3} ${unit}`:num3}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var RECORDS_EMPTY_COPY=/* @__PURE__ */Object.freeze({idle:/* @__PURE__ */Object.freeze({title:"Find your pet’s clinic",body:"Search for the clinic that holds your pet’s records. We’ll request them on your behalf once you sign the authorization.",action:null}),no_requests:/* @__PURE__ */Object.freeze({title:"No record requests yet",body:"When you request records from a clinic, you’ll be able to track every step here.",action:null}),no_records:/* @__PURE__ */Object.freeze({title:"Nothing to show just yet",body:"Once your pet’s records arrive and our team reviews them, lab trends and visits will appear here.",action:null}),rate_limited:/* @__PURE__ */Object.freeze({title:"Slow down a moment",body:"You’ve made a lot of requests just now. You can try again shortly.",action:"Try again"}),service_unavailable:/* @__PURE__ */Object.freeze({title:"Records search is temporarily down",body:"We’re working on it. Please try again in a few minutes.",action:"Try again"}),error:/* @__PURE__ */Object.freeze({title:"Couldn’t reach Everfur",body:"Check your connection and try again.",action:"Try again"})}),RATE_LIMIT_COOLDOWN_S=60;function coolingActionLabel(seconds){return`Try again in ${seconds}s`}var COOLING_A11Y_LABEL="Try again, available shortly";var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:/* @__PURE__ */Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date=>`Last done ${date}`,overdue:"Overdue",due:date=>`Due ${date}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date=>`Generated ${formatRecordsDate(date)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){case"identity_risk":return{label:"Identity mismatch",rank:0,tone:"critical"};case"benign":return{label:"Minor difference",rank:2,tone:"neutral"};default:return{label:"Needs review",rank:1,tone:"warning"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:/* @__PURE__ */Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date=formatRecordsDate(expiresAt);return date==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date}`:`Expires ${date}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
|
|
132
|
+
return Object.freeze([...rows.filter(r=>r.active),...rows.filter(r=>!r.active)])}function shareErrorMessage(error,action){let status=error?.httpStatus;if(isRecordsConsentRequired(error)){if(action==="create"||action==="email")return"Records access for this pet is off, so a new link cannot be created.";if(action==="download")return"Records access for this pet is off, so the PDF cannot be downloaded."}if(status===429)return"You are creating links a little too fast. Wait a moment, then try again.";if(action==="revoke"&&(status===404||status===409||status===410))return"That link was already turned off.";if(status===401||status===403)return"You need to be signed in as this pet's owner to do that.";if(action==="email"&&(status===400||status===422||error?.code==="validationFailed"))return SHARE_COPY.emailInvalid;switch(action){case"create":return"Could not create a share link. Please try again.";case"revoke":return"Could not turn off that link. Please try again.";case"email":return SHARE_COPY.emailFailed;default:return"Could not download the record PDF. Please try again."}}function SkeletonBlock({width:width,height:height,radius:radius,style:style}){let{color:color,radius:radii}=useEverfurTheme();/* @__PURE__ */
|
|
133
|
+
return jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:width,height:height,borderRadius:radius??radii.xs,backgroundColor:color.skeleton,flexShrink:0,...style}})}var DONUT=180,DISCLAIMER_H=44,TIMELINE_SEPARATOR_INSET=62;function DashboardSkeleton({testID:testID}){let s=useStyles(),action=key=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.actionRow,children:[
|
|
134
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.actionLeft,children:[
|
|
135
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:18,height:18,radius:9}),
|
|
136
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"55%",height:14,radius:7})]}),
|
|
137
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:18,height:18,radius:9})]},key);/* @__PURE__ */
|
|
138
|
+
return jsxRuntime.jsxs("div",{role:"progressbar","aria-label":DASHBOARD_COPY.loading,"aria-busy":"true",style:s.dashboard,"data-testid":testID,children:[
|
|
139
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.inset,children:/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.summaryCard,children:[
|
|
140
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:DONUT,height:DONUT,radius:DONUT/2}),
|
|
141
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.badges,children:[
|
|
142
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:70,height:22,radius:11}),
|
|
143
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:70,height:22,radius:11})]})]})}),
|
|
144
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.inset,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:150,height:16,radius:8})}),
|
|
145
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.carouselCard,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:300,radius:14})}),
|
|
146
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.dots,children:[
|
|
147
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:6,height:6,radius:3}),
|
|
148
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:18,height:6,radius:3}),
|
|
149
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:6,height:6,radius:3})]}),
|
|
150
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.centered,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:46,height:12,radius:6})}),
|
|
151
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.inset,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:DISCLAIMER_H,radius:12})}),
|
|
152
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...s.inset,...s.actions},children:[action("a"),action("b")]})]})}function RequestSkeleton({testID:testID}){let s=useStyles();/* @__PURE__ */
|
|
153
|
+
return jsxRuntime.jsxs("div",{role:"progressbar","aria-label":REQUEST_SCREEN_COPY.loading,"aria-busy":"true",style:s.request,"data-testid":testID,children:[
|
|
154
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{children:[0,1,2,3].map(index=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.railRow,children:[
|
|
155
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.railColumn,children:[
|
|
156
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:24,height:24,radius:12}),index<3?/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:2,height:20,radius:1}):null]}),
|
|
157
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.railBody,children:[
|
|
158
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"55%",height:14,radius:7}),
|
|
159
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"75%",height:11,radius:6})]})]},index))}),
|
|
160
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.statusCard,children:[
|
|
161
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"90%",height:13,radius:6}),
|
|
162
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"60%",height:13,radius:6})]}),
|
|
163
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:50,radius:25})]})}function TimelineSkeleton({testID:testID}){let s=useStyles();/* @__PURE__ */
|
|
164
|
+
return jsxRuntime.jsxs("div",{role:"progressbar","aria-label":DEPTH_COPY.loadingTimeline,"aria-busy":"true",style:s.timeline,"data-testid":testID,children:[
|
|
165
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.timelineDisclaimer,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:DISCLAIMER_H,radius:12})}),Array.from({length:6},(_,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{children:[index>0?/* @__PURE__ */jsxRuntime.jsx("div",{style:s.timelineSeparator}):null,
|
|
166
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.timelineRow,children:[
|
|
167
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:34,height:34,radius:17}),
|
|
168
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.timelineBody,children:[
|
|
169
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.timelineTop,children:[
|
|
170
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:44,height:10,radius:5}),
|
|
171
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:56,height:12,radius:6})]}),
|
|
172
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"70%",height:14,radius:7}),index%2===0?/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"45%",height:12,radius:6}):null]})]})]},index))]})}function ClinicsSkeleton({testID:testID}){let s=useStyles();/* @__PURE__ */
|
|
173
|
+
return jsxRuntime.jsx("div",{role:"progressbar","aria-label":CLINIC_PICKER_COPY.loading,"aria-busy":"true",style:s.clinics,"data-testid":testID,children:Array.from({length:5},(_,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.clinicRow,children:[
|
|
174
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"65%",height:14,radius:7}),
|
|
175
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"40%",height:11,radius:6})]},index))})}function SharesSkeleton({testID:testID}){let s=useStyles();/* @__PURE__ */
|
|
176
|
+
return jsxRuntime.jsx("div",{role:"progressbar","aria-label":SHARE_COPY.loadingLinks,"aria-busy":"true",style:s.shares,"data-testid":testID,children:[0,1].map(index=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.shareRow,children:[
|
|
177
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"55%",height:13}),
|
|
178
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"40%",height:11})]},index))})}function RecordsEmptyState({variant:variant,onAction:onAction,message:message,testID:testID}){let s=useStyles(),copy=RECORDS_EMPTY_COPY[variant],[cooldown,setCooldown]=react.useState(variant==="rate_limited"?RATE_LIMIT_COOLDOWN_S:0);react.useEffect(()=>{variant==="rate_limited"&&setCooldown(RATE_LIMIT_COOLDOWN_S)},[variant]),react.useEffect(()=>{if(cooldown<=0)return;let handle=setTimeout(()=>setCooldown(n=>Math.max(0,n-1)),1e3);return()=>clearTimeout(handle)},[cooldown]);let cooling=variant==="rate_limited"&&cooldown>0,label=cooling?coolingActionLabel(cooldown):copy.action;/* @__PURE__ */
|
|
179
|
+
return jsxRuntime.jsxs("section",{role:"status",style:s.empty,"data-testid":testID,children:[
|
|
180
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:s.emptyGlyph}),
|
|
181
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:s.emptyTitle,children:copy.title}),
|
|
182
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:s.emptyBody,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onAction,disabled:cooling,"aria-label":cooling?COOLING_A11Y_LABEL:label,style:{...s.emptyAction,...cooling?s.emptyActionDisabled:{}},"data-testid":testID?`${testID}-action`:`records-empty-${variant}-action`,children:label}):null]})}function useStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles2(theme),[theme])}function makeStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=`1px solid ${color.brandBorder}`;return{dashboard:{display:"flex",flexDirection:"column",gap:space.lg,padding:`${space.xs}px ${space.sm}px 0`,backgroundColor:color.background},inset:{padding:`0 ${space.sm}px`},summaryCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.md+space.xs/2,borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:`${space.lg+space.xs}px ${space.lg}px`},badges:{display:"flex",gap:space.md},carouselCard:{borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:space.lg},dots:{display:"flex",alignItems:"center",justifyContent:"center",gap:space.xs+space.xs/2},centered:{display:"flex",justifyContent:"center"},actions:{display:"flex",flexDirection:"column",gap:space.sm+space.xs/2},actionRow:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:radius.md,border:hairline,backgroundColor:color.surface,padding:space.lg},actionLeft:{flex:1,display:"flex",alignItems:"center",gap:space.md},request:{display:"flex",flexDirection:"column",gap:space.lg+space.xs/2,padding:`${space.xs}px ${space.lg}px 0`},railRow:{display:"flex",alignItems:"flex-start",gap:space.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.xs/2,width:24},railBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs+space.xs/2,paddingBottom:space.lg+space.xs/2},statusCard:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},timeline:{backgroundColor:color.background},timelineDisclaimer:{padding:`${space.xs}px ${space.lg}px ${space.md}px`},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1},timelineTop:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm},timelineSeparator:{height:1,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},clinics:{display:"flex",flexDirection:"column",gap:space.md},clinicRow:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.lg-space.xs/2,border:hairline,backgroundColor:color.surface,padding:`${space.md+space.xs/2}px`},shares:{display:"flex",flexDirection:"column",gap:space.md,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline},shareRow:{display:"flex",flexDirection:"column",gap:space.xs+space.xs/2},empty:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm+space.xs/2,padding:`${space.xxl}px ${space.xl}px`,textAlign:"center"},emptyGlyph:{boxSizing:"border-box",width:22,height:22,borderRadius:11,backgroundColor:color.brandSoft,border:hairline,marginBottom:space.xs},emptyTitle:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:`${Math.round(type.size.subtitle*type.lineHeight.snug)-1}px`,color:color.brandInk},emptyBody:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:`${Math.round(type.size.bodyTight*type.lineHeight.normal)}px`,color:color.text.muted,maxWidth:320},emptyAction:{boxSizing:"border-box",marginTop:space.sm,minHeight:40,borderRadius:radius.pill,padding:`0 ${space.lg+space.xs/2}px`,backgroundColor:color.brand,color:color.onPrimary,border:0,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.bodyTight},emptyActionDisabled:{opacity:.5,cursor:"default"}}}var EMAIL=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function EverfurClinicPicker(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
183
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,className:props.className,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(PickerBody,{...guardHostProps(props,["onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef]))})}function PickerBody({petRef:petRef,petName:petName,controller:controller,recordsController:recordsController,location:location2,onNavigate:onNavigate,onBack:onBack,style:style,className:className}){let{theme:theme,styles:styles}=useScreenStyles(),runtimeController=useEverfurRecordsClinic(),picker=useClinicPicker(controller??runtimeController,location2),records=useEverfurRecords(recordsController?{petRef:petRef,controller:recordsController}:{petRef:petRef}),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),[starting,setStarting]=react.useState(false),[startError,setStartError]=react.useState(null),[fallbackOpen,setFallbackOpen]=react.useState(false),[fallbackName,setFallbackName]=react.useState(""),[fallbackNameDirty,setFallbackNameDirty]=react.useState(false),[fallbackEmail,setFallbackEmail]=react.useState(""),[fallbackTouched,setFallbackTouched]=react.useState(false),select=react.useCallback(clinic=>{onNavigate?.({name:"consent",clinic:clinicDraftFor(clinic,null,"",keyFactory.current())})},[onNavigate]),startUpload=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}))},displayName=fallbackNameDirty?fallbackName:picker.query,fallbackEmailValid=EMAIL.test(fallbackEmail.trim()),canContinue=displayName.trim().length>0&&fallbackEmailValid,fallbackEmailWrong=fallbackTouched&&fallbackEmail.trim().length>0&&!fallbackEmailValid,listData=picker.isSearchActive?picker.clinics:picker.recent,emptyVariant=picker.isSearchActive?picker.error?recordsEmptyVariantForError(picker.error):!picker.initialLoading&&picker.clinics.length===0?"idle":null:picker.recent.length>0||picker.recentLoading?null:"idle",block={display:"flex",flexDirection:"column",gap:theme.space.sm},resultsAnnouncement=picker.isSearchActive&&!picker.initialLoading&&!picker.error&&picker.clinics.length>0?CLINIC_PICKER_COPY.resultsCountDraft(picker.clinics.length):"",onScroll=event=>{let el=event.currentTarget;el.scrollTop+el.clientHeight>=el.scrollHeight-el.clientHeight*.6&&picker.loadMore()};/* @__PURE__ */
|
|
184
|
+
return jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-clinic-picker",children:[
|
|
185
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:CLINIC_PICKER_COPY.titleFor(petName),onBack:onBack,testID:"records-clinic-header"}),
|
|
186
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.subLead,"data-testid":"records-clinic-lead",children:CLINIC_PICKER_COPY.leadWeb}),
|
|
187
|
+
/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:"records-clinic-search",style:{...styles.fieldLabel,padding:`0 ${theme.space.lg}px`},children:CLINIC_PICKER_COPY.searchLabelWeb}),
|
|
188
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm,margin:`0 ${theme.space.lg}px ${theme.space.sm}px`,padding:`0 ${theme.space.md+theme.space.xs/2}px`,height:44,borderRadius:22,backgroundColor:theme.color.surfaceSubtle,border:`1px solid ${theme.color.borderHairlineGreen}`},children:[
|
|
189
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{id:"records-clinic-search",type:"search",value:picker.query,onChange:event=>picker.setQuery(event.target.value),placeholder:CLINIC_PICKER_COPY.placeholder,maxLength:200,autoComplete:"off",style:{flex:1,border:0,background:"transparent",font:"inherit",fontSize:theme.type.size.body,color:theme.color.text.primary,outline:"none"},"data-testid":"records-clinic-search-input"}),picker.query.length>0?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>picker.setQuery(""),"aria-label":CLINIC_PICKER_COPY.clearSearch,style:{...styles.iconButton,width:32,height:32},"data-testid":"records-clinic-search-clear",children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.closeGlyph,children:"×"})}):null]}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...block,padding:`0 ${theme.space.lg}px ${theme.space.md}px`},children:[startError?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.errorBanner,children:startError}):null,
|
|
190
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:starting?CLINIC_PICKER_COPY.uploadOwnStarting:CLINIC_PICKER_COPY.uploadOwn,kind:"outline",busy:starting,onClick:startUpload,testID:"records-clinic-upload-own"})]}):null,
|
|
191
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:VISUALLY_HIDDEN,"data-testid":"records-clinic-results-status",children:resultsAnnouncement}),
|
|
192
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...styles.body,...styles.content,gap:theme.space.md},onScroll:picker.isSearchActive?onScroll:void 0,"data-testid":"records-clinic-results",children:[picker.isSearchActive?/* @__PURE__ */jsxRuntime.jsxs("section",{style:{...styles.creamCard,borderStyle:"dashed",padding:`${theme.space.md}px ${theme.space.md+theme.space.xs/2}px`},"data-testid":"records-clinic-fallback-card",children:[
|
|
193
|
+
/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",onClick:()=>setFallbackOpen(open=>!open),"aria-expanded":fallbackOpen,style:{display:"flex",alignItems:"center",gap:theme.space.md,width:"100%",minHeight:44,background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},"data-testid":"records-clinic-fallback",children:[
|
|
194
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:{flex:1,display:"flex",flexDirection:"column",gap:theme.space.xs/2},children:[
|
|
195
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold")},children:CLINIC_PICKER_COPY.fallback.title}),
|
|
196
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.muted,children:CLINIC_PICKER_COPY.fallback.subtitle})]}),
|
|
197
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{direction:fallbackOpen?"up":"down"})]}),fallbackOpen?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[
|
|
198
|
+
/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:"records-clinic-fallback-name",style:styles.fieldLabel,children:CLINIC_PICKER_COPY.fallback.nameLabel}),
|
|
199
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{id:"records-clinic-fallback-name",style:styles.field,value:displayName,onChange:event=>{setFallbackName(event.target.value),setFallbackNameDirty(true)},placeholder:CLINIC_PICKER_COPY.fallback.namePlaceholder,maxLength:200,autoComplete:"off","data-testid":"records-clinic-fallback-name"}),
|
|
200
|
+
/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:"records-clinic-fallback-email",style:styles.fieldLabel,children:CLINIC_PICKER_COPY.fallback.emailLabel}),
|
|
201
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{id:"records-clinic-fallback-email",type:"email",style:styles.field,value:fallbackEmail,onChange:event=>{setFallbackEmail(event.target.value),setFallbackTouched(false)},onBlur:()=>setFallbackTouched(true),placeholder:CLINIC_PICKER_COPY.fallback.emailPlaceholder,maxLength:320,autoComplete:"off","aria-invalid":fallbackEmailWrong?true:void 0,"aria-describedby":fallbackEmailWrong?"records-clinic-fallback-email-error":void 0,"data-testid":"records-clinic-fallback-email"}),fallbackEmailWrong?/* @__PURE__ */jsxRuntime.jsx("p",{id:"records-clinic-fallback-email-error",role:"alert",style:styles.errorText,children:REQUEST_SCREEN_COPY.errors.invalidEmail}):null,
|
|
202
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:CLINIC_PICKER_COPY.fallback.reviewNote}),
|
|
203
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_PICKER_COPY.fallback.submit,disabled:!canContinue||!onNavigate,onClick:()=>onNavigate?.({name:"consent",clinic:clinicDraftFor(null,displayName.trim(),fallbackEmail.trim().toLowerCase(),keyFactory.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):picker.recent.length>0?/* @__PURE__ */jsxRuntime.jsx("h3",{style:{...styles.fieldLabel,...faceCss(theme,"bold"),textTransform:"uppercase",marginBottom:0},"data-testid":"records-clinic-recent-label",children:CLINIC_PICKER_COPY.recentlyUsed}):null,picker.isSearchActive&&picker.initialLoading?/* @__PURE__ */jsxRuntime.jsx(ClinicsSkeleton,{testID:"records-clinic-page-loading"}):null,
|
|
204
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:{...styles.plainList,gap:theme.space.md},children:listData.map(clinic=>{let badge=clinicEmailStatusBadge(clinic.emailStatus),distance=formatClinicDistanceLabel(clinic.distanceKm),summary=[clinic.name,clinic.address,clinic.phone?`phone ${clinic.phone}`:null,distance?formatClinicDistanceForA11y(clinic.distanceKm):null,badge.a11y].filter(Boolean).join(", "),tone=badge.tone==="positive"?{backgroundColor:theme.color.badgeBgPositive,color:theme.color.success}:badge.tone==="caution"?{backgroundColor:theme.color.badgeBgCaution,color:theme.color.cautionAccent}:{backgroundColor:theme.color.badgeBgNeutral,color:theme.color.text.muted};/* @__PURE__ */
|
|
205
|
+
return jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",onClick:()=>select(clinic),"aria-label":CLINIC_PICKER_COPY.selectA11y(summary),style:{...styles.creamCard,backgroundColor:theme.color.surface,width:"100%",textAlign:"left",cursor:"pointer",gap:theme.space.sm,padding:`${theme.space.md}px ${theme.space.md+theme.space.xs/2}px`,font:"inherit",color:"inherit"},"data-testid":`records-clinic-${clinic.id}`,children:[
|
|
206
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm},children:[
|
|
207
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold"),color:theme.color.brandInk},children:clinic.name}),distance?/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...styles.muted,...styles.mono},children:distance}):null]}),clinic.address?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowDetail,children:clinic.address}):null,clinic.phone?/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.rowMuted,children:clinic.phone}):null,
|
|
208
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...styles.chip,...tone,...faceCss(theme,"bold"),fontSize:theme.type.size.micro,alignSelf:"flex-start"},children:badge.label})]})},clinic.id)})}),emptyVariant&&!picker.initialLoading?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:emptyVariant,message:picker.isSearchActive&&emptyVariant==="idle"?CLINIC_PICKER_COPY.noMatch(picker.debouncedQuery):picker.error?.displayMessage,onAction:picker.error?.retryable===true?picker.retry:void 0,testID:"records-clinic-empty"}):null,
|
|
209
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[picker.loadingMore?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:{...styles.muted,textAlign:"center"},"data-testid":"records-clinic-loading-more",children:CLINIC_PICKER_COPY.loadingMore}):null,picker.pageError?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:picker.loadMore,style:{...styles.pill,...styles.pillLink},"data-testid":"records-clinic-page-error-retry",children:CLINIC_PICKER_COPY.loadMoreFailed}):null]}),
|
|
210
|
+
/* @__PURE__ */jsxRuntime.jsx(HowItWorks,{petName:petName})]}),
|
|
211
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function HowItWorks({petName:petName}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
212
|
+
return jsxRuntime.jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surfaceSubtle,border:0},"aria-label":CLINIC_PICKER_COPY.howItWorks,"data-testid":"records-clinic-how",children:[
|
|
213
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sectionTitle,children:CLINIC_PICKER_COPY.howItWorks}),
|
|
214
|
+
/* @__PURE__ */jsxRuntime.jsx("ol",{style:{...styles.plainList,gap:theme.space.md},children:CLINIC_PICKER_COPY.howSteps(petNameOr(petName)).map((step,index)=>/* @__PURE__ */jsxRuntime.jsxs("li",{style:{display:"flex",gap:theme.space.md},children:[
|
|
215
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...styles.mono,...faceCss(theme,"monoBold"),fontSize:theme.type.size.caption,color:theme.color.brandInk,minWidth:theme.space.xl},children:String(index+1).padStart(2,"0")}),
|
|
216
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs/2},children:[
|
|
217
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold")},children:step.title}),
|
|
218
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowDetail,children:step.body})]})]},step.title))})]})}var CLINIC_BATCH_COPY=/* @__PURE__ */Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${RECORDS_CLINIC_BATCH_MAX} clinics`,send:n=>`Send ${n} ${n===1?"request":"requests"}`,sending:"Sending…",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:name=>`Remove ${name}`,emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn’t send any of these requests. See the details below and try again.",partial:(created,total,failed)=>`${created} of ${total} requests sent. ${failed} couldn’t be sent.`,allSent:created=>`${created} ${created===1?"request":"requests"} sent.`,responded:(responded,total)=>`${responded} of ${total} ${total===1?"clinic":"clinics"} responded`});var CLINIC_FORM_SEARCH_LIMIT=25,CLINIC_FORM_RESULTS_STEP=5;function useVisibleClinics(clinics){let[state,setState]=react.useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=react.useCallback(()=>{setState(previous=>({list:clinics,shown:(previous.list===clinics?previous.shown:CLINIC_FORM_RESULTS_STEP)+CLINIC_FORM_RESULTS_STEP}))},[clinics]);return{visible:clinics.slice(0,shown),hasMore:clinics.length>shown,showMore:showMore}}var SignatureUploadLegError=class extends Error{constructor(){super("Signature upload failed"),this.name="SignatureUploadLegError"}};function isSignatureUploadLegFailure(error){return error instanceof SignatureUploadLegError}var MAX_INLINE_SIGNATURE_BASE64=2*1024*1024;function inlineSignatureFits(base64){return base64.length>0&&base64.length<=MAX_INLINE_SIGNATURE_BASE64}function renderClinicScope(copy,owner,pet,clinic){let fields={owner_name:owner,pet_name:pet,clinic_name:clinic},unknown=false,text3=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text3)?null:text3}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinic,setClinic]=react.useState(null),[email2,setEmail]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[created,setCreated]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null),captureAbort=react.useRef(null),lifetime=react.useRef(0);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,attempt.current=null,captureAbort.current?.abort()}),[controller]),react.useEffect(()=>{let live=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let invalidate=()=>{attempt.current=null,setError(null)},clinicName=clinic?.name??query.trim(),scope=copy?renderClinicScope(copy,ownerName.trim(),props.petName,clinicName):null,needsEmail=clinicNeedsEmail(clinic),results=useVisibleClinics(clinics),ready=!!(copy&&scope&&ownerName.trim()&&props.petName.trim()&&clinicName&&(!needsEmail||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email2.trim()))&&capture),search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},submit=async()=>{if(locked.current||created||!ready||!copy||!scope||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(!attempt.current){captureAbort.current=new AbortController;let signature=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:clinicName,authorizationVersion:copy.authorizationVersion,scopeText:scope,signal:captureAbort.current.signal});if(!current()||signature===null)return;let target=clinic&&(!needsEmail||clinic.emailStatus==="none")?{clinicId:clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:email2.trim().toLowerCase()}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}if(!current())return;let result=await controller.createClinicRequest(attempt.current);if(!current())return;if(!result.ok){setError(result.error);return}if(result.value.petRef!==props.petRef){setError(makeEverfurError("internalError"));return}setCreated(result.value),attempt.current=null,props.onCreated?.(result.value)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}};return{ownerName:ownerName,query:query,clinic:clinic,email:email2,clinics:clinics,copy:copy,scope:scope,error:error,busy:busy,searching:searching,created:created,ready:ready,needsEmail:needsEmail,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0&&clinic===null?recent:[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(null),setEmail(""),setQueryValue(value))},setEmail(value){locked.current||(invalidate(),setEmail(value))},selectClinic(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(value),setQueryValue(value.name),setEmail(""))},invalidate:invalidate,search:search,submit:submit,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var EMAIL2=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function draftName(draft){return draft.clinic?.name??draft.freeText??""}function draftNeedsEmail(draft){return clinicNeedsEmail(draft.clinic)}function useClinicBatchForm(props,controller,batchClient,capture,registerSignature){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[drafts,setDrafts]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[outcome,setOutcome]=react.useState(null),[group,setGroup]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),lifetime=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),signature=react.useRef(null),captureAbort=react.useRef(null);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,signature.current=null,captureAbort.current?.abort()}),[controller,batchClient]),react.useEffect(()=>{let live=true;return setCopy(null),signature.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let results=useVisibleClinics(clinics),invalidate=()=>{signature.current=null,setError(null)},names=drafts.map(draftName),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),props.petName,name)):[],scopeText=scopes.every(s=>s!==null)?scopes.join(`\n\n`):null,draftsReady=drafts.length>0&&drafts.every(draft=>!draftNeedsEmail(draft)||EMAIL2.test(draft.email.trim())),atCap=drafts.length>=RECORDS_CLINIC_BATCH_MAX,ready=!!(copy&&scopeText&&ownerName.trim()&&props.petName.trim()&&draftsReady&&capture)&&outcome===null,search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},add=draft=>{locked.current||atCap||outcome!==null||draft.clinic!==null&&drafts.some(d=>d.clinic?.id===draft.clinic?.id)||(invalidate(),setDrafts(current=>[...current,{...draft,key:keyFactory.current(),idempotencyKey:keyFactory.current()}]),setClinics([]),setQueryValue(""))},submit=async()=>{if(locked.current||outcome!==null||!ready||!copy||!scopeText||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(signature.current===null){captureAbort.current=new AbortController;let captured=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:names.join(", "),authorizationVersion:copy.authorizationVersion,scopeText:scopeText,signal:captureAbort.current.signal});if(!current()||captured===null)return;if(signature.current=captured,captured.signaturePngBase64!==void 0&®isterSignature!==void 0);}let signed=signature.current,items=drafts.map(draft=>({...draft.clinic!==null&&(!draftNeedsEmail(draft)||draft.clinic.emailStatus==="none")?{clinicId:draft.clinic.id}:{clinicFreeText:draftName(draft)},...draftNeedsEmail(draft)?{clinicEmail:draft.email.trim().toLowerCase()}:{},...signed.signatureId!==void 0?{signatureId:signed.signatureId}:{signaturePngBase64:signed.signaturePngBase64},idempotencyKey:draft.idempotencyKey})),result=await batchClient.createClinicRequestBatch({petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,clinics:items});if(!current())return;if(!result.ok){setError(result.error);return}setOutcome(result.value),props.onCreated?.(result.value),loadGroup(result.value.requestGroupId,run)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}},loadGroup=async(requestGroupId,run)=>{try{let result=await controller.getRequestGroup(requestGroupId);if(!active.current||lifetime.current!==run)return;result.ok&&result.value.petRef===props.petRef&&setGroup(result.value)}catch{}},refreshGroup=async()=>{outcome===null||locked.current||await loadGroup(outcome.requestGroupId,lifetime.current)};return{ownerName:ownerName,query:query,clinics:clinics,copy:copy,scopeText:scopeText,error:error,busy:busy,searching:searching,drafts:drafts,outcome:outcome,group:group,ready:ready,atCap:atCap,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0?recent.filter(clinic=>!drafts.some(d=>d.clinic?.id===clinic.id)):[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(generation.current+=1,setSearching(false),setClinics([]),setQueryValue(value))},search:search,addClinic(clinic){add({clinic:clinic,freeText:null,email:""})},addFreeText(){let name=query.trim();name.length!==0&&add({clinic:null,freeText:name,email:""})},setDraftEmail(key,email2){locked.current||(invalidate(),setDrafts(current=>current.map(draft=>draft.key===key?{...draft,email:email2}:draft)))},removeDraft(key){locked.current||outcome!==null||(invalidate(),setDrafts(current=>current.filter(draft=>draft.key!==key)))},submit:submit,refreshGroup:refreshGroup,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}function trustedSignatureUploadUrl(value){try{let url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.port&&url.port!=="443")return!1;let host=url.hostname.toLowerCase();return host==="s3.amazonaws.com"||host.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(host)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(host)||host==="s3-accelerate.amazonaws.com"||host.endsWith(".s3-accelerate.amazonaws.com")||host==="s3-accelerate.dualstack.amazonaws.com"||host.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}function paintClinicTypedSignature(context,name,width,height){context.clearRect(0,0,width,height);let text3=name.trim();if(!text3)return;let maxWidth=Math.max(1,width-32),size=Math.min(44,Math.max(16,Math.round(height*.34))),font=()=>{context.font=`italic 700 ${size}px Georgia, "Times New Roman", serif`};for(font();size>12&&context.measureText(text3).width>maxWidth;)size-=2,font();context.textAlign="center",context.textBaseline="middle",context.fillText(text3,width/2,height/2,maxWidth)}function paintSignatureStrokes(context,strokes,width,height){context.clearRect(0,0,width,height);for(let points of strokes){let first=points[0];if(first!==void 0){context.beginPath(),context.moveTo(first[0],first[1]),points.length===1&&context.lineTo(first[0],first[1]);for(let index=1;index<points.length;index+=1){let point=points[index];point!==void 0&&context.lineTo(point[0],point[1])}context.stroke()}}}async function registerClinicSignature(canvas,controller,signal,fetchImpl=fetch){return uploadClinicSignature(await canvasPng(canvas,signal),controller,signal,fetchImpl)}async function captureClinicSignature(canvas,controller,signal,fetchImpl=fetch){let png=await canvasPng(canvas,signal);try{return await uploadClinicSignature(png,controller,signal,fetchImpl)}catch(error){if(!isSignatureUploadLegFailure(error)||signal.aborted)throw failure()}let inline=await blobBase64(png);if(!inlineSignatureFits(inline)||signal.aborted)throw failure();return{signaturePngBase64:inline}}var failure=()=>new Error("Signature upload failed");async function canvasPng(canvas,signal){let png=await new Promise(resolve=>canvas.toBlob(resolve,"image/png"));if(!png||!png.size||png.size>2*1024*1024||signal.aborted)throw failure();return png}async function uploadClinicSignature(png,controller,signal,fetchImpl){let initiated=await controller.initiateSignatureUpload(png.size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw failure();let body=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))body.append(key,value);body.append("file",png,"signature.png");let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,9e4);try{if(!(await fetchImpl(initiated.value.uploadUrl,{method:"POST",body:body,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:uploadAbort.signal})).ok||signal.aborted)throw failure()}catch{throw signal.aborted?failure():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw failure();return{signatureId:completed.value}}function blobBase64(blob){return new Promise((resolve,reject)=>{let reader=new FileReader;reader.onload=()=>{let url=typeof reader.result=="string"?reader.result:"",comma=url.indexOf(",");comma<0?reject(failure()):resolve(url.slice(comma+1))},reader.onerror=()=>reject(failure()),reader.readAsDataURL(blob)})}var MIN_DRAWN_POINTS=8,DEFAULT_PAD_WIDTH=480,DEFAULT_PAD_HEIGHT=160;function useSignatureCanvas(onEdit){let canvas=react.useRef(null),drawing=react.useRef(false),strokes=react.useRef([]),[mode,setMode]=react.useState("draw"),[typed,setTypedValue]=react.useState(""),[signed,setSigned]=react.useState(false),typedRef=react.useRef(typed);typedRef.current=typed;let repaint=react.useCallback(()=>{let element=canvas.current,ctx=element?.getContext("2d");if(!element||!ctx)return;let ratio=typeof window<"u"&&window.devicePixelRatio||1;ctx.setTransform(ratio,0,0,ratio,0,0);let width=element.width/ratio,height=element.height/ratio;if(typedRef.current.trim().length>0){ctx.fillStyle="#111",paintClinicTypedSignature(ctx,typedRef.current,width,height);return}ctx.lineWidth=2,ctx.lineCap="round",ctx.lineJoin="round",ctx.strokeStyle="#111",paintSignatureStrokes(ctx,strokes.current,width,height)},[]);react.useEffect(()=>{let element=canvas.current;if(!element)return;let resize=()=>{let rect=element.getBoundingClientRect(),ratio=typeof window<"u"&&window.devicePixelRatio||1,width=Math.max(1,Math.round((rect.width||element.clientWidth||DEFAULT_PAD_WIDTH)*ratio)),height=Math.max(1,Math.round((rect.height||element.clientHeight||DEFAULT_PAD_HEIGHT)*ratio));element.width!==width&&(element.width=width),element.height!==height&&(element.height=height),repaint()};if(resize(),typeof ResizeObserver>"u")return;let observer=new ResizeObserver(resize);return observer.observe(element),()=>observer.disconnect()},[repaint]);let clear=react.useCallback(()=>{onEdit?.(),strokes.current=[],setSigned(false),setTypedValue(""),typedRef.current="",repaint()},[onEdit,repaint]),point=event=>{let rect=event.currentTarget.getBoundingClientRect();return[event.clientX-rect.left,event.clientY-rect.top]},countPoints=()=>strokes.current.reduce((total,stroke)=>total+stroke.length,0);return{canvas:canvas,mode:mode,typed:typed,signed:signed,clear:clear,setTyped(value){onEdit?.(),setTypedValue(value),typedRef.current=value,setSigned(!!value.trim()),repaint()},toggle(){clear(),setMode(m=>m==="draw"?"type":"draw")},onPointerDown(event){mode==="draw"&&(onEdit?.(),drawing.current=true,event.currentTarget.setPointerCapture(event.pointerId),strokes.current=[...strokes.current,[point(event)]],repaint())},onPointerMove(event){if(!drawing.current||mode!=="draw")return;let current=strokes.current[strokes.current.length-1];current!==void 0&&(strokes.current=[...strokes.current.slice(0,-1),[...current,point(event)]],repaint(),setSigned(countPoints()>=MIN_DRAWN_POINTS))},onPointerUp(){drawing.current=false},register(controller,signal){return!canvas.current||!signed?Promise.reject(new Error("Signature upload failed")):registerClinicSignature(canvas.current,controller,signal)},capture(controller,signal){return!canvas.current||!signed?Promise.reject(new Error("Signature upload failed")):captureClinicSignature(canvas.current,controller,signal)}}}function SignatureCanvas({pad:pad,disabled:disabled}){let theme=useEverfurTheme(),typedName=pad.mode==="type"?pad.typed.trim():"",field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},button={...field,cursor:"pointer"};/* @__PURE__ */
|
|
219
|
+
return jsxRuntime.jsxs("div",{children:[
|
|
220
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{margin:`0 0 ${theme.space.sm}px`},children:pad.mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),
|
|
221
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:{...button,alignSelf:"flex-start",marginBottom:theme.space.sm,textDecoration:"underline"},disabled:disabled,onClick:pad.toggle,"data-testid":"records-consent-sign-mode-toggle",children:pad.mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw}),pad.mode==="type"&&/* @__PURE__ */jsxRuntime.jsx("input",{"aria-label":CLINIC_REQUEST_COPY.type,style:{...field,display:"block",width:"100%",boxSizing:"border-box"},maxLength:TYPED_SIGNATURE_MAX_LENGTH,value:pad.typed,disabled:disabled,autoComplete:"off",onChange:event=>pad.setTyped(event.target.value)}),
|
|
222
|
+
/* @__PURE__ */jsxRuntime.jsx("canvas",{ref:pad.canvas,role:"img","aria-label":typedName.length>0?CLINIC_REQUEST_COPY.typedSignatureA11y(typedName):CLINIC_REQUEST_COPY.sign,style:{display:"block",width:"100%",height:160,maxWidth:"100%",boxSizing:"border-box",touchAction:"none",background:"#fff",border:`1px solid ${theme.color.borderHairlineGreen}`,...disabled?{opacity:.6,pointerEvents:"none"}:{},...pad.mode==="type"?{pointerEvents:"none"}:{}},onPointerDown:event=>{disabled||pad.onPointerDown(event)},onPointerMove:event=>{disabled||pad.onPointerMove(event)},onPointerUp:pad.onPointerUp,onPointerCancel:pad.onPointerUp}),
|
|
223
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm,marginTop:theme.space.sm},children:[
|
|
224
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{margin:0,fontSize:theme.type.size.tiny,color:theme.color.text.muted},"data-testid":"records-signature-hint",children:pad.signed||pad.mode==="type"?" ":CLINIC_REQUEST_COPY.drawHint}),pad.mode==="type"?null:/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:disabled,onClick:pad.clear,"aria-label":CLINIC_REQUEST_COPY.clearA11y,"data-testid":"records-signature-clear",children:CLINIC_REQUEST_COPY.clear})]})]})}function EverfurClinicRequestBatch(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
225
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(BatchBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function BatchBody(props){let runtimeController=useEverfurRecordsClinic(),runtimeBatch=useEverfurRecordsClinicBatch(),controller=props.controller??runtimeController,theme=useEverfurTheme(),pad=useSignatureCanvas(),form=useClinicBatchForm(props,controller,props.batchClient??runtimeBatch,props.onCaptureSignature??(async context=>pad.signed?pad.capture(controller,context.signal):null)),signed=props.onCaptureSignature!==void 0||pad.signed,field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},input={...field,display:"block",width:"100%",boxSizing:"border-box"},button={...field,cursor:"pointer"},muted={margin:0,color:theme.color.text.muted,fontSize:theme.type.size.bodyTight},clinicLabel=clinic=>[clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),sendLabel=form.busy?CLINIC_BATCH_COPY.sending:form.drafts.length===0?CLINIC_BATCH_COPY.addToContinue:form.error?CLINIC_BATCH_COPY.tryAgain:CLINIC_BATCH_COPY.send(form.drafts.length),title=form.outcome?CLINIC_BATCH_COPY.resultTitle:CLINIC_BATCH_COPY.title;/* @__PURE__ */
|
|
226
|
+
return jsxRuntime.jsxs("section",{className:props.className,"aria-label":title,style:{...SURFACE_ROOT_RESET,background:theme.color.surface,color:theme.color.text.primary,padding:theme.space.lg,borderRadius:theme.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...props.style},children:[
|
|
227
|
+
/* @__PURE__ */jsxRuntime.jsx("h2",{style:{margin:0,fontSize:theme.type.size.heading},children:title}),
|
|
228
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{margin:`${theme.space.sm}px 0 ${theme.space.lg}px`},children:props.petName}),form.outcome?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"grid",gap:theme.space.sm},"data-testid":"records-batch-result",children:[
|
|
229
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:{margin:0},children:form.outcome.createdCount===0?CLINIC_BATCH_COPY.allFailed:form.outcome.failedCount>0?CLINIC_BATCH_COPY.partial(form.outcome.createdCount,form.outcome.results.length,form.outcome.failedCount):CLINIC_BATCH_COPY.allSent(form.outcome.createdCount)}),
|
|
230
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:{margin:0,fontSize:theme.type.size.subtitle},children:CLINIC_BATCH_COPY.perClinic}),
|
|
231
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:theme.space.sm},children:form.outcome.results.map((row,index)=>{let name=row.request?.clinicName??form.drafts[index]?.clinic?.name??row.clinicFreeText??"";/* @__PURE__ */
|
|
232
|
+
return jsxRuntime.jsxs("li",{"data-testid":`records-batch-row-${row.created?"created":"failed"}`,children:[
|
|
233
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{children:name})," ",
|
|
234
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:muted,children:row.created?CLINIC_BATCH_COPY.sent:CLINIC_BATCH_COPY.notSent}),row.created&&row.request?.statusLabel?/* @__PURE__ */jsxRuntime.jsx("p",{style:muted,children:row.request.statusLabel}):null,!row.created&&row.failureReason?/* @__PURE__ */jsxRuntime.jsx("p",{style:muted,children:row.failureReason}):null]},row.idempotencyKey)})}),form.group?/* @__PURE__ */jsxRuntime.jsx("p",{"aria-live":"polite",style:{margin:0},children:CLINIC_BATCH_COPY.responded(form.group.responded,form.group.total)}):null,form.group?.members.map(member=>member.statusLabel?/* @__PURE__ */jsxRuntime.jsx("p",{style:muted,children:[member.clinicName,member.statusLabel].filter(Boolean).join(": ")},member.id):null)]}):/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"grid",gap:theme.space.md},children:[
|
|
235
|
+
/* @__PURE__ */jsxRuntime.jsxs("label",{children:[CLINIC_REQUEST_COPY.ownerName,
|
|
236
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{style:input,maxLength:200,value:form.ownerName,disabled:form.busy,autoComplete:"name",onChange:event=>{pad.clear(),form.setOwnerName(event.target.value)}})]}),form.drafts.length>0&&/* @__PURE__ */jsxRuntime.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:theme.space.sm},children:form.drafts.map(draft=>/* @__PURE__ */jsxRuntime.jsxs("li",{"data-testid":`records-batch-draft-${draft.key}`,style:{display:"grid",gap:theme.space.xs},children:[
|
|
237
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{children:draftName(draft)}),draftNeedsEmail(draft)?/* @__PURE__ */jsxRuntime.jsxs("label",{children:[CLINIC_REQUEST_COPY.email,
|
|
238
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{style:input,type:"email",placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,maxLength:320,autoComplete:"off",value:draft.email,disabled:form.busy,onChange:event=>{pad.clear(),form.setDraftEmail(draft.key,event.target.value)}})]}):null,draftNeedsEmail(draft)&&!draft.email.trim()?/* @__PURE__ */jsxRuntime.jsx("p",{style:muted,children:CLINIC_BATCH_COPY.emailToAdd}):null,
|
|
239
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,"aria-label":CLINIC_BATCH_COPY.remove(draftName(draft)),onClick:()=>{pad.clear(),form.removeDraft(draft.key)},children:CLINIC_BATCH_COPY.remove(draftName(draft))})]},draft.key))}),
|
|
240
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{margin:0},children:form.atCap?CLINIC_BATCH_COPY.atCap:CLINIC_BATCH_COPY.addClinic}),!form.atCap&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
241
|
+
/* @__PURE__ */jsxRuntime.jsxs("label",{children:[CLINIC_REQUEST_COPY.clinic,
|
|
242
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{style:input,placeholder:CLINIC_REQUEST_COPY.placeholder,maxLength:200,value:form.query,disabled:form.busy,autoComplete:"off",onChange:event=>form.setQuery(event.target.value)})]}),
|
|
243
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy||form.searching||form.query.trim().length<2,onClick:()=>{form.search()},children:CLINIC_REQUEST_COPY.search}),form.query.trim().length>0&&form.clinics.length===0&&!form.searching&&/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,onClick:()=>{pad.clear(),form.addFreeText()},children:CLINIC_BATCH_COPY.addClinic}),form.searching&&/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsxRuntime.jsx("h3",{style:{margin:0,fontSize:theme.type.size.subtitle},children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,onClick:()=>{pad.clear(),form.addClinic(clinic)},children:clinicLabel(clinic)},`recent-${clinic.id}`)),form.visibleClinics.map(clinic=>/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,onClick:()=>{pad.clear(),form.addClinic(clinic)},children:clinicLabel(clinic)},clinic.id)),form.hasMoreClinics&&/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,onClick:form.showMoreClinics,"data-testid":"records-clinic-results-more",children:CLINIC_REQUEST_COPY.moreClinics})]}),
|
|
244
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:{margin:`${theme.space.sm}px 0 0`,fontSize:theme.type.size.subtitle},children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsxRuntime.jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:form.drafts.length>0&&form.ownerName.trim()?form.scopeText??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",children:RECORDS_COPY.loading}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignatureCanvas,{pad:pad,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert","data-testid":"records-batch-missing-signature",children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",children:form.error.displayMessage}),!form.copy&&form.error&&/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,onClick:form.retryCopy,children:RECORDS_COPY.retry}),
|
|
245
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:{...button,background:theme.color.primary,color:theme.color.onPrimary,opacity:form.busy||!form.ready||!signed?.5:1},disabled:form.busy||!form.ready||!signed,onClick:()=>{form.submit()},children:sendLabel})]}),props.onClose&&/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,onClick:props.onClose,children:CLINIC_REQUEST_COPY.cancel}),
|
|
246
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var RECORDS_CONSENT_COPY=/* @__PURE__ */Object.freeze({scopeHeading:"What we ask for",scopeBody:"You’re asking your pet’s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:/* @__PURE__ */Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:petName=>`I’m ${petNameOr(petName)}’s owner. I authorize Everfur to request these records on my behalf.`,missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We’ll email this clinic directly to request your pet’s medical records. Clinics usually reply within a week.",titleFreeText:"Check and send",titleDirectory:"Check and send",leadWeb:petName=>`The clinic gets a secure request, with your permission to release ${petNameOr(petName)}’s records to Everfur.`,leadNative:"The clinic gets a secure request, with your permission.",whatHappensNext:"What happens next",whatHappensNextBody:"Most clinics respond within 3 to 5 business days. We follow up automatically, and you can cancel any time before the records arrive.",noEmailNote:(petName,clinicName)=>`We don’t have an email on file for ${clinicName}. Add it so we can request ${petNameOr(petName)}’s records.`,emailLabel:"Clinic email for records",emailPlaceholder:"records@clinic.com",emailRequired:"Add the clinic’s records email to send the request.",emailInvalid:"That email doesn’t look right. Check it and try again.",reuseSignature:"Reuse a previous signature",reuseHint:"…or sign again below",reuseTileA11y:"Use this earlier signature",reuseTileSelectedA11y:"Earlier signature, selected",signType:"Type your name to sign",signDraw:"Sign with your finger",clear:"Clear",clearA11y:"Clear signature",fullName:"Your full name",fullNamePlaceholder:"Jane Doe",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",signatureHint:clinicName=>`Your signature is added to the authorization sent to ${clinicName}.`,submit:"Send request",submitting:"Sending…"});var FACT_VALUE_FIELD="value_text",FACT_ENTITY_TYPE_MAX=64,FACT_CANONICAL_KEY_MAX=512;function isFactReviewerLocked(error){return error!==null&&error.httpStatus===409&&!isRecordsConsentRequired(error)}var FACT_FIELD_BY_KIND=/* @__PURE__ */Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:FACT_VALUE_FIELD}),NUMERIC=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,ISO_DATE=/^\d{4}-\d{2}-\d{2}$/;function inferFactValueKind(value){if(value==null)return"text";let trimmed=value.trim();return NUMERIC.test(trimmed)?"num":ISO_DATE.test(trimmed)&&!Number.isNaN(Date.parse(trimmed))?"date":trimmed==="true"||trimmed==="false"?"bool":"text"}function factCorrectionFor(original,corrected){let next=corrected.trim(),kind=inferFactValueKind(original);if(kind==="num"&&NUMERIC.test(next)){let parsed=Number(next);if(Number.isFinite(parsed))/* @__PURE__ */return Object.freeze({[FACT_FIELD_BY_KIND.num]:parsed})}return kind==="date"&&ISO_DATE.test(next)&&!Number.isNaN(Date.parse(next))?/* @__PURE__ */Object.freeze({[FACT_FIELD_BY_KIND.date]:next}):/* @__PURE__ */Object.freeze(kind==="bool"&&(next==="true"||next==="false")?{[FACT_FIELD_BY_KIND.bool]:next==="true"}:{[FACT_FIELD_BY_KIND.text]:next})}var str2=/* @__PURE__ */zod.z.string().nullish(),num=/* @__PURE__ */zod.z.number().nullish(),pointSchema=/* @__PURE__ */zod.z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,ref_low:num,ref_high:num,status:str2,source_clinic:str2,source_doc_id:str2,doc_id:str2,reviewed:/* @__PURE__ */zod.z.boolean().nullish()}),latestSchema=/* @__PURE__ */zod.z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,status:str2}),markerSchema=/* @__PURE__ */zod.z.object({marker_id:/* @__PURE__ */zod.z.string().min(1),canonical_name:str2,name:str2,loinc_code:str2,canonical_unit:str2,unit:str2,panel_name:str2,panel:str2,meaning_text:str2,meaning:str2,latest:/* @__PURE__ */latestSchema.nullish(),trajectory:str2,points:/* @__PURE__ */zod.z.array(pointSchema).optional()}),summarySchema=/* @__PURE__ */zod.z.object({total_markers:/* @__PURE__ */zod.z.number().int().nonnegative(),in_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),out_of_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),unknown_count:/* @__PURE__ */zod.z.number().int().nonnegative()}),markersSchema=/* @__PURE__ */zod.z.object({markers:/* @__PURE__ */zod.z.array(markerSchema).optional(),summary:/* @__PURE__ */summarySchema.nullish(),disclaimer:/* @__PURE__ */zod.z.string().optional(),featured_marker_id:str2});function isObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function withheldMarkers(pet){/* @__PURE__ */
|
|
247
|
+
return Object.freeze({petRef:pet,withheld:true,markers:/* @__PURE__ */Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}function mapRecordMarkers(petRef,wire){let w=isObject2(wire)?wire:{},pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldMarkers(pet);let parsed=markersSchema.safeParse(w);if(!parsed.success)return withheldMarkers(pet);let m=parsed.data,point=p=>/* @__PURE__ */Object.freeze({at:p.collected_at??p.at??null,value:p.value??null,unit:p.unit??null,qualitativeResult:p.qualitative_result??null,refLow:p.ref_low??null,refHigh:p.ref_high??null,status:p.status??null,sourceClinic:p.source_clinic??null,docId:p.source_doc_id??p.doc_id??null,reviewed:p.reviewed===true}),markers=(m.markers??[]).map(marker=>/* @__PURE__ */Object.freeze({markerId:marker.marker_id,name:marker.canonical_name??marker.name??marker.marker_id,loincCode:marker.loinc_code??null,unit:marker.canonical_unit??marker.unit??null,panel:marker.panel_name??marker.panel??null,meaning:marker.meaning_text??marker.meaning??null,latest:marker.latest?/* @__PURE__ */Object.freeze({at:marker.latest.collected_at??marker.latest.at??null,value:marker.latest.value??null,unit:marker.latest.unit??null,qualitativeResult:marker.latest.qualitative_result??null,status:marker.latest.status??null}):null,trajectory:marker.trajectory??null,points:/* @__PURE__ */Object.freeze((marker.points??[]).map(point))}));/* @__PURE__ */
|
|
248
|
+
return Object.freeze({petRef:pet,withheld:false,markers:/* @__PURE__ */Object.freeze(markers),summary:m.summary?/* @__PURE__ */Object.freeze({totalMarkers:m.summary.total_markers,inRangeCount:m.summary.in_range_count,outOfRangeCount:m.summary.out_of_range_count,unknownCount:m.summary.unknown_count}):null,disclaimer:m.disclaimer??"",featuredMarkerId:m.featured_marker_id??null})}var https2=/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),itemSchema=/* @__PURE__ */zod.z.object({source_doc_id:/* @__PURE__ */zod.z.string().min(1),file_name:/* @__PURE__ */zod.z.string().nullish(),doc_format:/* @__PURE__ */zod.z.string().nullish(),byte_size:/* @__PURE__ */zod.z.number().int().nonnegative().nullish(),received_at:/* @__PURE__ */zod.z.string().nullish(),download_url:https2,expires_in_seconds:/* @__PURE__ */zod.z.number().int().nonnegative().nullish()}),listSchema2=/* @__PURE__ */zod.z.object({items:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.unknown()).optional()});function mapRequestDocuments(wire){let parsed=listSchema2.safeParse(wire);if(!parsed.success)return null;let rows=[];for(let raw of parsed.data.items??[]){let item=itemSchema.safeParse(raw);item.success&&rows.push(
|
|
249
|
+
/* @__PURE__ */Object.freeze({sourceDocId:item.data.source_doc_id,fileName:item.data.file_name??null,docFormat:item.data.doc_format??null,byteSize:item.data.byte_size??null,receivedAt:item.data.received_at??null,downloadUrl:item.data.download_url,expiresInSeconds:item.data.expires_in_seconds??0}))}/* @__PURE__ */
|
|
250
|
+
return Object.freeze(rows)}var listSchema3=/* @__PURE__ */zod.z.object({signatures:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({signature_id:/* @__PURE__ */zod.z.string().min(1),preview_url:/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),created_at:/* @__PURE__ */zod.z.string().nullish()})).optional()});function mapSignatureSuggestions(wire){let parsed=listSchema3.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.signatures??[]).map(row=>/* @__PURE__ */Object.freeze({signatureId:row.signature_id,previewUrl:row.preview_url,createdAt:row.created_at??null}))):null}var str3=/* @__PURE__ */zod.z.string().nullish(),num2=/* @__PURE__ */zod.z.number().nullish(),labPointSchema=/* @__PURE__ */zod.z.object({at:str3,value:num2,unit:str3,qualitative_result:str3,ref_low:num2,ref_high:num2,status:str3,doc_id:str3}),labMarkerSchema=/* @__PURE__ */zod.z.object({marker_id:/* @__PURE__ */zod.z.string(),name:/* @__PURE__ */zod.z.string(),loinc_code:str3,unit:str3,panel:str3,meaning:str3,latest:/* @__PURE__ */zod.z.object({at:str3,value:num2,unit:str3,qualitative_result:str3,status:str3}).nullish(),trajectory:str3,points:/* @__PURE__ */zod.z.array(labPointSchema).optional()}),encounterSchema=/* @__PURE__ */zod.z.object({encounter_id:/* @__PURE__ */zod.z.string(),date:str3,type:str3,clinic_name:str3,veterinarian:str3,doc_id:str3}),noteSchema=/* @__PURE__ */zod.z.object({note_id:/* @__PURE__ */zod.z.string(),encounter_id:str3,observed_on:str3,sections:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({section:/* @__PURE__ */zod.z.string(),text:/* @__PURE__ */zod.z.string()})).optional()}),examSchema=/* @__PURE__ */zod.z.object({exam_id:/* @__PURE__ */zod.z.string(),encounter_id:str3,observed_on:str3,doc_id:str3,systems:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.object({finding_status:str3,finding:str3})).optional()}),completenessSchema=/* @__PURE__ */zod.z.object({has_lab_history:/* @__PURE__ */zod.z.boolean().optional(),has_vaccination_history:/* @__PURE__ */zod.z.boolean().optional(),has_weight_history:/* @__PURE__ */zod.z.boolean().optional(),has_vitals_history:/* @__PURE__ */zod.z.boolean().optional(),has_physical_exam_history:/* @__PURE__ */zod.z.boolean().optional(),has_procedure_history:/* @__PURE__ */zod.z.boolean().optional(),has_genetic_history:/* @__PURE__ */zod.z.boolean().optional(),has_reproductive_history:/* @__PURE__ */zod.z.boolean().optional(),has_parasite_prevention_history:/* @__PURE__ */zod.z.boolean().optional(),earliest_record_at:str3,latest_record_at:str3,documents_ingested:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),documents_in_review:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),entities_pending_review:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.number().int().nonnegative()).optional(),held_total:/* @__PURE__ */zod.z.number().int().nonnegative().optional()}),conflictSchema=/* @__PURE__ */zod.z.object({conflict_id:/* @__PURE__ */zod.z.string(),entity_type:/* @__PURE__ */zod.z.string(),field:str3,severity:str3,candidates:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({value:/* @__PURE__ */zod.z.string(),source_doc_id:str3,doc_id:str3,collected_at:str3})).optional()}),depthSchema=/* @__PURE__ */zod.z.object({lab_results:/* @__PURE__ */zod.z.array(labMarkerSchema).optional(),encounters:/* @__PURE__ */zod.z.array(encounterSchema).optional(),clinician_notes:/* @__PURE__ */zod.z.array(noteSchema).optional(),physical_exams:/* @__PURE__ */zod.z.array(examSchema).optional(),completeness:/* @__PURE__ */completenessSchema.nullish(),conflicts:/* @__PURE__ */zod.z.array(conflictSchema).optional()}),timelineSchema=/* @__PURE__ */zod.z.object({visits:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({visit_id:/* @__PURE__ */zod.z.string(),visit_date:str3,veterinarian:str3,summary:str3,doc_id:str3})),vaccines:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({vaccine_id:/* @__PURE__ */zod.z.string(),product:str3,lot:str3,administered_on:str3,expires_on:str3,doc_id:str3})),weights:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({weight_id:/* @__PURE__ */zod.z.string(),observed_on:str3,weight_kg:num2,doc_id:str3})),medications:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({medication_id:/* @__PURE__ */zod.z.string(),drug_name:str3,dose:str3,route:str3,frequency:str3,sig:str3,rx_number:str3,started_on:str3,stopped_on:str3,doc_id:str3})),disclaimer:/* @__PURE__ */zod.z.string().optional()}),contributionsSchema=/* @__PURE__ */zod.z.object({document:documentSchema,contributions:/* @__PURE__ */zod.z.array(entitySchema),contribution_count:/* @__PURE__ */zod.z.number().int().nonnegative().optional()});function isObject3(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function petOf(w,petRef){return typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef}function emptyDepth(pet,withheld){/* @__PURE__ */
|
|
251
|
+
return Object.freeze({petRef:pet,available:false,withheld:withheld,labResults:/* @__PURE__ */Object.freeze([]),encounters:/* @__PURE__ */Object.freeze([]),clinicianNotes:/* @__PURE__ */Object.freeze([]),physicalExams:/* @__PURE__ */Object.freeze([]),completeness:null,conflicts:/* @__PURE__ */Object.freeze([])})}function mapRecordDepth(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return emptyDepth(pet,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(key=>key in w))return emptyDepth(pet,false);let parsed=depthSchema.safeParse(w);if(!parsed.success)return emptyDepth(pet,true);let d=parsed.data,point=p=>/* @__PURE__ */Object.freeze({at:p.at??null,value:p.value??null,unit:p.unit??null,qualitativeResult:p.qualitative_result??null,refLow:p.ref_low??null,refHigh:p.ref_high??null,status:p.status??null,docId:p.doc_id??null});/* @__PURE__ */
|
|
252
|
+
return Object.freeze({petRef:pet,available:true,withheld:false,labResults:/* @__PURE__ */Object.freeze((d.lab_results??[]).map(m=>/* @__PURE__ */Object.freeze({markerId:m.marker_id,name:m.name,loincCode:m.loinc_code??null,unit:m.unit??null,panel:m.panel??null,meaning:m.meaning??null,latest:/* @__PURE__ */Object.freeze({at:m.latest?.at??null,value:m.latest?.value??null,unit:m.latest?.unit??null,qualitativeResult:m.latest?.qualitative_result??null,status:m.latest?.status??null}),trajectory:m.trajectory??null,points:/* @__PURE__ */Object.freeze((m.points??[]).map(point))}))),encounters:/* @__PURE__ */Object.freeze((d.encounters??[]).map(e=>/* @__PURE__ */Object.freeze({encounterId:e.encounter_id,date:e.date??null,type:e.type??null,clinicName:e.clinic_name??null,veterinarian:e.veterinarian??null,docId:e.doc_id??null}))),clinicianNotes:/* @__PURE__ */Object.freeze((d.clinician_notes??[]).map(n=>/* @__PURE__ */Object.freeze({noteId:n.note_id,encounterId:n.encounter_id??null,observedOn:n.observed_on??null,sections:/* @__PURE__ */Object.freeze((n.sections??[]).map(s=>/* @__PURE__ */Object.freeze({section:s.section,text:s.text})))}))),physicalExams:/* @__PURE__ */Object.freeze((d.physical_exams??[]).map(x=>/* @__PURE__ */Object.freeze({examId:x.exam_id,encounterId:x.encounter_id??null,observedOn:x.observed_on??null,docId:x.doc_id??null,systems:/* @__PURE__ */Object.freeze(Object.entries(x.systems??{}).map(([system,field])=>/* @__PURE__ */Object.freeze({system:system,findingStatus:field.finding_status??null,finding:field.finding??null})))}))),completeness:d.completeness?/* @__PURE__ */Object.freeze({hasLabHistory:d.completeness.has_lab_history===true,hasVaccinationHistory:d.completeness.has_vaccination_history===true,hasWeightHistory:d.completeness.has_weight_history===true,hasVitalsHistory:d.completeness.has_vitals_history===true,hasPhysicalExamHistory:d.completeness.has_physical_exam_history===true,hasProcedureHistory:d.completeness.has_procedure_history===true,hasGeneticHistory:d.completeness.has_genetic_history===true,hasReproductiveHistory:d.completeness.has_reproductive_history===true,hasParasitePreventionHistory:d.completeness.has_parasite_prevention_history===true,earliestRecordAt:d.completeness.earliest_record_at??null,latestRecordAt:d.completeness.latest_record_at??null,documentsIngested:d.completeness.documents_ingested??0,documentsInReview:d.completeness.documents_in_review??0,entitiesPendingReview:/* @__PURE__ */Object.freeze({...d.completeness.entities_pending_review??{}}),heldTotal:d.completeness.held_total??0}):null,conflicts:/* @__PURE__ */Object.freeze((d.conflicts??[]).map(c=>/* @__PURE__ */Object.freeze({conflictId:c.conflict_id,entityType:c.entity_type,field:c.field??null,severity:c.severity??"needs_review",candidates:/* @__PURE__ */Object.freeze((c.candidates??[]).map(k=>/* @__PURE__ */Object.freeze({value:k.value,docId:k.source_doc_id??k.doc_id??null,collectedAt:k.collected_at??null})))})))})}function withheldTimeline(pet){/* @__PURE__ */
|
|
253
|
+
return Object.freeze({petRef:pet,withheld:true,isEmpty:false,visits:/* @__PURE__ */Object.freeze([]),vaccines:/* @__PURE__ */Object.freeze([]),weights:/* @__PURE__ */Object.freeze([]),medications:/* @__PURE__ */Object.freeze([]),disclaimer:""})}function mapRecordsTimeline(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return withheldTimeline(pet);let parsed=timelineSchema.safeParse(w);if(!parsed.success)return withheldTimeline(pet);let t=parsed.data,visits=t.visits.map(v=>/* @__PURE__ */Object.freeze({visitId:v.visit_id,visitDate:v.visit_date??null,veterinarian:v.veterinarian??null,summary:v.summary??null,docId:v.doc_id??null})),vaccines=t.vaccines.map(v=>/* @__PURE__ */Object.freeze({vaccineId:v.vaccine_id,product:v.product??null,lot:v.lot??null,administeredOn:v.administered_on??null,expiresOn:v.expires_on??null,docId:v.doc_id??null})),weights=t.weights.map(v=>/* @__PURE__ */Object.freeze({weightId:v.weight_id,observedOn:v.observed_on??null,weightKg:v.weight_kg??null,docId:v.doc_id??null})),medications=t.medications.map(m=>/* @__PURE__ */Object.freeze({medicationId:m.medication_id,drugName:m.drug_name??null,dose:m.dose??null,route:m.route??null,frequency:m.frequency??null,sig:m.sig??null,rxNumber:m.rx_number??null,startedOn:m.started_on??null,stoppedOn:m.stopped_on??null,docId:m.doc_id??null}));/* @__PURE__ */
|
|
254
|
+
return Object.freeze({petRef:pet,withheld:false,isEmpty:visits.length===0&&vaccines.length===0&&weights.length===0&&medications.length===0,visits:/* @__PURE__ */Object.freeze(visits),vaccines:/* @__PURE__ */Object.freeze(vaccines),weights:/* @__PURE__ */Object.freeze(weights),medications:/* @__PURE__ */Object.freeze(medications),disclaimer:t.disclaimer??""})}function mapDocumentContributions(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef),withheld=()=>/* @__PURE__ */Object.freeze({petRef:pet,withheld:true,document:null,contributions:/* @__PURE__ */Object.freeze([]),contributionCount:0});if(w.withheld===true)return withheld();let parsed=contributionsSchema.safeParse(w);if(!parsed.success)return withheld();let contributions=/* @__PURE__ */Object.freeze(parsed.data.contributions.map(mapEntityRow));/* @__PURE__ */
|
|
255
|
+
return Object.freeze({petRef:pet,withheld:false,document:mapDocumentRow(parsed.data.document),contributions:contributions,contributionCount:parsed.data.contribution_count??contributions.length})}var BASE3="/widget/v1/records/pets";function createRecordsDepthClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),segment=(value,max)=>typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)&&[...value].length<=max,read=async(call,petRef,path,map)=>{if(!segment(petRef,PET_REF_MAX))return invalid2();let result=await funnel.send(call,{method:"GET",path:path});if(!result.ok)return result;let view=map(result.value);return view.petRef===petRef?ok(view):err(makeEverfurError("internalError",{retryable:false}))},pet=petRef=>`${BASE3}/${encodeURIComponent(petRef)}`,record=petRef=>`${pet(petRef)}/everfur_record`,parsed=async(call,req,map)=>{let result=await funnel.send(call,req,req.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!result.ok)return result;let value=map(result.value);return value===null?err(makeEverfurError("internalError",{retryable:false})):ok(value)},factBody=(input,corrected)=>!segment(input.entityType,FACT_ENTITY_TYPE_MAX)||!segment(input.canonicalKey,FACT_CANONICAL_KEY_MAX)||input.idempotencyKey!==void 0&&!segment(input.idempotencyKey,IDEMPOTENCY_KEY_MAX)||corrected!==void 0&&Object.keys(corrected).length===0?null:{entity_type:input.entityType,canonical_key:input.canonicalKey,...corrected!==void 0?{corrected_fields:corrected}:{},...input.idempotencyKey!==void 0?{idempotency_key:input.idempotencyKey}:{}};return{getRecordDepth:petRef=>read("records.depth.record",petRef,`${pet(petRef)}/record`,wire=>mapRecordDepth(petRef,wire)),getTimeline:petRef=>read("records.depth.timeline",petRef,`${pet(petRef)}/timeline`,wire=>mapRecordsTimeline(petRef,wire)),getDocumentContributions(petRef,docId){return segment(docId,64)?read("records.depth.contributions",petRef,`${pet(petRef)}/documents/${encodeURIComponent(docId)}/contributions`,wire=>mapDocumentContributions(petRef,wire)):invalid2()},getMarkers:petRef=>read("records.depth.markers",petRef,`${pet(petRef)}/markers`,wire=>mapRecordMarkers(petRef,wire)),createShare(petRef,opts){if(!segment(petRef,PET_REF_MAX))return invalid2();let audience=opts?.audience;return audience!==void 0&&!RECORD_SHARE_AUDIENCES.includes(audience)?invalid2():parsed("records.share.create",{method:"POST",path:`${record(petRef)}/share`,...audience!==void 0?{body:{audience:audience}}:{}},wire=>mapRecordShareLink(wire,deps.apiBaseUrl))},emailShare(petRef,input){let kind=input.recipientKind,email2=typeof input.recipientEmail=="string"?input.recipientEmail.trim():"",kindOk=kind==="other"||RECORD_SHARE_AUDIENCES.includes(kind);return!segment(petRef,PET_REF_MAX)||!kindOk||!isShareRecipientEmail(email2)||hasLoneSurrogate(email2)?invalid2():parsed("records.share.email",{method:"POST",path:`${record(petRef)}/share/email`,body:{recipient_email:email2,recipient_kind:kind}},mapRecordShareEmailReceipt)},async readFeatures(){try{let result=await funnel.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return result.ok?mapRecordsFeatures(result.value):RECORDS_FEATURES_PDF_ONLY}catch{return RECORDS_FEATURES_PDF_ONLY}},listShares(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.share.list",{method:"GET",path:`${record(petRef)}/shares`},mapRecordShareList):invalid2()},async revokeShare(petRef,shareId){if(!segment(petRef,PET_REF_MAX)||!segment(shareId,64))return invalid2();let result=await funnel.send("records.share.revoke",{method:"DELETE",path:`${record(petRef)}/shares/${encodeURIComponent(shareId)}`},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},getPdfLink(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.pdf.link",{method:"GET",path:`${record(petRef)}/pdf-link`},mapRecordPdfLink):invalid2()},async editFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input,input.correctedFields):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.edit",{method:"POST",path:`${record(petRef)}/facts/edit`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},async removeFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.remove",{method:"POST",path:`${record(petRef)}/facts/remove`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},listRequestDocuments(requestId2){return segment(requestId2,64)?parsed("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(requestId2)}/documents`},mapRequestDocuments):invalid2()},listAuthorizationSignatures:()=>parsed("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mapSignatureSuggestions)}}function invalid2(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsDepthClient(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsDepthClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{},...typeof services.apiBaseUrl=="string"?{apiBaseUrl:services.apiBaseUrl}:{}})},[runtime,userRef,scopeEpoch])}function useRecordsDepthRead(petRef,read,isEmpty,extraKey=""){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),consentEpoch=useRecordsConsentEpoch(petRef),scope=react.useMemo(()=>({}),[client,petRef,extraKey,consentEpoch]),[state,setState]=react.useState({scope:scope,value:null,error:null,loading:true}),generation=react.useRef(0),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setState({scope:scope,value:null,error:null,loading:true}),userRef===null){setState({scope:scope,value:null,error:null,loading:false});return}let result=await read(client,petRef);gen===generation.current&&(result.ok?setState({scope:scope,value:result.value,error:null,loading:false}):setState({scope:scope,value:null,error:result.error,loading:false}))},[client,petRef,read,scope,userRef]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let current=state.scope===scope?state:{value:null,error:null,loading:true},refresh=react.useCallback(()=>{load()},[load]),available=current.error===null||current.error.httpStatus!==404,error=available?current.error:null,status=current.loading?"loading":error!==null?"error":current.value===null?"empty":current.value.withheld?"populated":isEmpty(current.value)?"empty":"populated";return react.useMemo(()=>({status:status,value:current.value,error:error,available:available,refresh:refresh}),[status,current.value,error,available,refresh])}function isDarkRouteError(error){return error!==null&&error.httpStatus===404}var readMarkers=(client,petRef)=>client.getMarkers(petRef),markersEmpty=value=>value.markers.length===0;function useRecordsMarkers(petRef){let state=useRecordsDepthRead(petRef,readMarkers,markersEmpty);return react.useMemo(()=>{let markers=state.available&&state.value!==null&&!state.value.withheld?state.value:null;return{status:state.status,markers:markers,available:state.available,error:state.error,refresh:state.refresh}},[state])}var EMAIL3=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function useRecordsConsentForm(input){let{clinic:clinic,controller:controller,depthClient:depthClient,capture:capture,onCreated:onCreated}=input,clinicName=clinic.clinic?.name??clinic.freeText??"",isFreeText=clinic.clinic===null,[authorized,setAuthorized]=react.useState(false),[ownerName,setOwnerName]=react.useState(input.ownerName),[email2,setEmail]=react.useState(clinic.email),[emailTouched,setEmailTouched]=react.useState(false),[copy,setCopy]=react.useState(null),[copyError,setCopyError]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[created,setCreated]=react.useState(null),[signatures,setSignatures]=react.useState([]),[reuseSignatureId,setReuseSignatureId]=react.useState(null),[signed,setSigned]=react.useState(false),locked=react.useRef(false),live=react.useRef(true),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null);react.useEffect(()=>(live.current=true,()=>{live.current=false,attempt.current=null}),[controller]),react.useEffect(()=>{let alive=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{alive&&(result.ok?(setCopy(result.value),setCopyError(null)):setCopyError(result.error))}).catch(()=>{alive&&setCopyError(makeEverfurError("internalError"))}),()=>{alive=false}},[controller,copyAttempt]),react.useEffect(()=>{if(depthClient===void 0)return;let alive=true;return depthClient.listAuthorizationSignatures().then(result=>{alive&&(result.ok?setSignatures(result.value):isDarkRouteError(result.error)||setSignatures([]))}).catch(()=>{}),()=>{alive=false}},[depthClient]);let needsEmail=clinicNeedsEmail(clinic.clinic),normalizedEmail=email2.trim().toLowerCase(),validEmail=EMAIL3.test(normalizedEmail),emailError=needsEmail&&(emailTouched||normalizedEmail.length>0)&&!validEmail?normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired:null,named=ownerName.trim().length>0,scope=copy&&named?renderClinicScope(copy,ownerName.trim(),petNameOr(input.petName),clinicName):null,hasSignature=input.hostCapture===true||signed||reuseSignatureId!==null,readyButSigned=!!(authorized&©&&scope&&named&&clinicName&&(!needsEmail||validEmail)),ready=readyButSigned&&hasSignature,submit=react.useCallback(async()=>{if(!(locked.current||created!==null||!copy||!scope)){if(!clinicName){setError(RECORDS_CONSENT_COPY.missingDraftError);return}if(needsEmail&&!validEmail){setEmailTouched(true),setError(normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired);return}if(!(!authorized||!ownerName.trim())){locked.current=true,setBusy(true),setError(null);try{if(attempt.current===null){let signature=reuseSignatureId!==null?{signatureId:reuseSignatureId}:await capture();if(!live.current)return;if(signature===null){setError(RECORDS_CONSENT_COPY.missingSignatureError);return}let target=clinic.clinic&&(!needsEmail||clinic.clinic.emailStatus==="none")?{clinicId:clinic.clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:input.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:normalizedEmail}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}let result=await controller.createClinicRequest(attempt.current);if(!live.current)return;if(!result.ok){setError(result.error.displayMessage);return}if(result.value.petRef!==input.petRef){setError(makeEverfurError("internalError").displayMessage);return}setCreated(result.value),attempt.current=null,onCreated?.(result.value)}catch{live.current&&setError(makeEverfurError("internalError").displayMessage)}finally{locked.current=false,live.current&&setBusy(false)}}}},[authorized,capture,clinic.clinic,clinicName,controller,copy,created,input.petRef,needsEmail,normalizedEmail,onCreated,ownerName,reuseSignatureId,scope,validEmail]),invalidate=react.useCallback(()=>{attempt.current=null,setError(null)},[]);return{title:isFreeText?RECORDS_CONSENT_COPY.titleFreeText:RECORDS_CONSENT_COPY.titleDirectory,clinicName:clinicName,isFreeText:isFreeText,authorized:authorized,ownerName:ownerName,email:email2,emailError:emailError,needsEmail:needsEmail,directoryClinicNoEmail:needsEmail&&clinic.clinic!==null,copy:copy,copyError:copyError,scope:scope,error:error,busy:busy,created:created,ready:ready,signatures:signatures,reuseSignatureId:reuseSignatureId,hasSignature:hasSignature,scopeAwaitingName:copy!==null&&!named,signatureLastMissing:readyButSigned&&!hasSignature,setAuthorized(value){locked.current||(invalidate(),setAuthorized(value))},setOwnerName(value){locked.current||(invalidate(),setOwnerName(value))},setEmail(value){locked.current||(invalidate(),setEmailTouched(false),setEmail(value))},setSigned(value){locked.current||(invalidate(),setSigned(value),value&&setReuseSignatureId(null))},pickReuseSignature(signatureId){locked.current||(invalidate(),setReuseSignatureId(signatureId))},retryCopy(){setCopyError(null),setCopyAttempt(n=>n+1)},submit:submit}}function EverfurRecordsConsent(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
256
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,className:props.className,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style,className:className}){let{theme:theme,styles:styles}=useScreenStyles(),runtimeController=useEverfurRecordsClinic(),resolved=controller??runtimeController,depthClient=useEverfurRecordsDepthClient(),pad=useSignatureCanvas(),rise=useSectionRise(),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:resolved,depthClient:depthClient,capture:onCaptureSignature?()=>onCaptureSignature({petRef:petRef,petName:petNameOr(petName),ownerName:form.ownerName,clinicName:form.clinicName,authorizationVersion:form.copy?.authorizationVersion??"",scopeText:form.scope??"",signal:(new AbortController).signal}):async()=>pad.signed?pad.capture(resolved,(new AbortController).signal):null,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),padSigned=pad.signed,formRef=react.useRef(form);formRef.current=form,react.useEffect(()=>{formRef.current.setSigned(padSigned)},[padSigned]);let busy=form.busy,block={display:"flex",flexDirection:"column",gap:theme.space.sm},ownerId="records-consent-owner-name",emailId="records-consent-clinic-email";/* @__PURE__ */
|
|
257
|
+
return jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-consent-screen",children:[
|
|
258
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:form.title,onBack:onBack,testID:"records-consent-header"}),
|
|
259
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.subLead,"data-testid":"records-consent-lead",children:RECORDS_CONSENT_COPY.leadWeb(petName)}),
|
|
260
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{ref:rise,style:{...styles.body,...styles.content,gap:theme.space.lg+theme.space.xs/2},"data-testid":"records-consent",children:[
|
|
261
|
+
/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.creamCard,"aria-label":RECORDS_CONSENT_COPY.scopeHeading,children:[
|
|
262
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:{...styles.sectionTitle,color:theme.color.brandInk},children:RECORDS_CONSENT_COPY.scopeHeading}),
|
|
263
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:RECORDS_CONSENT_COPY.scopeBody}),
|
|
264
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:{...styles.plainList,gap:theme.space.sm},children:RECORDS_CONSENT_COPY.whatWeDo.map(line=>/* @__PURE__ */jsxRuntime.jsxs("li",{style:{...styles.bodyText,display:"flex",gap:theme.space.sm},children:[
|
|
265
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{color:theme.color.brandInk,...faceCss(theme,"bold")},children:"✓"}),
|
|
266
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{children:line})]},line))}),
|
|
267
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.muted,paddingTop:theme.space.xs,borderTop:`1px solid ${theme.color.borderHairlineGreen}`},children:RECORDS_CONSENT_COPY.retentionNote}),form.copy&&form.scope?/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.rowDetail,whiteSpace:"pre-wrap"},"data-testid":"records-consent-scope",children:form.scope}):form.scopeAwaitingName?null:form.copyError?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
268
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.errorText,children:form.copyError.displayMessage}),
|
|
269
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onClick:form.retryCopy,testID:"records-consent-copy-retry"})]}):/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:styles.muted,children:RECORDS_COPY.loading})]}),
|
|
270
|
+
/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",role:"checkbox","aria-checked":form.authorized,onClick:()=>form.setAuthorized(!form.authorized),style:{display:"flex",alignItems:"flex-start",gap:theme.space.md,textAlign:"left",font:"inherit",cursor:"pointer",borderRadius:theme.radius.lg-theme.space.xs,border:`1px solid ${form.authorized?theme.color.brand:theme.color.brandBorder}`,backgroundColor:form.authorized?theme.color.brandSoft:theme.color.surface,padding:theme.space.md+theme.space.xs/2,color:theme.color.text.primary},"data-testid":"records-authorize-toggle",children:[
|
|
271
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{boxSizing:"border-box",flexShrink:0,width:theme.space.xl,height:theme.space.xl,borderRadius:theme.radius.xs+1,border:`1.6px solid ${theme.color.brandInk}`,backgroundColor:form.authorized?theme.color.brand:theme.color.surface,color:theme.color.onPrimary,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold")},children:form.authorized?"✓":""}),
|
|
272
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold"),fontSize:theme.type.size.bodyTight},children:RECORDS_CONSENT_COPY.authorizeLabel(petName)})]}),
|
|
273
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[
|
|
274
|
+
/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:ownerId,style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.fullName}),
|
|
275
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{id:ownerId,style:styles.field,value:form.ownerName,placeholder:RECORDS_CONSENT_COPY.fullNamePlaceholder,maxLength:200,disabled:busy,autoComplete:"name",onChange:event=>form.setOwnerName(event.target.value),"data-testid":"records-consent-owner-name"})]}),form.needsEmail?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,"data-testid":"records-consent-email-block",children:[form.directoryClinicNoEmail?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.cautionNote,"data-testid":"records-consent-no-email-note",children:RECORDS_CONSENT_COPY.noEmailNote(petName,form.clinicName)}):null,
|
|
276
|
+
/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:emailId,style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.emailLabel}),
|
|
277
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{id:emailId,type:"email",style:styles.field,value:form.email,placeholder:RECORDS_CONSENT_COPY.emailPlaceholder,maxLength:320,disabled:busy,autoComplete:"off","aria-invalid":form.emailError?true:void 0,"aria-describedby":form.emailError?`${emailId}-error`:void 0,onChange:event=>form.setEmail(event.target.value),"data-testid":"records-consent-clinic-email"}),form.emailError?/* @__PURE__ */jsxRuntime.jsx("p",{id:`${emailId}-error`,role:"alert",style:styles.errorText,children:form.emailError}):null,
|
|
278
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,"data-testid":"records-consent-review-note",children:RECORDS_CONSENT_COPY.newClinicDirectSendNote})]}):null,onCaptureSignature?null:/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[form.signatures.length>0?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[
|
|
279
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.reuseSignature}),
|
|
280
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:{display:"flex",gap:theme.space.sm,overflowX:"auto",padding:`${theme.space.xs}px 0`},children:form.signatures.map(sig=>{let selected=form.reuseSignatureId===sig.signatureId;/* @__PURE__ */
|
|
281
|
+
return jsxRuntime.jsx("button",{type:"button",onClick:()=>form.pickReuseSignature(selected?null:sig.signatureId),"aria-label":selected?RECORDS_CONSENT_COPY.reuseTileSelectedA11y:RECORDS_CONSENT_COPY.reuseTileA11y,"aria-pressed":selected,style:{flexShrink:0,width:112,height:56,borderRadius:theme.radius.sm,border:selected?`2px solid ${theme.color.brandInk}`:`1px solid ${theme.color.brandBorder}`,backgroundColor:theme.color.surface,padding:0,overflow:"hidden",cursor:"pointer"},"data-testid":`records-consent-reuse-${sig.signatureId}`,children:/* @__PURE__ */jsxRuntime.jsx("img",{src:sig.previewUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"contain"}})},sig.signatureId)})}),
|
|
282
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:RECORDS_CONSENT_COPY.reuseHint})]}):null,
|
|
283
|
+
/* @__PURE__ */jsxRuntime.jsx(SignatureCanvas,{pad:pad,disabled:busy}),
|
|
284
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:RECORDS_CONSENT_COPY.signatureHint(form.clinicName)}),form.signatureLastMissing?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,"data-testid":"records-consent-signature-required",children:RECORDS_CONSENT_COPY.missingSignatureError}):null]}),
|
|
285
|
+
/* @__PURE__ */jsxRuntime.jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surfaceSubtle,border:0},"aria-label":RECORDS_CONSENT_COPY.whatHappensNext,"data-testid":"records-consent-next",children:[
|
|
286
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sectionTitle,children:RECORDS_CONSENT_COPY.whatHappensNext}),
|
|
287
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:RECORDS_CONSENT_COPY.whatHappensNextBody})]}),form.error?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert","aria-live":"assertive",style:styles.errorBanner,children:form.error}):null,form.created?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:styles.bodyText,children:form.created.statusLabel||RECORDS_COPY.records}):null]}),
|
|
288
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm,padding:`${theme.space.md}px ${theme.space.lg}px ${theme.space.xxl}px`,borderTop:`1px solid ${theme.color.borderHairlineGreen}`,backgroundColor:theme.color.background},children:[onBack?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:BACK_LABEL,kind:"link",disabled:busy,onClick:onBack,style:{flex:"0 0 auto"},testID:"records-consent-cancel"}):null,
|
|
289
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?RECORDS_CONSENT_COPY.submitting:RECORDS_CONSENT_COPY.submit,disabled:!form.ready,busy:busy,onClick:()=>{form.submit()},style:{flex:"1 1 12rem",minWidth:0,minHeight:54},testID:"records-consent-submit"})]}),
|
|
290
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var KIND_ORDER=/* @__PURE__ */Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function toMillis(iso){if(!iso)return null;let ms=Date.parse(iso);return Number.isNaN(ms)?null:ms}function buildTimelineRows(timeline){let rows=[...timeline.visits.map((visit,index)=>({key:`visit-${index}-${visit.visitId}`,kind:"visit",kindLabel:DEPTH_COPY.kind.visit,at:visit.visitDate,date:formatRecordsDate(visit.visitDate),title:visit.summary??DEPTH_COPY.clinicVisit,detail:visit.veterinarian?DEPTH_COPY.doctor(visit.veterinarian):null,docId:visit.docId})),...timeline.vaccines.map((vaccine,index)=>{let parts=[];return vaccine.lot&&parts.push(DEPTH_COPY.lot(vaccine.lot)),vaccine.expiresOn&&parts.push(DEPTH_COPY.expires(formatRecordsDate(vaccine.expiresOn))),{key:`vaccine-${index}-${vaccine.vaccineId}`,kind:"vaccine",kindLabel:DEPTH_COPY.kind.vaccine,at:vaccine.administeredOn,date:formatRecordsDate(vaccine.administeredOn),title:vaccine.product||DEPTH_COPY.kind.vaccine,detail:parts.length?parts.join(" · "):null,docId:vaccine.docId}}),...timeline.weights.map((weight,index)=>({key:`weight-${index}-${weight.weightId}`,kind:"weight",kindLabel:DEPTH_COPY.kind.weight,at:weight.observedOn,date:formatRecordsDate(weight.observedOn),title:formatWeightKg(weight.weightKg),detail:null,docId:weight.docId})),...timeline.medications.map((medication,index)=>{let parts=[medication.dose,medication.route,medication.frequency].filter(p=>!!p);return{key:`medication-${index}-${medication.medicationId}`,kind:"medication",kindLabel:DEPTH_COPY.kind.medication,at:medication.startedOn,date:formatRecordsDate(medication.startedOn),title:medication.drugName||DEPTH_COPY.kind.medication,detail:parts.length?parts.join(" · "):null,docId:medication.docId}})];/* @__PURE__ */
|
|
291
|
+
return Object.freeze(rows.sort((a,b)=>{let am=toMillis(a.at),bm=toMillis(b.at);return am===null&&bm===null?KIND_ORDER[a.kind]-KIND_ORDER[b.kind]:am===null?1:bm===null?-1:bm!==am?bm-am:KIND_ORDER[a.kind]-KIND_ORDER[b.kind]}))}var SPINNER_DELAY_MS=300,MIN_SURFACE_HEIGHT2=120,MIN_TOUCH_TARGET2=44,readTimeline=(client,petRef)=>client.getTimeline(petRef),timelineEmpty=value=>value.isEmpty;var contributionsEmpty=value=>value.contributions.length===0;function EverfurRecordsTimeline({petRef:petRef,style:style,className:className,onBack:onBack}){let state=useRecordsDepthRead(petRef,readTimeline,timelineEmpty);/* @__PURE__ */
|
|
292
|
+
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,className:className,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DEPTH_COPY.timeline,onBack:guardHost(onBack),testID:"timeline-header"}),loading:/* @__PURE__ */jsxRuntime.jsx(TimelineSkeleton,{testID:"timeline-loading"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"timeline-empty"}),render:timeline=>/* @__PURE__ */jsxRuntime.jsx(TimelineBody,{timeline:timeline})})}function EverfurDocumentContributions({petRef:petRef,docId:docId,style:style,className:className,onBack:onBack}){let read=react.useCallback((client,pet)=>client.getDocumentContributions(pet,docId),[docId]),state=useRecordsDepthRead(petRef,read,contributionsEmpty,docId),title=state.value?.document?.title?.trim()||DEPTH_COPY.uploadedDocument;/* @__PURE__ */
|
|
293
|
+
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,className:className,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:title,onBack:guardHost(onBack),testID:"contributions-header"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"contributions-empty"}),render:view=>/* @__PURE__ */jsxRuntime.jsx(ContributionsBody,{view:view})})}function DepthSurface({state:state,style:style,className:className,header:header,loading:loading,empty:empty,render:render,onBack:onBack}){let{styles:styles}=useDepthTheme(),{userRef:userRef}=useEverfurContext();/* @__PURE__ */
|
|
294
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...recordsGateExit(guardHost(onBack),BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.container,...style},children:[header??null,
|
|
295
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:userRef===null?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.alertText,children:RECORDS_COPY.sessionRequired}):renderState(state,render,styles,loading,empty)}),
|
|
296
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function renderState(state,render,styles,loading,empty){switch(state.status){case"loading":return loading??/* @__PURE__ */jsxRuntime.jsx(LoadingState,{styles:styles});case"empty":return empty??/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.centered,children:/* @__PURE__ */jsxRuntime.jsx("div",{role:"img","aria-label":RECORDS_COPY.empty,style:styles.emptyGlyph})});case"error":return state.error?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(state.error),message:state.error.displayMessage,onAction:state.error.retryable?state.refresh:void 0,testID:"depth-error"}):null;case"populated":return state.value===null||state.value.withheld?null:render(state.value);default:return null}}function LoadingState({styles:styles}){let[visible,setVisible]=react.useState(false);return react.useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":RECORDS_COPY.loading,style:styles.centered,children:visible?/* @__PURE__ */jsxRuntime.jsx("div",{"aria-hidden":"true",style:styles.spinner}):null})}function TimelineBody({timeline:timeline}){let{styles:styles}=useDepthTheme(),rows=buildTimelineRows(timeline);/* @__PURE__ */
|
|
297
|
+
return jsxRuntime.jsxs("section",{"aria-label":DEPTH_COPY.timeline,style:styles.timelineList,children:[timeline.disclaimer.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{role:"note","aria-label":DASHBOARD_COPY.important(timeline.disclaimer),style:styles.timelineBand,children:timeline.disclaimer}):null,
|
|
298
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.plainList,children:rows.map((row,index)=>/* @__PURE__ */jsxRuntime.jsx("li",{style:index>0?styles.timelineSeparated:void 0,"data-testid":`records-timeline-row-${row.kind}`,children:/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.timelineRow,"aria-label":[row.kindLabel,row.date,row.title,row.detail].filter(Boolean).join(", "),children:[
|
|
299
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.timelineBubble}),
|
|
300
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.timelineBody,children:[
|
|
301
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.topLine,children:[
|
|
302
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.timelineKind,children:row.kindLabel}),
|
|
303
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.date,children:row.date})]}),
|
|
304
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.timelineTitle,children:row.title}),row.detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowDetail,children:row.detail}):null]})]})},row.key))})]})}function ContributionsBody({view:view}){let{styles:styles}=useDepthTheme();/* @__PURE__ */
|
|
305
|
+
return jsxRuntime.jsxs("section",{"aria-label":RECORDS_COPY.records,style:styles.list,children:[view.document?.receivedAt?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowDetail,children:formatRecordsDate(view.document.receivedAt)}):null,
|
|
306
|
+
/* @__PURE__ */jsxRuntime.jsx("dl",{style:styles.card,children:view.contributions.map(entity=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.row,children:[
|
|
307
|
+
/* @__PURE__ */jsxRuntime.jsx("dt",{style:styles.rowTitle,children:entity.label}),
|
|
308
|
+
/* @__PURE__ */jsxRuntime.jsx("dd",{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsxRuntime.jsx("dd",{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useDepthTheme(){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles3(theme),[theme]);return{theme:theme,styles:styles}}function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),cardText=slotText(slots.recordCard),inCard=(size,multiplier,fg,weight="regular")=>({...text3(size,multiplier,fg,weight),...cardText}),hairline=`1px solid ${color.brandBorder}`,errorColor=theme.brightness==="dark"?color.errorRed:color.danger;return{container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT2,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT2,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:space.lg,padding:space.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:24,height:24,borderRadius:radius.pill,border:`3px solid ${color.brandSofter}`,borderTopColor:color.brandInk},emptyGlyph:{boxSizing:"border-box",width:40,height:40,borderRadius:radius.lg,backgroundColor:color.brandSoft,border:hairline},alertText:text3(type.size.subtitle,type.lineHeight.snug,color.text.secondary),errorText:text3(type.size.subtitle,type.lineHeight.snug,errorColor),primaryButton:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,padding:`${space.md}px ${space.xl}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,border:0,cursor:"pointer",backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},list:{display:"flex",flexDirection:"column",gap:space.md,padding:space.lg},section:{display:"flex",flexDirection:"column",gap:space.sm},heading:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},card:{boxSizing:"border-box",listStyle:"none",display:"flex",flexDirection:"column",gap:space.sm,margin:0,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...slotBoxCss(slots.recordCard,1)},plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:space.sm},row:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.xs}px 0`,borderBottom:`1px solid ${color.borderHairlineGreen}`},topLine:{display:"flex",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(type.size.caption,type.lineHeight.normal,color.text.muted,"medium")},date:inCard(type.size.caption,type.lineHeight.normal,color.text.muted),rowTitle:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"bold")},rowValue:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),rowMuted:{...inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),opacity:.7},chip:{...text3(type.size.caption,type.lineHeight.normal,color.text.primary),alignSelf:"flex-start",padding:`${space.xs}px ${space.sm}px`,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:text3(type.size.caption,type.lineHeight.normal,color.text.muted),timelineList:{display:"flex",flexDirection:"column",paddingBottom:space.xxl},timelineBand:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,margin:`${space.xs}px ${space.lg}px ${space.md}px`},timelineSeparated:{borderTop:`1px solid ${color.brandBorder}`,marginLeft:TIMELINE_SEPARATOR_INSET,paddingLeft:0},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBubble:{boxSizing:"border-box",flexShrink:0,width:34,height:34,borderRadius:radius.pill,backgroundColor:color.brandSoft,border:hairline},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1,minWidth:0},timelineKind:{...faceCss(theme,"mono"),fontSize:type.size.micro,lineHeight:`${type.size.bodyTight}px`,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text3(type.size.body,type.lineHeight.normal,color.text.primary,"medium")}}}function useRecordShares(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),now=opts.now??Date.now,[shares,setShares]=react.useState(null),[loading,setLoading]=react.useState(true),[error,setError]=react.useState(null),[lit,setLit]=react.useState(null),available=lit===true,[urls,setUrls]=react.useState({}),[creating,setCreating]=react.useState(false),[revokingId,setRevokingId]=react.useState(null),[preparingPdf,setPreparingPdf]=react.useState(false),[consentRequired,setConsentRequired]=react.useState(false),[sending,setSending]=react.useState(false),[featuresState,setFeaturesState]=react.useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=react.useRef(0),live=react.useRef(true),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setLoading(true),setError(null),userRef===null){setShares(null),setLoading(false);return}let result=await client.listShares(petRef);gen!==generation.current||!live.current||(result.ok?(setShares(result.value),setLit(true)):isDarkRouteError(result.error)?(setShares(null),setLit(false)):(setShares(null),setError(result.error),answeredBehindGate(result)&&setLit(true)),setLoading(false))},[client,petRef,userRef]);react.useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),react.useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&setFeaturesState({client:client,value:value})},()=>{}),()=>{current=false}},[client,userRef]);let seenEpoch=react.useRef(consentEpoch);react.useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=react.useCallback(async audience=>{setCreating(true);let result=await(audience!==void 0&&shareAudiences.some(scope=>scope.audience===audience)?client.createShare(petRef,{audience:audience}):client.createShare(petRef));return live.current&&(setCreating(false),result.ok?(setUrls(current=>({...current,[result.value.shareId]:result.value.shareUrl})),load()):isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef,load,shareAudiences]),sendEmail=react.useCallback(async input=>{setSending(true);let result=await client.emailShare(petRef,input);return live.current&&(setSending(false),result.ok?load():isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)?setConsentRequired(true):result.error.httpStatus===502&&load()),result},[client,petRef,load]),revoke=react.useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=react.useCallback(async()=>{setPreparingPdf(true);let result=await client.getPdfLink(petRef);return live.current&&(setPreparingPdf(false),!result.ok&&isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef]),refresh=react.useCallback(()=>{setConsentRequired(false),load()},[load]),rows=react.useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return react.useMemo(()=>({status:status,rows:rows,available:available,consentRequired:consentRequired,error:error,creating:creating,revokingId:revokingId,preparingPdf:preparingPdf,shareAudiences:shareAudiences,features:features,sending:sending,createLink:createLink,sendEmail:sendEmail,revoke:revoke,pdfLink:pdfLink,refresh:refresh}),[status,rows,available,consentRequired,error,creating,revokingId,preparingPdf,shareAudiences,features,sending,createLink,sendEmail,revoke,pdfLink,refresh])}function answeredBehindGate(result){return result.ok||result.error.httpStatus!==void 0&&result.error.httpStatus!==404}function sharesListShown(shares){return shares.available||shares.status!=="empty"}function useRecordsDepthProbe(petRef){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=react.useState({scope:scope,lit:null});react.useEffect(()=>{if(userRef===null)return;let live=true;return client.listShares(petRef).then(result=>{live&&(!result.ok&&isDarkRouteError(result.error)?setState({scope:scope,lit:false}):answeredBehindGate(result)&&setState({scope:scope,lit:true}))},()=>{}),()=>{live=false}},[client,petRef,userRef,scope]);let lit=state.scope===scope?state.lit:null;return react.useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=react.useState(false),[error,setError]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=react.useCallback(async()=>{setPreparing(true),setError(null);let result=await client.getPdfLink(petRef);return live.current&&(setPreparing(false),result.ok||setError(result.error)),result},[client,petRef]);return react.useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}var CALL_CLINIC_COPY=/* @__PURE__ */Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment2){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment2()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment2){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment2)},[consentVersion,consentText,isDevelopment2])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face=>(fonts.add(face),!0)).catch(()=>!1)}catch{}loads.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;react.useEffect(()=>{for(let face of FACES){let url=fontUrls[face];url!=null&&loadBrandFont(families[face],url,namedFaces[face]?weight.regular:weight[FACE_WEIGHT[face]])}},[families,fontUrls,weight,namedFaces])}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return react.useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return react.useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return react.useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return react.useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});var isDevelopment=()=>webThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var PDF_SIGNATURE=[37,80,68,70,45],JPEG_SIGNATURE=[255,216,255],PNG_SIGNATURE=[137,80,78,71,13,10,26,10],HEAD_BYTES=12,BMFF_BRANDS=/* @__PURE__ */Object.freeze({heic:"image/heic",heix:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif"}),RECORDS_DOCUMENT_ACCEPT="application/pdf,.pdf",PHOTO_ACCEPT=/* @__PURE__ */Object.freeze({"image/jpeg":"image/jpeg,.jpg,.jpeg","image/png":"image/png,.png","image/heic":"image/heic,.heic","image/heif":"image/heif,.heif"});function recordsDocumentAccept(types){let photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>isAcceptedUploadType(type,types));return[RECORDS_DOCUMENT_ACCEPT,...photos.map(type=>PHOTO_ACCEPT[type])].join(",")}var NOT_A_PDF="application/octet-stream",WEB_FILE_URI="file:web-document";async function readHead(blob,length){let head=blob.slice(0,length);try{return typeof head.arrayBuffer=="function"?new Uint8Array(await head.arrayBuffer()):await new Promise(resolve=>{let reader=new FileReader;reader.onload=()=>{resolve(reader.result instanceof ArrayBuffer?new Uint8Array(reader.result):new Uint8Array)},reader.onerror=()=>resolve(new Uint8Array),reader.readAsArrayBuffer(head)})}catch{return new Uint8Array}}async function isPdfBlob(blob){if(blob.size<PDF_SIGNATURE.length)return false;let head=await readHead(blob,PDF_SIGNATURE.length);return startsWith(head,PDF_SIGNATURE)}function startsWith(head,signature,offset=0){return head.length>=offset+signature.length&&signature.every((byte,index)=>head[offset+index]===byte)}function photoTypeOf(head){return startsWith(head,JPEG_SIGNATURE)?"image/jpeg":startsWith(head,PNG_SIGNATURE)?"image/png":head.length>=HEAD_BYTES&&String.fromCharCode(...head.slice(4,8))==="ftyp"?BMFF_BRANDS[String.fromCharCode(...head.slice(8,12))]??null:null}async function detectedType(blob,types){if(await isPdfBlob(blob))return RECORDS_UPLOAD_CONTENT_TYPE;if(!RECORDS_PHOTO_CONTENT_TYPES.some(type=>isAcceptedUploadType(type,types)))return null;let photo=photoTypeOf(await readHead(blob,HEAD_BYTES));return photo!==null&&isAcceptedUploadType(photo,types)?photo:null}async function fileToHandle(file,types){let detected=await detectedType(file,types),rawName=file.name,name=typeof rawName=="string"?rawName:void 0;/* @__PURE__ */
|
|
309
|
+
return Object.freeze({uri:WEB_FILE_URI,mimeType:detected??NOT_A_PDF,sizeBytes:file.size,blob:file,...name!==void 0?{name:name}:{}})}function isUploadableHandle(handle,types){let size=handle.sizeBytes;return isAcceptedUploadType(handle.mimeType,types)&&typeof size=="number"&&Number.isFinite(size)&&size>0&&size<=MAX_UPLOAD_BYTES}function pickDocument(doc=document,types){return new Promise(resolve=>{let input=doc.createElement("input");input.type="file",input.accept=recordsDocumentAccept(types),input.hidden=true;let done=()=>{input.remove()};input.addEventListener("change",()=>{let file=input.files?.[0];if(done(),file===void 0){resolve(null);return}fileToHandle(file,types).then(resolve)},{once:true}),input.addEventListener("cancel",()=>{done(),resolve(null)},{once:true}),doc.body.appendChild(input),input.click()})}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=react.useState(""),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),[confirmingRevoke,setConfirmingRevoke]=react.useState(false),[settled,setSettled]=react.useState(null),locked=react.useRef(false),active=react.useRef(false),generation=react.useRef(0);react.useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&¤t.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&¤t.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),WIRE_FROM_STATUS=/* @__PURE__ */Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){case"submitted":case"sent":return 1;case"awaiting_response":return 2;case"records_received":return 3;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 4;case"published":return 5;default:return-1}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){case"awaiting_upload":return 3;case"records_received":return 4;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 5;case"published":return 6;default:return 3}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){case"submitted":case"sent":return 0;case"awaiting_upload":return 1;case"records_received":return 2;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 3;case"published":return 4;default:return-1}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null)}function inArtifactWords(events,request,petName){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now";function RequestTimeline({request:request,petName:petName}){let styles=useStyles2(),events=buildRequestTimeline(request,{petName:petName??null});
|
|
310
|
+
/* @__PURE__ */
|
|
311
|
+
return jsxRuntime.jsx("ol",{style:styles.list,"aria-label":REQUEST_SCREEN_COPY.timelineA11y,"data-testid":"records-timeline",children:events.map((event,idx)=>/* @__PURE__ */jsxRuntime.jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let date=event.at?formatRecordsDate(event.at):null,title={...styles.title,...event.state==="current"?styles.titleCurrent:{},...event.state==="failed"?styles.titleFailed:{},...event.state==="upcoming"?styles.titleUpcoming:{}};/* @__PURE__ */
|
|
312
|
+
return jsxRuntime.jsxs("li",{style:styles.row,"data-testid":`records-timeline-${event.key}`,children:[
|
|
313
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.railColumn,"aria-hidden":"true",children:[
|
|
314
|
+
/* @__PURE__ */jsxRuntime.jsx(Dot,{state:event.state,styles:styles}),isLast?null:/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.connector,...event.state==="done"?styles.connectorDone:{}}})]}),
|
|
315
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.body,children:[
|
|
316
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.titleRow,children:[
|
|
317
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:title,children:[event.title,event.state==="current"?/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.now,children:NOW}):null]}),date&&event.at?/* @__PURE__ */jsxRuntime.jsx("time",{dateTime:event.at,style:styles.date,children:date}):null]}),event.detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.detail,...event.state==="upcoming"?styles.detailUpcoming:{}},children:event.detail}):null,
|
|
318
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.srOnly,children:A11Y_STATE[event.state]})]})]})}function Dot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.dot,...styles.dotDone},children:"✓"}):state==="failed"?/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.dot,...styles.dotFailed},children:"!"}):state==="current"?/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.dot,...styles.dotCurrent},children:/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.dotCurrentCore})}):/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.dot,...styles.dotUpcoming}})}function useStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type,radius:radius}=theme,lh=size=>`${Math.round(size*type.lineHeight.snug)}px`,dot={boxSizing:"border-box",width:DOT_SIZE,height:DOT_SIZE,borderRadius:DOT_SIZE/2,display:"flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:type.size.caption,lineHeight:lh(type.size.caption)};return{list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},row:{display:"flex",alignItems:"flex-start",gap:space.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",alignSelf:"stretch",width:DOT_SIZE,flexShrink:0},body:{flex:1,minWidth:0,paddingTop:space.xs/2,paddingBottom:space.lg+space.xs/2,display:"flex",flexDirection:"column",gap:space.xs/2},titleRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm},dot:dot,dotDone:{backgroundColor:color.brand,color:color.onPrimary,border:`2px solid ${color.primaryEdge}`},dotFailed:{backgroundColor:color.danger,color:color.onDanger},dotCurrent:{border:`2px solid ${color.brandInk}`,backgroundColor:color.surface},dotCurrentCore:{width:10,height:10,borderRadius:5,backgroundColor:color.mark},dotUpcoming:{border:`2px solid ${color.structureEdge}`,backgroundColor:color.surface},connector:{width:2,flex:1,minHeight:22,backgroundColor:color.structureEdge,margin:"2px 0"},connectorDone:{backgroundColor:color.primaryEdge},title:{flex:1,display:"flex",flexWrap:"wrap",alignItems:"center",gap:space.sm,...faceCss(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:lh(type.size.bodyTight),color:color.text.primary},titleCurrent:{color:color.brandInk},titleFailed:{color:color.danger},titleUpcoming:{color:color.text.muted,...faceCss(theme,"regular")},date:{...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption),color:color.text.muted},detail:{...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.normal)}px`,color:color.text.muted},now:{display:"inline-flex",alignItems:"center",minHeight:20,padding:`0 ${space.sm}px`,borderRadius:radius.pill,backgroundColor:color.highlight,color:color.onHighlight,...faceCss(theme,"monoBold"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny),letterSpacing:"0.06em",textTransform:"uppercase"},detailUpcoming:{opacity:.7},srOnly:{position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0}}}function isFinitePoint(point){return point.value!==null&&Number.isFinite(point.value)}function pointDisplay(point){return point.display!==null&&point.display.length>0?point.display:point.value!==null?String(point.value):""}function buildTrendModel(series){let primary=series.find(s=>s.points.some(isFinitePoint));if(primary===void 0)return null;let numeric2=primary.points.filter(isFinitePoint),first=numeric2[0];if(first===void 0)return null;let values=numeric2.map(p=>p.value),lo=Math.min(...values),hi=Math.max(...values);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.18,yMin=lo-pad,yMax=hi+pad,span=yMax-yMin,xInset=6,count=numeric2.length,points=numeric2.map((p,index)=>({xPct:count<=1?50:xInset+index/(count-1)*(100-2*xInset),yPct:(yMax-p.value)/span*100})),bandTopPct=(yMax-hi)/span*100,bandBottomPct=(yMax-lo)/span*100,minPoint=numeric2.reduce((acc,p)=>p.value<acc.value?p:acc,first),maxPoint=numeric2.reduce((acc,p)=>p.value>acc.value?p:acc,first),lastNumeric=numeric2[numeric2.length-1]??first,latest=primary.points[primary.points.length-1]??lastNumeric,latestDisplay=pointDisplay(latest),heroDisplay=latestDisplay.length>0?latestDisplay:pointDisplay(lastNumeric);return{label:primary.label,heroDisplay:heroDisplay,minDisplay:pointDisplay(minPoint),maxDisplay:pointDisplay(maxPoint),firstDate:formatShortDate(primary.points[0]?.at??null),lastDate:formatShortDate(latest.at),points:points,bandTopPct:bandTopPct,bandBottomPct:bandBottomPct}}function entityTypeOf(key){let separator=key.indexOf(":");return separator<=0?null:key.slice(0,separator)}function groupSeriesByEntityType(series,order,labelFor){let byType=/* @__PURE__ */new Map,firstSeen=[];for(let one of series){let type=entityTypeOf(one.key)??"",bucket=byType.get(type);bucket===void 0?(byType.set(type,[one]),firstSeen.push(type)):bucket.push(one)}let listed=order.filter(type=>byType.has(type)),rest=firstSeen.filter(type=>!listed.includes(type));/* @__PURE__ */
|
|
319
|
+
return Object.freeze([...listed,...rest].map(type=>/* @__PURE__ */Object.freeze({entityType:type.length>0?type:null,label:type.length>0?labelFor(type):null,series:/* @__PURE__ */Object.freeze([...byType.get(type)??[]])})))}function TrendRangeCard({series:series}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles5(theme),[theme]),groups=react.useMemo(()=>groupSeriesByEntityType(series,ENTITY_SECTION_ORDER,entityTypeLabel),[series]);return groups.length===0?null:/* @__PURE__ */jsxRuntime.jsxs("section",{"aria-label":RECORD_SCREEN_COPY.careTimeline,style:styles.section,children:[
|
|
320
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{children:[
|
|
321
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sectionTitle,children:RECORD_SCREEN_COPY.careTimeline}),
|
|
322
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.sectionSub,children:RECORD_SCREEN_COPY.careTimelineSub})]}),groups.map(group=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.group,children:[group.label===null?null:/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.eyebrow,children:group.label}),group.series.map(one=>/* @__PURE__ */jsxRuntime.jsx(SeriesChart,{series:one,styles:styles},one.key))]},group.entityType??"_"))]})}function SeriesChart({series:series,styles:styles}){let model=react.useMemo(()=>buildTrendModel([series]),[series]);if(model===null){let display=series.points[series.points.length-1]?.display??null;/* @__PURE__ */
|
|
323
|
+
return jsxRuntime.jsxs("div",{style:styles.card,children:[
|
|
324
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.eyebrow,children:series.label}),display!==null&&display.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.hero,children:display}):null]})}/* @__PURE__ */
|
|
325
|
+
return jsxRuntime.jsx(TrendChart,{model:model,styles:styles})}function TrendChart({model:model,styles:styles}){let summary=model.heroDisplay.length>0?`${model.label}, ${model.heroDisplay}`:model.label,bandHeightPct=Math.max(0,model.bandBottomPct-model.bandTopPct),last=model.points.length-1;/* @__PURE__ */
|
|
326
|
+
return jsxRuntime.jsxs("div",{style:styles.card,children:[
|
|
327
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{role:"img","aria-label":summary,children:[
|
|
328
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.eyebrow,children:model.label}),model.heroDisplay.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.hero,children:model.heroDisplay}):null]}),
|
|
329
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{"aria-hidden":"true",style:styles.plot,children:[model.points.map((p,index)=>/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.guide,left:`${p.xPct}%`}},`g-${index}`)),
|
|
330
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.band,top:`${model.bandTopPct}%`,height:`${bandHeightPct}%`}}),model.points.map((p,index)=>/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.point,...index===last?styles.pointLatest:null,left:`${p.xPct}%`,top:`${p.yPct}%`}},`pt-${index}`)),model.maxDisplay.length>0?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.edgeLabel,top:`${model.bandTopPct}%`},children:model.maxDisplay}):null,model.minDisplay.length>0?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.edgeLabel,top:`${model.bandBottomPct}%`},children:model.minDisplay}):null]}),model.firstDate.length>0||model.lastDate.length>0?/* @__PURE__ */jsxRuntime.jsxs("div",{"aria-hidden":"true",style:styles.dates,children:[
|
|
331
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{children:model.firstDate}),
|
|
332
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{children:model.lastDate})]}):null]})}function makeStyles5(theme){let{color:color,space:space,radius:radius,type:type}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,dot=space.sm;return{section:{display:"flex",flexDirection:"column",gap:space.lg},sectionTitle:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:lh(type.size.subtitle,type.lineHeight.snug),letterSpacing:"-0.02em",color:color.text.primary},sectionSub:{margin:`${space.xs}px 0 0`,...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted},group:{display:"flex",flexDirection:"column",gap:space.sm},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.sm,padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderRingCream}`},eyebrow:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},hero:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.verdict,lineHeight:lh(type.size.verdict,type.lineHeight.tight),color:color.text.primary,letterSpacing:type.letterSpacing.tight},plot:{position:"relative",height:space.xxl*3,marginTop:space.xs},guide:{position:"absolute",top:0,bottom:0,width:1,backgroundColor:color.borderHairlineGreen},band:{position:"absolute",left:space.xs,right:space.xs,borderRadius:radius.sm,backgroundColor:color.brandSoft},point:{boxSizing:"border-box",position:"absolute",width:dot,height:dot,marginLeft:-(dot/2),marginTop:-(dot/2),borderRadius:radius.pill,backgroundColor:color.brand,border:`1px solid ${color.surfaceCream}`},pointLatest:{backgroundColor:color.accent,borderColor:color.onAccent},edgeLabel:{position:"absolute",right:0,marginTop:-space.sm,...faceCss(theme,"medium"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny,type.lineHeight.tight),color:color.text.muted,whiteSpace:"nowrap"},dates:{display:"flex",justifyContent:"space-between",...faceCss(theme,"regular"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny,type.lineHeight.normal),color:color.text.muted}}}var SPINNER_DELAY_MS2=300,SPINNER_LOOP_MS=900,MIN_SURFACE_HEIGHT3=120,MIN_TOUCH_TARGET3=44,GLYPH_SIZE=40,SPINNER_SIZE=24,SPINNER_STROKE=3;function renderErrorFamily(records,onGrant,canGrant,consentText){let errorView=selectErrorView(records,canGrant);switch(errorView.kind){case"consent_required":/* @__PURE__ */
|
|
333
|
+
return jsxRuntime.jsx(ConsentRequiredState,{onGrant:onGrant,consentText:consentText});case"consent_unavailable":/* @__PURE__ */
|
|
334
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.consentRequired,glyph:"empty"});case"session_required":/* @__PURE__ */
|
|
335
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"});case"withheld":/* @__PURE__ */
|
|
336
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.recordUnavailable,glyph:"withheld"});case"pet_not_found":case"error":/* @__PURE__ */
|
|
337
|
+
return jsxRuntime.jsx(ErrorState,{error:errorView.error,onRetry:records.refresh});default:return assertNever(errorView)}}function LoadingState2(){let{theme:theme,styles:styles}=useRecordsTheme(),[visible,setVisible]=react.useState(false),ref=react.useRef(null);react.useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS2);return()=>clearTimeout(id)},[]);let animate=visible&&!theme.motion.reducedMotion;return react.useEffect(()=>{let node=ref.current;if(!animate||node===null||typeof node.animate!="function")return;let animation=node.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:SPINNER_LOOP_MS,iterations:1/0});return()=>animation.cancel()},[animate]),/* @__PURE__ */jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":RECORDS_COPY.loading,style:styles.centered,children:visible?/* @__PURE__ */jsxRuntime.jsx("div",{ref:ref,"aria-hidden":"true",style:styles.spinner}):null})}function UploadQueue({records:records}){let{styles:styles}=useRecordsTheme(),queue=records.uploadQueue;if(queue.length===0)return null;let rows=queue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,skipped=skippedFilesMessage(skippedOf(queue));/* @__PURE__ */
|
|
338
|
+
return jsxRuntime.jsxs("div",{style:styles.card,"data-testid":"records-upload-queue",children:[skipped!==null?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.errorText,children:skipped}):null,rows.length>0?/* @__PURE__ */jsxRuntime.jsx("ul",{"aria-live":"polite","aria-label":records.isUploading?UPLOAD_QUEUE_COPY.uploading(done,rows.length):UPLOAD_QUEUE_COPY.uploaded(done,rows.length),style:{listStyle:"none",margin:0,padding:0},children:rows.map(item=>{let pct=Math.round(item.progress*100);/* @__PURE__ */
|
|
339
|
+
return jsxRuntime.jsxs("li",{style:styles.row,"data-testid":`records-upload-file-${item.status}`,children:[
|
|
340
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowLabel,children:item.name??""}),
|
|
341
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowValue,children:uploadItemStatusLabel(item)}),item.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx("progress",{max:100,value:pct,style:{width:"100%"}}):null,item.status==="failed"&&item.error?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.timelineMeta,children:item.error.displayMessage}):null]},item.key)})}):null]})}function ConsentRequiredState({onGrant:onGrant,consentText:consentText}){let{styles:styles}=useRecordsTheme(),text3=presentConsentText(consentText);/* @__PURE__ */
|
|
342
|
+
return jsxRuntime.jsxs("div",{role:"alert","aria-live":"assertive",style:styles.centered,children:[
|
|
343
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.alertText,children:RECORDS_COPY.consentRequired}),text3!==null?/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.disclaimer,whiteSpace:"pre-line"},"data-testid":"records-consent-gate-body",children:text3}):null,
|
|
344
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onGrant,style:styles.primaryButton,children:RECORDS_COPY.allow})]})}function AlertState({label:label,glyph:glyph}){let{styles:styles}=useRecordsTheme();/* @__PURE__ */
|
|
345
|
+
return jsxRuntime.jsxs("div",{role:"alert","aria-live":"assertive",style:styles.centered,children:[
|
|
346
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{"aria-hidden":"true",style:glyph==="withheld"?styles.withheldGlyph:styles.emptyGlyph}),
|
|
347
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.alertText,children:label})]})}function ErrorState({error:error,onRetry:onRetry}){let{styles:styles}=useRecordsTheme();/* @__PURE__ */
|
|
348
|
+
return jsxRuntime.jsxs("div",{role:"alert","aria-live":"assertive",style:styles.centered,children:[
|
|
349
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.errorText,children:error.displayMessage}),error.retryable?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onRetry,style:styles.primaryButton,children:RECORDS_COPY.retry}):null]})}function ClinicCallCard({call:call,prompt:prompt}){let{styles:styles}=useRecordsTheme(),intro=prompt.trim().length>0?prompt:CALL_CLINIC_COPY.fallbackPrompt;/* @__PURE__ */
|
|
350
|
+
return jsxRuntime.jsxs("div",{style:styles.callCard,children:[
|
|
351
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.timelineLabel,children:CALL_CLINIC_COPY.heading}),
|
|
352
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.timelineMeta,children:intro}),
|
|
353
|
+
/* @__PURE__ */jsxRuntime.jsx("a",{href:call.dial,"aria-label":CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,"data-testid":"records-call-clinic",children:CALL_CLINIC_COPY.call})]})}function useRecordsTheme(){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles6(theme),[theme]);return{theme:theme,styles:styles}}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,hairline=`1px solid ${color.brandBorder}`,card=slotBoxCss(slots.recordCard,1),cardText=slotText(slots.recordCard),text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),inCard=(size,multiplier,fg,weight="regular")=>({...text3(size,multiplier,fg,weight),...cardText}),button={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET3,minWidth:MIN_TOUCH_TARGET3,padding:`${space.md}px ${space.xl}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,letterSpacing:type.letterSpacing.tight},glyph={boxSizing:"border-box",width:GLYPH_SIZE,height:GLYPH_SIZE},errorColor=theme.brightness==="dark"?color.errorRed:color.danger;return{container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT3,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT3,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:space.lg,padding:space.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:SPINNER_SIZE,height:SPINNER_SIZE,borderRadius:radius.pill,border:`${SPINNER_STROKE}px solid ${color.brandSofter}`,borderTopColor:color.brandInk},emptyGlyph:{...glyph,borderRadius:radius.lg,backgroundColor:color.brandSoft,border:hairline},withheldGlyph:{...glyph,borderRadius:radius.sm,backgroundColor:color.badgeBgCaution,border:`1px solid ${color.cautionAccent}`},alertText:text3(type.size.subtitle,type.lineHeight.snug,color.text.secondary),errorText:text3(type.size.subtitle,type.lineHeight.snug,errorColor),primaryButton:{...button,border:0,cursor:"pointer",backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},disabledButton:{...button,border:hairline,cursor:"default",backgroundColor:color.surfaceSubtle,color:color.text.muted},list:{display:"flex",flexDirection:"column",gap:space.md,padding:space.lg},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.md}px ${space.lg}px`,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...card},cardTitle:{...inCard(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),letterSpacing:type.letterSpacing.tight},callCard:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...card},linkButton:{...button,display:"inline-flex",alignItems:"center",justifyContent:"center",alignSelf:"flex-start",textDecoration:"none",border:0,backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},timelineLabel:{...inCard(type.size.subtitle,type.lineHeight.snug,color.text.secondary,"bold")},timelineMeta:inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),row:{display:"flex",justifyContent:"space-between",gap:space.md,padding:`${space.xs}px 0`,borderBottom:`1px solid ${color.borderHairlineGreen}`},rowLabel:inCard(type.size.body,type.lineHeight.normal,color.text.muted),rowValue:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"medium"),textAlign:"right"},disclaimer:text3(type.size.caption,type.lineHeight.normal,color.text.muted)}}var RECORD_PDF_FILENAME="everfur-record.pdf";function copyText(text3){return typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("clipboard unavailable")):navigator.clipboard.writeText(text3)}function isAbort(error){return typeof error=="object"&&error!==null&&error.name==="AbortError"}async function shareLinkInPlace(url,copy=copyText){let nav=typeof navigator>"u"?void 0:navigator;if(nav!==void 0&&typeof nav.share=="function")try{return await nav.share({url:url}),"shared"}catch(error){if(isAbort(error))return"dismissed"}return await copy(url),"copied"}function inPlaceRoute(url,base){let parsed;try{parsed=new URL(url,base)}catch{return null}if(parsed.protocol==="blob:"||parsed.protocol==="data:")return"download";if(base!==void 0)try{if(new URL(base).origin===parsed.origin)return"download"}catch{}let disposition=parsed.searchParams.get("response-content-disposition");return disposition!==null&&/^\s*attachment\b/i.test(disposition)?"attachment":null}function locationHref(){return typeof location>"u"?void 0:location.href}function isFramedDocument(win=(typeof window>"u"?void 0:window)){if(win===void 0)return false;try{return win.self!==win.top}catch{return true}}function clickDownload(href,filename){let anchor=document.createElement("a");anchor.href=href,anchor.download=filename,anchor.rel="noopener",anchor.style.display="none",document.body.appendChild(anchor);try{anchor.click()}finally{anchor.remove()}}var SAVE_FRAME_TTL_MS=6e4;function saveThroughNestedFrame(href){let frame=document.createElement("iframe");frame.setAttribute("sandbox","allow-downloads"),frame.setAttribute("aria-hidden","true"),frame.tabIndex=-1,frame.style.display="none",frame.src=href,document.body.appendChild(frame),setTimeout(()=>frame.remove(),SAVE_FRAME_TTL_MS)}async function downloadInPlace(url,filename,framed=isFramedDocument()){if(typeof document>"u")return false;let route=inPlaceRoute(url,locationHref());if(route==="attachment"&&framed)return saveThroughNestedFrame(url),true;if(route!==null)return clickDownload(url,filename),true;let blob;try{let response=await fetch(url,{credentials:"omit"});if(!response.ok)return!1;blob=await response.blob()}catch{return false}let objectUrl=URL.createObjectURL(blob);try{clickDownload(objectUrl,filename)}finally{setTimeout(()=>URL.revokeObjectURL(objectUrl),1e4)}return true}var COPY=RECORD_SCREEN_COPY.document,DOCUMENT_ENTITY_ORDER=/* @__PURE__ */Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),readDepth=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty=value=>!value.available;function documentIsEmpty(record,depth){return record.identity.length===0&&record.entities.length===0&&record.forwardLooking.length===0&&(depth===null||depth.labResults.length===0&&depth.physicalExams.length===0&&depth.clinicianNotes.length===0)}function EverfurRecordDocument(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onBack"]),{userRef:userRef}=useEverfurContext(),{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
354
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.root,backgroundColor:theme.color.surface,...style},"data-testid":"record-document-screen",children:[userRef===null?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsxRuntime.jsx(DocumentBody,{...rest}),
|
|
355
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function DocumentBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onBack:onBack,onOpenUrl:onOpenUrl}){let{theme:theme,styles:styles}=useScreenStyles(),s=useDocStyles(),recordsOpts=react.useMemo(()=>controller?{petRef:petRef,controller:controller}:{petRef:petRef},[petRef,controller]),records=useEverfurRecords(recordsOpts),depth=useRecordsDepthRead(petRef,readDepth,depthEmpty),pdf=useRecordPdfLink(petRef);useConsentTextWarning2(consentVersion,consentText);let canGrant=canGrantConsent(consentVersion,records.consent),onGrant=()=>{let version=resolveConsentVersion(consentVersion,records.consent);version.length!==0&&records.grantConsent(version,`records-consent-${Date.now().toString(36)}`)},depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,[saveFailed,setSaveFailed]=react.useState(false),download=()=>{setSaveFailed(false),pdf.pdfLink().then(result=>{result.ok&&(onOpenUrl?callHostAsync(onOpenUrl,result.value.downloadUrl,"record_pdf"):downloadInPlace(result.value.downloadUrl,RECORD_PDF_FILENAME).then(saved=>setSaveFailed(!saved)))})},body,documentShown=false;if(records.status==="loading"||depth.status==="loading"&&record!==null)body=/* @__PURE__ */jsxRuntime.jsx("div",{"data-testid":"record-document-loading",children:/* @__PURE__ */jsxRuntime.jsx(LoadingState2,{})});else if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?()=>{records.refresh(),depth.refresh()}:void 0,testID:"record-document-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else record===null||documentIsEmpty(record,depthView)?body=/* @__PURE__ */jsxRuntime.jsx("p",{style:s.empty,"data-testid":"record-document-empty",children:COPY.empty}):(documentShown=true,body=/* @__PURE__ */jsxRuntime.jsx(RecordDocument,{record:record,depth:depthView,petName:petName,wordmark:theme.meta.displayName})/* @__PURE__ */);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
356
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:download,disabled:pdf.preparing,"aria-busy":pdf.preparing,"aria-label":COPY.download,style:styles.iconButton,"data-testid":"record-document-download",children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:12,height:12,borderLeft:`2px solid ${theme.color.brandInk}`,borderBottom:`2px solid ${theme.color.brandInk}`,transform:"rotate(-45deg)"}})}):void 0}),pdf.error?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:{...styles.errorText,padding:`0 ${theme.space.lg}px`},children:pdf.error.displayMessage}):saveFailed?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:{...styles.errorText,padding:`0 ${theme.space.lg}px`},"data-testid":"record-document-save-failed",children:shareErrorMessage(null,"download")}):null,
|
|
357
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:body})]})}function RecordDocument({record:record,depth:depth,petName:petName,wordmark:wordmark}){let s=useDocStyles(),groups=react.useMemo(()=>{let order=[],byType=/* @__PURE__ */new Map;for(let entity of record.entities){let category=entity.category.trim();if(category.length===0)continue;let bucket=byType.get(category);bucket===void 0?(order.push(category),byType.set(category,[entity])):bucket.push(entity)}let known=DOCUMENT_ENTITY_ORDER.filter(type=>order.includes(type)),rest=order.filter(type=>!DOCUMENT_ENTITY_ORDER.includes(type));return[...known,...rest].map(type=>({type:type,rows:byType.get(type)??[]}))},[record.entities]),now=Date.now(),section=(title,children,testID)=>/* @__PURE__ */jsxRuntime.jsxs("section",{style:s.section,"data-testid":testID,children:[
|
|
358
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.sectionHeader,children:[
|
|
359
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:s.sectionTitle,children:title}),
|
|
360
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rule})]}),
|
|
361
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{children:children})]},testID),row=(index,extra)=>({...s.row,...index>0?s.rowDivider:{},...extra});/* @__PURE__ */
|
|
362
|
+
return jsxRuntime.jsxs("article",{style:s.page,"data-testid":"record-document",children:[
|
|
363
|
+
/* @__PURE__ */jsxRuntime.jsxs("header",{style:s.letterhead,children:[
|
|
364
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.wordmark,children:wordmark}),
|
|
365
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.docTitle,children:COPY.docTitle}),
|
|
366
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.petName,children:petName?.trim()||COPY.namelessPet}),
|
|
367
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.generated,children:COPY.generated(record.generatedAt)})]}),record.identity.length>0?section(COPY.identity,record.identity.map((field,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:row(index),children:[
|
|
368
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rowLabel,children:field.label}),
|
|
369
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rowValue,children:field.value})]},`${index}:${field.label}`)),"record-document-identity"):null,depth&&depth.labResults.length>0?section(COPY.labs,depth.labResults.map((marker,index)=>{let status=markerStatusLabel(marker.latest.status),band=formatReferenceBand(marker.points[marker.points.length-1]??null),value=formatMarkerReading(marker.latest.value,marker.latest.unit??marker.unit,marker.latest.qualitativeResult);/* @__PURE__ */
|
|
370
|
+
return jsxRuntime.jsxs("div",{style:row(index,status.outOfRange?s.rowFlag:void 0),children:[
|
|
371
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:s.rowMain,children:[
|
|
372
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rowLabel,children:marker.name}),
|
|
373
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:s.rowMeta,children:[band?COPY.ref(band):COPY.noRange,marker.latest.at?` · ${formatRecordsDate(marker.latest.at)}`:""]})]}),
|
|
374
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:s.rowRight,children:[value!=="-"?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.rowValue,...status.outOfRange?s.alert:{}},children:value}):null,
|
|
375
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.markerStatus,...status.outOfRange?s.alert:{}},children:status.label})]})]},marker.markerId)}),"record-document-labs"):null,groups.map(({type:type,rows:rows})=>section(entityTypeLabel(type),rows.map((entity,index)=>{let detail=[formatEntityValue(entity.value,entity.unit),entity.observedAt?formatRecordsDate(entity.observedAt):null].filter(part=>part&&part.length>0).join(" · ");/* @__PURE__ */
|
|
376
|
+
return jsxRuntime.jsx("div",{style:row(index),children:/* @__PURE__ */jsxRuntime.jsxs("span",{style:s.rowMain,children:[
|
|
377
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rowLabel,children:entity.label}),detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rowMeta,children:detail}):null]})},entity.key)}),`record-document-${type}`)),record.forwardLooking.length>0?section(COPY.upcomingCare,record.forwardLooking.map((item,index)=>{let badge=dueBadge(item.dueAt,now);/* @__PURE__ */
|
|
378
|
+
return jsxRuntime.jsxs("div",{style:row(index),children:[
|
|
379
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:s.rowMain,children:[
|
|
380
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rowLabel,children:item.title}),item.detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:s.rowMeta,children:item.detail}):null]}),badge?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.rowValue,...badge.overdue?s.alert:{}},children:badge.label}):null]},`${item.title}-${index}`)}),"record-document-upcoming"):null,depth&&depth.physicalExams.length>0?section(COPY.physicalExams,depth.physicalExams.map((exam,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...s.block,...index>0?s.rowDivider:{}},children:[exam.observedOn?/* @__PURE__ */jsxRuntime.jsx("span",{style:s.blockDate,children:formatRecordsDate(exam.observedOn)}):null,exam.systems.filter(system=>system.finding).map(system=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.fieldRow,children:[
|
|
381
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.fieldLabel,children:bodySystemLabel(system.system)}),
|
|
382
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.fieldValue,children:system.finding})]},system.system))]},exam.examId)),"record-document-exams"):null,depth&&depth.clinicianNotes.length>0?section(COPY.clinicianNotes,depth.clinicianNotes.map((note,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...s.block,...index>0?s.rowDivider:{}},children:[note.observedOn?/* @__PURE__ */jsxRuntime.jsx("span",{style:s.blockDate,children:formatRecordsDate(note.observedOn)}):null,note.sections.filter(sec=>sec.text).map((sec,i)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.noteSection,children:[
|
|
383
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.noteLabel,children:soapSectionLabel(sec.section)}),
|
|
384
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:s.noteBody,children:sec.text})]},`${sec.section}-${i}`))]},note.noteId)),"record-document-notes"):null,disclaimerRepeatsFootnote(record.disclaimer)?null:/* @__PURE__ */jsxRuntime.jsx("p",{style:s.disclaimer,children:record.disclaimer})]})}function useDocStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeDocStyles(theme),[theme])}function makeDocStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:`${Math.round(size*multiplier)}px`,color:fg}),monoText=(size,fg)=>({margin:0,...faceCss(theme,"mono"),fontSize:size,lineHeight:`${size+space.xs-1}px`,color:fg,letterSpacing:type.letterSpacing.eyebrow/2,textTransform:"uppercase"}),hairline=`1px solid ${color.borderHairlineGreen}`;return{empty:{...text3(type.size.body,type.lineHeight.normal,color.text.muted,"medium"),textAlign:"center",padding:`${space.xxl}px ${space.xxl}px`},page:{padding:`0 ${space.lg+space.xs}px ${space.xxl+space.lg}px`,...faceCss(theme,"regular")},letterhead:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.xs+space.xs/2,padding:`${space.md}px 0 ${space.lg+space.xs+space.xs/2}px`,borderBottom:`2px solid ${color.brandInk}`,marginBottom:space.sm},wordmark:{...text3(type.size.heading,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:type.letterSpacing.headerBrand},docTitle:{...monoText(type.size.caption,color.brandInk),marginTop:space.sm+space.xs/2,letterSpacing:type.letterSpacing.eyebrow+.4},petName:text3(type.size.verdict+space.xs/2,type.lineHeight.tight,color.text.primary),generated:{...monoText(type.size.tiny,color.text.muted),textTransform:"none"},section:{marginTop:space.lg+space.xs+space.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:space.sm+space.xs/2,marginBottom:space.sm},sectionTitle:monoText(type.size.tiny,color.brandInk),rule:{flex:1,height:1,backgroundColor:color.borderHairlineGreen},row:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.md+space.xs/2,padding:`${space.sm+1}px 0`},rowDivider:{borderTop:hairline},rowFlag:{backgroundColor:color.badgeBgCritical,margin:`0 -${space.sm}px`,padding:`${space.sm+1}px ${space.sm}px`,borderRadius:radius.xs},rowMain:{display:"flex",flexDirection:"column",minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:space.xs/2},rowLabel:{...text3(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowValue:{...text3(type.size.body,type.lineHeight.normal,color.text.primary,"bold"),textAlign:"right"},alert:{color:color.danger},rowMeta:{marginTop:space.xs/2,...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,color:color.text.muted},markerStatus:monoText(type.size.micro,color.text.muted),block:{padding:`${space.sm+space.xs/2}px 0`},blockDate:{...monoText(type.size.tiny,color.text.muted),display:"block",marginBottom:space.xs+space.xs/2},fieldRow:{display:"flex",alignItems:"flex-start",gap:space.md+space.xs/2,padding:`${space.xs-1}px 0`},fieldLabel:{width:120,flexShrink:0,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted,"medium")},fieldValue:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"medium")},noteSection:{marginTop:space.sm},noteLabel:{...monoText(type.size.tiny,color.brandInk),display:"block",marginBottom:space.xs/2},noteBody:text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),disclaimer:{...text3(type.size.tiny,type.lineHeight.relaxed,color.text.muted),marginTop:radius.xl,paddingTop:space.md+space.xs/2,borderTop:hairline}}}var FACT_EDIT_COPY=/* @__PURE__ */Object.freeze({editA11y:label=>`Edit ${label}. Correct or remove this record detail.`,title:label=>`Edit ${label}`,helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",confirmRemove:"Remove this detail from your record? This can't be undone.",removeConfirm:"Remove",removing:"Removing...",keep:"Keep",noChange:"Change a value before saving.",saved:"Saved.",removed:"Removed.",detail:"record detail"});function factEditErrorMessage(error,mode){return isRecordsConsentRequired(error)?mode==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":isFactReviewerLocked(error)?mode==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":mode==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}var EMPTY_FACT_OVERLAY=/* @__PURE__ */Object.freeze({edits:/* @__PURE__ */Object.freeze({}),removed:/* @__PURE__ */Object.freeze([])});function applyFactOverlay(entities,overlay){if(Object.keys(overlay.edits).length===0&&overlay.removed.length===0)return entities;let out=[];for(let entity of entities){let key=entity.canonicalKey??null;if(key!==null&&overlay.removed.includes(key))continue;let edited=key!==null?overlay.edits[key]:void 0;out.push(edited===void 0?entity:/* @__PURE__ */Object.freeze({...entity,value:edited}))}/* @__PURE__ */
|
|
385
|
+
return Object.freeze(out)}function isFactEditable(entity){return typeof entity.canonicalKey=="string"&&entity.canonicalKey.length>0}function defaultFactKey(){return`records-fact-${Date.now().toString(36)}`}function useRecordFactEdit(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[overlay,setOverlay]=react.useState(EMPTY_FACT_OVERLAY),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[darkScope,setDarkScope]=react.useState(null),markDark=react.useCallback(()=>setDarkScope(scope),[scope]),available=userRef!==null&&darkScope!==scope,locked=react.useRef(false),mintRef=react.useRef(opts.newIdempotencyKey);mintRef.current=opts.newIdempotencyKey;let mint=react.useCallback(()=>(mintRef.current??defaultFactKey)(),[]),settle=react.useCallback((result,rollback,mode)=>{if(setBusy(false),!result.ok){if(rollback(),isDarkRouteError(result.error)){markDark();return}setError(factEditErrorMessage(result.error,mode))}},[markDark]),edit=react.useCallback(async(entity,value)=>{let key=entity.canonicalKey??"",next=value.trim();if(locked.current||key.length===0||next.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,edits:{...current.edits,[key]:next}}));let result=await client.editFact(petRef,{entityType:entity.category,canonicalKey:key,correctedFields:factCorrectionFor(entity.value,next),idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"edit"),result},[client,petRef,overlay,settle,mint]),remove=react.useCallback(async entity=>{let key=entity.canonicalKey??"";if(locked.current||key.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,removed:[...current.removed,key]}));let result=await client.removeFact(petRef,{entityType:entity.category,canonicalKey:key,idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"remove"),result},[client,petRef,overlay,settle,mint]),clearError=react.useCallback(()=>setError(null),[]);return react.useMemo(()=>({overlay:overlay,busy:busy,error:error,available:available,edit:edit,remove:remove,clearError:clearError}),[overlay,busy,error,available,edit,remove,clearError])}var FALLBACK_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccination",medication:"Medication",problem:"Problem",body_weight:"Weight",allergy:"Allergy",vital:"Vital",lab_result:"Lab result",parasite_prevention:"Preventive"}),GIVEN_PREFIX="Given",ISO_DATE_PREFIX=/^\d{4}-\d{2}-\d{2}/,DETAIL_SEPARATOR=" · ";function joinDetail(parts){let kept=parts.filter(part=>part!==null&&part.trim().length>0);return kept.length>0?kept.join(DETAIL_SEPARATOR):null}function rowTitle(facts,humanizeCategory){let label=facts.label.trim();if(label.length>0)return label;let fallback=FALLBACK_TITLE[facts.category];return fallback!==void 0?fallback:humanizeCategory(facts.category)}function entityRowSummary(facts,fmt){let title=rowTitle(facts,fmt.humanize),value=fmt.formatEntityValue(facts.value,facts.unit),shownValue=value.trim().length>0?value:null,rawDate=facts.observedAt!==null&&facts.observedAt.trim().length>0?fmt.formatRecordsDate(facts.observedAt):null,observed=rawDate!==null&&rawDate!=="-"?rawDate:null;switch(facts.category){case"vaccination":{let valueIsDate=facts.value!==null&&ISO_DATE_PREFIX.test(facts.value.trim()),givenOn=valueIsDate?fmt.formatRecordsDate(facts.value):observed;return givenOn!==null&&givenOn!=="-"?{title:title,detail:joinDetail([`${GIVEN_PREFIX} ${givenOn}`,valueIsDate?null:shownValue])}:{title:title,detail:joinDetail([shownValue])}}case"medication":return{title:title,detail:joinDetail([observed])};case"problem":return{title:title,detail:joinDetail([observed])};case"body_weight":return{title:title,detail:joinDetail([observed])};case"allergy":return{title:title,detail:joinDetail([observed])};case"vital":return{title:title,detail:joinDetail([shownValue,observed])};case"lab_result":return{title:title,detail:joinDetail([shownValue,observed])};default:return{title:title,detail:joinDetail([shownValue,observed])}}}function markerStatusTone(status){return status==="above"||status==="below"?"critical":status==="in_range"?"positive":"neutral"}function markerStatusSpoken(status){switch(status){case"above":return"above the reference range";case"below":return"below the reference range";case"in_range":return"within range";default:return"no reference range on file"}}function rangePhrase(point){return point.refLow!==null&&point.refHigh!==null?`, reference range ${point.refLow} to ${point.refHigh}`:point.refLow!==null?`, reference range at least ${point.refLow}`:point.refHigh!==null?`, reference range up to ${point.refHigh}`:""}function formatReferenceRange(point,unit){let u=unit?` ${unit}`:"";return point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}${u}`:point.refLow!==null?`≥ ${point.refLow}${u}`:point.refHigh!==null?`≤ ${point.refHigh}${u}`:"-"}function markerPointSpoken(marker,point){let reviewed=point.reviewed?", reviewed by our team":"",clinic=point.sourceClinic?`, from ${point.sourceClinic}`:"";return`${formatRecordsDate(point.at)}: ${formatMarkerReading(point.value,marker.unit,point.qualitativeResult)}, ${markerStatusSpoken(point.status)}${rangePhrase(point)}${clinic}${reviewed}`}function lead(petName){return petName?.trim()||"my pet"}function clause(text3){let t=text3.trim();return/[.!?]$/.test(t)?t:`${t}.`}function buildMarkerAskPrompt(petName,input){let name=input.canonicalName.trim()||"a lab marker",parts=[`I'm looking at ${lead(petName)}'s ${name}`],stats=[input.latestValueText?.trim(),input.statusText?.trim(),input.trajectoryText?.trim()].filter(Boolean).join(", ");return parts[0]+=stats?`: ${stats}.`:".",input.meaningText?.trim()&&parts.push(clause(input.meaningText)),parts.push(`What does this trend tell me, and should I do anything differently for ${lead(petName)}?`),{prompt:parts.join(" "),entityRef:{type:"marker",id:input.markerId,payload:{marker:name,...input.statusText?.trim()?{status:input.statusText.trim()}:{}}}}}function buildMarkerSummaryAskPrompt(petName,summary,petId){let{totalMarkers:totalMarkers,inRangeCount:inRangeCount,outOfRangeCount:outOfRangeCount,unknownCount:unknownCount}=summary;if(totalMarkers===0)return{prompt:`I'm looking at ${lead(petName)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${lead(petName)}?`,entityRef:{type:"marker_summary",id:petId,payload:{total:0}}};let tail=unknownCount>0?`, ${unknownCount} without a reference range`:"";return{prompt:`I'm looking at ${lead(petName)}'s lab markers: ${totalMarkers} total, ${inRangeCount} in range, ${outOfRangeCount} out of range${tail}. What should I focus on?`,entityRef:{type:"marker_summary",id:petId,payload:{total:totalMarkers,inRange:inRangeCount,outOfRange:outOfRangeCount,unknown:unknownCount}}}}function buildMarkerReadingAskPrompt(petName,input){let name=input.canonicalName.trim()||"a lab marker",bits=[`${name}: ${input.valueText.trim()}`];input.collectedAt?.trim()&&bits.push(`collected ${input.collectedAt.trim()}`),input.sourceClinic?.trim()&&bits.push(`from ${input.sourceClinic.trim()}`),input.referenceText?.trim()&&bits.push(`reference range ${input.referenceText.trim()}`),input.flagged&&bits.push(`flagged ${input.flagged}`);let payload={marker:name};return input.flagged&&(payload.status=input.flagged),input.reviewed!==void 0&&(payload.reviewed=input.reviewed),{prompt:`I'm looking at ${lead(petName)}'s ${bits.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:input.entityId,payload:payload}}}function buildRecordsRequestAskPrompt(petName,input,requestId2){let clinic=input.clinicName?.trim(),held=input.heldItemCount??0,heldPhrase=held>0?`, ${held} fact${held===1?"":"s"} being verified`:"";return{prompt:`I'm looking at ${lead(petName)}'s records request${clinic?` to ${clinic}`:""}, status: ${input.statusLabel.trim()}${heldPhrase}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:requestId2,payload:{status:input.status,held:held,...clinic?{clinic:clinic}:{}}}}}var ENTITY_TYPE_MAP=/* @__PURE__ */Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function buildEntityRowAskPrompt(petName,input,entityType,entityId){let kind=input.entityTypeLabel.trim()||"record",title=input.title.trim()||kind,detail=input.detail?.trim();return{prompt:`I'm looking at ${lead(petName)}'s ${kind.toLowerCase()}: ${title}${detail?`, ${detail}`:""}. What does this mean, and what should I keep on top of for ${lead(petName)}?`,entityRef:{type:ENTITY_TYPE_MAP[entityType]??entityType,id:entityId,payload:{kind:kind,title:title,...detail?{detail:detail}:{}}}}}function buildUpcomingCareAskPrompt(petName,items,petId){let list=items.filter(i=>i.label.trim()),entityRef={type:"upcoming_care",id:petId};if(list.length===0)return{prompt:`I'm looking at ${lead(petName)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${lead(petName)} be on?`,entityRef:entityRef};let named=[...list].sort((a,b)=>(a.tone==="overdue"?0:1)-(b.tone==="overdue"?0:1)).slice(0,4).map(i=>i.relativeText.trim()?`${i.label.trim()} (${i.relativeText.trim().toLowerCase()})`:i.label.trim());return{prompt:`I'm looking at ${lead(petName)}'s upcoming care: ${named.join(", ")}. What should I prioritize for ${lead(petName)}, and how do I stay on top of these?`,entityRef:entityRef}}function buildPhysicalExamAskPrompt(petName,input,examId){let parts=[`I'm looking at ${lead(petName)}'s physical exam${input.observedOn?.trim()?` from ${input.observedOn.trim()}`:""}.`],abnormal=input.abnormal.filter(a=>a.system.trim());return abnormal.length>0?(parts.push(`Abnormal: ${abnormal.slice(0,6).map(a=>`${a.system.trim()}: ${a.finding.trim()}`).join("; ")}.`),parts.push(`What do these findings mean, and what should I follow up on for ${lead(petName)}?`)):parts.push(`Everything examined came back normal. What does this tell me about ${lead(petName)}'s health?`),{prompt:parts.join(" "),entityRef:{type:"physical_exam",id:examId}}}function buildVisitNoteAskPrompt(petName,input,noteId){let parts=[`I'm looking at ${lead(petName)}'s visit notes${input.observedOn?.trim()?` from ${input.observedOn.trim()}`:""}.`];for(let s of input.sections.filter(section=>section.text.trim()).slice(0,3))parts.push(`${s.label.trim()||"Note"}: ${clause(s.text)}`);return parts.push(`Can you summarize what happened and what I should follow up on for ${lead(petName)}?`),{prompt:parts.join(" "),entityRef:{type:"visit",id:noteId}}}function buildConflictAskPrompt(petName,input,conflictId){let scope=input.scopeLabel.trim()||"a detail",cands=input.candidates.filter(c=>c.value.trim()),rendered=cands.slice(0,3).map(c=>`"${c.value.trim()}"${c.clinicName?.trim()?` (${c.clinicName.trim()})`:""}`).join(" vs ");return{prompt:`Two of ${lead(petName)}'s documents disagree on ${scope}: ${rendered}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:conflictId,payload:{field:scope,severity:input.severity,values:cands.map(c=>c.value.trim()).join(" | ")}}}}var FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=react.useRef(null),wasOpen=react.useRef(false),opener=react.useRef(null),trigger=react.useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=react.useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||document.activeElement===target)&&(opener.current=null)},[]);react.useEffect(()=>{let node=dialogRef.current;if(!wasOpen.current){let active=typeof document>"u"?null:document.activeElement;active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(document.activeElement)||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),react.useEffect(()=>restoreFocus,[restoreFocus]),react.useEffect(()=>{let node=dialogRef.current;if(node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&document.activeElement!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown=react.useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=document.activeElement;event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=react.useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown,onCancel:onCancel}}var FOCUSABLE2='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function RecordsDialog({label:label,onClose:onClose,shape:shape="modal",returnFocusTo:returnFocusTo,panelStyle:panelStyle,testID:testID,children:children}){let{styles:styles}=useScreenStyles(),dialog=useModalDialog(true,onClose,returnFocusTo);react.useEffect(()=>{let node=dialog.dialogRef.current;node===null||node.contains(document.activeElement)||(node.querySelector(FOCUSABLE2)??node).focus()},[dialog.dialogRef]);let side=shape==="side";/* @__PURE__ */
|
|
386
|
+
return jsxRuntime.jsx("dialog",{ref:dialog.dialogRef,"aria-label":label,"aria-modal":"true",onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.dialogFrame,"data-testid":testID,children:/* @__PURE__ */jsxRuntime.jsx("div",{style:side?styles.dialogScrimSide:styles.dialogScrim,onClick:event=>{event.target===event.currentTarget&&onClose()},"data-testid":testID?`${testID}-scrim`:void 0,children:/* @__PURE__ */jsxRuntime.jsx("div",{style:{...side?styles.dialogPanelSide:styles.dialogPanel,...panelStyle},children:children})})})}function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let{theme:theme,styles:styles}=useScreenStyles(),[open,setOpen]=react.useState(false),trigger=react.useRef(null),label=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
|
|
387
|
+
return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm},children:[
|
|
388
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:children}),
|
|
389
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{ref:trigger,type:"button",onClick:()=>setOpen(true),"aria-label":FACT_EDIT_COPY.editA11y(label),style:styles.iconButton,"data-testid":`fact-edit-open-${entity.canonicalKey??entity.key}`,children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:theme.space.md+theme.space.xs/2,height:2,backgroundColor:theme.color.brand,borderRadius:theme.radius.pill,transform:"rotate(-45deg)"}})}),open?/* @__PURE__ */jsxRuntime.jsx(FactEditSheet,{entity:entity,title:label,factEdit:factEdit,onClose:()=>setOpen(false),returnFocusTo:trigger}):null]})}function FactEditSheet({entity:entity,title:title,factEdit:factEdit,onClose:onClose,returnFocusTo:returnFocusTo}){let{theme:theme,styles:styles}=useScreenStyles(),[draft,setDraft]=react.useState(entity.value??""),[localError,setLocalError]=react.useState(null),[confirmingRemove,setConfirmingRemove]=react.useState(false);react.useEffect(()=>{factEdit.clearError()},[factEdit]);let changed=draft.trim().length>0&&draft.trim()!==(entity.value??"").trim(),error=localError??factEdit.error,busy=factEdit.busy,submitEdit=()=>{if(!changed){setLocalError(FACT_EDIT_COPY.noChange);return}setLocalError(null),factEdit.edit(entity,draft).then(result=>{result.ok&&onClose()})},submitRemove=()=>{setLocalError(null),factEdit.remove(entity).then(result=>{result.ok?onClose():setConfirmingRemove(false)})},fieldId=`fact-edit-${entity.key}`;
|
|
390
|
+
/* @__PURE__ */
|
|
391
|
+
return jsxRuntime.jsxs(RecordsDialog,{label:FACT_EDIT_COPY.title(title),onClose:onClose,returnFocusTo:returnFocusTo,testID:"fact-edit-sheet",children:[
|
|
392
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.sheetHeader,children:[
|
|
393
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:theme.space.xs},children:[
|
|
394
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sheetTitle,children:FACT_EDIT_COPY.title(title)}),
|
|
395
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{role:"status","aria-live":"polite",style:{...styles.sheetHelper,...error?styles.errorText:{}},children:error??FACT_EDIT_COPY.helper})]}),
|
|
396
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,"aria-label":FACT_EDIT_COPY.close,style:styles.iconButton,"data-testid":"fact-edit-close",children:/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.closeGlyph,"aria-hidden":"true",children:"×"})})]}),
|
|
397
|
+
/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:fieldId,style:styles.fieldLabel,children:entity.label}),
|
|
398
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{id:fieldId,style:styles.field,value:draft,onChange:event=>{setDraft(event.target.value),setLocalError(null)},disabled:busy,maxLength:512,"data-testid":"fact-edit-field"}),confirmingRemove?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.sm,padding:theme.space.md,borderRadius:theme.radius.md,backgroundColor:theme.color.badgeBgCritical},"data-testid":"fact-edit-confirm-remove",children:[
|
|
399
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:FACT_EDIT_COPY.confirmRemove}),
|
|
400
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",gap:theme.space.sm},children:[
|
|
401
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.removing:FACT_EDIT_COPY.removeConfirm,kind:"danger",busy:busy,onClick:submitRemove,style:{flex:1},testID:"fact-edit-remove-confirm"}),
|
|
402
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:FACT_EDIT_COPY.keep,kind:"outline",disabled:busy,onClick:()=>setConfirmingRemove(false),style:{flex:1},testID:"fact-edit-remove-cancel"})]})]}):/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.sm},children:[
|
|
403
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.saving:FACT_EDIT_COPY.save,busy:busy,disabled:!changed,onClick:submitEdit,testID:"fact-edit-save"}),
|
|
404
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",disabled:busy,onClick:()=>{setLocalError(null),setConfirmingRemove(true)},style:{...styles.pill,...styles.pillLink,color:theme.color.danger,...busy?styles.pillDisabled:{}},"data-testid":"fact-edit-remove",children:FACT_EDIT_COPY.remove})]})]})}function RecordSections({record:record,depth:depth,petName:petName,showLabs:showLabs=true,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit,nowMs:nowMs}){let{theme:theme,styles:styles}=useScreenStyles(),now=nowMs??Date.now(),entities=react.useMemo(()=>factEdit?applyFactOverlay(record.entities,factEdit.overlay):record.entities,[record.entities,factEdit]),byType=react.useMemo(()=>{let order=[],groups=/* @__PURE__ */new Map;for(let entity of entities){let category=entity.category.trim();if(category.length===0)continue;let bucket=groups.get(category);bucket===void 0?(order.push(category),groups.set(category,[entity])):bucket.push(entity)}return{order:orderEntityTypes(order),groups:groups}},[entities]),documents=Object.values(record.documents),editable=factEdit!==void 0&&factEdit.available,ask=(build,label,testID)=>onAsk?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>{let built=build();onAsk(built.prompt,built.entityRef)},"aria-label":label,style:{...styles.pill,...styles.pillAsk,marginTop:theme.space.lg,alignSelf:"flex-start"},"data-testid":testID,children:label}):null,sectionStack={display:"flex",flexDirection:"column",gap:theme.space.lg+theme.space.xs},rowStyle2=index=>({...styles.row,...index>0?styles.rowDivider:{}}),cardBlock={...styles.card,padding:`${theme.space.md}px ${theme.space.lg}px`,display:"flex",flexDirection:"column"};/* @__PURE__ */
|
|
405
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
406
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:sectionStack,children:[depth&&depth.conflicts.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-conflicts",children:[
|
|
407
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.needsAttention,count:depth.conflicts.length}),[...depth.conflicts].sort((a,b)=>conflictSeverityMeta(a.severity).rank-conflictSeverityMeta(b.severity).rank).map(conflict=>{let meta=conflictSeverityMeta(conflict.severity),scope=humanize(conflict.field??conflict.entityType);/* @__PURE__ */
|
|
408
|
+
return jsxRuntime.jsxs("div",{style:{...cardBlock,borderColor:styles.chipTones[meta.tone].color,gap:theme.space.sm},children:[
|
|
409
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm},children:[
|
|
410
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold"),flex:1},children:meta.label}),
|
|
411
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:scope,tone:meta.tone})]}),
|
|
412
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowDetail,children:RECORD_SCREEN_COPY.conflictSub}),conflict.candidates.map((candidate,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:{borderTop:`1px solid ${theme.color.borderHairlineGreen}`,paddingTop:theme.space.sm},children:[
|
|
413
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowTitle,children:candidate.value}),
|
|
414
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowMuted,children:[candidate.docId?record.documents[candidate.docId]?.title??RECORD_SCREEN_COPY.uploadedDocument:RECORD_SCREEN_COPY.uploadedDocument,candidate.collectedAt?formatRecordsDate(candidate.collectedAt):null].filter(Boolean).join(" · ")})]},index)),ask(()=>buildConflictAskPrompt(petName,{scopeLabel:scope,severity:conflict.severity,candidates:conflict.candidates.map(c=>({value:c.value,clinicName:c.docId?record.documents[c.docId]?.title??null:null}))},conflict.conflictId),RECORD_SCREEN_COPY.askConflict,`records-ask-conflict-${conflict.conflictId}`)]},conflict.conflictId)})]}):null,depth?.completeness?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-completeness",children:[
|
|
415
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.whatsOnFile}),
|
|
416
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.card,children:[
|
|
417
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm,padding:`${theme.space.md}px 0`},children:[[RECORD_SCREEN_COPY.coverage.labs,depth.completeness.hasLabHistory],[RECORD_SCREEN_COPY.coverage.vaccines,depth.completeness.hasVaccinationHistory],[RECORD_SCREEN_COPY.coverage.weight,depth.completeness.hasWeightHistory],[RECORD_SCREEN_COPY.coverage.vitals,depth.completeness.hasVitalsHistory],[RECORD_SCREEN_COPY.coverage.exams,depth.completeness.hasPhysicalExamHistory],[RECORD_SCREEN_COPY.coverage.procedures,depth.completeness.hasProcedureHistory],[RECORD_SCREEN_COPY.coverage.genetics,depth.completeness.hasGeneticHistory],[RECORD_SCREEN_COPY.coverage.parasite,depth.completeness.hasParasitePreventionHistory],[RECORD_SCREEN_COPY.coverage.reproductive,depth.completeness.hasReproductiveHistory]].map(([label,present])=>/* @__PURE__ */jsxRuntime.jsx("span",{"aria-label":`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,style:{...styles.chip,...present?styles.chipTones.positive:{backgroundColor:theme.color.badgeBgNeutral,color:theme.color.text.muted},fontSize:theme.type.size.caption},children:label},label))}),
|
|
418
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm,paddingBottom:theme.space.md},children:[
|
|
419
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowDetail,flex:1,marginTop:0},children:RECORD_SCREEN_COPY.documentsOnFile(depth.completeness.documentsIngested)}),depth.completeness.documentsInReview>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.inReviewChip(depth.completeness.documentsInReview),tone:"warning"}):null,heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)>0?/* @__PURE__ */jsxRuntime.jsx("span",{"aria-label":RECORD_SCREEN_COPY.beingVerifiedA11y(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.beingVerified(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),depth.completeness.earliestRecordAt||depth.completeness.latestRecordAt?/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.rowDetail,paddingBottom:theme.space.md},children:RECORD_SCREEN_COPY.dateRange(depth.completeness.earliestRecordAt,depth.completeness.latestRecordAt)}):null,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).length>0?/* @__PURE__ */jsxRuntime.jsxs("p",{style:{...styles.rowMuted,paddingBottom:theme.space.md},children:[RECORD_SCREEN_COPY.pendingReview,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).map(([type,count])=>`${entityTypeLabel(type)} (${count})`).join(", ")]}):null]})]}):null,documents.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-documents",children:[
|
|
420
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.documents,count:documents.length}),
|
|
421
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.card,children:documents.map((doc,index)=>{let title=doc.title?.trim()||RECORD_SCREEN_COPY.uploadedDocument,meta=RECORD_SCREEN_COPY.documentMeta(doc.pageCount,doc.receivedAt),body=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
422
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:styles.rowMain,children:[
|
|
423
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:title}),meta?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowDetail,display:"block"},children:meta}):null]}),onNavigate?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]});/* @__PURE__ */
|
|
424
|
+
return jsxRuntime.jsx("li",{style:rowStyle2(index),children:onNavigate?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>onNavigate({name:"contributions",docId:doc.docId}),"aria-label":RECORD_SCREEN_COPY.documentRowA11y(title),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:theme.space.md,width:"100%",background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},"data-testid":`records-document-row-${doc.docId}`,children:body}):body},doc.docId)})})]}):null,record.identity.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-identity",children:[
|
|
425
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.identity}),
|
|
426
|
+
/* @__PURE__ */jsxRuntime.jsx("dl",{style:styles.card,children:record.identity.map((field,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:rowStyle2(index),children:[
|
|
427
|
+
/* @__PURE__ */jsxRuntime.jsx("dt",{style:{...styles.rowDetail,...faceCss(theme,"medium"),marginTop:0},children:field.label}),
|
|
428
|
+
/* @__PURE__ */jsxRuntime.jsx("dd",{style:{...styles.rowTitle,margin:0,textAlign:"right"},children:formatIdentityValue(field.value)})]},`${index}:${field.label}`))})]}):null,
|
|
429
|
+
/* @__PURE__ */jsxRuntime.jsx(TrendRangeCard,{series:record.entitySeries}),record.forwardLooking.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-upcoming",children:[
|
|
430
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.upcomingCare,count:record.forwardLooking.length}),
|
|
431
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.card,children:record.forwardLooking.map((item,index)=>{let badge=dueBadge(item.dueAt,now);/* @__PURE__ */
|
|
432
|
+
return jsxRuntime.jsxs("li",{style:rowStyle2(index),children:[
|
|
433
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:styles.rowMain,children:[
|
|
434
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:item.title}),item.detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowDetail,display:"block"},children:item.detail}):null]}),badge?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:badge.label,tone:badge.overdue?"critical":"info"}):null]},`${item.title}-${index}`)})}),ask(()=>buildUpcomingCareAskPrompt(petName,record.forwardLooking.map(item=>{let badge=dueBadge(item.dueAt,now);return{label:item.title,relativeText:badge?.label??"",tone:badge?.overdue?"overdue":"upcoming"}}),record.petRef),RECORD_SCREEN_COPY.askUpcomingCare,"records-ask-upcoming-care")]}):null,byType.order.map(category=>{let rows=byType.groups.get(category)??[];if(rows.length===0)return null;let label=entityTypeLabel(category);/* @__PURE__ */
|
|
435
|
+
return jsxRuntime.jsxs("section",{style:styles.section,"data-testid":`record-section-${category}`,children:[
|
|
436
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:label,count:rows.length}),
|
|
437
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.card,children:rows.map((entity,index)=>{let summary=entityRowSummary(entity,{formatEntityValue:formatEntityValue,formatRecordsDate:formatRecordsDate,humanize:humanize}),detail=summary.detail,row=/* @__PURE__ */jsxRuntime.jsxs("div",{style:rowStyle2(index),children:[
|
|
438
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...styles.rowMain,display:"flex",flexDirection:"column"},children:[
|
|
439
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:summary.title}),detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowDetail,children:detail}):null,ask(()=>buildEntityRowAskPrompt(petName,{entityTypeLabel:label,title:summary.title,detail:detail},category,entity.key),RECORD_SCREEN_COPY.askEverfur,`records-ask-entity-${entity.key}`)]}),entity.status?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:humanize(entity.status)}):null]});/* @__PURE__ */
|
|
440
|
+
return jsxRuntime.jsx("li",{children:editable&&isFactEditable(entity)&&factEdit?/* @__PURE__ */jsxRuntime.jsx(FactEditAffordance,{entity:entity,factEdit:factEdit,children:row}):row},entity.key)})})]},category)}),depth&&depth.physicalExams.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-exams",children:[
|
|
441
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.physicalExams,count:depth.physicalExams.length}),depth.physicalExams.map(exam=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:cardBlock,children:[
|
|
442
|
+
/* @__PURE__ */jsxRuntime.jsx("h4",{style:{...styles.rowTitle,paddingTop:theme.space.sm},children:exam.observedOn?formatRecordsDate(exam.observedOn):DEPTH_COPY.exam}),
|
|
443
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.plainList,children:exam.systems.map((system,index)=>{let abnormal=system.findingStatus==="abnormal",label=abnormal?DEPTH_COPY.abnormal:system.findingStatus==="not_examined"?DEPTH_COPY.notExamined:DEPTH_COPY.normal;/* @__PURE__ */
|
|
444
|
+
return jsxRuntime.jsxs("li",{style:rowStyle2(index),children:[
|
|
445
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:styles.rowMain,children:[
|
|
446
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:bodySystemLabel(system.system)}),abnormal&&system.finding?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowDetail,display:"block"},children:system.finding}):null]}),
|
|
447
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:label,tone:abnormal?"warning":system.findingStatus==="not_examined"?"neutral":"positive"})]},system.system)})}),ask(()=>buildPhysicalExamAskPrompt(petName,{observedOn:exam.observedOn?formatRecordsDate(exam.observedOn):null,abnormal:exam.systems.filter(s=>s.findingStatus==="abnormal").map(s=>({system:bodySystemLabel(s.system),finding:s.finding??""}))},exam.examId),RECORD_SCREEN_COPY.askExam,`records-ask-exam-${exam.examId}`)]},exam.examId))]}):null,depth&&depth.clinicianNotes.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-notes",children:[
|
|
448
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.visitNotes,count:depth.clinicianNotes.length}),depth.clinicianNotes.map(note=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:cardBlock,children:[
|
|
449
|
+
/* @__PURE__ */jsxRuntime.jsx("h4",{style:{...styles.rowTitle,paddingTop:theme.space.sm},children:note.observedOn?formatRecordsDate(note.observedOn):DEPTH_COPY.visitNote}),
|
|
450
|
+
/* @__PURE__ */jsxRuntime.jsx("dl",{style:styles.plainList,children:note.sections.map((section,index)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:{padding:`${theme.space.md}px 0`,...index>0?styles.rowDivider:{}},children:[
|
|
451
|
+
/* @__PURE__ */jsxRuntime.jsx("dt",{style:{...styles.rowDetail,...faceCss(theme,"bold"),marginTop:0,textTransform:"uppercase"},children:soapSectionLabel(section.section)}),
|
|
452
|
+
/* @__PURE__ */jsxRuntime.jsx("dd",{style:{...styles.bodyText,marginLeft:0,...section.text?{}:{color:theme.color.text.muted,fontStyle:"italic"}},children:section.text||DEPTH_COPY.notRecorded})]},`${section.section}:${index}`))}),ask(()=>buildVisitNoteAskPrompt(petName,{observedOn:note.observedOn?formatRecordsDate(note.observedOn):null,sections:note.sections.map(s=>({label:soapSectionLabel(s.section),text:s.text}))},note.noteId),RECORD_SCREEN_COPY.askVisit,`records-ask-note-${note.noteId}`)]},note.noteId))]}):null,showLabs&&depth&&depth.labResults.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-labs",children:[
|
|
453
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.labResults,count:depth.labResults.length}),
|
|
454
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.card,children:depth.labResults.map((marker,index)=>{let status=markerStatusLabel(marker.latest.status),detail=labDetailLine(marker.latest.at,marker.trajectory,marker.points.length);/* @__PURE__ */
|
|
455
|
+
return jsxRuntime.jsxs("li",{style:rowStyle2(index),children:[
|
|
456
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:{...styles.rowMain,display:"flex",flexDirection:"column"},children:[
|
|
457
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:marker.name}),
|
|
458
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowValue,children:formatMarkerReading(marker.latest.value,marker.latest.unit,marker.latest.qualitativeResult)}),detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowDetail,children:detail}):null]}),
|
|
459
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:status.label,tone:markerStatusTone(marker.latest.status)})]},marker.markerId)})})]}):null,depth&&depth.encounters.length>0?/* @__PURE__ */jsxRuntime.jsxs("section",{style:styles.section,"data-testid":"record-section-visits",children:[
|
|
460
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.visits,count:depth.encounters.length}),
|
|
461
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.card,children:depth.encounters.map((encounter,index)=>{let detail=[encounter.date?formatRecordsDate(encounter.date):null,encounter.clinicName,encounter.veterinarian].filter(p=>p&&p!=="-").join(" · ");/* @__PURE__ */
|
|
462
|
+
return jsxRuntime.jsx("li",{style:rowStyle2(index),children:/* @__PURE__ */jsxRuntime.jsxs("span",{style:styles.rowMain,children:[
|
|
463
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:encounter.type?humanize(encounter.type):DEPTH_COPY.visit}),detail?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowDetail,display:"block"},children:detail}):null]})},encounter.encounterId)})})]}):null]}),
|
|
464
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function ShareSheet({petRef:petRef,petName:petName,onClose:onClose,onNavigate:onNavigate,onOpenUrl:onOpenUrl,onCopy:onCopy,returnFocusTo:returnFocusTo}){let{theme:theme,styles:styles}=useScreenStyles(),shares=useRecordShares(petRef),[notice,setNotice]=react.useState(null),[pendingRevokeId,setPendingRevokeId]=react.useState(null),[audience,setAudience]=react.useState("vet"),[email2,setEmail]=react.useState(""),audienceGroup=react.useId(),shareRowId=react.useId(),mintable=shares.available&&!shares.consentRequired,armed=shares.shareAudiences.length>0,scope=shares.shareAudiences.find(served=>served.audience===audience)??null,included=scope!==null?shareIncludedLines(scope,shares.features):[],open=(url,kind)=>{if(onOpenUrl){callHostAsync(onOpenUrl,url,kind).then(outcome=>{outcome.ok||setNotice(SHARE_COPY.toasts.shareSheet)});return}if(kind==="share_link"){shareLinkInPlace(url,onCopy??copyText).then(outcome=>{outcome==="copied"&&setNotice(SHARE_COPY.toasts.copied)},()=>setNotice(SHARE_COPY.toasts.shareSheet));return}downloadInPlace(url,RECORD_PDF_FILENAME).then(saved=>{saved||setNotice(shareErrorMessage(null,"download"))})},onCreateLink=()=>{setNotice(null),shares.createLink(armed?audience:void 0).then(result=>{result.ok?open(result.value.shareUrl,"share_link"):setNotice(shareErrorMessage(result.error,"create"))})},onSend=event=>{if(event?.preventDefault(),shares.sending)return;setNotice(null);let address=email2.trim();if(address.length===0){setNotice(SHARE_COPY.addEmailFor(petName));return}if(!isShareRecipientEmail(address)){setNotice(SHARE_COPY.emailInvalid);return}shares.sendEmail({recipientEmail:address,recipientKind:audience}).then(result=>{result.ok?(setEmail(""),setNotice(SHARE_COPY.toasts.sentTo(address))):setNotice(shareErrorMessage(result.error,"email"))})},onDownload=()=>{setNotice(null),shares.pdfLink().then(result=>{result.ok?open(result.value.downloadUrl,"record_pdf"):setNotice(shareErrorMessage(result.error,"download"))})},onCopyRow=row=>{row.shareUrl!==null&&callHostAsync(onCopy??copyText,row.shareUrl).then(outcome=>setNotice(outcome.ok?SHARE_COPY.toasts.copied:SHARE_COPY.toasts.copyFailed))},onConfirmRevoke=shareId=>{shares.revoke(shareId).then(result=>{setPendingRevokeId(null),setNotice(result.ok?SHARE_COPY.toasts.turnedOff:shareErrorMessage(result.error,"revoke"))})},stateCard={display:"flex",flexDirection:"column",gap:theme.space.sm,padding:theme.space.md,borderRadius:theme.radius.md,backgroundColor:theme.color.surfaceCream,border:`1px solid ${theme.color.brandBorder}`},choice=selected=>({boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_TOUCH_TARGET,display:"flex",alignItems:"center",gap:theme.space.sm,padding:`${theme.space.sm}px ${theme.space.md}px`,borderRadius:theme.radius.md,cursor:"pointer",border:selected?`1.5px solid ${theme.color.brandInk}`:`1px solid ${theme.color.borderHairlineGreen}`,backgroundColor:selected?theme.color.brandSoft:theme.color.surface,...styles.rowTitle,...faceCss(theme,selected?"bold":"medium")});
|
|
465
|
+
/* @__PURE__ */
|
|
466
|
+
return jsxRuntime.jsxs(RecordsDialog,{label:SHARE_COPY.titleFor(petName),onClose:onClose,shape:"side",returnFocusTo:returnFocusTo,testID:"share-record-sheet",children:[
|
|
467
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.sheetHeader,children:[
|
|
468
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:theme.space.xs},children:[
|
|
469
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sheetTitle,children:SHARE_COPY.titleFor(petName)}),
|
|
470
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.sheetHelper,children:armed?SHARE_COPY.leadWebFor(petName):SHARE_COPY.helper})]}),
|
|
471
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,"aria-label":SHARE_COPY.close,style:styles.iconButton,"data-testid":"share-record-close",children:/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.closeGlyph,"aria-hidden":"true",children:"×"})})]}),
|
|
472
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.sm},children:[onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.viewDocument,onClick:()=>{onClose(),onNavigate({name:"document"})},testID:"share-view-document"}):null,mintable?/* @__PURE__ */jsxRuntime.jsxs("form",{onSubmit:onSend,noValidate:true,style:{display:"flex",flexDirection:"column",gap:theme.space.md,margin:0},"data-testid":"share-email-form",children:[
|
|
473
|
+
/* @__PURE__ */jsxRuntime.jsxs("fieldset",{style:{border:0,margin:0,padding:0,minWidth:0},children:[
|
|
474
|
+
/* @__PURE__ */jsxRuntime.jsx("legend",{style:{...styles.fieldLabel,padding:0},children:SHARE_COPY.audienceLabel}),
|
|
475
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm},children:RECORD_SHARE_AUDIENCES.map(option=>/* @__PURE__ */jsxRuntime.jsxs("label",{style:choice(audience===option),children:[
|
|
476
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{type:"radio",name:audienceGroup,value:option,checked:audience===option,onChange:()=>setAudience(option),style:{margin:0,accentColor:theme.color.brandInk},"data-testid":`share-audience-${option}`}),SHARE_COPY.audiences[option]]},option))})]}),armed&&included.length>0?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs},"data-testid":"share-included",children:[
|
|
477
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.fieldLabel,margin:0},children:SHARE_COPY.included}),
|
|
478
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:{...styles.bodyText,margin:0,paddingLeft:theme.space.lg},children:included.map(line=>/* @__PURE__ */jsxRuntime.jsx("li",{children:line},line))})]}):null,
|
|
479
|
+
/* @__PURE__ */jsxRuntime.jsxs("label",{style:{...styles.fieldLabel,margin:0},children:[SHARE_COPY.sendTo,
|
|
480
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{type:"email",style:{...styles.field,marginTop:theme.space.xs},placeholder:SHARE_COPY.sendToPlaceholder,value:email2,maxLength:SHARE_RECIPIENT_EMAIL_MAX,autoComplete:"email",disabled:shares.sending,onChange:event=>setEmail(event.target.value),"data-testid":"share-email-input"})]}),
|
|
481
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.sending?SHARE_COPY.sending:SHARE_COPY.send,busy:shares.sending,onClick:()=>onSend(),testID:"share-email-send"})]}):null,mintable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.creating?SHARE_COPY.creatingLink:SHARE_COPY.createLink,kind:"outline",busy:shares.creating,onClick:onCreateLink,testID:"share-create-link"}):null,mintable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.preparingPdf?SHARE_COPY.preparingPdf:SHARE_COPY.downloadPdf,kind:"outline",busy:shares.preparingPdf,onClick:onDownload,testID:"share-download-pdf"}):null,mintable?/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.muted,textAlign:"center"},"data-testid":"share-link-terms",children:SHARE_COPY.linkTerms}):null]}),shares.consentRequired?/* @__PURE__ */jsxRuntime.jsxs("div",{style:stateCard,"data-testid":"share-consent-off",children:[
|
|
482
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowTitle,children:SHARE_COPY.consentOffTitle}),
|
|
483
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:SHARE_COPY.consentOffBody}),
|
|
484
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.retry,kind:"outline",onClick:shares.refresh,testID:"share-consent-retry"})]}):null,notice?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status","aria-live":"polite",style:styles.infoNote,"data-testid":"share-notice",children:notice}):null,sharesListShown(shares)?/* @__PURE__ */jsxRuntime.jsxs("section",{"aria-label":SHARE_COPY.activeLinks,style:{display:"flex",flexDirection:"column",gap:theme.space.sm},children:[
|
|
485
|
+
/* @__PURE__ */jsxRuntime.jsx("h4",{style:{...styles.fieldLabel,...faceCss(theme,"bold"),textTransform:"uppercase"},children:SHARE_COPY.activeLinks}),shares.status==="loading"?/* @__PURE__ */jsxRuntime.jsx(SharesSkeleton,{testID:"share-record-loading"}):shares.status==="error"?/* @__PURE__ */jsxRuntime.jsxs("div",{style:stateCard,"data-testid":"share-record-error",children:[
|
|
486
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowTitle,children:SHARE_COPY.errorTitle}),
|
|
487
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:SHARE_COPY.errorBody}),
|
|
488
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.retry,kind:"outline",onClick:shares.refresh,testID:"share-record-retry"})]}):shares.rows.length===0?/* @__PURE__ */jsxRuntime.jsxs("div",{style:stateCard,"data-testid":"share-record-empty",children:[
|
|
489
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowTitle,children:SHARE_COPY.emptyTitle}),
|
|
490
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:SHARE_COPY.emptyBody})]}):/* @__PURE__ */jsxRuntime.jsx("ul",{style:{...styles.plainList,gap:theme.space.md},children:shares.rows.map(row=>/* @__PURE__ */jsxRuntime.jsxs("li",{style:{...stateCard},"data-testid":`share-row-${row.shareId}`,children:[
|
|
491
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{id:`${shareRowId}-${row.shareId}`,"aria-label":row.a11yLabel,children:[
|
|
492
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm},children:[
|
|
493
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:theme.space.sm,height:theme.space.sm,borderRadius:theme.space.xs,backgroundColor:row.active?theme.color.success:theme.color.text.muted}}),
|
|
494
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold")},children:row.statusLabel}),
|
|
495
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.muted,children:row.expiryLabel})]}),row.createdLabel?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:row.createdLabel}):null]}),pendingRevokeId===row.shareId?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.sm},"data-testid":`share-revoke-confirm-${row.shareId}`,children:[
|
|
496
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:SHARE_COPY.confirmTurnOff}),
|
|
497
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm},children:[
|
|
498
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.revokingId===row.shareId?SHARE_COPY.turningOff:SHARE_COPY.turnOff,kind:"danger",busy:shares.revokingId===row.shareId,onClick:()=>onConfirmRevoke(row.shareId),testID:`share-revoke-do-${row.shareId}`}),
|
|
499
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.keep,kind:"outline",disabled:shares.revokingId===row.shareId,onClick:()=>setPendingRevokeId(null),testID:`share-revoke-cancel-${row.shareId}`})]})]}):/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm},children:[
|
|
500
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.copyLink,kind:"outline",disabled:row.shareUrl===null,ariaDescribedBy:`${shareRowId}-${row.shareId}`,onClick:()=>onCopyRow(row),testID:`share-copy-${row.shareId}`}),
|
|
501
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.turnOff,kind:"danger",ariaLabel:SHARE_COPY.turnOffA11y(row.actionContext),onClick:()=>setPendingRevokeId(row.shareId),testID:`share-ask-revoke-${row.shareId}`})]})]},row.shareId))})]}):null]})}var readDepth2=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty2=value=>!value.available;function EverfurRecordDetail(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
502
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"everfur-record-screen",children:[userRef===null?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsxRuntime.jsx(RecordBody,{...rest}),
|
|
503
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function RecordBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,onOpenUrl:onOpenUrl,onCopy:onCopy}){let{theme:theme,styles:styles}=useScreenStyles(),recordsOpts=react.useMemo(()=>controller?{petRef:petRef,controller:controller}:{petRef:petRef},[petRef,controller]),records=useEverfurRecords(recordsOpts),depth=useRecordsDepthRead(petRef,readDepth2,depthEmpty2),factEdit=useRecordFactEdit(petRef),shareProbe=useRecordsDepthProbe(petRef),[sharing,setSharing]=react.useState(false),rise=useSectionRise(),shareTrigger=react.useRef(null);useConsentTextWarning2(consentVersion,consentText);let canGrant=canGrantConsent(consentVersion,records.consent),onGrant=()=>{let version=resolveConsentVersion(consentVersion,records.consent);version.length!==0&&records.grantConsent(version,`records-consent-${Date.now().toString(36)}`)},depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,retry=()=>{records.refresh(),depth.refresh()},shareable=onNavigate!==void 0||shareProbe.lit===true,body;if(records.status==="loading"||depth.status==="loading"&&record!==null&&!record.isEmpty)body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"everfur-record-loading"});else if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?retry:void 0,testID:"everfur-record-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else if(record===null||record.isEmpty){let inReview=depthView?.completeness?.documentsInReview??0;body=/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.content,"data-testid":"everfur-record-empty",children:[
|
|
504
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",message:inReview>0?RECORD_SCREEN_COPY.inReview(inReview):void 0}),
|
|
505
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record?.disclaimer??""})]})}else body=/* @__PURE__ */jsxRuntime.jsx("div",{ref:rise,style:{...styles.content,gap:theme.space.lg+theme.space.xs,paddingBottom:theme.space.xxl+theme.space.sm},"data-testid":"everfur-record",children:/* @__PURE__ */jsxRuntime.jsx(RecordSections,{record:record,depth:depthView,petName:petName,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit})});/* @__PURE__ */
|
|
506
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
507
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:RECORD_SCREEN_COPY.title,onBack:onBack,testID:"everfur-record-header",right:shareable||onNavigate?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[onNavigate?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>onNavigate({name:"clinicBatch"}),"aria-label":RECORD_SCREEN_COPY.requestClinicsA11y,style:styles.iconButton,"data-testid":"everfur-record-request-clinics",children:/* @__PURE__ */jsxRuntime.jsx(HeaderGlyph,{name:"send",color:theme.color.brandInk})}):null,shareable?/* @__PURE__ */jsxRuntime.jsx("button",{ref:shareTrigger,type:"button",onClick:()=>setSharing(true),"aria-label":SHARE_COPY.openA11yFor(petName),style:styles.iconButton,"data-testid":"everfur-record-share",children:/* @__PURE__ */jsxRuntime.jsx(HeaderGlyph,{name:"share2",color:theme.color.brandInk})}):null]}):void 0}),
|
|
508
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:body}),sharing?/* @__PURE__ */jsxRuntime.jsx(ShareSheet,{petRef:petRef,petName:petName,onClose:()=>setSharing(false),returnFocusTo:shareTrigger,onNavigate:onNavigate,...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{}}):null]})}var REQUEST_DOCUMENTS_COPY=/* @__PURE__ */Object.freeze({download:"Download",downloadA11y:title=>`Download, ${title}`,listA11y:"You added these records"});function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}function formatLabel(docFormat){let trimmed=docFormat?.trim();return trimmed?trimmed.toUpperCase():null}function requestDocumentRows(items){/* @__PURE__ */
|
|
509
|
+
return Object.freeze(items.map(item=>{let format=formatLabel(item.docFormat),date=item.receivedAt?formatRecordsDate(item.receivedAt):null,title=item.fileName??format??date??item.sourceDocId,meta=[item.fileName!==null&&format!==null&&item.fileName.toUpperCase().endsWith(`.${format}`)||title===format?null:format,item.byteSize!==null?formatBytes(item.byteSize):null,title===date?null:date].filter(part=>!!part).join(" · ");/* @__PURE__ */
|
|
510
|
+
return Object.freeze({key:item.sourceDocId,title:title,meta:meta||null,downloadUrl:item.downloadUrl})}))}function requestDocumentFileName(item){let base=item.fileName?.trim()||item.sourceDocId,extension=item.docFormat?.trim().toLowerCase().replace(/^\./,"")??"";return extension.length===0||base.toLowerCase().endsWith(`.${extension}`)?base:`${base}.${extension}`}function useRequestDocuments(requestId2,opts={}){let enabled=opts.enabled??true,client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[documents,setDocuments]=react.useState(null),[loading,setLoading]=react.useState(enabled),[error,setError]=react.useState(null),generation=react.useRef(0),live=react.useRef(true),load=react.useCallback(async()=>{let gen=generation.current+=1;if(!enabled||userRef===null){setDocuments(null),setError(null),setLoading(false);return}setLoading(true),setError(null);let result=await client.listRequestDocuments(requestId2);gen!==generation.current||!live.current||(result.ok?setDocuments(result.value):(setDocuments(null),setError(result.error)),setLoading(false))},[client,enabled,requestId2,userRef]);react.useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]);let rows=react.useMemo(()=>documents===null?[]:requestDocumentRows(documents),[documents]),refresh=react.useCallback(()=>{load()},[load]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated";return react.useMemo(()=>({status:status,rows:rows,error:error,refresh:refresh}),[status,rows,error,refresh])}function RequestDocumentsList({requestId:requestId2,open:open=true,onOpenUrl:onOpenUrl,testID:testID="records-request-documents"}){let{theme:theme,styles:styles}=useScreenStyles(),documents=useRequestDocuments(requestId2,{enabled:open}),client=useEverfurRecordsDepthClient(),[savingKey,setSavingKey]=react.useState(null),[failedKey,setFailedKey]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let save=async row=>{setSavingKey(row.key),setFailedKey(null);let fresh=await client.listRequestDocuments(requestId2),doc=fresh.ok?fresh.value.find(item=>item.sourceDocId===row.key)??null:null,failed=doc===null;doc!==null&&live.current&&(onOpenUrl?await callHostAsync(onOpenUrl,doc.downloadUrl,"request_document"):failed=!await downloadInPlace(doc.downloadUrl,requestDocumentFileName(doc))),live.current&&(setSavingKey(null),failed&&setFailedKey(row.key))};return open?documents.status==="loading"?/* @__PURE__ */jsxRuntime.jsx("div",{style:{paddingTop:theme.space.sm},"aria-busy":"true","data-testid":`${testID}-loading`,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:theme.space.lg+theme.space.md})}):documents.status==="error"?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm,paddingTop:theme.space.sm},"data-testid":`${testID}-error`,children:[
|
|
511
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.muted,margin:0},role:"alert",children:documents.error?.displayMessage??""}),documents.error?.retryable===true?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onClick:documents.refresh,testID:`${testID}-retry`}):null]}):documents.status==="empty"?null:/* @__PURE__ */jsxRuntime.jsx("ul",{"aria-label":REQUEST_DOCUMENTS_COPY.listA11y,style:{...styles.plainList,paddingTop:theme.space.sm},"data-testid":testID,children:documents.rows.map((row,index)=>/* @__PURE__ */jsxRuntime.jsxs("li",{style:rowStyle(theme.space.sm,index===0?null:theme.color.brandBorder),children:[
|
|
512
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{minWidth:0},children:[
|
|
513
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.rowTitle,margin:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:row.title}),row.meta!==null?/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.muted,margin:0,fontVariantNumeric:"tabular-nums"},children:row.meta}):null]}),
|
|
514
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_DOCUMENTS_COPY.download,kind:"outline",ariaLabel:REQUEST_DOCUMENTS_COPY.downloadA11y(row.title),busy:savingKey===row.key,onClick:()=>{save(row)},testID:`${testID}-download-${row.key}`}),failedKey===row.key?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:{...styles.errorText,flexBasis:"100%"},"data-testid":`${testID}-save-failed-${row.key}`,children:RECORDS_EMPTY_COPY.error.title}):null]},row.key))}):null}function rowStyle(gap,borderTopColor){return{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:gap,paddingTop:gap,paddingBottom:gap,...borderTopColor!==null?{borderTop:`1px solid ${borderTopColor}`}:{}}}function EverfurRecordsUpload(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
515
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"upload-screen",children:[userRef===null?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsxRuntime.jsx(UploadBody,{...rest}),
|
|
516
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function UploadBody({petRef:petRef,petName:petName,controller:controller,onNavigate:onNavigate,onBack:onBack}){let{theme:theme,styles:styles}=useScreenStyles(),{runtime:runtime}=useEverfurContext(),recordsOpts=react.useMemo(()=>controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true},[petRef,controller]),records=useEverfurRecords(recordsOpts),canUpload=controller!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport);/* @__PURE__ */
|
|
517
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
518
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:"",onBack:onBack,testID:"upload-header"}),
|
|
519
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...styles.body,...styles.content,padding:theme.space.lg+theme.space.xs,gap:theme.space.lg+theme.space.xs},children:[
|
|
520
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:theme.space.sm,textAlign:"center"},children:[
|
|
521
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"block",width:52,height:52,borderRadius:theme.radius.pill,backgroundColor:theme.color.brandSoft,border:`1px solid ${theme.color.brandBorder}`}}),
|
|
522
|
+
/* @__PURE__ */jsxRuntime.jsx("h2",{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:{...styles.sectionTitle,fontSize:theme.type.size.heading,color:theme.color.brandInk},"data-testid":"upload-title",children:UPLOAD_COPY.screenTitle}),
|
|
523
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.muted,fontSize:theme.type.size.body,maxWidth:340},children:UPLOAD_COPY.subtitle(petName)})]}),
|
|
524
|
+
/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:null,canUpload:canUpload,onDone:onNavigate?requestId2=>onNavigate({name:"request",requestId:requestId2}):void 0})]})]})}function UploadRecordCard({records:records,requestId:requestId2,canUpload:canUpload,onDone:onDone}){let{theme:theme,styles:styles}=useScreenStyles(),inputRef=react.useRef(null),hintId=`records-upload-format-hint-${requestId2??"new"}`,[pickError,setPickError]=react.useState(null),[batchCount,setBatchCount]=react.useState(0),[pending,setPending]=react.useState(false),resolvedId=react.useRef(requestId2),failedFiles=react.useRef([]),rows=records.uploadQueue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,failed=rows.filter(item=>item.status==="failed").length,settled=!records.isUploading&&!pending&&batchCount>0,types=records.uploadContentTypes,photos=acceptsPhotos(types),run=react.useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photos);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal),setPending(true);try{let target=resolvedId.current;if(target===null){let created=await records.createRequest(`records-upload-${Date.now().toString(36)}`);if(!created.ok){setPickError(UPLOAD_COPY.errors.start);return}target=created.value.id,resolvedId.current=target}setBatchCount(n=>n+1);let outcome=await records.uploadDocuments(target,uploadable);failedFiles.current=outcome.flatMap((item,index)=>item.status==="failed"&&uploadable[index]!==void 0?[uploadable[index]]:[])}finally{setPending(false)}},[records,types,photos]),onChange=event=>{let files=Array.from(event.currentTarget.files??[]);event.currentTarget.value="",!(files.length===0||!canUpload)&&(async()=>{let handles=[];for(let file of files)handles.push(await fileToHandle(file,types));await run(handles)})()},pick=()=>inputRef.current?.click(),busy=records.isUploading||pending;/* @__PURE__ */
|
|
525
|
+
return jsxRuntime.jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface},"data-testid":"records-upload-card",children:[
|
|
526
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:{...styles.rowTitle,...faceCss(theme,"bold"),fontSize:theme.type.size.subtitle},children:UPLOAD_COPY.cardTitle}),
|
|
527
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{id:hintId,style:styles.muted,children:photos?UPLOAD_PHOTO_COPY.note:UPLOAD_COPY.cardSubtitle}),
|
|
528
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{ref:inputRef,type:"file",accept:recordsDocumentAccept(types),multiple:true,tabIndex:-1,"aria-hidden":"true",hidden:true,disabled:!canUpload,onChange:onChange,"data-testid":"records-upload-input"}),pickError?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.errorBanner,children:pickError}):null,
|
|
529
|
+
/* @__PURE__ */jsxRuntime.jsx(UploadQueue,{records:records}),busy?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:UPLOAD_COPY.uploading(done,rows.length)}):settled?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.sm},children:[done>0?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:styles.bodyText,children:UPLOAD_COPY.received(done)}):null,failed>0?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.retryFailed(failed),kind:"link",onClick:()=>{run(failedFiles.current)},testID:"records-upload-retry-failed"}):null,
|
|
530
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.rowTitle,...faceCss(theme,"bold"),marginTop:theme.space.xs},children:UPLOAD_COPY.haveMore}),photos?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:UPLOAD_PHOTO_COPY.haveMoreLead}):null,
|
|
531
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm},children:[
|
|
532
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.addMore,kind:"link",ariaLabel:UPLOAD_COPY.addMoreA11y,ariaDescribedBy:hintId,disabled:!canUpload,onClick:pick,testID:"records-upload-another"}),onDone&&resolvedId.current!==null&&done>0?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.done,ariaLabel:UPLOAD_COPY.doneA11y,onClick:()=>onDone(resolvedId.current),testID:"records-upload-done"}):null]})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,ariaDescribedBy:hintId,disabled:!canUpload,onClick:pick,testID:"records-upload-choose"})]})}function EverfurRecordsRequest(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
533
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-request-screen",children:[userRef===null?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsxRuntime.jsx(RequestBody,{...rest}),
|
|
534
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function RequestBody({petRef:petRef,petName:petName,requestId:requestId2,controller:controller,onNavigate:onNavigate,onBack:onBack,onOpenUrl:onOpenUrl,nowMs:nowMs}){let{styles:styles}=useScreenStyles(),{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),request=records.requests.find(r=>r.id===requestId2)??null,canUpload=controller!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport),body;return records.status==="loading"?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-request-loading"}):records.status==="error"&&records.error?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(records.error),message:records.error.displayMessage,onAction:records.error.retryable?records.refresh:void 0,testID:"records-request-error"}):request===null?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-request-missing"}):body=/* @__PURE__ */jsxRuntime.jsx(RequestDetail,{petName:petName,request:request,records:records,canUpload:canUpload,onNavigate:onNavigate,onOpenUrl:onOpenUrl,nowMs:nowMs},JSON.stringify([userRef,scopeEpoch,request.id])),/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
535
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:request?selectRequestTitle(request):"",onBack:onBack,testID:"records-request-header"}),
|
|
536
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:body})]})}function RequestDetail({petName:petName,request:request,records:records,canUpload:canUpload,onNavigate:onNavigate,onOpenUrl:onOpenUrl,nowMs:nowMs}){let{theme:theme,styles:styles}=useScreenStyles(),form=useRecordsRecovery({request:request,onRecovered:records.refresh,canUpload:canUpload},useEverfurRecordsClinic()),[lastAction,setLastAction]=react.useState(null),[starting,setStarting]=react.useState(false),[startError,setStartError]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let current=form.request,now=nowMs??Date.now(),published=current.status==="published",terminal=current.status==="published"||current.status==="failed"||current.status==="revoked",failed=isTerminalFailure(current),clinicNoRecords=current.wireStatus==="clinic_responded_no_records",waitingTooLong=requestWaitingTooLong(current,now),expectation=terminal?null:current.waitingExpectation?.trim()||null,call=selectClinicCall(current),actionError=form.error!==null&&lastAction!==null?lastAction==="revoke"?REQUEST_SCREEN_COPY.errors.cancel:REQUEST_SCREEN_COPY.errors[lastAction]:null,run=(action,fn)=>{setLastAction(action),fn()},startFresh=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(live.current){if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}}))},block={display:"flex",flexDirection:"column",gap:theme.space.sm},errorBanner=message=>/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.errorBanner,children:message}),emailId=`records-failure-clinic-email-${current.id}`,rise=useSectionRise(),clinicName=current.clinicName?.trim()??"",clinicRequest=!isOwnerSourcedRequest(current)&&clinicName.length>0,awaitingClinic=clinicRequest&&(current.status==="requested"||current.status==="awaiting_clinic"),sentDate=formatRecordsDate(current.createdAt);/* @__PURE__ */
|
|
537
|
+
return jsxRuntime.jsxs("div",{ref:rise,style:{...styles.content,gap:theme.space.lg+theme.space.xs/2},"data-testid":`records-request-${current.id}`,children:[awaitingClinic?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs},"data-testid":"records-request-sent",children:[
|
|
538
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:{...styles.sectionTitle,color:theme.color.brandInk},children:REQUEST_SCREEN_COPY.sentTitle}),
|
|
539
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:REQUEST_SCREEN_COPY.sentLeadWeb(clinicName,petNameOr(petName))})]}):null,current.statusLabel.length>0||current.heldItemCount>0?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm},"data-testid":"records-request-status-row",children:[current.statusLabel.length>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:current.statusLabel,tone:selectRequestStatusTone(current),testID:"records-request-status-chip"}):null,current.heldItemCount>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:heldItemsLabel(current.heldItemCount),tone:"neutral",testID:"records-request-held-count"}):null]}):null,current.status==="awaiting_upload"?/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:current.id,canUpload:canUpload}):null,expectation&&!waitingTooLong?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.infoNote,children:expectation}):current.wireStatus==="awaiting_response"&&!waitingTooLong?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.infoNote,children:REQUEST_SCREEN_COPY.awaitingNote}):null,waitingTooLong?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.cautionNote,"data-testid":"records-request-waiting-banner",children:REQUEST_SCREEN_COPY.waitingBanner(requestElapsedDays(current,now))}):null,published&&onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.viewRecords,onClick:()=>onNavigate({name:"dashboard"}),testID:"records-request-view-dashboard"}):null,shouldOfferRecovery(current)?/* @__PURE__ */jsxRuntime.jsxs("section",{style:{...block,gap:theme.space.md,borderRadius:theme.radius.lg-theme.space.xs,padding:theme.space.md+theme.space.xs/2,backgroundColor:failed?theme.color.badgeBgCritical:theme.color.badgeBgCaution},"data-testid":"records-failure-card",children:[
|
|
540
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.rowTitle,...faceCss(theme,"bold"),color:failed?theme.color.danger:theme.color.warningStrong},children:failureTitle(current)}),current.canUpdateClinicEmail!==true&¤t.canRetrySend!==true?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowDetail,children:REQUEST_SCREEN_COPY.nextStep}):null,current.canUpdateClinicEmail===true?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[
|
|
541
|
+
/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:emailId,style:styles.fieldLabel,children:RECORDS_RECOVERY_COPY.email}),
|
|
542
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{id:emailId,type:"email",style:styles.field,placeholder:RECORDS_RECOVERY_COPY.emailPlaceholder,autoComplete:"off",maxLength:320,value:form.email,disabled:form.busy,"aria-invalid":form.emailInvalid?true:void 0,"aria-describedby":form.emailInvalid?`${emailId}-error`:void 0,onChange:event=>form.setEmail(event.target.value),"data-testid":"records-failure-clinic-email"}),form.emailInvalid?/* @__PURE__ */jsxRuntime.jsx("p",{id:`${emailId}-error`,role:"alert",style:styles.errorText,children:REQUEST_SCREEN_COPY.errors.invalidEmail}):null,
|
|
543
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.updateEmail,disabled:!form.canUpdateEmail,busy:form.busy&&lastAction==="email",onClick:()=>run("email",form.updateEmail),testID:"records-failure-update-email"})]}):null,current.canRetrySend===true?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.retry,kind:"outline",ariaLabel:RECORDS_RECOVERY_COPY.retryA11y,disabled:!form.canRetry,busy:form.busy&&lastAction==="retry",onClick:()=>run("retry",form.retry),testID:"records-failure-retry-send"}):null,current.canRetrySend===true&&form.hasEmailEdit?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.rowDetail,children:RECORDS_RECOVERY_COPY.retryHint}):null,actionError&&(lastAction==="email"||lastAction==="retry")?errorBanner(actionError):null]}):null,(failed||clinicNoRecords)&&onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.tryAnotherClinic,kind:"outline",onClick:()=>onNavigate({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,call!==null?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[
|
|
544
|
+
/* @__PURE__ */jsxRuntime.jsx(ClinicCallCard,{call:call,prompt:current.statusLabel}),current.canRetrySend===true?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:form.busy&&lastAction==="retry"?REQUEST_SCREEN_COPY.resending:REQUEST_SCREEN_COPY.resend,kind:"outline",disabled:!form.canRetry,onClick:()=>run("retry",form.retry),testID:"records-resend-authorization"}):null]}):null,form.canConvert?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[
|
|
545
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:form.busy&&lastAction==="convert"?REQUEST_SCREEN_COPY.converting:REQUEST_SCREEN_COPY.convert,busy:form.busy&&lastAction==="convert",onClick:()=>run("convert",form.convert),testID:"records-convert-upload"}),
|
|
546
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:REQUEST_SCREEN_COPY.convertHint}),actionError&&lastAction==="convert"?errorBanner(actionError):null]}):null,terminal&&!published?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,children:[
|
|
547
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:starting?REQUEST_SCREEN_COPY.freshUploadStarting:REQUEST_SCREEN_COPY.freshUpload,kind:failed||clinicNoRecords?"outline":"primary",busy:starting,onClick:startFresh,testID:"records-upload-own-fresh"}),startError?errorBanner(startError):null]}):null,actionError&&lastAction==="revoke"?errorBanner(actionError):null,current.canRevoke===true?form.confirmingRevoke?/* @__PURE__ */jsxRuntime.jsxs("div",{style:block,"data-testid":"records-revoke-confirm",children:[
|
|
548
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.rowTitle,...faceCss(theme,"bold"),fontSize:theme.type.size.subtitle},children:RECORDS_RECOVERY_COPY.cancelQuestion}),
|
|
549
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:RECORDS_RECOVERY_COPY.cancelConsequence}),
|
|
550
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:form.busy&&lastAction==="revoke"?REQUEST_SCREEN_COPY.cancelling:REQUEST_SCREEN_COPY.cancel,kind:"danger",busy:form.busy&&lastAction==="revoke",onClick:()=>run("revoke",form.revoke),testID:"records-revoke-do"}),
|
|
551
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onClick:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onClick:form.askRevoke,testID:"records-revoke"}):null,
|
|
552
|
+
/* @__PURE__ */jsxRuntime.jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface},"aria-label":REQUEST_SCREEN_COPY.whereItStands,"data-testid":"records-request-where",children:[
|
|
553
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sectionTitle,children:REQUEST_SCREEN_COPY.whereItStands}),
|
|
554
|
+
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:current,petName:petName})]}),clinicRequest?/* @__PURE__ */jsxRuntime.jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface},"aria-label":REQUEST_SCREEN_COPY.details,"data-testid":"records-request-details",children:[
|
|
555
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sectionTitle,children:REQUEST_SCREEN_COPY.details}),
|
|
556
|
+
/* @__PURE__ */jsxRuntime.jsxs("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"baseline",columnGap:theme.space.lg,rowGap:theme.space.sm},children:[
|
|
557
|
+
/* @__PURE__ */jsxRuntime.jsx("dt",{style:styles.muted,children:REQUEST_SCREEN_COPY.detailsClinic}),
|
|
558
|
+
/* @__PURE__ */jsxRuntime.jsx("dd",{style:{...styles.bodyText,margin:0},children:clinicName}),sentDate!=="-"?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
559
|
+
/* @__PURE__ */jsxRuntime.jsx("dt",{style:styles.muted,children:REQUEST_SCREEN_COPY.detailsSent}),
|
|
560
|
+
/* @__PURE__ */jsxRuntime.jsx("dd",{style:{...styles.bodyText,margin:0},children:/* @__PURE__ */jsxRuntime.jsx("time",{dateTime:current.createdAt,children:sentDate})})]}):null]})]}):null,isOwnerSourcedRequest(current)?/* @__PURE__ */jsxRuntime.jsx(RequestDocumentsList,{requestId:current.id,...onOpenUrl?{onOpenUrl:onOpenUrl}:{}}):null]})}function isOverlayScreen(screen){return screen.name==="request"||screen.name==="clinicPicker"||screen.name==="consent"||screen.name==="clinicBatch"||screen.name==="upload"}function recordsPageNavReducer(state,action){if(action.type!=="closeOverlay")return recordsNavReducer(state,action);let keep=state.stack.length;for(;keep>1&&isOverlayScreen(state.stack[keep-1]);)keep-=1;return keep===state.stack.length?state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,keep))})}function splitRecordsPageNav(state){let{stack:stack}=state,top=stack[stack.length-1],overlay=isOverlayScreen(top)?top:null,bodyIndex=stack.length-1;for(;bodyIndex>0&&isOverlayScreen(stack[bodyIndex]);)bodyIndex-=1;let bodyScreen=stack[bodyIndex],body=isOverlayScreen(bodyScreen)?{name:"dashboard"}:bodyScreen,below=overlay===null?null:stack[stack.length-2];/* @__PURE__ */
|
|
561
|
+
return Object.freeze({body:body,overlay:overlay,overlayCanStepBack:below!=null&&isOverlayScreen(below),bodyCanGoBack:bodyIndex>0})}function seamsOf(ctx){return{...ctx.petName!==void 0?{petName:ctx.petName}:{},...ctx.onOpenUrl?{onOpenUrl:ctx.onOpenUrl}:{},...ctx.onCopy?{onCopy:ctx.onCopy}:{},...ctx.onAsk?{onAsk:ctx.onAsk}:{},...ctx.location?{location:ctx.location}:{}}}function RecordsPageBodyScreenView({screen:screen,ctx:ctx,onBack:onBack}){let seams={...seamsOf(ctx),onNavigate:ctx.navigate,onBack:onBack},records={...ctx.controller?{controller:ctx.controller}:{},...ctx.consentVersion!==void 0?{consentVersion:ctx.consentVersion}:{},...ctx.consentText!==void 0?{consentText:ctx.consentText}:{}},style=PAGE_SCREEN;switch(screen.name){case"record":/* @__PURE__ */
|
|
562
|
+
return jsxRuntime.jsx(EverfurRecordDetail,{petRef:ctx.petRef,...seams,...records,style:style});case"timeline":/* @__PURE__ */
|
|
563
|
+
return jsxRuntime.jsx(EverfurRecordsTimeline,{petRef:ctx.petRef,...seams,style:style});case"document":/* @__PURE__ */
|
|
564
|
+
return jsxRuntime.jsx(EverfurRecordDocument,{petRef:ctx.petRef,...seams,...records,style:style});case"contributions":/* @__PURE__ */
|
|
565
|
+
return jsxRuntime.jsx(EverfurDocumentContributions,{petRef:ctx.petRef,docId:screen.docId,...seams,style:style});default:return assertNever(screen)}}function RecordsPageOverlay({screen:screen,ctx:ctx,requests:requests,onBack:onBack,onClose:onClose}){let focusRoot=useFocusScreenOnChange(screen),label=react.useMemo(()=>overlayLabel(screen,requests),[screen,requests]),hostAsk=ctx.onAsk,ask=hostAsk?{onAsk:(prompt,entityRef)=>{onClose(),hostAsk(prompt,entityRef)}}:{},seams={...seamsOf(ctx),...ask,onNavigate:ctx.navigate,onBack:onBack},clinic=ctx.clinicController?{controller:ctx.clinicController}:{},signature=ctx.onCaptureSignature?{onCaptureSignature:ctx.onCaptureSignature}:{},content;switch(screen.name){case"request":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsRequest,{petRef:ctx.petRef,requestId:screen.requestId,...seams,...ctx.controller?{controller:ctx.controller}:{},style:SHEET_SCREEN});break;case"clinicPicker":content=/* @__PURE__ */jsxRuntime.jsx(EverfurClinicPicker,{petRef:ctx.petRef,...seams,...clinic,...ctx.controller?{recordsController:ctx.controller}:{},style:SHEET_SCREEN});break;case"consent":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsConsent,{petRef:ctx.petRef,clinic:screen.clinic,...seams,...ctx.ownerName!==void 0?{ownerName:ctx.ownerName}:{},...signature,...clinic,style:SHEET_SCREEN});break;case"clinicBatch":content=/* @__PURE__ */jsxRuntime.jsx(EverfurClinicRequestBatch,{petRef:ctx.petRef,petName:ctx.petName??"",ownerName:ctx.ownerName??"",onClose:onBack,onCreated:()=>ctx.navigate({name:"dashboard"}),...signature,...clinic,style:SHEET_SCREEN});break;case"upload":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsUpload,{petRef:ctx.petRef,...seams,...ctx.controller?{controller:ctx.controller}:{},style:SHEET_SCREEN});break;default:content=assertNever(screen)}/* @__PURE__ */
|
|
566
|
+
return jsxRuntime.jsx(RecordsDialog,{label:label,onClose:onClose,shape:"side",panelStyle:SHEET_PANEL,testID:"everfur-records-page-sheet",children:/* @__PURE__ */jsxRuntime.jsx("div",{ref:focusRoot,tabIndex:-1,style:SHEET_ROOT,children:content})})}function overlayLabel(screen,requests){if(screen.name==="upload")return CONSUMER_PAGE_COPY.uploadAction;if(screen.name!=="request")return CONSUMER_PAGE_COPY.requestRecords;let request=requests.find(row=>row.id===screen.requestId);return request?consumerRequestSource(request):CONSUMER_PAGE_COPY.requestTimeline}var PAGE_SCREEN=/* @__PURE__ */Object.freeze({height:"auto"}),SHEET_PANEL=/* @__PURE__ */Object.freeze({padding:0,gap:0}),SHEET_ROOT=/* @__PURE__ */Object.freeze({height:"100%",outline:"none"}),SHEET_SCREEN=/* @__PURE__ */Object.freeze({height:"100%"});function RecordsPageRequests({requests:requests,petName:petName,level:level,headingId:headingId,onOpenRequest:onOpenRequest,onUpload:onUpload,onOpenUrl:onOpenUrl}){let{theme:theme,styles:styles}=useScreenStyles(),SectionTitle=headingTag(level),hasRequests=requests.length>0;/* @__PURE__ */
|
|
567
|
+
return jsxRuntime.jsxs("section",{"aria-labelledby":headingId,style:styles.section,"data-testid":"everfur-records-page-requests",children:[
|
|
568
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.sectionHeader,children:[
|
|
569
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionTitle,{id:headingId,style:{...styles.sectionTitle,color:theme.color.brandInk},children:CONSUMER_PAGE_COPY.requestsFor(petName)}),hasRequests?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.sectionCount,"data-testid":"everfur-records-page-requests-count",children:requests.length}):null]}),hasRequests?/* @__PURE__ */jsxRuntime.jsx("ul",{style:{...styles.plainList,gap:theme.space.md},children:requests.map(request=>{let source=consumerRequestSource(request),resumeUpload=selectResumableUploadRequest(null,request)!==null;/* @__PURE__ */
|
|
570
|
+
return jsxRuntime.jsxs("li",{style:styles.creamCard,"data-testid":`everfur-records-page-request-${request.id}`,children:[
|
|
571
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm},children:[
|
|
572
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,fontSize:theme.type.size.subtitle},children:source}),onOpenRequest?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm},children:[resumeUpload?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.cardTitle,onClick:()=>onOpenRequest(request),testID:`everfur-records-page-resume-upload-${request.id}`}):null,
|
|
573
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CONSUMER_PAGE_COPY.requestTimeline,kind:"outline",ariaLabel:CONSUMER_PAGE_COPY.requestTimelineA11y(source),onClick:()=>onOpenRequest(request),testID:`everfur-records-page-open-${request.id}`})]}):null]}),
|
|
574
|
+
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:request}),isOwnerSourcedRequest(request)?/* @__PURE__ */jsxRuntime.jsx(RequestDocumentsList,{requestId:request.id,...onOpenUrl?{onOpenUrl:onOpenUrl}:{}}):null]},request.id)})}):
|
|
575
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.creamCard,"data-testid":"everfur-records-page-upload-prompt",children:[
|
|
576
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,fontSize:theme.type.size.subtitle},children:CONSUMER_PAGE_COPY.uploadPromptTitle(petName)}),
|
|
577
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:CONSUMER_PAGE_COPY.uploadPromptBody}),onUpload?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CONSUMER_PAGE_COPY.uploadAction,onClick:onUpload,testID:"everfur-records-page-upload"}):null]})]})}var PAGE_MAX_WIDTH=1248,PAGE_ROOT=/* @__PURE__ */Object.freeze({height:"auto"}),PAGE_BODY=/* @__PURE__ */Object.freeze({overflowY:"visible",flex:"0 0 auto"});function EverfurRecordsPage(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
578
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...PAGE_ROOT,...style},"data-testid":"everfur-records-page",children:[userRef===null?
|
|
579
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.body,...PAGE_BODY},children:/* @__PURE__ */jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsxRuntime.jsx(RecordsPageBody,{...rest}),
|
|
580
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function RecordsPageBody(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onNavigate:onNavigate,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location2}=props;useConsentTextWarning2(consentVersion,consentText);let[nav,dispatch]=react.useReducer(recordsPageNavReducer,void 0,()=>initialRecordsNav()),navigate=react.useCallback(to=>{onNavigate?onNavigate(to):dispatch({type:"navigate",screen:to})},[onNavigate]),{body:body,overlay:overlay,overlayCanStepBack:overlayCanStepBack,bodyCanGoBack:bodyCanGoBack}=splitRecordsPageNav(nav),recordsOpts=react.useMemo(()=>controller?{petRef:petRef,controller:controller}:{petRef:petRef},[petRef,controller]),records=useEverfurRecords(recordsOpts),{refresh:refresh}=records,sheetWasOpen=react.useRef(false);react.useEffect(()=>{overlay!==null?sheetWasOpen.current=true:sheetWasOpen.current&&(sheetWasOpen.current=false,refresh())},[overlay,refresh]);let bodyRoot=useFocusScreenOnChange(body),ctx={petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,navigate:navigate,...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location2?{location:location2}:{}},pageShown=body.name==="dashboard"||body.name==="requests";/* @__PURE__ */
|
|
581
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
582
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{ref:bodyRoot,tabIndex:-1,style:BODY_ROOT,children:pageShown?/* @__PURE__ */jsxRuntime.jsx(RecordsPageContent,{...props,records:records,navigate:navigate}):
|
|
583
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnoteDrawnAbove.Provider,{value:true,children:/* @__PURE__ */jsxRuntime.jsx(RecordsPageBodyScreenView,{screen:body,ctx:ctx,onBack:bodyCanGoBack?()=>dispatch({type:"pop"}):()=>navigate({name:"dashboard"})})})}),overlay!==null?/* @__PURE__ */jsxRuntime.jsx(RecordsPageOverlay,{screen:overlay,ctx:ctx,requests:records.requests,onBack:overlayCanStepBack?()=>dispatch({type:"pop"}):()=>dispatch({type:"closeOverlay"}),onClose:()=>dispatch({type:"closeOverlay"})}):null]})}var BODY_ROOT=/* @__PURE__ */Object.freeze({outline:"none"});function RecordsPageContent({petRef:petRef,petName:petName,consentVersion:consentVersion,consentText:consentText,onAsk:onAsk,onOpenUrl:onOpenUrl,headingLevel:hostLevel,records:records,navigate:navigate}){let{theme:theme,styles:styles}=useScreenStyles(),clinicDecision=useCapability("recordsClinic"),canRequestFromClinic=clinicDecision.enabled||clinicDecision.isPending,pageLevel=headingLevel(hostLevel??DEFAULT_ROOT_HEADING_LEVEL),PageTitle=headingTag(pageLevel),requestsHeadingId=`${react.useId()}-requests-heading`,canGrant=canGrantConsent(consentVersion,records.consent),onGrant=()=>{let version=resolveConsentVersion(consentVersion,records.consent);version.length!==0&&records.grantConsent(version,`records-consent-${Date.now().toString(36)}`)},column={boxSizing:"border-box",width:"100%",maxWidth:PAGE_MAX_WIDTH,margin:"0 auto",display:"flex",flexDirection:"column",gap:theme.space.lg+theme.space.xs,padding:`${theme.space.lg}px ${theme.space.lg}px ${theme.space.xxl}px`};if(records.status==="loading")/* @__PURE__ */
|
|
584
|
+
return jsxRuntime.jsx("div",{style:{...styles.body,...PAGE_BODY},children:/* @__PURE__ */jsxRuntime.jsx("div",{style:column,children:/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"everfur-records-page-loading"})})});if(records.status==="error"){let errorView=selectErrorView(records,canGrant),body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?()=>records.refresh():void 0,testID:"everfur-records-page-error"}):renderErrorFamily(records,onGrant,canGrant,consentText);/* @__PURE__ */
|
|
585
|
+
return jsxRuntime.jsx("div",{style:{...styles.body,...PAGE_BODY},children:/* @__PURE__ */jsxRuntime.jsx("div",{style:column,children:body})})}/* @__PURE__ */
|
|
586
|
+
return jsxRuntime.jsx("div",{style:{...styles.body,...PAGE_BODY},children:/* @__PURE__ */jsxRuntime.jsxs("div",{style:column,"data-testid":"everfur-records-page-content",children:[
|
|
587
|
+
/* @__PURE__ */jsxRuntime.jsxs("header",{style:{...styles.creamCard,gap:theme.space.md,padding:`${theme.space.lg+theme.space.xs}px ${theme.space.lg+theme.space.md}px`},"data-testid":"everfur-records-page-header",children:[
|
|
588
|
+
/* @__PURE__ */jsxRuntime.jsx(PageTitle,{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:{...styles.headerTitle,whiteSpace:"normal",overflow:"visible"},children:CONSUMER_PAGE_COPY.titleFor(petName)}),
|
|
589
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:CONSUMER_PAGE_COPY.lead}),
|
|
590
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm},"data-testid":"everfur-records-page-actions",children:[canRequestFromClinic?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CONSUMER_PAGE_COPY.requestRecords,onClick:()=>navigate({name:"clinicPicker"}),testID:"everfur-records-page-request-records"}):null,
|
|
591
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CONSUMER_PAGE_COPY.uploadAction,kind:"outline",onClick:()=>navigate({name:"upload"}),testID:"everfur-records-page-upload-action"}),onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CONSUMER_PAGE_COPY.askA11y(petName),kind:"ask",ariaLabel:CONSUMER_PAGE_COPY.askA11y(petName),onClick:()=>onAsk(buildRecordsPageAskPrompt(petName),{type:"marker_summary",id:petRef}),testID:"everfur-records-page-ask"}):null]}),
|
|
592
|
+
/* @__PURE__ */jsxRuntime.jsxs("nav",{style:{display:"flex",flexWrap:"wrap",columnGap:theme.space.lg,rowGap:theme.space.xs},"data-testid":"everfur-records-page-links",children:[
|
|
593
|
+
/* @__PURE__ */jsxRuntime.jsx(PageLink,{label:CONSUMER_PAGE_COPY.viewRecord,onClick:()=>navigate({name:"record"}),testID:"everfur-records-page-link-record"}),
|
|
594
|
+
/* @__PURE__ */jsxRuntime.jsx(PageLink,{label:CONSUMER_PAGE_COPY.viewTimeline,onClick:()=>navigate({name:"timeline"}),testID:"everfur-records-page-link-timeline"})]})]}),
|
|
595
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsPageRequests,{requests:records.requests,petName:petName,level:nextHeadingLevel(pageLevel),headingId:requestsHeadingId,onOpenRequest:request=>navigate({name:"request",requestId:request.id}),onUpload:()=>navigate({name:"upload"}),...onOpenUrl?{onOpenUrl:onOpenUrl}:{}})]})})}function PageLink({label:label,onClick:onClick,testID:testID}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
596
|
+
return jsxRuntime.jsx("button",{type:"button",onClick:onClick,style:{...styles.pill,...styles.pillLink,minHeight:44,padding:0,fontSize:theme.type.size.bodyTight,textDecoration:"underline",textUnderlineOffset:4},"data-testid":testID,children:label})}var SIZE=200,STROKE=16,RADIUS2=(SIZE-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS2;function MarkerSummaryCard({summary:summary,onAsk:onAsk,testID:testID}){let s=useStyles3(),{theme:theme,styles:styles}=useScreenStyles(),{totalMarkers:totalMarkers,inRangeCount:inRangeCount,outOfRangeCount:outOfRangeCount,unknownCount:unknownCount}=summary,denominator=inRangeCount+outOfRangeCount+unknownCount,arcs=react.useMemo(()=>{if(!(denominator>0))return[];let buckets=[{key:"in_range",color:theme.color.success,count:inRangeCount},{key:"out_of_range",color:theme.color.danger,count:outOfRangeCount},{key:"unknown",color:theme.color.text.muted,count:unknownCount}],cumulative=0;return buckets.filter(b=>b.count>0).map(b=>{let length=b.count/denominator*CIRCUMFERENCE,offset=-cumulative;return cumulative+=length,{key:b.key,color:b.color,length:length,offset:offset}})},[denominator,inRangeCount,outOfRangeCount,unknownCount,theme]);/* @__PURE__ */
|
|
597
|
+
return jsxRuntime.jsxs("section",{role:"group","aria-label":MARKER_SUMMARY_COPY.title,style:s.card,"data-testid":testID,children:[
|
|
598
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:s.title,children:MARKER_SUMMARY_COPY.title}),
|
|
599
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.ringRow,children:/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.ringWrap,role:"img","aria-label":MARKER_SUMMARY_COPY.a11y(totalMarkers,inRangeCount,outOfRangeCount,unknownCount),children:[
|
|
600
|
+
/* @__PURE__ */jsxRuntime.jsxs("svg",{width:SIZE,height:SIZE,viewBox:`0 0 ${SIZE} ${SIZE}`,"aria-hidden":"true",focusable:"false",children:[
|
|
601
|
+
/* @__PURE__ */jsxRuntime.jsx("circle",{cx:SIZE/2,cy:SIZE/2,r:RADIUS2,stroke:theme.color.surfaceSubtle,strokeWidth:STROKE,fill:"none"}),
|
|
602
|
+
/* @__PURE__ */jsxRuntime.jsx("g",{transform:`rotate(-90 ${SIZE/2} ${SIZE/2})`,children:arcs.map(arc=>/* @__PURE__ */jsxRuntime.jsx("circle",{cx:SIZE/2,cy:SIZE/2,r:RADIUS2,stroke:arc.color,strokeWidth:STROKE,fill:"none",strokeDasharray:`${arc.length} ${CIRCUMFERENCE}`,strokeDashoffset:arc.offset,strokeLinecap:arcs.length>1?"round":"butt","data-testid":`marker-ring-${arc.key}`},arc.key))})]}),
|
|
603
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.center,"aria-hidden":"true",children:[
|
|
604
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.centerCount,children:totalMarkers}),
|
|
605
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.centerLabel,children:totalMarkers===1?MARKER_SUMMARY_COPY.marker:MARKER_SUMMARY_COPY.markers})]})]})}),arcs.length>0?/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.badges,children:[
|
|
606
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.badge,borderColor:theme.color.danger,color:theme.color.danger},children:`${outOfRangeCount} ${MARKER_SUMMARY_COPY.outOfRange}`}),
|
|
607
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.badge,borderColor:theme.color.success,color:theme.color.success},children:`${inRangeCount} ${MARKER_SUMMARY_COPY.inRange}`}),unknownCount>0?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.badge,borderColor:theme.color.text.muted,color:theme.color.text.muted},children:`${unknownCount} ${MARKER_SUMMARY_COPY.noRange}`}):null]}):null,
|
|
608
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:s.subtitle,children:MARKER_SUMMARY_COPY.subtitle}),onAsk?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onAsk,style:{...styles.pill,...styles.pillAsk},"data-testid":"marker-summary-ask",children:MARKER_SUMMARY_COPY.ask}):null]})}function useStyles3(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles7(theme),[theme])}function makeStyles7(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.sm+space.xs/2,borderRadius:radius.lg,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderRingCream}`,padding:space.lg},title:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,color:color.brandInk,letterSpacing:"-0.02em"},ringRow:{display:"flex",justifyContent:"center"},ringWrap:{position:"relative",width:SIZE,height:SIZE},center:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},centerCount:{...faceCss(theme,"medium"),fontSize:type.size.verdict*2,lineHeight:1.1,color:color.text.primary},centerLabel:{...faceCss(theme,"medium"),fontSize:type.size.heading-1,lineHeight:1.2,color:color.text.primary},badges:{display:"flex",flexWrap:"wrap",justifyContent:"center",gap:space.sm},badge:{border:"1px solid",borderRadius:radius.pill,padding:`${space.xs}px ${space.sm+space.xs/2}px`,...faceCss(theme,"mono"),fontSize:type.size.nano,lineHeight:`${type.size.tiny}px`,textTransform:"uppercase",letterSpacing:type.letterSpacing.headerBrand/2},subtitle:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.relaxed)}px`,color:color.text.primary}}}function numeric(point){return point.value!==null&&Number.isFinite(point.value)}function buildMarkerChart(marker){let readings=marker.points.filter(numeric);if(readings.length===0)return null;let latest=marker.points[marker.points.length-1]??null,refLow=latest?.refLow??null,refHigh=latest?.refHigh??null,values=readings.map(p=>p.value),lo=Math.min(...values,...refLow!==null?[refLow]:[],...refHigh!==null?[refHigh]:[]),hi=Math.max(...values,...refLow!==null?[refLow]:[],...refHigh!==null?[refHigh]:[]);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.18,yMin=lo-pad,yMax=hi+pad,span=yMax-yMin,y=value=>(yMax-value)/span*100,xInset=6,count=readings.length,points=readings.map((point,index)=>({index:index,xPct:count<=1?50:xInset+index/(count-1)*(100-2*xInset),yPct:y(point.value),status:point.status,point:point})),band=refLow!==null||refHigh!==null?{topPct:refHigh!==null?y(refHigh):0,bottomPct:refLow!==null?y(refLow):100}:null;return{points:points,band:band,firstDate:readings[0]?.at??null,lastDate:readings[readings.length-1]?.at??null}}var PLOT_W=100,PLOT_H=44;function MarkerTrendCard({marker:marker,onPointPress:onPointPress,onAsk:onAsk}){let s=useStyles4(),{theme:theme,styles:styles}=useScreenStyles(),status=markerStatusLabel(marker.latest?.status??null),traj=trajectoryLabel(marker.trajectory,marker.points.length),chart=react.useMemo(()=>buildMarkerChart(marker),[marker]),latestReading=marker.latest?formatMarkerReading(marker.latest.value,marker.unit,marker.latest.qualitativeResult):null;/* @__PURE__ */
|
|
609
|
+
return jsxRuntime.jsx("li",{style:s.page,"data-testid":`marker-card-${marker.markerId}`,children:/* @__PURE__ */jsxRuntime.jsxs("article",{style:s.card,children:[
|
|
610
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.headerRow,children:[
|
|
611
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.nameColumn,children:[
|
|
612
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.markerName,children:marker.name}),marker.unit?/* @__PURE__ */jsxRuntime.jsx("span",{style:s.unit,children:marker.unit}):null]}),
|
|
613
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-label":MARKER_CARD_COPY.status(status.label),children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:status.label,tone:markerStatusTone(marker.latest?.status??null)})})]}),marker.latest&&latestReading!==null?/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.latestRow,children:[
|
|
614
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.latestValue,...status.outOfRange?s.latestValueDanger:{}},"aria-label":MARKER_CARD_COPY.latestA11y(latestReading,status.label,formatRecordsDate(marker.latest.at)),children:latestReading}),
|
|
615
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.latestDate,children:formatRecordsDate(marker.latest.at)})]}):null,traj?/* @__PURE__ */jsxRuntime.jsx("p",{style:s.trajectory,children:traj}):null,chart!==null?/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.chartWrap,children:[
|
|
616
|
+
/* @__PURE__ */jsxRuntime.jsxs("svg",{viewBox:`0 0 ${PLOT_W} ${PLOT_H}`,preserveAspectRatio:"none",style:s.plot,"aria-hidden":"true",focusable:"false",children:[chart.band?/* @__PURE__ */jsxRuntime.jsx("rect",{x:0,y:chart.band.topPct/100*PLOT_H,width:PLOT_W,height:Math.max(0,(chart.band.bottomPct-chart.band.topPct)/100*PLOT_H),fill:theme.color.badgeBgPositive}):null,chart.points.length>1?/* @__PURE__ */jsxRuntime.jsx("polyline",{fill:"none",stroke:theme.color.brandBorder,strokeWidth:.6,vectorEffect:"non-scaling-stroke",points:chart.points.map(p=>`${p.xPct},${p.yPct/100*PLOT_H}`).join(" ")}):null]}),
|
|
617
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.dotLayer,children:chart.points.map(p=>/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>onPointPress(marker,p.point),"aria-label":markerPointSpoken(marker,p.point),style:{...s.dot,...p.status==="above"||p.status==="below"?s.dotDanger:{},left:`${p.xPct}%`,top:`${p.yPct}%`},"data-testid":`marker-point-${marker.markerId}-${p.index}`},p.index))}),
|
|
618
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{"aria-label":MARKER_CARD_COPY.readingsA11y(marker.name),style:s.a11yTable,children:marker.points.map((point,index)=>/* @__PURE__ */jsxRuntime.jsx("li",{children:markerPointSpoken(marker,point)},index))}),
|
|
619
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:marker.points.length===1?s.singleHint:s.tapHint,children:marker.points.length===1?MARKER_CARD_COPY.singleHint:MARKER_CARD_COPY.tapHint})]}):/* @__PURE__ */jsxRuntime.jsx("p",{style:s.emptyBody,children:MARKER_CARD_COPY.empty}),onAsk?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>onAsk(marker),style:{...styles.pill,...styles.pillAsk},"data-testid":`marker-ask-${marker.markerId}`,children:MARKER_CARD_COPY.askNamed(marker.name)}):null]})})}function MarkerTrendCarousel({markers:markers,onPointPress:onPointPress,onAsk:onAsk}){let s=useStyles4(),[activeIndex,setActiveIndex]=react.useState(0),onScroll=event=>{let el=event.currentTarget;el.clientWidth<=0||setActiveIndex(Math.max(0,Math.min(Math.round(el.scrollLeft/el.clientWidth),markers.length-1)))},active=markers[activeIndex]??null;/* @__PURE__ */
|
|
620
|
+
return jsxRuntime.jsxs("div",{style:s.carousel,"data-testid":"marker-carousel",children:[
|
|
621
|
+
/* @__PURE__ */jsxRuntime.jsx("ul",{style:s.track,onScroll:onScroll,children:markers.map(marker=>/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCard,{marker:marker,onPointPress:onPointPress,onAsk:onAsk},marker.markerId))}),
|
|
622
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.footer,"aria-label":MARKER_CAROUSEL_COPY.a11y(active?.name??null,activeIndex,markers.length),children:[
|
|
623
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:s.dots,"aria-hidden":"true",children:markers.map((marker,index)=>/* @__PURE__ */jsxRuntime.jsx("span",{style:{...s.dotIndicator,...index===activeIndex?s.dotActive:{}}},marker.markerId))}),
|
|
624
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.counter,children:MARKER_CAROUSEL_COPY.counter(activeIndex,markers.length)})]})]})}function MarkerProvenanceDialog({marker:marker,point:point,onClose:onClose,onAsk:onAsk}){let s=useStyles4(),{styles:styles}=useScreenStyles();if(marker===null||point===null)return null;let row=(label,value)=>/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.detailRow,children:[
|
|
625
|
+
/* @__PURE__ */jsxRuntime.jsx("dt",{style:s.detailLabel,children:label}),
|
|
626
|
+
/* @__PURE__ */jsxRuntime.jsx("dd",{style:s.detailValue,children:value})]},label);
|
|
627
|
+
/* @__PURE__ */
|
|
628
|
+
return jsxRuntime.jsxs(RecordsDialog,{label:PROVENANCE_COPY.title,onClose:onClose,panelStyle:s.sheetBg,testID:"marker-provenance-sheet",children:[
|
|
629
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.sheetHeader,children:[
|
|
630
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:styles.sheetTitle,children:PROVENANCE_COPY.title}),
|
|
631
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,"aria-label":PROVENANCE_COPY.close,style:styles.iconButton,"data-testid":"marker-provenance-close",children:/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.closeGlyph,"aria-hidden":"true",children:"×"})})]}),
|
|
632
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:s.valueRow,children:[
|
|
633
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.markerName,children:marker.name}),
|
|
634
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:s.latestValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsxRuntime.jsx("span",{style:s.reviewed,children:PROVENANCE_COPY.reviewed}):null,
|
|
635
|
+
/* @__PURE__ */jsxRuntime.jsxs("dl",{style:s.details,children:[row(PROVENANCE_COPY.collected,formatRecordsDate(point.at)),point.sourceClinic?row(PROVENANCE_COPY.clinic,point.sourceClinic):null,row(PROVENANCE_COPY.referenceRange,point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):PROVENANCE_COPY.noRange),point.docId?row(PROVENANCE_COPY.sourceDocument,point.docId):null]}),point.reviewed?null:/* @__PURE__ */jsxRuntime.jsx("p",{style:s.unverified,children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onAsk,style:{...styles.pill,...styles.pillAsk},"data-testid":"marker-provenance-ask",children:PROVENANCE_COPY.ask}):null]})}function useStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:`${Math.round(size*multiplier)}px`,color:fg}),dot=space.md;return{page:{flex:"0 0 100%",scrollSnapAlign:"start",boxSizing:"border-box",padding:`0 ${space.sm}px`,listStyle:"none"},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,borderRadius:radius.lg,border:`1px solid ${color.borderRingCream}`,backgroundColor:color.surface,padding:space.lg},headerRow:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,display:"flex",flexDirection:"column",gap:space.xs/2,minWidth:0},markerName:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold")},unit:{...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,color:color.text.muted},latestRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...text3(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold")},latestValueDanger:{color:color.danger},latestDate:text3(type.size.caption,type.lineHeight.normal,color.text.muted),trajectory:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),chartWrap:{position:"relative",display:"flex",flexDirection:"column",gap:space.sm},plot:{display:"block",width:"100%",height:140,borderRadius:radius.sm,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderHairlineGreen}`},dotLayer:{position:"absolute",left:0,right:0,top:0,height:140},dot:{position:"absolute",boxSizing:"border-box",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,border:`2px solid ${color.surface}`,padding:0,cursor:"pointer"},dotDanger:{backgroundColor:color.danger},a11yTable:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",margin:0,padding:0,listStyle:"none"},tapHint:{...text3(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center"},singleHint:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},emptyBody:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",padding:`${space.xxl+space.xs}px 0`},carousel:{display:"flex",flexDirection:"column"},track:{display:"flex",overflowX:"auto",scrollSnapType:"x mandatory",margin:0,padding:0,listStyle:"none"},footer:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{display:"flex",gap:space.xs+space.xs/2},dotIndicator:{display:"block",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs-1,backgroundColor:color.borderHairlineGreen},dotActive:{width:space.lg+space.xs/2,backgroundColor:color.brand},counter:{...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},sheetBg:{backgroundColor:color.surfaceCream},valueRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,padding:`${space.xs}px ${space.sm+space.xs/2}px`,backgroundColor:color.badgeBgPositive,...text3(type.size.tiny,type.lineHeight.normal,color.success,"medium")},details:{margin:0,display:"flex",flexDirection:"column",gap:space.md},detailRow:{display:"flex",flexDirection:"column",gap:space.xs/2},detailLabel:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted,"medium")},detailValue:{...text3(type.size.body,type.lineHeight.normal,color.text.primary),marginLeft:0},unverified:text3(type.size.caption,type.lineHeight.normal,color.text.muted)}}var readDepth3=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty3=value=>!value.available;function EverfurRecordsDashboard(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
636
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-dashboard",children:[userRef===null?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsxRuntime.jsx(DashboardBody,{...rest}),
|
|
637
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function DashboardBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk}){let{theme:theme,styles:styles}=useScreenStyles(),recordsOpts=react.useMemo(()=>controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true},[petRef,controller]),records=useEverfurRecords(recordsOpts),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth3,depthEmpty3),[provenance,setProvenance]=react.useState(null),onPointPress=react.useCallback((marker,point)=>setProvenance({marker:marker,point:point}),[]);useConsentTextWarning2(consentVersion,consentText);let canGrant=canGrantConsent(consentVersion,records.consent),onGrant=()=>{let version=resolveConsentVersion(consentVersion,records.consent);version.length!==0&&records.grantConsent(version,`records-consent-${Date.now().toString(36)}`)},markerList=markers.markers?.markers??[],hasMarkers=markerList.length>0,hasFullRecord=records.record!==null&&!records.record.isEmpty&&!records.record.withheld,drivingRequest=pickPetRecordsRequest(records.requests,petRef),dashboardState=deriveRecordsDashboardState({hasMarkers:hasMarkers,requests:records.requests,petRef:petRef}),view=selectDashboardView({recordLoading:records.status==="loading",hasFullRecord:hasFullRecord,recordError:records.status==="error",markersLoading:markers.status==="loading",markersError:markers.status==="error",hasMarkers:hasMarkers,requestsLoading:records.status==="loading",dashboardState:dashboardState,drivingRequest:drivingRequest}),disclaimer=markers.markers?.disclaimer??records.record?.disclaimer??"",retryAll=()=>{records.refresh(),markers.refresh(),depth.refresh()},depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,name=petNameOr(petName),rise=useSectionRise(),askSummary=onAsk&&markers.markers?.summary?()=>{let built=buildMarkerSummaryAskPrompt(petName,markers.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},petRef);onAsk(built.prompt,built.entityRef)}:void 0,askMarker=onAsk?marker=>{let built=buildMarkerAskPrompt(petName,{canonicalName:marker.name,markerId:marker.markerId,latestValueText:marker.latest?formatMarkerReading(marker.latest.value,marker.unit,marker.latest.qualitativeResult):null,statusText:marker.latest?markerStatusLabel(marker.latest.status).label:null,trajectoryText:trajectoryLabel(marker.trajectory,marker.points.length),meaningText:marker.meaning});onAsk(built.prompt,built.entityRef)}:void 0,askReading=onAsk&&provenance?()=>{let{marker:marker,point:point}=provenance,built=buildMarkerReadingAskPrompt(petName,{canonicalName:marker.name,valueText:formatMarkerReading(point.value,marker.unit,point.qualitativeResult),collectedAt:formatRecordsDate(point.at),sourceClinic:point.sourceClinic,referenceText:point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):null,flagged:point.status==="above"?"above":point.status==="below"?"below":null,reviewed:point.reviewed,entityId:point.docId??marker.markerId});setProvenance(null),onAsk(built.prompt,built.entityRef)}:void 0,actionRow=(label,onClick,testID)=>/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",onClick:onClick,"aria-label":label,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",borderRadius:theme.radius.lg,border:`1px solid ${theme.color.borderRingCream}`,backgroundColor:theme.color.surface,padding:theme.space.lg,cursor:"pointer",font:"inherit",color:theme.color.text.primary,textAlign:"left"},"data-testid":testID,children:[
|
|
638
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:theme.space.md},children:[
|
|
639
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:18,height:18,borderRadius:theme.radius.xs,backgroundColor:theme.color.brandSoft,border:`1px solid ${theme.color.brandBorder}`}}),
|
|
640
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle},children:label})]}),
|
|
641
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]}),labs=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[markers.markers?.summary?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(MarkerSummaryCard,{summary:markers.markers.summary,onAsk:askSummary,testID:"dashboard-marker-summary"})}):null,
|
|
642
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.lead,children:DASHBOARD_COPY.lead(petName)}),
|
|
643
|
+
/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCarousel,{markers:markerList,onPointPress:onPointPress,onAsk:askMarker})]}),actions=withRecord=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...styles.inset,display:"flex",flexDirection:"column",gap:theme.space.sm+theme.space.xs/2},children:[withRecord?actionRow(DASHBOARD_COPY.viewFullRecord,()=>onNavigate({name:"record"}),"dashboard-full-record-action"):null,actionRow(DASHBOARD_COPY.viewTimeline,()=>onNavigate({name:"timeline"}),"dashboard-timeline-action")]}):null,body;if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?retryAll:void 0,testID:"dashboard-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else switch(view){case"loading":body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"dashboard-loading"});break;case"record":body=/* @__PURE__ */jsxRuntime.jsxs("div",{ref:rise,style:styles.contentTight,"data-testid":"dashboard-record",children:[hasMarkers?labs:markers.status==="error"?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.inset,children:actionRow(DASHBOARD_COPY.retryMarkers,retryAll,"dashboard-markers-retry")}):null,
|
|
644
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.inset,children:records.record?/* @__PURE__ */jsxRuntime.jsx(RecordSections,{record:records.record,depth:depthView,petName:petName,showLabs:!hasMarkers,onNavigate:onNavigate,onAsk:onAsk}):null}),actions(true)]});break;case"error":{let error=markers.error??records.error;body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(error),message:error?.displayMessage,onAction:error?.retryable?retryAll:void 0,testID:"dashboard-error"});break}case"in_progress":body=/* @__PURE__ */jsxRuntime.jsxs("div",{ref:rise,style:styles.content,"data-testid":"dashboard-in-progress",children:[drivingRequest?/* @__PURE__ */jsxRuntime.jsx(InProgressCard,{request:drivingRequest,petName:name,onOpen:onNavigate?()=>onNavigate({name:"request",requestId:drivingRequest.id}):void 0,onAsk:onAsk?()=>{let built=buildRecordsRequestAskPrompt(petName,{clinicName:drivingRequest.clinicName??null,statusLabel:selectPrimaryLabel(drivingRequest),status:drivingRequest.status,heldItemCount:drivingRequest.heldItemCount},drivingRequest.id);onAsk(built.prompt,built.entityRef)}:void 0}):null,onNavigate?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.sm},"data-testid":"dashboard-ways",children:[
|
|
645
|
+
/* @__PURE__ */jsxRuntime.jsx(WayCard,{title:IN_PROGRESS_COPY.anotherClinic,sub:IN_PROGRESS_COPY.anotherClinicSub,onClick:()=>onNavigate({name:"clinicPicker"}),testID:"dashboard-way-clinic"}),
|
|
646
|
+
/* @__PURE__ */jsxRuntime.jsx(WayCard,{title:REQUEST_PROMPT_COPY.uploadDocument,...acceptsPhotos(records.uploadContentTypes)?{sub:IN_PROGRESS_COPY.uploadDocumentPhotoSub}:{},dashed:true,onClick:()=>onNavigate({name:"upload"}),testID:"dashboard-way-upload"})]}):null,
|
|
647
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"none":body=/* @__PURE__ */jsxRuntime.jsxs("div",{ref:rise,style:styles.content,"data-testid":"dashboard-request-prompt",children:[
|
|
648
|
+
/* @__PURE__ */jsxRuntime.jsxs("section",{style:{...styles.creamCard,gap:theme.space.md},children:[
|
|
649
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:{...styles.sectionTitle,color:theme.color.brandInk},children:REQUEST_PROMPT_COPY.firstRecordTitle(petName)}),
|
|
650
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.bodyText,children:REQUEST_PROMPT_COPY.body}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
651
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.muted,children:REQUEST_PROMPT_COPY.requestFromClinicSub}),
|
|
652
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.requestFromClinic,onClick:()=>onNavigate({name:"clinicPicker"}),testID:"dashboard-request-prompt-clinic"}),
|
|
653
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.uploadDocument,kind:"outline",onClick:()=>onNavigate({name:"upload"}),testID:"dashboard-request-prompt-upload"})]}):null]}),
|
|
654
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"labs_only":body=/* @__PURE__ */jsxRuntime.jsxs("div",{ref:rise,style:styles.contentTight,"data-testid":"dashboard-labs-only",children:[labs,
|
|
655
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})}),actions(false)]});break;default:body=assertNever(view)}/* @__PURE__ */
|
|
656
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
657
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DASHBOARD_COPY.titleWeb(petName),onBack:onBack,testID:"dashboard-header",right:onNavigate?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>onNavigate({name:"timeline"}),"aria-label":DASHBOARD_COPY.openTimeline,style:styles.iconButton,"data-testid":"dashboard-timeline-link",children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:4},children:[0,1,2].map(i=>/* @__PURE__ */jsxRuntime.jsx("span",{style:{display:"block",width:18,height:2,borderRadius:2,backgroundColor:theme.color.brand}},i))})}):void 0}),
|
|
658
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:body}),
|
|
659
|
+
/* @__PURE__ */jsxRuntime.jsx(MarkerProvenanceDialog,{marker:provenance?.marker??null,point:provenance?.point??null,onClose:()=>setProvenance(null),onAsk:askReading})]})}function InProgressCard({request:request,petName:petName,onOpen:onOpen,onAsk:onAsk}){let{theme:theme,styles:styles}=useScreenStyles(),title=IN_PROGRESS_COPY.title(petName),clinic=request.clinicName?.trim()??"",status=selectPrimaryLabel(request),content=/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.lg},children:[
|
|
660
|
+
/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm},children:[
|
|
661
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs/2,minWidth:0},children:[
|
|
662
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.sectionTitle,color:theme.color.brandInk},children:title}),clinic.length>0?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowDetail,children:clinic}):null]}),onOpen?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]}),
|
|
663
|
+
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:request,petName:petName}),status.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.statusCard,children:status}):null]});/* @__PURE__ */
|
|
664
|
+
return jsxRuntime.jsxs("section",{"aria-label":onOpen?void 0:IN_PROGRESS_COPY.a11y(petName),style:{...styles.creamCard,backgroundColor:theme.color.surface,padding:theme.space.lg+theme.space.xs/2,gap:theme.space.lg},"data-testid":"dashboard-in-progress-card",children:[onOpen?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onOpen,"aria-label":[title,clinic,status].filter(part=>part.length>0).join(". "),style:{background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit",width:"100%"},"data-testid":"dashboard-in-progress-open",children:content}):content,onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",onClick:onAsk,testID:"dashboard-in-progress-ask"}):null]})}function WayCard({title:title,sub:sub,ariaLabel:ariaLabel,dashed:dashed=false,onClick:onClick,testID:testID}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
665
|
+
return jsxRuntime.jsxs("button",{type:"button",onClick:onClick,"aria-label":ariaLabel,style:{...styles.creamCard,width:"100%",textAlign:"left",cursor:"pointer",font:"inherit",color:"inherit",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:theme.space.md,...dashed?{borderStyle:"dashed",borderColor:theme.color.brandBorderStrong}:{}},"data-testid":testID,children:[
|
|
666
|
+
/* @__PURE__ */jsxRuntime.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs/2},children:[
|
|
667
|
+
/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold")},children:title}),sub?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.muted,children:sub}):null]}),
|
|
668
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function EverfurRecordsRequests(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
669
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-requests-screen",children:[userRef===null?/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsxRuntime.jsx(RequestsBody,{...rest}),
|
|
670
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function RequestsBody({petRef:petRef,petName:petName,controller:controller,onNavigate:onNavigate,onBack:onBack,onOpenUrl:onOpenUrl}){let{theme:theme,styles:styles}=useScreenStyles(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),requests=react.useMemo(()=>selectRequestList(records.requests.filter(r=>r.petRef===petRef)),[records.requests,petRef]),clinicDecision=useCapability("recordsClinic"),headingId=`${react.useId()}-requests-heading`,body;return records.status==="loading"&&requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-requests-loading"}):records.status==="error"&&records.error&&requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(records.error),message:records.error.displayMessage,onAction:records.error.retryable?records.refresh:void 0,testID:"records-requests-error"}):body=/* @__PURE__ */jsxRuntime.jsx(RecordsPageRequests,{requests:requests,petName:petName,level:3,headingId:headingId,onOpenRequest:onNavigate?request=>onNavigate({name:"request",requestId:request.id}):void 0,onUpload:onNavigate?()=>onNavigate({name:"upload"}):void 0,...onOpenUrl?{onOpenUrl:onOpenUrl}:{}}),/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
671
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:CONSUMER_PAGE_COPY.title,onBack:onBack,testID:"records-requests-header"}),
|
|
672
|
+
/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsxs("div",{style:{...styles.content,gap:theme.space.lg},children:[onNavigate?/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm},"data-testid":"records-requests-actions",children:[clinicDecision.enabled||clinicDecision.isPending?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CONSUMER_PAGE_COPY.requestRecords,onClick:()=>onNavigate({name:"clinicPicker"}),testID:"records-requests-request-records"}):null,
|
|
673
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CONSUMER_PAGE_COPY.uploadAction,kind:"outline",onClick:()=>onNavigate({name:"upload"}),testID:"records-requests-upload"})]}):null,body]})})]})}function EverfurRecordsFlow(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,initialScreen:initialScreen,historyMode:historyMode="memory",onExit:onExit,style:style,className:className,renderPending:renderPending,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location2}=guardHostProps(props,["onExit"]),[nav,dispatch]=react.useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length,depthRef=react.useRef(depth);depthRef.current=depth;let pushedRef=react.useRef(depth),fromHistoryRef=react.useRef(false);react.useEffect(()=>{if(historyMode!=="browser"||typeof window>"u")return;let onPopState=event=>{let state=event.state;(typeof state?.efRecords=="number"?state.efRecords:1)<depthRef.current&&(fromHistoryRef.current=true,dispatch({type:"pop"}))};return window.addEventListener("popstate",onPopState),()=>window.removeEventListener("popstate",onPopState)},[historyMode]),react.useEffect(()=>{if(historyMode!=="browser"||typeof window>"u")return;let pushed=pushedRef.current;depth>pushed?window.history.pushState({efRecords:depth},""):depth<pushed&&!fromHistoryRef.current&&window.history.go(depth-pushed),fromHistoryRef.current=false,pushedRef.current=depth},[historyMode,depth]);let onNavigate=react.useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=react.useMemo(()=>popRecordsNav(nav).handled?()=>dispatch({type:"pop"}):onExit,[nav,onExit]),focusRoot=useFocusScreenOnChange(screen,initialScreen!==void 0),seams={onNavigate:onNavigate,...onBack?{onBack:onBack}:{},...petName!==void 0?{petName:petName}:{},...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location2?{location:location2}:{}},records={...controller?{controller:controller}:{},...consentVersion!==void 0?{consentVersion:consentVersion}:{},...consentText!==void 0?{consentText:consentText}:{}},box={...style?{style:style}:{},...className!==void 0?{className:className}:{}},pending=renderPending?{renderPending:renderPending}:{},content;switch(screen.name){case"dashboard":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,...box});break;case"request":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsRequest,{petRef:petRef,requestId:screen.requestId,...seams,...controller?{controller:controller}:{},...pending,...box});break;case"timeline":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsTimeline,{petRef:petRef,...seams,...box});break;case"record":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordDetail,{petRef:petRef,...seams,...records,...pending,...box});break;case"document":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordDocument,{petRef:petRef,...seams,...records,...pending,...box});break;case"contributions":content=/* @__PURE__ */jsxRuntime.jsx(EverfurDocumentContributions,{petRef:petRef,docId:screen.docId,...seams,...box});break;case"clinicPicker":content=/* @__PURE__ */jsxRuntime.jsx(EverfurClinicPicker,{petRef:petRef,...seams,...clinicController?{controller:clinicController}:{},...controller?{recordsController:controller}:{},...box});break;case"clinicBatch":content=/* @__PURE__ */jsxRuntime.jsx(EverfurClinicRequestBatch,{petRef:petRef,petName:petName??"",ownerName:ownerName??"",...onBack?{onClose:onBack}:{},onCreated:()=>dispatch({type:"navigate",screen:{name:"dashboard"}}),...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},...box});break;case"consent":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsConsent,{petRef:petRef,clinic:screen.clinic,...seams,...ownerName!==void 0?{ownerName:ownerName}:{},...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},...box});break;case"upload":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsUpload,{petRef:petRef,...seams,...controller?{controller:controller}:{},...pending,...box});break;case"requests":content=/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsRequests,{petRef:petRef,...seams,...controller?{controller:controller}:{},...pending,...box});break;default:content=assertNever(screen)}
|
|
674
|
+
/* @__PURE__ */
|
|
675
|
+
return jsxRuntime.jsx("div",{ref:focusRoot,style:FLOW_ROOT,"data-testid":"everfur-records-flow",children:content})}var FLOW_ROOT=/* @__PURE__ */Object.freeze({display:"contents"}),EverfurRecords=EverfurRecordsFlow;function EverfurClinicRequest(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
676
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ClinicRequestBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function ClinicRequestBody(props){let runtimeController=useEverfurRecordsClinic(),controller=props.controller??runtimeController,theme=useEverfurTheme(),formRef={current:null},pad=useSignatureCanvas(()=>formRef.current?.invalidate()),form=useClinicRequestForm(props,controller,props.onCaptureSignature??(async context=>pad.signed?pad.capture(controller,context.signal):null));formRef.current=form;let field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},button={...field,cursor:"pointer"},clear=()=>{form.busy||pad.clear()};/* @__PURE__ */
|
|
677
|
+
return jsxRuntime.jsxs("section",{className:props.className,"aria-label":CLINIC_REQUEST_COPY.title,style:{background:theme.color.surface,color:theme.color.text.primary,padding:theme.space.lg,borderRadius:theme.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...props.style},children:[
|
|
678
|
+
/* @__PURE__ */jsxRuntime.jsx("h2",{style:{margin:0,fontSize:theme.type.size.heading},children:CLINIC_REQUEST_COPY.title}),
|
|
679
|
+
/* @__PURE__ */jsxRuntime.jsx("p",{style:{margin:`${theme.space.sm}px 0 ${theme.space.lg}px`},children:props.petName}),form.created?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",children:form.created.statusLabel||RECORDS_COPY.records}):/* @__PURE__ */jsxRuntime.jsxs("div",{style:{display:"grid",gap:theme.space.md},children:[
|
|
680
|
+
/* @__PURE__ */jsxRuntime.jsxs("label",{children:[CLINIC_REQUEST_COPY.ownerName,
|
|
681
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box"},maxLength:200,value:form.ownerName,disabled:form.busy,autoComplete:"name",onChange:event=>{clear(),form.setOwnerName(event.target.value)}})]}),
|
|
682
|
+
/* @__PURE__ */jsxRuntime.jsxs("label",{children:[CLINIC_REQUEST_COPY.clinic,
|
|
683
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box"},placeholder:CLINIC_REQUEST_COPY.placeholder,maxLength:200,value:form.query,disabled:form.busy,autoComplete:"off",onChange:event=>{clear(),form.setQuery(event.target.value)}})]}),
|
|
684
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy||form.searching||form.query.trim().length<2,onClick:()=>{form.search()},children:CLINIC_REQUEST_COPY.search}),form.searching&&/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsxRuntime.jsx("h3",{style:{margin:`${theme.space.sm}px 0 0`,fontSize:theme.type.size.subtitle},"data-testid":"records-clinic-recent-label",children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",style:button,disabled:form.busy,onClick:()=>{clear(),form.selectClinic(clinic)},children:[clinic.name,clinic.address?`, ${clinic.address}`:"",clinic.phone?`, ${clinic.phone}`:""]},`recent-${clinic.id}`)),form.visibleClinics.map(clinic=>/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",style:button,disabled:form.busy,onClick:()=>{clear(),form.selectClinic(clinic)},children:[clinic.name,clinic.address?`, ${clinic.address}`:"",clinic.phone?`, ${clinic.phone}`:""]},clinic.id)),form.hasMoreClinics&&/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,onClick:form.showMoreClinics,"data-testid":"records-clinic-results-more",children:CLINIC_REQUEST_COPY.moreClinics}),form.needsEmail&&/* @__PURE__ */jsxRuntime.jsxs("label",{children:[CLINIC_REQUEST_COPY.email,
|
|
685
|
+
/* @__PURE__ */jsxRuntime.jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box"},type:"email",placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,maxLength:320,autoComplete:"off",value:form.email,disabled:form.busy,onChange:event=>{clear(),form.setEmail(event.target.value)}})]}),
|
|
686
|
+
/* @__PURE__ */jsxRuntime.jsx("h3",{style:{margin:`${theme.space.sm}px 0 0`,fontSize:theme.type.size.subtitle},children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsxRuntime.jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:form.query.trim()&&form.ownerName.trim()?form.scope??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",children:RECORDS_COPY.loading}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignatureCanvas,{pad:pad,disabled:form.busy}),form.error&&/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",children:form.error.displayMessage}),!form.copy&&form.error&&/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,onClick:form.retryCopy,children:RECORDS_COPY.retry}),
|
|
687
|
+
/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:{...button,background:theme.color.primary,color:theme.color.onPrimary,opacity:form.busy||!form.ready||!props.onCaptureSignature&&!pad.signed?.5:1},disabled:form.busy||!form.ready||!props.onCaptureSignature&&!pad.signed,onClick:()=>{form.submit()},children:form.busy?CLINIC_REQUEST_COPY.sending:CLINIC_REQUEST_COPY.send})]}),props.onClose&&/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",style:button,disabled:form.busy,onClick:props.onClose,children:CLINIC_REQUEST_COPY.cancel}),
|
|
688
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var FILE_FIELD="file",NO_BYTES="records upload: the file handle carries no bytes",FAILED="records upload failed";function createWebRecordsUploadTransport(options={}){let makeXhr=options.xhr??(()=>new XMLHttpRequest);/* @__PURE__ */
|
|
689
|
+
return Object.freeze({postMultipart(policy,file,opts){return new Promise((resolve,reject)=>{let blob=file.blob;if(blob===void 0){reject(new Error(NO_BYTES));return}let{signal:signal,onProgress:onProgress}=opts;if(signal?.aborted===true){reject(new Error(FAILED));return}let form=new FormData;for(let[name,value]of Object.entries(policy.upload_fields))form.append(name,value);form.append(FILE_FIELD,blob,recordsUploadFilename(file.mimeType));let xhr=makeXhr(),settled=false,settle=ok2=>{settled||(settled=true,signal?.removeEventListener("abort",onAbort),ok2?resolve():reject(new Error(FAILED)))},onAbort=()=>{xhr.abort(),settle(false)};xhr.open("POST",policy.upload_url,true),xhr.withCredentials=false,onProgress&&(xhr.upload.onprogress=event=>{!event.lengthComputable||event.total<=0||onProgress(Math.min(1,Math.max(0,event.loaded/event.total)))}),xhr.onload=()=>settle(xhr.status>=200&&xhr.status<300),xhr.onerror=()=>settle(false),xhr.onabort=()=>settle(false),xhr.ontimeout=()=>settle(false),signal?.addEventListener("abort",onAbort,{once:true}),xhr.send(form)})}})}exports.EverfurClinicPicker=EverfurClinicPicker;exports.EverfurClinicRequest=EverfurClinicRequest;exports.EverfurClinicRequestBatch=EverfurClinicRequestBatch;exports.EverfurRecordDetail=EverfurRecordDetail;exports.EverfurRecordDocument=EverfurRecordDocument;exports.EverfurRecords=EverfurRecords;exports.EverfurRecordsConsent=EverfurRecordsConsent;exports.EverfurRecordsDashboard=EverfurRecordsDashboard;exports.EverfurRecordsFlow=EverfurRecordsFlow;exports.EverfurRecordsPage=EverfurRecordsPage;exports.EverfurRecordsRequest=EverfurRecordsRequest;exports.EverfurRecordsRequests=EverfurRecordsRequests;exports.EverfurRecordsUpload=EverfurRecordsUpload;exports.RECORDS_CLINIC_BATCH_MAX=RECORDS_CLINIC_BATCH_MAX;exports.RECORDS_DOCUMENT_ACCEPT=RECORDS_DOCUMENT_ACCEPT;exports.RECORDS_TERMINAL=RECORDS_TERMINAL;exports.REQUEST_TIMELINE_TITLES=REQUEST_TIMELINE_TITLES;exports.RequestDocumentsList=RequestDocumentsList;exports.SignatureCanvas=SignatureCanvas;exports.acceptsPhotos=acceptsPhotos;exports.applyFactOverlay=applyFactOverlay;exports.buildRequestTimeline=buildRequestTimeline;exports.createWebRecordsUploadTransport=createWebRecordsUploadTransport;exports.currentRecordsScreen=currentRecordsScreen;exports.deriveRecordsDashboardState=deriveRecordsDashboardState;exports.fileToHandle=fileToHandle;exports.initialRecordsNav=initialRecordsNav;exports.isFactEditable=isFactEditable;exports.isPdfBlob=isPdfBlob;exports.isTerminalStatus=isTerminalStatus;exports.isUploadableHandle=isUploadableHandle;exports.pickDocument=pickDocument;exports.pickPetRecordsRequest=pickPetRecordsRequest;exports.popRecordsNav=popRecordsNav;exports.pushRecordsNav=pushRecordsNav;exports.recordsDenialReasonOf=recordsDenialReasonOf;exports.recordsDocumentAccept=recordsDocumentAccept;exports.recordsNavReducer=recordsNavReducer;exports.replaceRecordsNav=replaceRecordsNav;exports.requestDocumentRows=requestDocumentRows;exports.resetRecordsNav=resetRecordsNav;exports.selectClinicCall=selectClinicCall;exports.selectDashboardView=selectDashboardView;exports.selectPrimaryLabel=selectPrimaryLabel;exports.selectRequestList=selectRequestList;exports.selectRequestTitle=selectRequestTitle;exports.transitionRecordsNav=transitionRecordsNav;exports.useEverfurRecords=useEverfurRecords;exports.useEverfurRecordsClinic=useEverfurRecordsClinic;exports.useEverfurRecordsClinicBatch=useEverfurRecordsClinicBatch;exports.useRecordFactEdit=useRecordFactEdit;exports.useRecordPdfLink=useRecordPdfLink;exports.useRecordShares=useRecordShares;exports.useRecordsMarkers=useRecordsMarkers;exports.useRequestDocuments=useRequestDocuments;exports.useSignatureCanvas=useSignatureCanvas;
|