@everfur/sdk 0.7.0 → 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 +326 -0
- package/README.md +24 -16
- package/dist/{Chat-DZpYH8Uh.d.ts → Chat-Cv9EYMYA.d.ts} +3 -3
- package/dist/{Chat-bATY4atj.d.cts → Chat-s2vcPbw3.d.cts} +3 -3
- package/dist/{DepthViews-qBIoA48w.d.ts → DepthViews-CVxUHOJ-.d.ts} +1 -1
- package/dist/{DepthViews-C4DC4Kom.d.cts → DepthViews-Cz7mSW7p.d.cts} +1 -1
- package/dist/{DepthViews-dLTizxjr.d.ts → DepthViews-DNRY0Ugm.d.ts} +1 -1
- package/dist/{DepthViews-BpHUbjSY.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/{BookedScreen-DFJcgf1e.d.ts → IntakeMedia-BH0fYDT2.d.cts} +58 -2
- package/dist/{BookedScreen-R5X_Zrlh.d.cts → IntakeMedia-Bavl7E4Z.d.ts} +58 -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-CPRFfoHT.d.ts → attachments-BaslXMdS.d.ts} +3 -3
- package/dist/{attachments-CUOGILir.d.cts → attachments-DbFwz4iq.d.cts} +7 -7
- package/dist/{attachments-Ce06TWqe.d.cts → attachments-y3EcOX_w.d.cts} +3 -3
- package/dist/{attachments-CXAnZcEg.d.ts → attachments-y_aO4hlk.d.ts} +7 -7
- package/dist/{bookingCopy-BwVopcoV.d.cts → bookingCopy-4i1R7klo.d.cts} +15 -7
- package/dist/{bookingCopy-DFTv9w6J.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-CJchNp3x.d.cts → casesRepository-B6Z0XBIb.d.cts} +2 -2
- package/dist/{casesRepository-DAVcY3jC.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-ZxwCylac.d.ts → config-Cvo47voG.d.ts} +3 -3
- package/dist/{config-h5h6TsHL.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-CtsAgJnc.d.cts → context-BZOtJbBO.d.cts} +9 -9
- package/dist/{context-DtPIshVA.d.ts → context-cZ7NZ0sG.d.ts} +9 -9
- package/dist/{copy-Cg89Qoal.d.ts → copy-CZBUHbyS.d.ts} +5 -5
- package/dist/{copy-CaWaplQc.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-EXZYEO70.d.cts → depth-CRyU7-pf.d.cts} +8 -7
- package/dist/{depth-Bo4bAwcn.d.ts → depth-vNpwOkZ8.d.ts} +8 -7
- package/dist/{entitlementRepository-BYtVb1oU.d.cts → entitlementRepository-Bv8nSYRd.d.cts} +4 -4
- package/dist/{entitlementRepository-DcbIx8yV.d.ts → entitlementRepository-CUdxbQrP.d.ts} +4 -4
- package/dist/{identity-EC5-apbY.d.ts → identity-B8GkH53J.d.ts} +2 -2
- package/dist/{identity-b5Vp32Vp.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-DM8QvKLo.d.cts → pets-BI7Ji8hi.d.cts} +2 -2
- package/dist/{pets-B_27_agU.d.ts → pets-Dnn-DK1T.d.ts} +2 -2
- package/dist/{petsRepository-CuYZZaI5.d.ts → petsRepository-B2lO1sKS.d.ts} +2 -2
- package/dist/{petsRepository-BJsJ4cju.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-nXHf50_X.d.ts → ports-BUXF0Rp3.d.ts} +7 -7
- package/dist/{ports-ZmJYgd5I.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-Ve9BshTB.d.ts → requestFunnel-BrOijMcw.d.ts} +5 -5
- package/dist/{requestFunnel-C_cZXhIA.d.cts → requestFunnel-BxNVGyGm.d.cts} +5 -5
- package/dist/{runtimeTypes-ByKsp8hm.d.ts → runtimeTypes-CvI1ZH8j.d.ts} +7 -7
- package/dist/{runtimeTypes-D155OlBW.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-DXpjECfA.d.ts → timelineRows-CEx2TzYB.d.ts} +1 -1
- package/dist/{timelineRows-BNF43SXK.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-BqfwxZH4.d.cts → typeStyle-C3IG9Sft.d.ts} +22 -3
- package/dist/{typeStyle-DKz02DGU.d.ts → typeStyle-CZ3Tj60N.d.cts} +22 -3
- package/dist/{useRecordsDepth-CARTuHKh.d.cts → useRecordsDepth-D6a6-_u_.d.cts} +7 -6
- package/dist/{useRecordsDepth-fPSv-GXU.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-Dc-JlFkf.d.ts → view-BSmN5RWf.d.ts} +5 -5
- package/dist/{view-DGPaVno8.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 +26 -74
- package/dist/web/televet/booking/index.d.ts +26 -74
- 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 +29 -10
- package/dist/web/televet/index.d.ts +29 -10
- package/dist/web/televet/index.js +102 -4
- package/package.json +20 -4
- package/web/records/upload/native-blocked.cjs +12 -0
- package/web/records/upload/package.json +8 -0
- package/dist/televetGlobal-CEk0_cW9.d.cts +0 -34
- package/dist/televetGlobal-Cs9Wbqsy.d.ts +0 -34
package/dist/records/index.cjs
CHANGED
|
@@ -1,4 +1,742 @@
|
|
|
1
|
-
'use strict';var react=require('react'),zod=require('zod'),reactNative=require('react-native'),jsxRuntime=require('react/jsx-runtime');var Mu=Object.defineProperty;var i=(e,t)=>Mu(e,"name",{value:t,configurable:true});var gi=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(gi.map(e=>e.wireCode));var Hu=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"}),Ta=Object.freeze(gi.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Hu[e.wireCode]}))),Bu=new Map(Ta.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Uu=Object.freeze(["http_envelope",...[...new Set(Ta.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Kn(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...Uu]){let n=Bu.get(o+r);if(n)return n}}i(Kn,"contractErrorFor");function ju(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(ju,"contractDocUrl");function ka(e){return null}i(ka,"publishedDocUrl");var $u=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 _a(e){return $u[e]}i(_a,"categoryFor");function Pa(e){let t=Kn(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),o=r.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(r.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(Pa,"fromWire");var Wu=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function bi(e){return Wu.has(e)}i(bi,"isAutoRetryable");var Gu=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Ia(e){return bi(e)||Gu.has(e)}i(Ia,"isRetryableCode");var Yu=500,hi=8e3,Da=4;function Aa(e,t=Math.random){let r=Math.max(0,e),o=Math.min(Yu*2**r,hi);return Math.floor(t()*o)}i(Aa,"backoffDelayMs");var Ku=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 Ri(e){return Ku[e]}i(Ri,"userFacingError");function Oa(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Oa,"defineHidden");var Qu=/^[a-z][a-z0-9_]{0,63}$/;function W(e,t){let r=Kn(t?.wireCode,t?.wireEnvelope),o={code:e,category:_a(e),retryable:t?.retryable??Ia(e),displayMessage:Ri(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&Qu.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&Oa(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Oa(o,"raw",t.raw),Object.freeze(o)}i(W,"makeEverfurError");function Ve(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(Ve,"ok");function te(e){return Object.freeze({ok:false,error:e})}i(te,"err");var Qn=class Qn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Qn.prototype);}};i(Qn,"EverfurConfigError");var bn=Qn;var Zr=Object.freeze(["vet","groomer","boarding"]),Xu=zod.z.string().min(1).refine(e=>e.startsWith("https://")),Jr=zod.z.string().nullish(),vi=zod.z.unknown().optional(),Ju=zod.z.object({share_id:zod.z.string().min(1),share_url:zod.z.string().min(1),expires_at:Jr,audience:vi}),Zu=zod.z.object({shares:zod.z.array(zod.z.object({share_id:zod.z.string().min(1),expires_at:Jr,created_at:Jr,view_count:zod.z.number().int().nonnegative().nullish(),last_viewed_at:Jr,audience:vi})).optional()}),ep=zod.z.object({download_url:Xu,expires_at:Jr}),tp=zod.z.object({share_id:zod.z.string().min(1),expires_at:Jr,audience:vi}),rp=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()}),wi=254;function Xn(e){let t=e.trim();return t.length>0&&t.length<=wi&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(t)}i(Xn,"isShareRecipientEmail");var La=i(e=>typeof e=="string"&&Zr.includes(e),"isAudience");function xi(e){return La(e)?e:null}i(xi,"audienceOf");function Va(e){let t=zod.z.array(rp).safeParse(e);if(!t.success)return Object.freeze([]);let r=new Set,o=[];for(let n of t.data)!La(n.audience)||r.has(n.audience)||(r.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(Va,"mapShareAudiences");function np(e,t){let r=e.trim();if(r.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i(np,"resolveShareUrl");function Fa(e,t){let r=Ju.safeParse(e);if(!r.success)return null;let o=np(r.data.share_url,t);return o===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:o,expiresAt:r.data.expires_at??null,audience:xi(r.data.audience)})}i(Fa,"mapRecordShareLink");function qa(e){let t=Zu.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null,audience:xi(r.audience)}))):null}i(qa,"mapRecordShareList");function za(e){let t=tp.safeParse(e);return t.success?Object.freeze({shareId:t.data.share_id,expiresAt:t.data.expires_at??null,audience:xi(t.data.audience)}):null}i(za,"mapRecordShareEmailReceipt");function Na(e){let t=ep.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Na,"mapRecordPdfLink");var Ci="application/pdf",Ma=Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Mt=Object.freeze({features:Object.freeze({}),uploadContentTypes:Object.freeze([Ci]),shareAudiences:Object.freeze([])}),op=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()}),Ha=i(e=>Ma.includes(e),"isPhotoType");function Jn(e){let t=op.safeParse(e);if(!t.success)return Mt;let r=t.data.upload_content_types??[],o=Ma.filter(n=>r.includes(n));return Object.freeze({features:Object.freeze({...t.data.features}),uploadContentTypes:Object.freeze([Ci,...o]),shareAudiences:Va(t.data.share_audiences)})}i(Jn,"mapRecordsFeatures");function hn(e){return e!==void 0&&e.some(Ha)}i(hn,"acceptsPhotos");function Zn(e,t){return e===Ci||t!==void 0&&Ha(e)&&t.includes(e)}i(Zn,"isAcceptedUploadType");var Wa=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Ba=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 ip(e){let t=Object.prototype.hasOwnProperty.call(Ba,e)?Ba[e]:void 0;if(t!==void 0)return t;let r=e;return Wa.has(r)?r:"parsing"}i(ip,"normalizeStatus");function Ga(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Ga,"normalizeOrigin");var sp=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 Tr(e){let t=sp.safeParse(e);if(!t.success)return null;let r=t.data,o=lp(r.simple_status),n=o==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":o??ip(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:ja(r.document_count,0),heldItemCount:ja(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(Tr,"mapRequestView");var ap=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 Ya(e){let t=ap.safeParse(e);if(!t.success)return null;let r=t.data,o=Ei(r.members);return o.some(n=>n.petRef!==r.pet_ref)?null:Object.freeze({requestGroupId:r.request_group_id,petRef:r.pet_ref,total:r.total,responded:r.responded,pending:r.pending,members:o})}i(Ya,"mapRequestGroup");function lp(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Wa.has(e)?e:null}i(lp,"normalizeSimpleStatus");function Ei(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=Tr(o);n!==null&&r.push(n);}return Object.freeze(r)}i(Ei,"mapRequestList");var cp=zod.z.object({source_doc_id:zod.z.string().min(1),request_id:zod.z.string().min(1)});function Ka(e){let t=cp.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(Ka,"mapUploadedDocument");var dp=zod.z.object({label:zod.z.string(),value:zod.z.string()}),Si=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()}),up=zod.z.object({at:zod.z.string(),value:zod.z.number().nullish(),display:zod.z.string().nullish(),origin:zod.z.string().nullish()}),pp=zod.z.object({key:zod.z.string(),label:zod.z.string().optional(),points:zod.z.array(up).optional()}),mp=zod.z.object({title:zod.z.string(),detail:zod.z.string().nullish(),due_at:zod.z.string().nullish()}),Ti=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 ki(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:Ga(e.origin),canonicalKey:e.canonical_key??null})}i(ki,"mapEntityRow");function _i(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(_i,"mapDocumentRow");var yp=zod.z.object({identity:zod.z.array(dp).optional(),entities:zod.z.array(Si).optional(),entity_series:zod.z.array(pp).optional(),forward_looking:zod.z.array(mp).optional(),documents:zod.z.array(Ti).optional()});function Qa(e,t){let r=gp(t)?t:{},o=$a(r.schema_version,"epdf/1.0"),n=$a(r.disclaimer,""),l=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Ua(l,o,n);let a=yp.safeParse(r);if(!a.success)return Ua(l,o,n);let c=a.data,s=(c.identity??[]).map(w=>Object.freeze({label:w.label,value:w.value})),d=(c.entities??[]).map(ki),u=(c.entity_series??[]).map(w=>Object.freeze({key:w.key,label:w.label??w.key,points:Object.freeze((w.points??[]).map(R=>Object.freeze({at:R.at,value:R.value??null,display:R.display??null,origin:Ga(R.origin)})))})),m=(c.forward_looking??[]).map(w=>Object.freeze({title:w.title,detail:w.detail??null,dueAt:w.due_at??null})),y={};for(let w of c.documents??[])y[w.doc_id]=_i(w);let g=r.is_empty===true||s.length===0&&d.length===0&&u.length===0&&m.length===0&&Object.keys(y).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:g,withheld:false,generatedAt:bp(r.generated_at),identity:Object.freeze(s),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(m),documents:Object.freeze(y),disclaimer:n})}i(Qa,"mapRecordView");function Ua(e,t,r){return Object.freeze({petRef:e,schemaVersion:t,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:r})}i(Ua,"withheldView");var fp=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 eo(e,t){let r=fp.safeParse(t),o=r.success?r.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(eo,"mapConsent");function gp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(gp,"isObject");function ja(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(ja,"numberOr");function $a(e,t){return typeof e=="string"&&e.length>0?e:t}i($a,"strOr");function bp(e){return typeof e=="string"&&e.length>0?e:null}i(bp,"strOrNull");var Xa=Object.freeze(["published","failed","revoked"]);function kr(e){return Xa.includes(e)}i(kr,"isTerminalStatus");function _r(e){if(e===null)return null;let t=e.recordsReason;return t==="consent_required"||t==="session_required"||t==="entitlement"||t==="pet_not_found"?t:null}i(_r,"recordsDenialReasonOf");var hp="records_consent_required";function Rp(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof o=="string"&&o.length>0?o:null}i(Rp,"recordsWireCodeOf");function ar(e){return e===null||e.httpStatus!==409?false:Rp(e)===hp}i(ar,"isRecordsConsentRequired");var vp=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function to(e){return e!==vp}i(to,"isUploadTransportAvailable");var Ja=Object.freeze({record(){}}),Pr=25*1024*1024,Za=64,Rn=128,Rt=128;var el=9e4;function rl(e){return new Pi(e)}i(rl,"createRecordsController");var Ii=class Ii{constructor(t){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.features=Mt;this.repository=t.repository,this.uploads=t.uploads,this.telemetry=t.telemetry??Ja,this.newIdempotencyKey=t.newIdempotencyKey??Sp(),this.timers=t.timers??Cp,this.uploadDeadlineMs=t.uploadDeadlineMs??el;}async createUploadRequest(t){let r=await this.repository.createRequest({pet_ref:t.petRef,idempotency_key:t.idempotencyKey});if(!r.ok)return this.onRequestError(r.error);let o=Tr(r.value);return o===null?te(ro()):(this.observeRequest(o),Ve(o))}async getRequest(t){let r=await this.repository.getRequest(t);if(!r.ok)return this.onRequestError(r.error);let o=Tr(r.value);return o===null?te(ro()):(this.observeRequest(o),Ve(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=Ei(t.value);for(let o of r)this.observeRequest(o);return Ve(r)}async readFeatures(){let t=this.repository.getFeatures;if(t===void 0)return this.features=Mt;let r=Mt;try{let o=await t.call(this.repository);o.ok&&(r=Jn(o.value));}catch{}return this.features=r,r}async uploadDocument(t){let{requestId:r,file:o}=t,n=wp(o,this.features.uploadContentTypes);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),te(tl(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(r,{content_type:o.mimeType,file_size:o.sizeBytes});if(!l.ok)return this.onRequestError(l.error);let a=await this.postToS3(l.value,o,t);if(!a.ok)return this.telemetry.record("records.upload.failed",{reason:a.reason}),te(tl(a.reason));let c=await this.repository.completeUpload(r,{upload_id:l.value.upload_id});if(!c.ok)return c.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:xp(c.error)??"corrupt"}),this.onRequestError(c.error);let s=Ka(c.value);return s===null?te(ro()):Ve(s)}async postToS3(t,r,o){let n=new AbortController,l=Ep(n.signal,o.signal),a=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let c={signal:l};return o.onProgress&&(c.onProgress=o.onProgress),await this.uploads.postMultipart(t,r,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(t){let r=this.consentEpoch.get(t)??0,o=await this.repository.getRecord(t);if(r!==(this.consentEpoch.get(t)??0))return te(Object.freeze({...W("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=_r(o.error);return l==="consent_required"?(this.recordCache.delete(t),this.telemetry.record("records.consent.denied",{pet_ref:t})):l==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t}),te(o.error)}let n=Qa(t,o.value);return n.petRef!==t?te(ro()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:t}),this.recordCache.delete(t),Ve(n)):(this.recordCache.set(t,n),Ve(n))}peekCachedRecord(t){return this.recordCache.get(t)??null}async getConsent(t){let r=await this.repository.getConsent(t);return r.ok?Ve(eo(t,r.value)):te(r.error)}async grantConsent(t){let r=await this.repository.putConsent(t.petRef,{consent_version:t.consentVersion,idempotency_key:t.idempotencyKey});return r.ok?Ve(eo(t.petRef,r.value)):(_r(r.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t.petRef}),te(r.error))}async revokeConsent(t){let r=await this.repository.deleteConsent(t);return r.ok?(this.consentEpoch.set(t,(this.consentEpoch.get(t)??0)+1),this.recordCache.delete(t),Ve(eo(t,r.value))):te(r.error)}reportCapabilityDenied(t){this.telemetry.record("records.capability.denied",t?{pet_ref:t}:{});}observeRequest(t){t.reviewStartedAt!==null&&!this.reportedGaps.has(t.id)&&(this.reportedGaps.add(t.id),this.telemetry.record("records.parse.gap",{request_id:t.id}));}onRequestError(t){return _r(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),te(t)}};i(Ii,"RecordsControllerImpl");var Pi=Ii;function wp(e,t){if(!Zn(e.mimeType,t))return "unsupported_format";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>Pr?"oversize":null}i(wp,"validateFile");function xp(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(xp,"reasonFromWire");function tl(e){return W("mediaUploadFailed",{retryable:false,wireMessage:e})}i(tl,"uploadFailed");function ro(){return W("internalError",{retryable:true})}i(ro,"internal");var Cp={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Ep(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let o=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),r.signal}i(Ep,"mergeSignals");function Sp(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Sp,"defaultIdempotencyFactory");function Ir(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Ir,"assertNever");function nl(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(nl,"errorFrame");function _p(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(_p,"authHeaders");function vn(e,t){return {...e,headers:{...Pp(e.headers),..._p(t)}}}i(vn,"withAuthHeaders");function Pp(e){if(!e)return {};let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(t[r]=o);}return t}i(Pp,"stripAuthHeaders");async function ol(e,t){if(t.mode==="anonymous")return t.transport.request(vn(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return te(Di())}let o=await t.transport.request(vn(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await t.identity.currentToken({forceRefresh:!0});}catch{return te(Di())}let l=await t.transport.request(vn(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?te(Di(l.error.httpStatus)):l}i(ol,"authedSend");function Di(e){return W("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(Di,"authRejectedError");function il(e){return W("internalError",{retryable:true,wireMessage:Ip(e)})}i(il,"networkError");function Ip(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Ip,"describeCause");var Dp=3e4,Ap=hi*2,Op="idempotency-key",Lp=new Set(["POST","PUT","PATCH","DELETE"]),Vp=Object.freeze({onEvent(){}}),Fp=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function qp(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(qp,"seededIdempotencyKey");function Dr(e){let t=e.observer??Vp,r=e.timers??Fp,o=e.rng??Math.random,n=e.sleep??((y,g)=>Qp(y,r,g)),l=e.maxAttempts??Da,a=e.unaryTimeoutMs??Dp,c=e.newIdempotencyKey??gr(),s=i(y=>{try{t.onEvent(y);}catch{}},"emit");async function d(y,g,w){let R=w?.maxAttempts,v=Math.max(1,R??l),f=w?.idempotent??Lp.has(g.method),b=w?.idempotencyKey===void 0?null:qp(w.idempotencyKey),C=f?b??c():null,h=zp(g,C),I=0;for(;;){let T=i(z=>Object.freeze({call:y,method:g.method,path:g.path,attempt:I,...C?{idempotencyKey:C}:{},...z}),"stamp");s(T({phase:"attempt"}));let k=Yp(a,r),_=Kp(k.signal,g.signal),E;try{E=await ol({...h,signal:_.signal},e.auth);}catch(z){E=te(il(z));}finally{_.dispose(),k.cancel();}if(E.ok)return s(T({phase:"settled",ok:true,reason:"ok"})),E;let B=E.error,x=Mp(B,I,{maxAttempts:v,rng:o,now:r.now(),aborted:g.signal?.aborted===true,...R!==void 0?{perCallMaxAttempts:R}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),A={ok:false,code:B.code,reason:x.reason,...B.httpStatus!==void 0?{httpStatus:B.httpStatus}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}};if(!x.retry)return s(T({phase:"settled",...A})),te(B);if(s(T({phase:"retry",...A,delayMs:x.delayMs})),await n(x.delayMs,g.signal),g.signal?.aborted===true)return s(T({phase:"settled",...A,reason:"aborted"})),te(B);I+=1;}}i(d,"send");async function u(y){return vn(y,await Gp(e.auth))}i(u,"authorize");async function*m(y,g,w){s(Object.freeze({call:y,phase:"stream.open",method:g.method,path:g.path,attempt:0}));try{yield*e.auth.transport.stream(g,w);}catch{yield nl({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(m,"stream"),Object.freeze({send:d,authorize:u,stream:m})}i(Dr,"createRequestFunnel");function zp(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==Op&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(zp,"assembleHeaders");function gr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(gr,"defaultIdempotencyKeyFactory");var Np=10;function Mp(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=Hp(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!bi(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(Np,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let s=Bp(e,r.now);return s!==null?s>Ap?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:s}:{retry:true,reason:n,delayMs:Aa(t,r.rng)}}i(Mp,"decideRetry");function Hp(e){let t=e.code==="unknown"?Pa(Wp(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(Hp,"throttleKind");function Bp(e,t){let r=jp(e.raw);if(r!==null){let n=r-t;return n>0?n:0}let o=Up(e.raw);return o===null?null:Math.round(o*1e3)}i(Bp,"retryOverrideMs");function Up(e){for(let t of Ai(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(Up,"findRetryAfterSeconds");function jp(e){for(let t of Ai(e)){let r=t.resets_at,o=$p(r);if(o!==null)return o}return null}i(jp,"findResetsAt");function Ai(e){if(!sl(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];sl(o)&&t.push(o);}return t}i(Ai,"candidateScopes");function $p(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i($p,"parseInstantMs");function Wp(e){for(let t of Ai(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Wp,"rawWireCode");function sl(e){return typeof e=="object"&&e!==null}i(sl,"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 Yp(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(Yp,"boundedSignal");function Kp(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let o=new AbortController;if(e.aborted||t.aborted)return o.abort(),{signal:o.signal,dispose:r};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",n);},"dispose")}}i(Kp,"mergeSignals");function Qp(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(o=>{let n=t.setTimeout(()=>{r?.removeEventListener("abort",l),o();},e),l=i(()=>{t.clearTimeout(n),o();},"onAbort");r?.addEventListener("abort",l,{once:true});})}i(Qp,"delayAbortable");function br(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let o=e.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(br,"hasLoneSurrogate");var lr="/widget/v1/records";function ll(e){let{auth:t}=e,r=t.mode,o=e.funnel??Dr({auth:t,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(s,d,u)=>{let m=await o.send(s,d);return m.ok?m:te(Zp(m.error,r,u))},"send"),l=i((s,d)=>typeof d!="string"||d.length===0?W("validationFailed",{retryable:false,wireMessage:`${s} is required and must be a non-empty string`}):br(d)?W("validationFailed",{retryable:false,wireMessage:`${s} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),a=i((s,d,u)=>{let m=l(s,d);if(m!==null)return m;let g=[...d].length;return g>u?W("validationFailed",{retryable:false,wireMessage:`${s} is ${g} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...s)=>s.find(d=>d!==null)??null,"firstError");return {createRequest:i(s=>{let d=c(a("idempotency_key",s.idempotency_key,Rn),a("pet_ref",s.pet_ref,Rt));return d?Promise.resolve(te(d)):n("records.createRequest",Oi(`${lr}/requests`,s),"request")},"createRequest"),initiateUpload:i((s,d)=>{let u=l("request_id",s);return u?Promise.resolve(te(u)):n("records.initiateUpload",Oi(`${lr}/requests/${encodeURIComponent(s)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((s,d)=>{let u=l("request_id",s);return u?Promise.resolve(te(u)):n("records.completeUpload",Oi(`${lr}/requests/${encodeURIComponent(s)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(s=>{let d=l("request_id",s);return d?Promise.resolve(te(d)):n("records.getRequest",wn(`${lr}/requests/${encodeURIComponent(s)}`),"request")},"getRequest"),listRequests:i(async()=>{let s=await n("records.listRequests",wn(`${lr}/requests`),"request");if(!s.ok)return s;let d=s.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(s=>{let d=a("pet_ref",s,Rt);return d?Promise.resolve(te(d)):n("records.getRecord",wn(`${lr}/pets/${encodeURIComponent(s)}/record`),"content")},"getRecord"),getConsent:i(s=>{let d=a("pet_ref",s,Rt);return d?Promise.resolve(te(d)):n("records.getConsent",wn(`${lr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"getConsent"),putConsent:i((s,d)=>{let u=c(a("consent_version",d.consent_version,Za),a("idempotency_key",d.idempotency_key,Rn),a("pet_ref",s,Rt));return u?Promise.resolve(te(u)):n("records.putConsent",em(`${lr}/pets/${encodeURIComponent(s)}/consent`,d),"consent")},"putConsent"),getFeatures:i(()=>n("records.getFeatures",wn(`${lr}/features`),"request"),"getFeatures"),deleteConsent:i(s=>{let d=a("pet_ref",s,Rt);return d?Promise.resolve(te(d)):n("records.deleteConsent",tm(`${lr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"deleteConsent")}}i(ll,"createHttpRecordsRepository");function al(e,t){let r={...e,recordsReason:t};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(r,o,n);}return Object.freeze(r)}i(al,"withReason");var Xp="pet_not_registered";function Jp(e){return e.httpStatus!==404?null:e.reasonCode===Xp?"pet_not_found":"entitlement"}i(Jp,"recordsErrorReasonFor");function Zp(e,t,r){let o=Jp(e);return o!==null?al(e,o):e.code!=="accessDenied"?e:al(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(Zp,"tagReason");function wn(e){return {method:"GET",path:e}}i(wn,"get");function Oi(e,t){return {method:"POST",path:e,body:t}}i(Oi,"post");function em(e,t){return {method:"PUT",path:e,body:t}}i(em,"put");function tm(e){return {method:"DELETE",path:e}}i(tm,"del");var cl=Symbol.for("@everfur/sdk#EverfurContext@v1"),dl=globalThis,ul=dl[cl]??(dl[cl]=react.createContext(null));ul.displayName??="EverfurContext";function Te(){let e=react.useContext(ul);if(e===null)throw new bn("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Te,"useEverfurContext");var Li=new Map,Vi=new Set;function pl(e){Li.set(e,(Li.get(e)??0)+1);for(let t of [...Vi])t();}i(pl,"notifyRecordsConsentWithdrawn");function sm(e){return Li.get(e)??0}i(sm,"recordsConsentEpochOf");function am(e){return Vi.add(e),()=>{Vi.delete(e);}}i(am,"subscribe");function no(e){let t=react.useCallback(()=>sm(e),[e]);return react.useSyncExternalStore(am,t,t)}i(no,"useRecordsConsentEpoch");var qi={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:Mt.uploadContentTypes},yl=4e3,cm=30;function mt(e){let{petRef:t}=e,r=react.useRef(e.uploadTransport);r.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:l,scopeEpoch:a}=Te(),c=react.useMemo(()=>({}),[n,l,t,a,e.controller]),s=react.useRef(c),[d,u]=react.useState({scope:c,controller:e.controller??null}),m=e.controller??(d.scope===c?d.controller:null),[y,g]=react.useState({scope:c,value:qi}),w=y.scope===c?y.value:qi,R=react.useCallback(O=>{g(U=>U.scope===c?{scope:c,value:O(U.value)}:U);},[c]),v=react.useRef(0);react.useEffect(()=>(s.current=c,g({scope:c,value:qi}),()=>{s.current=null,v.current+=1;}),[c]),react.useEffect(()=>{if(e.controller)return;let{services:O}=n.registry,U={record:i((q,ee)=>O.telemetry.track(q,ee),"record")},D=n.registry.acquire("records",`${l??""}|${t}${o?"|own-upload":""}`,()=>rl({repository:ll({auth:O.authFor(l),...O.errorPolicy?{errorPolicy:O.errorPolicy}:{}}),uploads:o?{postMultipart:i((q,ee,J)=>(r.current??O.uploadTransport).postMultipart(q,ee,J),"postMultipart")}:O.uploadTransport,telemetry:U}),()=>{});return u({scope:c,controller:D}),()=>{n.registry.release(D);}},[n,l,t,e.controller,a,c,o]);let f=react.useCallback(O=>{R(U=>({...U,...O}));},[R]),b=react.useCallback(async()=>{if(!m||s.current!==c)return;let O=v.current+=1;k.current=0,B(),f({loading:true,error:null,denialReason:null,withheld:false});let[U,D]=await Promise.all([m.getConsent(t),m.listRequests()]);if(O!==v.current)return;let q=U.ok?U.value:null,ee=D.ok?D.value.filter(H=>H.petRef===t):[],J=D.ok?null:D.error;if(q&&q.granted){let H=await m.getRecord(t);if(O!==v.current)return;if(H.ok){f({consent:q,requests:ee,record:H.value,withheld:H.value.withheld,error:H.value.withheld?mm():J,denialReason:null,loading:false});return}f({consent:q,requests:ee,record:null,error:H.error,denialReason:_r(H.error),withheld:false,loading:false});return}f({consent:q,requests:ee,record:null,error:U.ok?J:U.error,denialReason:q?"consent_required":pm(U),withheld:false,loading:false});},[m,t,f,c]);react.useEffect(()=>(b(),()=>{v.current+=1;}),[b]);let C=e.readUploadFeatures===true;react.useEffect(()=>{if(!C||!m?.readFeatures)return;let O=true;return m.readFeatures().then(U=>{O&&s.current===c&&f({uploadContentTypes:U.uploadContentTypes});}),()=>{O=false;}},[m,C,f,c]);let h=react.useMemo(()=>um(w.requests),[w.requests]),I=h?.id??null,T=h?.status??null,k=react.useRef(0),_=react.useRef(null),[E,B]=react.useReducer(O=>O+1,0);react.useEffect(()=>{if(!m||I===null||T===null||kr(T)||T==="in_review")return;_.current!==String(I)&&(_.current=String(I),k.current=0);let O=false,U=i(async()=>{if(O||k.current>=cm)return;k.current+=1;let q=await m.getRequest(I);if(!O){if(q.ok&&q.value.petRef===t){if(R(ee=>({...ee,requests:oo(ee.requests,q.value)})),kr(q.value.status)){q.value.status==="published"&&b();return}if(q.value.status==="in_review")return}D=setTimeout(()=>{U();},yl);}},"tick"),D=setTimeout(()=>{U();},yl);return ()=>{O=true,clearTimeout(D);}},[m,I,T,b,E,t,R]);let x=react.useCallback(async O=>{if(!m||s.current!==c)return io();let U=await m.createUploadRequest({petRef:t,idempotencyKey:O});return s.current===c&&U.ok&&U.value.petRef===t&&R(D=>({...D,requests:oo(D.requests,U.value)})),U},[m,t,c,R]),A=react.useCallback((O,U)=>{R(D=>({...D,uploadQueue:D.uploadQueue.map(q=>q.key===O?U(q):q)}));},[R]),z=react.useCallback(async(O,U)=>{let D=Date.now().toString(36),q=U.map((J,H)=>{let N=fl(J,w.uploadContentTypes);return {key:`${D}-${H}`,name:J.name??null,status:N===null?"queued":"skipped",progress:0,skipReason:N,error:null}}),ee=[...q];if(!m||s.current!==c)return Object.freeze(ee);R(J=>({...J,uploadQueue:q,isUploading:true,uploadProgress:0}));for(let[J,H]of U.entries()){let N=q[J];if(N.status==="skipped")continue;if(s.current!==c)break;A(N.key,Le=>({...Le,status:"uploading",progress:0})),f({uploadProgress:0});let ie=await m.uploadDocument({requestId:O,file:H,onProgress:i(Le=>{if(s.current!==c)return;let rt=Math.min(1,Math.max(0,Le));A(N.key,Ee=>({...Ee,progress:Math.max(Ee.progress,rt)})),f({uploadProgress:rt});},"onProgress")});if(s.current!==c)break;let Ce=ie.ok?{...N,status:"done",progress:1}:{...N,status:"failed",error:ie.error};if(ee[J]=Ce,A(N.key,()=>Ce),ie.ok){let Le=await m.getRequest(O);s.current===c&&Le.ok&&Le.value.petRef===t&&R(rt=>({...rt,requests:oo(rt.requests,Le.value)}));}}return s.current===c&&f({isUploading:false,uploadProgress:null}),Object.freeze(ee)},[m,f,A,t,c,R,w.uploadContentTypes]),de=react.useCallback(async(O,U)=>{if(!m||s.current!==c)return io();let D=`${Date.now().toString(36)}-0`;R(ee=>({...ee,isUploading:true,uploadProgress:0,uploadQueue:[{key:D,name:U.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let q=await m.uploadDocument({requestId:O,file:U,onProgress:i(ee=>{s.current===c&&(f({uploadProgress:ee}),A(D,J=>({...J,progress:Math.max(J.progress,Math.min(1,ee))})));},"onProgress")});if(s.current!==c)return q;if(f({isUploading:false,uploadProgress:null}),A(D,ee=>q.ok?{...ee,status:"done",progress:1}:{...ee,status:"failed",error:q.error}),q.ok){let ee=await m.getRequest(O);s.current===c&&ee.ok&&ee.value.petRef===t&&R(J=>({...J,requests:oo(J.requests,ee.value)}));}return q},[m,f,A,t,c,R]),G=react.useCallback(async(O,U)=>{if(!m||s.current!==c)return io();let D=await m.grantConsent({petRef:t,consentVersion:O,idempotencyKey:U});return D.ok&&s.current===c&&b(),D},[m,t,b,c]),ae=react.useCallback(async()=>{if(!m||s.current!==c)return io();let O=await m.revokeConsent(t);return O.ok&&pl(t),O.ok&&s.current===c&&(v.current+=1,f({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:O.value})),O},[m,t,f,c]),M=react.useCallback(()=>b(),[b]),$=dm(w,m!==null);return react.useMemo(()=>({status:$,record:w.record,requests:w.requests,activeRequest:h,consent:w.consent,error:w.error,denialReason:w.denialReason,withheld:w.withheld,isUploading:w.isUploading,uploadProgress:w.uploadProgress,uploadQueue:w.uploadQueue,uploadContentTypes:w.uploadContentTypes,createRequest:x,uploadDocument:de,uploadDocuments:z,grantConsent:G,revokeConsent:ae,refresh:M}),[$,w,h,x,de,z,G,ae,M])}i(mt,"useEverfurRecords");function fl(e,t){if(!Zn(e.mimeType,t))return "unsupported";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>Pr?"too_large":null}i(fl,"skipReasonFor");function gl(e,t){let r=[],o=[];for(let n of e){let l=fl(n,t);l===null?r.push(n):o.push({name:n.name??null,reason:l});}return {uploadable:r,skipped:o}}i(gl,"classifyPick");function dm(e,t){return e.loading||!t?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(dm,"selectStatus");function um(e){if(e.length===0)return null;let t=e[0];for(let r of e)r.updatedAt>t.updatedAt&&(t=r);return t}i(um,"newestRequest");function oo(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(oo,"replaceRequest");function pm(e){return e.ok?"consent_required":_r(e.error)??"consent_required"}i(pm,"consentDenial");function mm(){return W("internalError",{retryable:false})}i(mm,"withheldSentinel");function io(){return {ok:false,error:W("internalError",{retryable:true})}}i(io,"notReady");function zi(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(zi,"reportHostFailure");function ym(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(ym,"isThenable");function so(e,...t){if(typeof e=="function")try{let r=e(...t);return ym(r)&&Promise.resolve(r).then(void 0,zi),r}catch(r){zi(r);return}}i(so,"callHost");var bl=new WeakMap;function En(e){if(typeof e!="function")return;let t=bl.get(e);if(t!==void 0)return t;let r=i((...o)=>{so(e,...o);},"guarded");return bl.set(e,r),r}i(En,"guardHost");function Be(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=En(n));}return r??e}i(Be,"guardHostProps");function Ar(e,...t){let r;try{r=e(...t);}catch(o){return zi(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(Ar,"callHostAsync");var hl=Object.freeze({name:"dashboard"});function ao(e=hl){return Object.freeze({stack:Object.freeze([e])})}i(ao,"initialRecordsNav");function lo(e){return e.stack[e.stack.length-1]??hl}i(lo,"currentRecordsScreen");function Ni(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(Ni,"pushRecordsNav");function Mi(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(Mi,"replaceRecordsNav");function Hi(e){return ao(e)}i(Hi,"resetRecordsNav");function co(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(co,"popRecordsNav");function Rl(e,t){return t.name==="dashboard"?Hi(t):lo(e).name==="upload"&&t.name==="request"?Mi(e,t):Ni(e,t)}i(Rl,"transitionRecordsNav");function Bi(e,t){switch(t.type){case "push":return Ni(e,t.screen);case "pop":return co(e).state;case "replace":return Mi(e,t.screen);case "reset":return Hi(t.screen);case "navigate":return Rl(e,t.screen);default:return e}}i(Bi,"recordsNavReducer");function $i(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))$i(e[t]);}return e}i($i,"deepFreeze");var fm=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),wl={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},xl={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},vl={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},gm={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},bm={regular:"400",medium:"500",bold:"700"},hm={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Rm=0,uo="System",po="monospace",vm=["content","heading","control","compact","badge"];function wm(e){let t={};for(let r of vm)t[r]=e;return t}i(wm,"authoredTierSizes");function Cl(){return {family:uo,mono:po,fontUrl:null,families:{regular:uo,medium:uo,bold:uo,mono:po,monoMedium:po,monoBold:po},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:vl,tierSizes:wm(vl),lineHeight:gm,weight:bm,letterSpacing:hm,scale:1,maxScale:Rm,scaleCaps:fm}}i(Cl,"baseType");var El={},Ui=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function ji(e){return `cubic-bezier(${e.join(", ")})`}i(ji,"cssCubicBezier");var Sl={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:ji(Ui.standard),emphasized:ji(Ui.emphasized),exit:ji(Ui.exit)},reducedMotion:false},xm={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)"},Tl=$i({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:xm,space:wl,radius:xl,type:Cl(),motion:Sl,slots:El}),Cm={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)"};$i({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Cm,space:wl,radius:xl,type:Cl(),motion:Sl,slots:El});var kl=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),_l=globalThis,Wi=_l[kl]??(_l[kl]=react.createContext(Tl));Wi.displayName??="EverfurThemeContext";function V(){return react.useContext(Wi)}i(V,"useEverfurTheme");function Pm(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Pm,"tierMultiplier");function p({tier:e="content",...t}){let{type:r}=V(),o=Pm(r,e);return react.createElement(reactNative.Text,o===void 0?t:{maxFontSizeMultiplier:o,...t})}i(p,"Text");var Qe=react.forwardRef(i(function(t,r){return react.createElement(reactNative.TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Im=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function S(e,t){let r=e.type,o=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:o}:{fontFamily:o,fontWeight:r.weight[Im[t]]}}i(S,"face");var Z=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"});var xe=Object.freeze({title:Z.title,titleFor:i(e=>{let t=e?.trim()??"";return t.length>0?`Request ${t}\u2019s records`:Z.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:Z.placeholder,searchA11y:Z.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:Z.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 Il(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(Il,"clinicEmailStatusBadge");var Dm=1.609344;function Dl(e){return e===null||!Number.isFinite(e)?null:(e/Dm).toFixed(1)}i(Dl,"milesLabel");function Al(e){let t=Dl(e);return t===null?"":`${t} mi`}i(Al,"formatClinicDistanceLabel");function Ol(e){let t=Dl(e);return t===null?"":`${t} ${t==="1.0"?"mile":"miles"} away`}i(Ol,"formatClinicDistanceForA11y");var Ll=300,Gi=2;var ve=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"}),Vl="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var Am="your pet";function ke(e){let t=e?.trim()??"";return t.length>0?t:Am}i(ke,"petNameOr");var vt=Object.freeze({title:"Health records",titleWeb:i(e=>{let t=e?.trim()??"";return t.length>0?`${t}\u2019s Records`:"Health records"},"titleWeb"),titleNative:i(e=>{let t=e?.trim()??"";return t.length>0?t:"Health records"},"titleNative"),openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${ke(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")}),Qt=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,t,r,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${t} in range, ${r} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),Yi=Object.freeze({counter:i((e,t)=>`${e+1} of ${t}`,"counter"),a11y:i((e,t,r)=>e!==null?`${e}, marker ${t+1} of ${r}. Swipe left or right to see more markers.`:`Marker ${t+1} of ${r}`,"a11y")}),hr=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 t=e?.trim()??"";return t.length>0?`Ask about ${t}`:"Ask about this marker"},"askNamed"),askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),status:i(e=>`Status: ${e}`,"status"),latestA11y:i((e,t,r)=>`Latest reading ${e}, ${t}, collected ${r}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),At=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"}),Xt=Object.freeze({title:i(e=>`${ke(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 ${ke(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 ${ke(e)}.`,"a11y"),openA11y:i((e,t)=>`Open ${ke(e)}\u2019s records request. ${t}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),Ot=Object.freeze({title:i(e=>`Add ${ke(e)}\u2019s records`,"title"),firstRecordTitle:i(e=>`Add ${ke(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 ${ke(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${ke(e)}\u2019s records`,"uploadDocumentA11y")});function Fl(e){return !kr(e.status)}i(Fl,"isRecordsInProgress");function mo(e,t){if(t===null)return null;let r=e.filter(l=>l.petRef===t);if(r.length===0)return null;let o=r.find(l=>l.status==="published");return o!==void 0?o:r.filter(Fl).sort((l,a)=>a.updatedAt.localeCompare(l.updatedAt))[0]??null}i(mo,"pickPetRecordsRequest");function Ki(e){if(e.hasMarkers)return "published";let t=mo(e.requests,e.petRef);return t===null?"none":t.status==="published"||Fl(t)?"in_progress":"none"}i(Ki,"deriveRecordsDashboardState");function Om(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(Om,"selectDashboardLoading");function Qi(e){return Om(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(Qi,"selectDashboardView");function wt(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(wt,"recordsEmptyVariantForError");var fe=Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:i((e,t)=>`${e} has the request. We\u2019ll let you know when ${t}\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 Lm(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(Lm,"fallbackFailureTitle");function ql(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Lm(e)}i(ql,"failureTitle");var Vm=1440*60*1e3;function Xi(e,t){if(!e.createdAt)return 0;let r=Date.parse(e.createdAt);if(Number.isNaN(r))return 0;let o=t-r;return o<=0?0:Math.floor(o/Vm)}i(Xi,"requestElapsedDays");var Fm=7;function zl(e,t){return e.wireStatus!=="awaiting_response"?false:Xi(e,t)>=Fm}i(zl,"requestWaitingTooLong");function Ji(e){return e.status==="failed"}i(Ji,"isTerminalFailure");function Nl(e){return Ji(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(Nl,"shouldOfferRecovery");function Bl(e,t){let[r,o]=react.useState(""),[n,l]=react.useState(""),[a,c]=react.useState([]),[s,d]=react.useState(null),[u,m]=react.useState([]),[y,g]=react.useState(true),[w,R]=react.useState(false),[v,f]=react.useState(false),[b,C]=react.useState(null),[h,I]=react.useState(null),[T,k]=react.useState(0),_=react.useRef(0),E=react.useRef(true),B=t?.latitude,x=t?.longitude,A=react.useMemo(()=>B!==void 0&&x!==void 0?{latitude:B,longitude:x}:void 0,[B,x]);react.useEffect(()=>(E.current=true,()=>{E.current=false,_.current+=1;}),[e]),react.useEffect(()=>{let M=true;return g(true),e.recentClinics({limit:5}).then($=>{M&&($.ok&&m($.value.clinics),g(false));}).catch(()=>{M&&g(false);}),()=>{M=false;}},[e]),react.useEffect(()=>{let M=r.trim();if(M.length<Gi){l("");return}let $=setTimeout(()=>l(M),Ll);return ()=>clearTimeout($)},[r]);let z=n.length>=Gi;react.useEffect(()=>{let M=_.current+=1;if(c([]),d(null),C(null),I(null),!z){R(false);return}R(true),e.searchClinics({query:n,limit:25,...A?{location:A}:{}}).then($=>{!E.current||M!==_.current||($.ok?(c($.value.clinics),d($.value.nextCursor)):C($.error),R(false));}).catch(()=>{E.current&&M===_.current&&R(false);});},[e,n,z,A,T]);let de=react.useCallback(()=>{if(!z||s===null||v)return;let M=_.current;f(true),I(null),e.searchClinics({query:n,limit:25,cursor:s,...A?{location:A}:{}}).then($=>{!E.current||M!==_.current||($.ok?(c(O=>[...O,...$.value.clinics]),d($.value.nextCursor)):I($.error),f(false));}).catch(()=>{E.current&&M===_.current&&f(false);});},[e,s,n,z,v,A]),G=react.useCallback(M=>o(M),[]),ae=react.useCallback(()=>k(M=>M+1),[]);return react.useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:z,clinics:a,recent:u,recentLoading:y,initialLoading:w,loadingMore:v,hasNextPage:s!==null,error:b,pageError:h,setQuery:G,loadMore:de,retry:ae}),[r,n,z,a,u,y,w,v,s,b,h,G,de,ae])}i(Bl,"useClinicPicker");function es(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(es,"clinicDraftFor");var tn=10,fo=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),Sn=i((e,t=1)=>zod.z.string().refine(r=>!br(r)&&[...r].length>=t&&[...r].length<=e),"text"),jl=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),qm=zod.z.object({clinicId:fo.optional(),clinicFreeText:Sn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Sn(320,3).refine(e=>!jl(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:fo.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)),zm=zod.z.object({petRef:Sn(128),ownerName:Sn(200).refine(e=>e.trim().length>0&&!jl(e)),authorizationVersion:Sn(64),clinics:zod.z.array(qm).min(1).max(tn)}).strict(),Nm=zod.z.object({request_group_id:fo,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:fo.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 $l(e){let t=e.funnel??Dr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!zm.safeParse(r).success)return te(W("validationFailed",{retryable:false}));let o=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(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=Nm.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return Ul();let l=[];for(let a of n.data.results){let c=a.request===void 0||a.request===null?null:Tr(a.request);if(a.created!==(c!==null))return Ul();l.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 Ve(Object.freeze({requestGroupId:n.data.request_group_id,petRef:n.data.pet_ref,results:Object.freeze(l),createdCount:n.data.created_count,failedCount:n.data.failed_count}))}}}i($l,"createRecordsClinicBatchClient");function Ul(){return te(W("internalError",{retryable:false}))}i(Ul,"malformed");var Wl=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),Mm=zod.z.object({clinics:zod.z.array(zod.z.object({clinic_id:Wl,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()}),Hm=zod.z.object({authorization_version:zod.z.string().min(1),scope_template:zod.z.string().min(1),authorization_template:zod.z.string().min(1)}),Bm=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 Gl(e){let{repository:t}=e,r=i(async n=>{let l=await n;if(!l.ok)return l;let a=Tr(l.value);return a===null?Mr():Ve(a)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let a=Mm.safeParse(l.value);return a.success?Ve(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})):Mr()},"page");return {searchClinics:i((n={})=>o(t.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(t.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let l=await t.getRequestGroup(n);if(!l.ok)return l;let a=Ya(l.value);return a===null?Mr():Ve(a)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let l=Hm.safeParse(n.value);return l.success?Ve(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):Mr()},async createClinicRequest(n){let l=await r(t.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?Mr():l},retryRequest:i(n=>r(t.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>r(t.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,l)=>r(t.updateClinicEmail(n,l)),"updateClinicEmail"),convertToUpload:i(n=>r(t.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let l=await t.initiateSignatureUpload(n);if(!l.ok)return l;let a=Bm.safeParse(l.value);return a.success?Ve(Object.freeze({uploadId:a.data.upload_id,uploadUrl:a.data.upload_url,uploadFields:Object.freeze(a.data.upload_fields)})):Mr()},async completeSignatureUpload(n){let l=await t.completeSignatureUpload(n);if(!l.ok)return l;let a=zod.z.object({signature_id:Wl}).safeParse(l.value);return a.success?Ve(a.data.signature_id):Mr()}}}i(Gl,"createRecordsClinicController");function Mr(){return te(W("internalError",{retryable:false}))}i(Mr,"malformed");var Or="/widget/v1/records",Yl=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),Vr=i((e,t=1)=>zod.z.string().refine(r=>!br(r)&&[...r].length>=t&&[...r].length<=e),"text"),Ql=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Xl=Vr(320,3).refine(e=>!Ql(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),Kl=Vr(64),Um=zod.z.object({limit:zod.z.number().int().min(1).max(25).optional()}).strict(),jm=zod.z.object({query:Vr(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:Vr(512,0).optional()}).strict(),$m=zod.z.object({petRef:Vr(128),ownerName:Vr(200).refine(e=>e.trim().length>0&&!Ql(e)),authorizationVersion:Vr(64),clinicId:Yl.optional(),clinicFreeText:Vr(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Xl.optional(),signatureId:Yl.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 Jl(e){let t=e.funnel??Dr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((n,l,a=false)=>t.send(`records.clinic.${n}`,l,l.method==="GET"||a?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,l,a)=>Kl.safeParse(n).success?r(l,{method:"POST",path:`${Or}/requests/${encodeURIComponent(n)}/${l}`,...a?{body:a}:{}}):Lr(),"recover");return {searchClinics(n){return jm.safeParse(n).success?r("search",{method:"GET",path:`${Or}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):Lr()},recentClinics(n){return Um.safeParse(n).success?r("recent",{method:"GET",path:`${Or}/clinics/recent`,query:{limit:n.limit}}):Lr()},getRequestGroup(n){return Kl.safeParse(n).success?r("requestGroup",{method:"GET",path:`${Or}/request-groups/${encodeURIComponent(n)}`}):Lr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${Or}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return $m.safeParse(n).success?r("create",{method:"POST",path:`${Or}/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):Lr()},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,l){return Xl.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):Lr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?Lr():r("signatureInitiate",{method:"POST",path:`${Or}/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)?r("signatureComplete",{method:"POST",path:`${Or}/signatures/complete`,body:{upload_id:n}}):Lr()}}}i(Jl,"createHttpRecordsClinicRepository");function Lr(){return Promise.resolve(te(W("validationFailed",{retryable:false})))}i(Lr,"invalid");function Zt(){let{runtime:e,userRef:t,scopeEpoch:r}=Te(),o=react.useMemo(()=>{let{services:l}=e.registry;return Gl({repository:Jl({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})})},[e,t,r]),n=react.useRef(o);return react.useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),react.useMemo(()=>{let l=i(async a=>{if(t===null||n.current!==o)return te(W("accessDenied"));let c=await a();return n.current===o?c:te(W("accessDenied"))},"run");return {searchClinics:i(a=>l(()=>o.searchClinics(a)),"searchClinics"),recentClinics:i(a=>l(()=>o.recentClinics(a)),"recentClinics"),getRequestGroup:i(a=>l(()=>o.getRequestGroup(a)),"getRequestGroup"),getAuthorizationCopy:i(()=>l(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(a=>l(()=>o.createClinicRequest(a)),"createClinicRequest"),retryRequest:i(a=>l(()=>o.retryRequest(a)),"retryRequest"),revokeRequest:i(a=>l(()=>o.revokeRequest(a)),"revokeRequest"),updateClinicEmail:i((a,c)=>l(()=>o.updateClinicEmail(a,c)),"updateClinicEmail"),convertToUpload:i(a=>l(()=>o.convertToUpload(a)),"convertToUpload"),initiateSignatureUpload:i(a=>l(()=>o.initiateSignatureUpload(a)),"initiateSignatureUpload"),completeSignatureUpload:i(a=>l(()=>o.completeSignatureUpload(a)),"completeSignatureUpload")}},[o,t])}i(Zt,"useEverfurRecordsClinic");function ts(){let{runtime:e,userRef:t,scopeEpoch:r}=Te(),o=react.useMemo(()=>{let{services:l}=e.registry;return $l({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})},[e,t,r]),n=react.useRef(o);return react.useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),react.useMemo(()=>({async createClinicRequestBatch(l){if(t===null||n.current!==o)return te(W("accessDenied"));let a=await o.createClinicRequestBatch(l);return n.current===o?a:te(W("accessDenied"))}}),[o,t])}i(ts,"useEverfurRecordsClinicBatch");var os=class os extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,o){return Object.is(r.resetKey,o.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(os,"HostRenderBoundary");var rs=os;function Gm({render:e}){return e()}i(Gm,"RenderHost");function ns({render:e,fallback:t,resetKey:r}){return react.createElement(rs,{fallback:t,resetKey:r,children:react.createElement(Gm,{render:e})})}i(ns,"HostRender");var Ym=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 Km(e){return Ym[e]}i(Km,"requires");function rc(e,t,r){let o=Km(e),n=new Map;for(let c of t)n.set(c.resource,c);if(r?.isPending===true&&o.some(c=>!n.has(c)))return is({name:e,enabled:false,isPending:true,limits:{}});let l=Qm(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?is({name:e,enabled:true,isPending:false,limits:l}):is({name:e,enabled:false,isPending:false,limits:l,disabled:Xm(o,n)})}i(rc,"decideCapability");function Qm(e,t){let r={};for(let o of e){let n=t.get(o)?.limits;if(n)for(let[l,a]of Object.entries(n)){let c=r[l];r[l]=c===void 0?a:Math.min(c,a);}}return r}i(Qm,"mergeLimits");function Xm(e,t){for(let r of e){let o=t.get(r)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:Ri("accessDenied"),level:"user_entitlement",recoverable:false})}i(Xm,"disabledFor");function is(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(is,"freezeDecision");function Tn(e){let{runtime:t}=Te(),r=t.entitlements,o=react.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return react.useMemo(()=>rc(e,o.decisions,{isPending:o.isPending}),[e,o])}i(Tn,"useCapability");var ey=48;function ty(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(ty,"selectView");function Ue(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:l}=e,a=Tn(t),c=react.useMemo(()=>ty(a),[a]);switch(c){case "enabled":return r;case "pending":return n?jsxRuntime.jsx(ns,{render:n,fallback:jsxRuntime.jsx(oc,{capability:t,style:l})}):jsxRuntime.jsx(oc,{capability:t,style:l});case "disabled":return o?jsxRuntime.jsx(ns,{render:()=>o(a),fallback:jsxRuntime.jsx(ic,{decision:a,style:l}),resetKey:a}):jsxRuntime.jsx(ic,{decision:a,style:l});default:return Ir(c)}}i(Ue,"CapabilityGate");function oc({capability:e,style:t}){let r=V(),o=react.useMemo(()=>sc(r),[r]);return jsxRuntime.jsx(reactNative.View,{style:[o.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsxRuntime.jsx(reactNative.View,{style:o.skeletonBar})})}i(oc,"PendingSkeleton");function ic({decision:e,style:t}){let r=V(),o=react.useMemo(()=>sc(r),[r]),n=e.disabled?.reason??"";return jsxRuntime.jsx(reactNative.View,{style:[o.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:n,children:n.length>0?jsxRuntime.jsx(p,{style:o.offstateText,children:n}):null})}i(ic,"OffState");function sc(e){let{color:t,space:r,radius:o,type:n}=e;return reactNative.StyleSheet.create({offstate:{minHeight:ey,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:o.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...S(e,"regular"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:o.xs,backgroundColor:t.brandSofter}})}i(sc,"makeStyles");function je(e){let t=V(),r=react.useMemo(()=>oy(t),[t]);return jsxRuntime.jsx(p,{style:[r.footnote,e.style],accessibilityRole:"text",testID:"records-footnote",children:Vl})}i(je,"RecordsFootnote");function oy(e){let{color:t,space:r,type:o}=e;return reactNative.StyleSheet.create({footnote:{...S(e,"regular"),paddingHorizontal:r.lg,paddingTop:r.md,paddingBottom:r.lg,textAlign:"center",fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.normal),color:t.text.muted,backgroundColor:t.background}})}i(oy,"makeStyles");function dt(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(dt,"slotBox");function yt(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(yt,"slotText");var ac=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"})}),ls=60;function lc(e){return `Try again in ${e}s`}i(lc,"coolingActionLabel");var cc="Try again, available shortly";function Xe({variant:e,onAction:t,message:r,testID:o}){let n=cy(),l=ac[e],[a,c]=react.useState(e==="rate_limited"?ls:0);react.useEffect(()=>{e==="rate_limited"&&c(ls);},[e]),react.useEffect(()=>{if(a<=0)return;let u=setTimeout(()=>c(m=>Math.max(0,m-1)),1e3);return ()=>clearTimeout(u)},[a]);let s=e==="rate_limited"&&a>0,d=s?lc(a):l.action;return jsxRuntime.jsxs(reactNative.View,{style:n.container,accessibilityRole:"summary",testID:o,children:[jsxRuntime.jsx(reactNative.View,{style:n.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(p,{style:n.title,children:l.title}),jsxRuntime.jsx(p,{style:n.body,children:r??l.body}),d!==null&&t?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,disabled:s,accessibilityRole:"button",accessibilityLabel:s?cc:d,accessibilityState:{disabled:s},style:[n.action,s?n.actionDisabled:null],testID:o?`${o}-action`:`records-empty-${e}-action`,children:jsxRuntime.jsx(p,{style:n.actionLabel,children:d})}):null]})}i(Xe,"RecordsEmptyState");function cy(){let e=V();return react.useMemo(()=>dy(e),[e])}i(cy,"useStyles");function dy(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,a=r.lg+r.xs+r.xs/2;return reactNative.StyleSheet.create({container:{paddingVertical:r.xxl,paddingHorizontal:r.xl,alignItems:"center",gap:r.sm+r.xs/2},glyph:{width:a,height:a,borderRadius:a/2,backgroundColor:t.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...S(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug)-1,color:t.brandInk,textAlign:"center"},body:{...S(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.normal),color:t.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:r.sm,minHeight:r.xxl+r.sm,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,backgroundColor:t.brand,alignItems:"center",justifyContent:"center",...dt(l.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...S(e,"bold"),color:t.onPrimary,fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug)-1,...yt(l.primaryButton)}})}i(dy,"makeStyles");var ot="Back";function it({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let l=_n();return jsxRuntime.jsxs(reactNative.View,{style:l.row,testID:o,children:[t?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:ot,hitSlop:12,style:l.back,testID:o?`${o}-back`:void 0,children:jsxRuntime.jsx(reactNative.View,{style:l.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):jsxRuntime.jsx(reactNative.View,{style:l.back}),e.trim().length>0?jsxRuntime.jsx(p,{style:n==="document"?l.documentTitle:l.title,accessibilityRole:"header",numberOfLines:1,children:e}):jsxRuntime.jsx(reactNative.View,{style:l.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:o?`${o}-spacer`:void 0}),jsxRuntime.jsx(reactNative.View,{style:l.right,children:r??jsxRuntime.jsx(reactNative.View,{style:l.back})})]})}i(it,"ScreenHeader");function mc(){let e=_n();return jsxRuntime.jsxs(reactNative.View,{style:e.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsxRuntime.jsx(reactNative.View,{style:e.listBar}),jsxRuntime.jsx(reactNative.View,{style:e.listBar}),jsxRuntime.jsx(reactNative.View,{style:e.listBar})]})}i(mc,"ListGlyph");function yc(){let e=_n();return jsxRuntime.jsxs(reactNative.View,{style:e.shareGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsxRuntime.jsx(reactNative.View,{style:[e.shareDot,e.shareDotTop]}),jsxRuntime.jsx(reactNative.View,{style:[e.shareDot,e.shareDotLeft]}),jsxRuntime.jsx(reactNative.View,{style:[e.shareDot,e.shareDotBottom]}),jsxRuntime.jsx(reactNative.View,{style:[e.shareStroke,e.shareStrokeUp]}),jsxRuntime.jsx(reactNative.View,{style:[e.shareStroke,e.shareStrokeDown]})]})}i(yc,"ShareGlyph");function fc(){let e=_n();return jsxRuntime.jsxs(reactNative.View,{style:e.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsxRuntime.jsx(reactNative.View,{style:e.sendBody}),jsxRuntime.jsx(reactNative.View,{style:e.sendFold})]})}i(fc,"SendGlyph");function gc(){let e=_n();return jsxRuntime.jsxs(reactNative.View,{style:e.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsxRuntime.jsx(reactNative.View,{style:e.downloadStem}),jsxRuntime.jsx(reactNative.View,{style:e.downloadHead}),jsxRuntime.jsx(reactNative.View,{style:e.downloadTray})]})}i(gc,"DownloadGlyph");function _n(){let e=V();return react.useMemo(()=>fy(e),[e])}i(_n,"useStyles");function fy(e){let{color:t,space:r,type:o}=e,n=r.xxl+r.md,l=r.md,a=r.xs/2,c=r.lg+r.xs+r.xs/2;return reactNative.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md,gap:r.sm},back:{width:n,height:n,alignItems:"center",justifyContent:"center"},chevron:{width:l,height:l,borderLeftWidth:a,borderBottomWidth:a,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginLeft:r.xs},title:{flex:1,...S(e,"bold"),fontSize:o.size.heading,lineHeight:Math.round(o.size.heading*o.lineHeight.tight)+1,color:t.brandInk},spacer:{flex:1},documentTitle:{flex:1,textAlign:"center",...S(e,"bold"),fontSize:o.size.subtitle,lineHeight:Math.round(o.size.subtitle*o.lineHeight.snug),color:t.text.primary},right:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2},listGlyph:{width:c,height:c,justifyContent:"space-evenly"},listBar:{height:a,borderRadius:a,backgroundColor:t.brandInk},shareGlyph:{width:c-r.xs,height:c-r.xs},shareDot:{position:"absolute",width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs,borderWidth:a,borderColor:t.brandInk},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:r.xs+r.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:r.xs,top:r.sm,width:r.sm+r.xs/2,height:a,backgroundColor:t.brandInk},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:c-r.xs,height:c-r.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:a,borderColor:t.brandInk,transform:[{rotate:"45deg"}],borderRadius:a},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:a,backgroundColor:t.brandInk},downloadGlyph:{width:c-r.xs,height:c-r.xs,alignItems:"center"},downloadStem:{width:a,height:r.sm+r.xs/2,backgroundColor:t.brandInk},downloadHead:{width:r.sm,height:r.sm,borderRightWidth:a,borderBottomWidth:a,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginTop:-r.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:r.xs+r.xs/2,borderLeftWidth:a,borderRightWidth:a,borderBottomWidth:a,borderColor:t.brandInk}})}i(fy,"makeStyles");var hy=120,Ry=44;function vy({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:l,radius:a,type:c}=V();return jsxRuntime.jsxs(reactNative.View,{testID:"records-gate-off",style:[{minHeight:hy,justifyContent:"center",gap:l.md,padding:l.lg,borderRadius:a.md,borderWidth:1,borderColor:n.brandBorder,backgroundColor:n.surfaceCream},o],children:[e.length>0?jsxRuntime.jsx(p,{style:{fontSize:c.size.bodyTight,color:n.text.muted},children:e}):null,jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:r,testID:"records-gate-off-exit",style:{minHeight:Ry,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:l.lg,borderRadius:a.pill,borderWidth:1.5,borderColor:n.brandInk},children:jsxRuntime.jsx(p,{style:{fontSize:c.size.body,color:n.brandInk},children:r})})]})}i(vy,"RecordsGateOffState");function $e(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsxRuntime.jsx(vy,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i($e,"recordsGateExit");var ho=Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var Sy=52,Ro="rgba(0,0,0,0.4)";function Re(){let e=V();return react.useMemo(()=>ky(e),[e])}i(Re,"useScreenStyles");function Fr({disclaimer:e,style:t}){let r=Re();return e.trim().length===0?null:jsxRuntime.jsxs(reactNative.View,{style:[r.band,t],accessible:true,accessibilityRole:"text",accessibilityLabel:vt.important(e),testID:"records-disclaimer-band",children:[jsxRuntime.jsx(reactNative.View,{style:r.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(p,{style:r.infoGlyphText,children:"i"})}),jsxRuntime.jsx(p,{style:r.bandText,children:e})]})}i(Fr,"DisclaimerBand");function X({label:e,onPress:t,kind:r="primary",disabled:o=false,busy:n=false,accessibilityLabel:l,testID:a,style:c}){let s=Re(),d=V(),u=d.motion.reducedMotion,m=r==="primary"?s.pillPrimary:r==="outline"?s.pillOutline:r==="danger"?s.pillDanger:r==="ask"?s.pillAsk:s.pillLink,y=r==="primary"?s.pillPrimaryLabel:r==="danger"?s.pillDangerLabel:r==="ask"?s.pillAskLabel:r==="link"?s.pillLinkLabel:s.pillOutlineLabel;return jsxRuntime.jsxs(reactNative.Pressable,{onPress:t,disabled:o||n,accessibilityRole:"button",accessibilityLabel:l??e,accessibilityState:{disabled:o||n,busy:n},style:({pressed:g})=>[s.pill,m,o?s.pillDisabled:null,g&&!u?s.pressed:null,c],testID:a,children:[n?jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:r==="primary"?d.color.onPrimary:d.color.brandInk}):null,jsxRuntime.jsx(p,{style:y,children:e})]})}i(X,"Pill");function Lt({label:e,tone:t="neutral",testID:r}){let o=Re(),{bg:n,fg:l}=o.chipTones[t],a=e.length>Ty;return jsxRuntime.jsx(reactNative.View,{style:[o.chip,a?o.chipSentence:null,n],testID:r,children:jsxRuntime.jsx(p,{style:[o.chipText,a?o.chipSentenceText:null,l],children:e})})}i(Lt,"Chip");var Ty=24;function Bt({title:e,count:t}){let r=Re();return jsxRuntime.jsxs(reactNative.View,{style:r.sectionHeader,children:[jsxRuntime.jsx(p,{style:r.sectionTitle,accessibilityRole:"header",children:e}),t!==void 0?jsxRuntime.jsx(p,{style:r.sectionCount,children:t}):null]})}i(Bt,"SectionHeader");function er({direction:e="right"}){let t=Re(),r=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsxRuntime.jsx(reactNative.View,{style:[t.chevron,{transform:[{rotate:r}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(er,"Chevron");function ky(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:a,lineHeight:c}=n,s=i((v,f)=>Math.round(v*f),"lh"),d=reactNative.StyleSheet.hairlineWidth,u=r.xxl+r.md,m=i((v,f,b,C="regular")=>({...S(e,C),fontSize:v,lineHeight:s(v,f),color:b}),"text"),y=yt(l.recordCard),g=e.brightness==="dark"?t.errorRed:t.danger,w=i((v,f)=>({bg:{backgroundColor:v,borderColor:"transparent"},fg:{color:f}}),"tone"),R=i((v,f)=>({bg:{backgroundColor:t.surface,borderColor:v},fg:{color:f}}),"edge");return {chipTones:{neutral:R(t.brandBorderStrong,t.text.primary),info:w(t.brandSoft,t.brandInk),warning:R(t.cautionAccent,t.text.primary),critical:R(t.danger,t.danger),positive:R(t.success,t.brandInk)},...reactNative.StyleSheet.create({root:{flex:1,backgroundColor:t.background},body:{flex:1},content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg},contentTight:{paddingHorizontal:r.sm,paddingBottom:r.xxl,gap:r.lg},inset:{paddingHorizontal:r.sm},section:{gap:r.sm+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.xs},sectionTitle:{...m(a.subtitle,c.snug,t.text.primary,"bold"),letterSpacing:-0.4},sectionCount:{...m(a.bodyTight,c.snug,t.text.muted,"medium")},card:{borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.xs,...dt(l.recordCard,d)},creamCard:{borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md,...dt(l.recordCard,d)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,paddingVertical:r.md},rowDivider:{borderTopWidth:d,borderTopColor:t.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:r.xs+r.xs/2},rowTitle:{...m(a.body,c.snug,t.text.primary,"medium"),...y},rowDetail:{...m(a.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...y},rowValue:{...m(a.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...y},rowMuted:{...m(a.caption,c.normal,t.text.muted),...y},chip:{minHeight:24,justifyContent:"center",borderRadius:o.pill,borderWidth:1.5,paddingHorizontal:r.sm+r.xs/2,alignSelf:"flex-start"},chipText:{...m(a.tiny+1,c.snug,t.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:o.md,paddingVertical:r.xs,alignSelf:"stretch"},chipSentenceText:{...m(a.caption,c.normal,t.text.primary,"medium"),letterSpacing:0,textTransform:"none"},pill:{minHeight:Sy,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm},pillPrimary:{backgroundColor:t.brand,...dt(l.primaryButton)},pillPrimaryLabel:{...m(a.body,c.snug,t.onPrimary,"bold"),...yt(l.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...m(a.body,c.snug,t.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:t.danger,backgroundColor:t.surface},pillDangerLabel:{...m(a.bodyTight,c.snug,t.danger,"bold")},pillAsk:{borderWidth:d,borderColor:t.borderRingCream,backgroundColor:t.surface},pillAskLabel:{...m(a.body,c.snug,t.text.primary,"bold")},pillLink:{minHeight:u,backgroundColor:"transparent",paddingHorizontal:r.sm},pillLinkLabel:{...m(a.body,c.snug,t.linkInk,"bold")},pillDisabled:{opacity:.5},pressed:{transform:[{scale:ho.pressScale}]},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},infoNoteText:{flex:1,...m(a.bodyTight,c.normal,t.text.primary)},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCaution,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},cautionNoteText:{flex:1,...m(a.bodyTight,c.normal,t.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2},statusText:m(a.bodyTight,c.relaxed,t.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCritical,padding:r.md},errorText:{flex:1,...m(a.bodyTight,c.normal,g)},band:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft},bandText:{flex:1,...m(a.caption,c.normal,t.text.secondary)},infoGlyph:{width:r.md+r.xs/2,height:r.md+r.xs/2,borderRadius:o.pill,borderWidth:1,borderColor:t.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...m(a.small,c.tight,t.text.secondary,"bold")},chevron:{width:r.sm,height:r.sm,borderTopWidth:r.xs/2,borderRightWidth:r.xs/2,borderColor:t.text.muted},lead:{paddingHorizontal:r.sm,...m(a.body+1,c.snug,t.text.primary,"bold")},field:{minHeight:u,paddingHorizontal:r.md,paddingVertical:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,...S(e,"regular"),fontSize:a.body},fieldLabel:{...m(a.bodyTight,c.normal,t.text.secondary,"medium")},muted:m(a.caption,c.normal,t.text.muted),bodyText:m(a.body,c.normal,t.text.primary)})}}i(ky,"makeScreenStyles");function rn(e,t){return e===null?"":t?`${e} ${t}`:e}i(rn,"formatEntityValue");var hc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function re(e){if(!e)return "-";let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t!==null){let n=hc[Number(t[2])-1];return n===void 0?"-":`${n} ${Number(t[3])}, ${t[1]}`}let r=Date.parse(e);if(Number.isNaN(r))return "-";let o=new Date(r);return `${hc[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(re,"formatRecordsDate");function Rc(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=re(e),r=Number(e.slice(8,10));return t==="-"||r<1||r>31?e:t}i(Rc,"formatIdentityValue");var be=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 pr(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(pr,"markerStatusLabel");function nn(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(nn,"trajectoryLabel");function Rr(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(Rr,"humanize");var vc=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 Hr(e){return Object.prototype.hasOwnProperty.call(vc,e)?vc[e]:Rr(e)}i(Hr,"bodySystemLabel");var wc=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 on(e){return Object.prototype.hasOwnProperty.call(wc,e)?wc[e]:Rr(e)}i(on,"soapSectionLabel");function xc(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(xc,"formatWeightKg");function Vt(e,t,r){if((e===null||!Number.isFinite(e))&&r)return r;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return t?`${o} ${t}`:o}i(Vt,"formatMarkerReading");function ds(e,t,r){let o=nn(t,r);return e?`${be.measured(re(e))}${o?` \xB7 ${o}`:""}`:o}i(ds,"labDetailLine");var ne=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,t)=>`${re(e)} to ${re(t)}`,"dateRange"),documents:"Sources on file",uploadedDocument:be.uploadedDocument,documentRowA11y:i(e=>`View what ${e} contributed to this record`,"documentRowA11y"),documentMeta:i((e,t)=>{let r=t?re(t):null,n=[e!==null&&Number.isInteger(e)&&e>0?`${e} ${e===1?"page":"pages"}`:null,r].filter(l=>l!==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:be.labResults,visits:be.visits,physicalExams:be.physicalExams,visitNotes:be.visitNotes,document:Object.freeze({title:"Health Record",titleFor:i(e=>{let t=e?.trim()??"";return t.length>0?`${t}\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 ${re(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"})}),Cc=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 vr(e){return Object.prototype.hasOwnProperty.call(Cc,e)?Cc[e]:Rr(e)}i(vr,"entityTypeLabel");var Ec=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function vo(e){let t=Ec.filter(o=>e.includes(o)),r=e.filter(o=>!Ec.includes(o));return [...t,...r]}i(vo,"orderEntityTypes");function wo(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(wo,"conflictSeverityMeta");function Dn(e,t){if(!e)return null;let r=Date.parse(e);if(Number.isNaN(r))return null;let o=r<t-1440*60*1e3;return {label:o?ne.overdue:ne.due(re(e)),overdue:o}}i(Dn,"dueBadge");function Sc(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(Sc,"formatReferenceBand");var j=Object.freeze({openA11y:"Share medical record",openA11yFor:i(e=>{let t=e?.trim()??"";return t.length>0?`Share ${t}\u2019s record`:"Share medical record"},"openA11yFor"),title:"Share medical record",titleFor:i(e=>{let t=e?.trim()??"";return t.length>0?`Send ${t}\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 t=e?.trim()??"";return t.length>0?`Share a snapshot of what ${t}\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 t=e?.trim()??"";return t.length>0?`Add an email to send ${t}\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")})}),_y=Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),Py=Object.freeze([["encounters","encounters",be.visits],["lab_results","markers",be.labResults],["physical_exams","physical_exams",be.physicalExams]]);function Tc(e,t){let r=[];e.sections.includes("entities")&&(e.entityTypes===null?r.push(..._y):r.push(...vo(e.entityTypes).map(vr)));for(let[o,n,l]of Py)e.sections.includes(o)&&t[n]===true&&r.push(l);return e.sections.includes("forward_looking")&&r.push(ne.upcomingCare),Object.freeze(r)}i(Tc,"shareIncludedLines");function Iy(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(Iy,"isShareExpired");function Dy(e,t){let r=re(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(Dy,"formatShareExpiry");function kc(e,t,r){let o=e.map(n=>{let l=Iy(n.expiresAt,r),a=Dy(n.expiresAt,l),c=re(n.createdAt),s=l?"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:t[n.shareId]??null,active:!l,statusLabel:s,expiryLabel:a,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${s}. ${a}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(kc,"buildShareRows");function An(e,t){let r=e?.httpStatus;if(ar(e)){if(t==="create"||t==="email")return "Records access for this pet is off, so a new link cannot be created.";if(t==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(r===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(t==="revoke"&&(r===404||r===409||r===410))return "That link was already turned off.";if(r===401||r===403)return "You need to be signed in as this pet's owner to do that.";if(t==="email"&&(r===400||r===422||e?.code==="validationFailed"))return j.emailInvalid;switch(t){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 j.emailFailed;default:return "Could not download the record PDF. Please try again."}}i(An,"shareErrorMessage");function _e({width:e,height:t,radius:r,style:o}){let{color:n,radius:l}=V();return jsxRuntime.jsx(reactNative.View,{style:[{width:e,height:t,borderRadius:r??l.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(_e,"SkeletonBlock");var us=180,Pc=70,xo=22,Oy=300,Ic=44,Co=24,ps=34,Ly=6,Vy=5;function Eo({testID:e}){let t=On(),r=i(o=>jsxRuntime.jsxs(reactNative.View,{style:t.actionRow,children:[jsxRuntime.jsxs(reactNative.View,{style:t.actionLeft,children:[jsxRuntime.jsx(_e,{width:18,height:18,radius:9}),jsxRuntime.jsx(_e,{width:"55%",height:14,radius:7})]}),jsxRuntime.jsx(_e,{width:18,height:18,radius:9})]},o),"action");return jsxRuntime.jsxs(reactNative.View,{style:t.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:vt.loading,testID:e,children:[jsxRuntime.jsx(reactNative.View,{style:t.inset,children:jsxRuntime.jsxs(reactNative.View,{style:t.summaryCard,children:[jsxRuntime.jsx(_e,{width:us,height:us,radius:us/2}),jsxRuntime.jsxs(reactNative.View,{style:t.badges,children:[jsxRuntime.jsx(_e,{width:Pc,height:xo,radius:xo/2}),jsxRuntime.jsx(_e,{width:Pc,height:xo,radius:xo/2})]})]})}),jsxRuntime.jsx(_e,{width:150,height:16,radius:8,style:t.inset}),jsxRuntime.jsx(reactNative.View,{style:t.carouselCard,children:jsxRuntime.jsx(_e,{width:"100%",height:Oy,radius:14})}),jsxRuntime.jsxs(reactNative.View,{style:t.dots,children:[jsxRuntime.jsx(_e,{width:6,height:6,radius:3}),jsxRuntime.jsx(_e,{width:18,height:6,radius:3}),jsxRuntime.jsx(_e,{width:6,height:6,radius:3})]}),jsxRuntime.jsx(_e,{width:46,height:12,radius:6,style:t.centered}),jsxRuntime.jsx(reactNative.View,{style:t.inset,children:jsxRuntime.jsx(_e,{width:"100%",height:Ic,radius:12})}),jsxRuntime.jsxs(reactNative.View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(Eo,"DashboardSkeleton");function So({testID:e}){let t=On();return jsxRuntime.jsxs(reactNative.View,{style:t.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:fe.loading,testID:e,children:[jsxRuntime.jsx(reactNative.View,{children:[0,1,2,3].map(r=>jsxRuntime.jsxs(reactNative.View,{style:t.railRow,children:[jsxRuntime.jsxs(reactNative.View,{style:t.railColumn,children:[jsxRuntime.jsx(_e,{width:Co,height:Co,radius:Co/2}),r<3?jsxRuntime.jsx(_e,{width:2,height:20,radius:1,style:t.connector}):null]}),jsxRuntime.jsxs(reactNative.View,{style:t.railBody,children:[jsxRuntime.jsx(_e,{width:"55%",height:14,radius:7}),jsxRuntime.jsx(_e,{width:"75%",height:11,radius:6})]})]},r))}),jsxRuntime.jsxs(reactNative.View,{style:t.statusCard,children:[jsxRuntime.jsx(_e,{width:"90%",height:13,radius:6}),jsxRuntime.jsx(_e,{width:"60%",height:13,radius:6})]}),jsxRuntime.jsx(_e,{width:"100%",height:50,radius:25})]})}i(So,"RequestSkeleton");function Dc({testID:e}){let t=On();return jsxRuntime.jsxs(reactNative.View,{style:t.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:be.loadingTimeline,testID:e,children:[jsxRuntime.jsx(reactNative.View,{style:t.timelineDisclaimer,children:jsxRuntime.jsx(_e,{width:"100%",height:Ic,radius:12})}),Array.from({length:Ly},(r,o)=>jsxRuntime.jsxs(reactNative.View,{children:[o>0?jsxRuntime.jsx(reactNative.View,{style:t.timelineSeparator}):null,jsxRuntime.jsxs(reactNative.View,{style:t.timelineRow,children:[jsxRuntime.jsx(_e,{width:ps,height:ps,radius:ps/2}),jsxRuntime.jsxs(reactNative.View,{style:t.timelineBody,children:[jsxRuntime.jsxs(reactNative.View,{style:t.timelineTop,children:[jsxRuntime.jsx(_e,{width:44,height:10,radius:5}),jsxRuntime.jsx(_e,{width:56,height:12,radius:6})]}),jsxRuntime.jsx(_e,{width:"70%",height:14,radius:7}),o%2===0?jsxRuntime.jsx(_e,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Dc,"TimelineSkeleton");function Ac({testID:e}){let t=On();return jsxRuntime.jsx(reactNative.View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:xe.loading,testID:e,children:Array.from({length:Vy},(r,o)=>jsxRuntime.jsxs(reactNative.View,{style:t.clinicRow,children:[jsxRuntime.jsx(_e,{width:"65%",height:14,radius:7}),jsxRuntime.jsx(_e,{width:"40%",height:11,radius:6})]},o))})}i(Ac,"ClinicsSkeleton");function Oc({testID:e}){let t=On();return jsxRuntime.jsx(reactNative.View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:j.loadingLinks,testID:e,children:[0,1].map(r=>jsxRuntime.jsxs(reactNative.View,{style:t.shareRow,children:[jsxRuntime.jsx(_e,{width:"55%",height:13}),jsxRuntime.jsx(_e,{width:"40%",height:11})]},r))})}i(Oc,"SharesSkeleton");var ms=62;function On(){let e=V();return react.useMemo(()=>Fy(e),[e])}i(On,"useStyles");function Fy(e){let{color:t,space:r,radius:o}=e,n=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({dashboard:{flex:1,paddingHorizontal:r.sm,paddingTop:r.xs,gap:r.lg,backgroundColor:t.background},inset:{paddingHorizontal:r.sm},summaryCard:{alignItems:"center",borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg+r.xs,gap:r.md+r.xs/2},badges:{flexDirection:"row",gap:r.md},carouselCard:{borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.xs+r.xs/2},centered:{alignSelf:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},request:{paddingHorizontal:r.lg,paddingTop:r.xs,gap:r.lg+r.xs/2,backgroundColor:t.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md},railColumn:{alignItems:"center",width:Co},connector:{marginVertical:r.xs/2},railBody:{flex:1,paddingBottom:r.lg+r.xs/2,gap:r.xs+r.xs/2},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2,gap:r.sm},timeline:{flex:1,backgroundColor:t.background},timelineDisclaimer:{paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBody:{flex:1,gap:r.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},timelineSeparator:{height:n,backgroundColor:t.brandBorder,marginLeft:ms},clinics:{gap:r.md},clinicRow:{borderRadius:o.lg-r.xs/2,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2,gap:r.sm},shares:{gap:r.md,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:n,borderColor:t.brandBorder},shareRow:{gap:r.xs+r.xs/2}})}i(Fy,"makeStyles");var By=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function ys(e){let{userRef:t,scopeEpoch:r}=Te();return jsxRuntime.jsx(Ue,{capability:"recordsClinic",style:e.style,...$e(e.onBack,ot),children:t===null?jsxRuntime.jsx(p,{accessibilityRole:"alert",children:ve.sessionRequired}):jsxRuntime.jsx(Uy,{...Be(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i(ys,"EverfurClinicPicker");function Uy({petRef:e,petName:t,controller:r,recordsController:o,location:n,onNavigate:l,onBack:a,style:c}){let s=Re(),d=$y(),u=V(),m=Zt(),y=Bl(r??m,n),g=mt(o?{petRef:e,controller:o}:{petRef:e}),w=react.useRef(gr()),[R,v]=react.useState(false),[f,b]=react.useState(null),[C,h]=react.useState(false),[I,T]=react.useState(""),[k,_]=react.useState(false),[E,B]=react.useState(""),[x,A]=react.useState(false),z=react.useCallback(D=>{l?.({name:"consent",clinic:es(D,null,"",w.current())});},[l]),de=i(()=>{R||(v(true),b(null),g.createRequest(`records-upload-${Date.now().toString(36)}`).then(D=>{if(v(false),!D.ok){b(fe.errors.start);return}l?.({name:"request",requestId:D.value.id});}));},"startUpload"),G=k?I:y.query,ae=By.test(E.trim()),M=G.trim().length>0&&ae,$=i(D=>{let{layoutMeasurement:q,contentOffset:ee,contentSize:J}=D.nativeEvent;q.height+ee.y>=J.height-q.height*.6&&y.loadMore();},"onEndReached"),O=y.isSearchActive?y.clinics:y.recent,U=y.isSearchActive?y.error?wt(y.error):!y.initialLoading&&y.clinics.length===0?"idle":null:y.recent.length>0||y.recentLoading?null:"idle";return jsxRuntime.jsxs(reactNative.View,{style:[s.root,c],children:[jsxRuntime.jsx(it,{title:xe.titleFor(t),onBack:a,testID:"records-clinic-header"}),jsxRuntime.jsx(p,{style:d.lead,testID:"records-clinic-lead",children:xe.leadNative}),jsxRuntime.jsxs(reactNative.View,{style:d.searchBar,children:[jsxRuntime.jsx(reactNative.View,{style:d.searchGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(Qe,{value:y.query,onChangeText:y.setQuery,placeholder:xe.placeholder,placeholderTextColor:u.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:xe.searchA11y,style:d.searchInput,testID:"records-clinic-search-input"}),y.query.length>0?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>y.setQuery(""),accessibilityRole:"button",accessibilityLabel:xe.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:jsxRuntime.jsx(p,{style:d.clearGlyph,children:"\xD7"})}):null]}),l?jsxRuntime.jsxs(reactNative.View,{style:d.uploadWrap,children:[f?jsxRuntime.jsx(reactNative.View,{style:s.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(p,{style:s.errorText,children:f})}):null,jsxRuntime.jsx(X,{label:R?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",accessibilityLabel:xe.uploadOwnA11y,busy:R,onPress:de,testID:"records-clinic-upload-own"})]}):null,jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:d.list,keyboardShouldPersistTaps:"handled",onScroll:y.isSearchActive?$:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[y.isSearchActive?jsxRuntime.jsxs(reactNative.View,{style:d.fallbackCard,testID:"records-clinic-fallback-card",children:[jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>h(D=>!D),accessibilityRole:"button",accessibilityLabel:C?xe.fallback.collapseA11y:xe.fallback.expandA11y,style:d.fallbackHeader,testID:"records-clinic-fallback",children:[jsxRuntime.jsxs(reactNative.View,{style:d.fallbackCopy,children:[jsxRuntime.jsx(p,{style:d.fallbackTitle,numberOfLines:1,children:xe.fallback.title}),jsxRuntime.jsx(p,{style:d.fallbackSubtitle,numberOfLines:2,children:xe.fallback.subtitle})]}),jsxRuntime.jsx(er,{direction:C?"up":"down"})]}),C?jsxRuntime.jsxs(reactNative.View,{style:d.fallbackForm,children:[jsxRuntime.jsx(p,{style:s.fieldLabel,children:xe.fallback.nameLabel}),jsxRuntime.jsx(Qe,{accessibilityLabel:xe.fallback.nameLabel,style:s.field,value:G,onChangeText:D=>{T(D),_(true);},placeholder:xe.fallback.namePlaceholder,placeholderTextColor:u.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),jsxRuntime.jsx(p,{style:s.fieldLabel,children:xe.fallback.emailLabel}),jsxRuntime.jsx(Qe,{accessibilityLabel:xe.fallback.emailLabel,style:s.field,value:E,onChangeText:D=>{B(D),A(false);},onBlur:()=>A(true),placeholder:xe.fallback.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),x&&E.trim().length>0&&!ae?jsxRuntime.jsx(p,{style:s.errorText,accessibilityRole:"alert",children:fe.errors.invalidEmail}):null,jsxRuntime.jsx(p,{style:s.muted,children:xe.fallback.reviewNote}),jsxRuntime.jsx(X,{label:xe.fallback.submit,accessibilityLabel:xe.fallback.submitA11y,disabled:!M||!l,onPress:()=>l?.({name:"consent",clinic:es(null,G.trim(),E.trim().toLowerCase(),w.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):y.recent.length>0?jsxRuntime.jsx(p,{style:d.sectionLabel,accessibilityRole:"header",testID:"records-clinic-recent-label",children:xe.recentlyUsed}):null,y.isSearchActive&&y.initialLoading?jsxRuntime.jsx(Ac,{testID:"records-clinic-page-loading"}):null,O.map(D=>jsxRuntime.jsx(jy,{clinic:D,onSelect:z,styles:d},D.id)),U&&!y.initialLoading?jsxRuntime.jsx(Xe,{variant:U,message:y.isSearchActive&&U==="idle"?xe.noMatch(y.debouncedQuery):y.error?.displayMessage,onAction:y.error?.retryable===true?y.retry:void 0,testID:"records-clinic-empty"}):null,jsxRuntime.jsxs(reactNative.View,{style:d.footer,children:[y.loadingMore?jsxRuntime.jsxs(reactNative.View,{style:d.footerLoading,testID:"records-clinic-loading-more",children:[jsxRuntime.jsx(reactNative.ActivityIndicator,{color:u.color.brandInk,size:"small"}),jsxRuntime.jsx(p,{style:s.muted,children:xe.loadingMore})]}):null,y.pageError?jsxRuntime.jsx(reactNative.Pressable,{onPress:y.loadMore,accessibilityRole:"button",accessibilityLabel:xe.loadMoreRetryA11y,style:d.footerRetry,testID:"records-clinic-page-error-retry",children:jsxRuntime.jsx(p,{style:d.footerRetryLabel,children:xe.loadMoreFailed})}):null]}),jsxRuntime.jsxs(reactNative.View,{style:d.howCard,accessibilityRole:"summary",testID:"records-clinic-how",children:[jsxRuntime.jsx(p,{style:d.howTitle,accessibilityRole:"header",children:xe.howItWorks}),xe.howSteps(ke(t)).map((D,q)=>jsxRuntime.jsxs(reactNative.View,{style:d.howRow,children:[jsxRuntime.jsx(p,{style:d.howNumber,accessibilityElementsHidden:true,importantForAccessibility:"no",children:String(q+1).padStart(2,"0")}),jsxRuntime.jsxs(reactNative.View,{style:d.howText,children:[jsxRuntime.jsx(p,{style:d.howStepTitle,children:D.title}),jsxRuntime.jsx(p,{style:d.howStepBody,children:D.body})]})]},D.title))]})]}),jsxRuntime.jsx(je,{})]})}i(Uy,"PickerBody");function jy({clinic:e,onSelect:t,styles:r}){let o=Il(e.emailStatus),n=Al(e.distanceKm),l=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?Ol(e.distanceKm):null,o.a11y].filter(Boolean).join(", ");return jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:xe.selectA11y(l),hitSlop:8,style:r.item,testID:`records-clinic-${e.id}`,children:[jsxRuntime.jsxs(reactNative.View,{style:r.itemHeader,children:[jsxRuntime.jsx(p,{style:r.itemName,numberOfLines:1,children:e.name}),n?jsxRuntime.jsx(p,{style:r.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:n}):null]}),e.address?jsxRuntime.jsx(p,{style:r.itemAddress,numberOfLines:2,children:e.address}):null,e.phone?jsxRuntime.jsx(p,{style:r.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:e.phone}):null,jsxRuntime.jsx(reactNative.View,{style:[r.badge,o.tone==="positive"?r.badgePositive:o.tone==="caution"?r.badgeCaution:r.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(p,{style:[r.badgeLabel,o.tone==="positive"?r.badgePositiveText:o.tone==="caution"?r.badgeCautionText:r.badgeNeutralText],children:o.label})})]})}i(jy,"ClinicRow");function $y(){let e=V();return react.useMemo(()=>Wy(e),[e])}i($y,"useLocalStyles");function Wy(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,a=i((c,s,d,u="regular")=>({...S(e,u),fontSize:c,lineHeight:Math.round(c*s),color:d}),"text");return reactNative.StyleSheet.create({lead:{...a(n.size.body,n.lineHeight.normal,t.text.muted),paddingHorizontal:r.lg,paddingBottom:r.md},howCard:{borderRadius:o.lg,backgroundColor:t.surfaceSubtle,padding:r.lg,gap:r.md,marginTop:r.sm},howTitle:{...a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),letterSpacing:-0.4},howRow:{flexDirection:"row",gap:r.md},howNumber:{...S(e,"monoBold"),fontSize:n.size.caption,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.brandInk,minWidth:r.xl},howText:{flex:1,gap:r.xs/2},howStepTitle:a(n.size.body,n.lineHeight.snug,t.text.primary,"bold"),howStepBody:a(n.size.caption,n.lineHeight.normal,t.text.secondary),searchBar:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.md+r.xs/2,height:r.xxl+r.md,marginHorizontal:r.lg,marginBottom:r.sm,borderRadius:o.lg+r.xs/2,backgroundColor:t.surfaceSubtle,borderWidth:l,borderColor:t.borderHairlineGreen},searchGlyph:{width:r.md,height:r.md,borderRadius:o.pill,borderWidth:2,borderColor:t.text.muted},searchInput:{flex:1,...a(n.size.body,n.lineHeight.snug,t.text.primary),paddingVertical:0},clearGlyph:a(n.size.heading,n.lineHeight.tight,t.text.muted),uploadWrap:{paddingHorizontal:r.lg,paddingBottom:r.md,gap:r.sm},list:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.md},sectionLabel:{...a(n.size.caption,n.lineHeight.normal,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:o.lg-r.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.md},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:r.md,minHeight:r.xxl+r.md},fallbackCopy:{flex:1,gap:r.xs/2},fallbackTitle:{...a(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},fallbackSubtitle:a(n.size.caption,n.lineHeight.normal,t.text.muted),fallbackForm:{gap:r.sm},item:{borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},itemName:{flex:1,...a(n.size.body,n.lineHeight.snug,t.brandInk,"bold")},itemDistance:{...S(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},itemAddress:a(n.size.caption,n.lineHeight.normal,t.text.primary),itemPhone:a(n.size.caption,n.lineHeight.normal,t.text.muted),badge:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+1,paddingVertical:r.xs},badgePositive:{backgroundColor:t.badgeBgPositive},badgeCaution:{backgroundColor:t.badgeBgCaution},badgeNeutral:{backgroundColor:t.badgeBgNeutral},badgeLabel:{...a(n.size.micro,n.lineHeight.snug,t.text.muted,"bold")},badgePositiveText:{color:t.success},badgeCautionText:{color:t.cautionAccent},badgeNeutralText:{color:t.text.muted},footer:{gap:r.sm,paddingTop:r.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.md},footerRetry:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...a(n.size.bodyTight,n.lineHeight.snug,t.brandInk,"bold")}})}i(Wy,"makeLocalStyles");var We=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${tn} 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,t,r)=>`${e} of ${t} requests sent. ${r} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,t)=>`${e} of ${t} ${t===1?"clinic":"clinics"} responded`,"responded")});var _o=25,ko=5;function Po(e){let[t,r]=react.useState({list:e,shown:ko}),o=t.list===e?t.shown:ko,n=react.useCallback(()=>{r(l=>({list:e,shown:(l.list===e?l.shown:ko)+ko}));},[e]);return {visible:e.slice(0,o),hasMore:e.length>o,showMore:n}}i(Po,"useVisibleClinics");function Ln(e,t,r,o){let n={owner_name:t,pet_name:r,clinic_name:o},l=false,a=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,s)=>Object.prototype.hasOwnProperty.call(n,s)?n[s]??"":(l=true,""));return l||/[{}]/.test(a)?null:a}i(Ln,"renderClinicScope");function Vn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(Vn,"clinicNeedsEmail");function Vc(e,t,r){let[o,n]=react.useState(e.ownerName),[l,a]=react.useState(""),[c,s]=react.useState(null),[d,u]=react.useState(""),[m,y]=react.useState([]),[g,w]=react.useState([]),[R,v]=react.useState(null),[f,b]=react.useState(null),[C,h]=react.useState(false),[I,T]=react.useState(false),[k,_]=react.useState(null),[E,B]=react.useState(0),x=react.useRef(false),A=react.useRef(false),z=react.useRef(0),de=react.useRef(gr()),G=react.useRef(null),ae=react.useRef(null),M=react.useRef(0);react.useEffect(()=>(x.current=true,A.current=false,h(false),()=>{x.current=false,M.current+=1,z.current+=1,G.current=null,ae.current?.abort();}),[t]),react.useEffect(()=>{let N=true;return v(null),G.current=null,t.getAuthorizationCopy().then(ie=>{N&&(ie.ok?(v(ie.value),b(null)):b(ie.error));}).catch(()=>{N&&b(W("internalError"));}),()=>{N=false;}},[t,E]),react.useEffect(()=>{let N=true;return w([]),t.recentClinics({limit:5}).then(ie=>{N&&ie.ok&&w(ie.value.clinics);}).catch(()=>{}),()=>{N=false;}},[t]);let $=i(()=>{G.current=null,b(null);},"invalidate"),O=c?.name??l.trim(),U=R?Ln(R,o.trim(),e.petName,O):null,D=Vn(c),q=Po(m),ee=!!(R&&U&&o.trim()&&e.petName.trim()&&O&&(!D||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),J=i(async()=>{if(A.current)return;let N=++z.current;T(true);try{let ie=await t.searchClinics({query:l.trim(),limit:_o});if(!x.current||N!==z.current)return;ie.ok?(y(ie.value.clinics),b(null)):b(ie.error);}catch{x.current&&N===z.current&&b(W("internalError"));}finally{x.current&&N===z.current&&T(false);}},"search"),H=i(async()=>{if(A.current||k||!ee||!R||!U||!r)return;A.current=true;let N=M.current,ie=i(()=>x.current&&M.current===N,"current");h(true),b(null);try{if(!G.current){ae.current=new AbortController;let Le=await r({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:O,authorizationVersion:R.authorizationVersion,scopeText:U,signal:ae.current.signal});if(!ie()||Le===null)return;let rt=c&&(!D||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:O};G.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:R.authorizationVersion,...rt,...D?{clinicEmail:d.trim().toLowerCase()}:{},...Le.signatureId!==void 0?{signatureId:Le.signatureId}:{signaturePngBase64:Le.signaturePngBase64},idempotencyKey:de.current()};}if(!ie())return;let Ce=await t.createClinicRequest(G.current);if(!ie())return;if(!Ce.ok){b(Ce.error);return}if(Ce.value.petRef!==e.petRef){b(W("internalError"));return}_(Ce.value),G.current=null,e.onCreated?.(Ce.value);}catch{ie()&&b(W("internalError"));}finally{A.current=false,ie()&&h(false);}},"submit");return {ownerName:o,query:l,clinic:c,email:d,clinics:m,copy:R,scope:U,error:f,busy:C,searching:I,created:k,ready:ee,needsEmail:D,visibleClinics:q.visible,hasMoreClinics:q.hasMore,showMoreClinics:q.showMore,recent:m.length===0&&c===null?g:[],setOwnerName(N){A.current||($(),n(N));},setQuery(N){A.current||($(),z.current+=1,T(false),y([]),s(null),u(""),a(N));},setEmail(N){A.current||($(),u(N));},selectClinic(N){A.current||($(),z.current+=1,T(false),y([]),s(N),a(N.name),u(""));},invalidate:$,search:J,submit:H,retryCopy(){b(null),B(N=>N+1);}}}i(Vc,"useClinicRequestForm");var Ky=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function qn(e){return e.clinic?.name??e.freeText??""}i(qn,"draftName");function Fn(e){return Vn(e.clinic)}i(Fn,"draftNeedsEmail");function Fc(e,t,r,o,n){let[l,a]=react.useState(e.ownerName),[c,s]=react.useState(""),[d,u]=react.useState([]),[m,y]=react.useState([]),[g,w]=react.useState([]),[R,v]=react.useState(null),[f,b]=react.useState(null),[C,h]=react.useState(false),[I,T]=react.useState(false),[k,_]=react.useState(null),[E,B]=react.useState(null),[x,A]=react.useState(0),z=react.useRef(false),de=react.useRef(false),G=react.useRef(0),ae=react.useRef(0),M=react.useRef(gr()),$=react.useRef(null),O=react.useRef(null);react.useEffect(()=>(z.current=true,de.current=false,h(false),()=>{z.current=false,ae.current+=1,G.current+=1,$.current=null,O.current?.abort();}),[t,r]),react.useEffect(()=>{let le=true;return v(null),$.current=null,t.getAuthorizationCopy().then(Pe=>{le&&(Pe.ok?(v(Pe.value),b(null)):b(Pe.error));}).catch(()=>{le&&b(W("internalError"));}),()=>{le=false;}},[t,x]),react.useEffect(()=>{let le=true;return y([]),t.recentClinics({limit:5}).then(Pe=>{le&&Pe.ok&&y(Pe.value.clinics);}).catch(()=>{}),()=>{le=false;}},[t]);let U=Po(d),D=i(()=>{$.current=null,b(null);},"invalidate"),q=g.map(qn),ee=R?q.map(le=>Ln(R,l.trim(),e.petName,le)):[],J=ee.every(le=>le!==null)?ee.join(`
|
|
2
|
-
|
|
3
|
-
`):null,H=g.length>0&&g.every(le=>!Fn(le)||Ky.test(le.email.trim())),N=g.length>=tn,ie=!!(R&&J&&l.trim()&&e.petName.trim()&&H&&o)&&k===null,Ce=i(async()=>{if(de.current)return;let le=++G.current;T(true);try{let Pe=await t.searchClinics({query:c.trim(),limit:_o});if(!z.current||le!==G.current)return;Pe.ok?(u(Pe.value.clinics),b(null)):b(Pe.error);}catch{z.current&&le===G.current&&b(W("internalError"));}finally{z.current&&le===G.current&&T(false);}},"search"),Le=i(le=>{de.current||N||k!==null||le.clinic!==null&&g.some(Pe=>Pe.clinic?.id===le.clinic?.id)||(D(),w(Pe=>[...Pe,{...le,key:M.current(),idempotencyKey:M.current()}]),u([]),s(""));},"add"),rt=i(async()=>{if(de.current||k!==null||!ie||!R||!J||!o)return;de.current=true;let le=ae.current,Pe=i(()=>z.current&&ae.current===le,"current");h(true),b(null);try{if($.current===null){O.current=new AbortController;let Dt=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:q.join(", "),authorizationVersion:R.authorizationVersion,scopeText:J,signal:O.current.signal});if(!Pe()||Dt===null)return;if($.current=Dt,Dt.signaturePngBase64!==void 0&&n!==void 0){let Nu=await n(Dt.signaturePngBase64,O.current.signal);if(!Pe())return;$.current={signatureId:Nu.signatureId};}}let Kt=$.current,fn=g.map(Dt=>({...Dt.clinic!==null&&(!Fn(Dt)||Dt.clinic.emailStatus==="none")?{clinicId:Dt.clinic.id}:{clinicFreeText:qn(Dt)},...Fn(Dt)?{clinicEmail:Dt.email.trim().toLowerCase()}:{},...Kt.signatureId!==void 0?{signatureId:Kt.signatureId}:{signaturePngBase64:Kt.signaturePngBase64},idempotencyKey:Dt.idempotencyKey})),gn=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:R.authorizationVersion,clinics:fn});if(!Pe())return;if(!gn.ok){b(gn.error);return}_(gn.value),e.onCreated?.(gn.value),Ee(gn.value.requestGroupId,le);}catch{Pe()&&b(W("internalError"));}finally{de.current=false,Pe()&&h(false);}},"submit"),Ee=i(async(le,Pe)=>{try{let Kt=await t.getRequestGroup(le);if(!z.current||ae.current!==Pe)return;Kt.ok&&Kt.value.petRef===e.petRef&&B(Kt.value);}catch{}},"loadGroup"),Tt=i(async()=>{k===null||de.current||await Ee(k.requestGroupId,ae.current);},"refreshGroup");return {ownerName:l,query:c,clinics:d,copy:R,scopeText:J,error:f,busy:C,searching:I,drafts:g,outcome:k,group:E,ready:ie,atCap:N,visibleClinics:U.visible,hasMoreClinics:U.hasMore,showMoreClinics:U.showMore,recent:d.length===0?m.filter(le=>!g.some(Pe=>Pe.clinic?.id===le.id)):[],setOwnerName(le){de.current||(D(),a(le));},setQuery(le){de.current||(G.current+=1,T(false),u([]),s(le));},search:Ce,addClinic(le){Le({clinic:le,freeText:null,email:""});},addFreeText(){let le=c.trim();le.length!==0&&Le({clinic:null,freeText:le,email:""});},setDraftEmail(le,Pe){de.current||(D(),w(Kt=>Kt.map(fn=>fn.key===le?{...fn,email:Pe}:fn)));},removeDraft(le){de.current||k!==null||(D(),w(Pe=>Pe.filter(Kt=>Kt.key!==le)));},submit:rt,refreshGroup:Tt,retryCopy(){b(null),A(le=>le+1);}}}i(Fc,"useClinicBatchForm");function qc(e){try{let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443")return !1;let r=t.hostname.toLowerCase();return r==="s3.amazonaws.com"||r.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(r)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(r)||r==="s3-accelerate.amazonaws.com"||r.endsWith(".s3-accelerate.amazonaws.com")||r==="s3-accelerate.dualstack.amazonaws.com"||r.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(qc,"trustedSignatureUploadUrl");var Qy="Signature upload failed",Xy=3e4;function Jy(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(Jy,"base64ByteLength");async function bs(e,t,r,o){let n=i(()=>new Error(Qy),"fail"),l=Jy(e);if(l<=0||r.aborted)throw n();let a=await t.initiateSignatureUpload(l);if(!a.ok||r.aborted||!qc(a.value.uploadUrl))throw n();let c=new FormData;for(let[y,g]of Object.entries(a.value.uploadFields))c.append(y,g);c.append("file",{uri:`data:image/png;base64,${e}`,name:"signature.png",type:"image/png"});let s=new AbortController,d=i(()=>s.abort(),"onAbort");r.addEventListener("abort",d,{once:true});let u=setTimeout(d,Xy);try{if(!(await(o??fetch)(a.value.uploadUrl,{method:"POST",body:c,credentials:"omit",signal:s.signal})).ok||r.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),r.removeEventListener("abort",d);}let m=await t.completeSignatureUpload(a.value.uploadId);if(!m.ok||r.aborted)throw n();return {signatureId:m.value}}i(bs,"registerRnSignature");var sn=Object.freeze({width:360,height:120});function Hc(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(Hc,"blank");function Bc(e,t,r,o){for(let n=-o;n<=o;n+=1)for(let l=-o;l<=o;l+=1){if(l*l+n*n>o*o+o)continue;let a=t+l,c=r+n;a<0||c<0||a>=e.width||c>=e.height||(e.pixels[c*e.width+a]=1);}}i(Bc,"stamp");var Zy=16384;function ef(e,t){let[r,o]=e;if(!Number.isFinite(r)||!Number.isFinite(o))return null;let n=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),l=Math.min(2*t.height,Math.max(-t.height,Math.round(o)));return [n,l]}i(ef,"padPoint");function tf(e,t,r,o,n){let[l,a]=t,[c,s]=r,d=Math.abs(c-l),u=-Math.abs(s-a),m=l<c?1:-1,y=a<s?1:-1,g=d+u,w=0;for(;w<n&&(Bc(e,l,a,o),w+=1,!(l===c&&a===s));){let R=2*g;R>=u&&(g+=u,l+=m),R<=d&&(g+=d,a+=y);}return w}i(tf,"line");function Uc(e,t=1){let r=Hc(sn.width,sn.height);for(let o of e){let n=[];for(let a of o){let c=ef(a,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[a,c]=n[0];Bc(r,a,c,t);continue}let l=Zy;for(let a=1;a<n.length&&l>0;a+=1)l-=tf(r,n[a-1],n[a],t,l);}return r}i(Uc,"rasterizeStrokes");var rf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",nf="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",of="0123456789abcdefghijklmnopqrstuv",Cs=5,Es=7,hs=Cs+1;function sf(e,t){let r=rf.indexOf(e);return r<0?0:of.indexOf(nf.charAt(r*Es+t))}i(sf,"glyphRow");function jc(e){let t=Hc(sn.width,sn.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*hs-1)*n>t.width-8;)n-=1;let l=(o.length*hs-1)*n,a=Math.max(0,Math.floor((t.width-l)/2)),c=Math.floor((t.height-Es*n)/2);return o.forEach((s,d)=>{let u=a+d*hs*n;for(let m=0;m<Es;m+=1){let y=sf(s,m);for(let g=0;g<Cs;g+=1)if((y>>Cs-1-g&1)!==0)for(let w=0;w<n;w+=1)for(let R=0;R<n;R+=1){let v=u+g*n+R,f=c+m*n+w;v<t.width&&f<t.height&&(t.pixels[f*t.width+v]=1);}}}),t}i(jc,"rasterizeTypedName");var _s=class _s{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let o=0;for(let n=0;n<r;n+=1)o=o<<1|t>>n&1;this.writeBits(o,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(_s,"BitWriter");var Ss=_s;function Ts(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(Ts,"writeLiteral");var Rs=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],zc=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],vs=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Nc=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function af(e,t,r){let o=Rs.length-1;for(;Rs[o]>t;)o-=1;Ts(e,257+o),zc[o]>0&&e.writeBits(t-Rs[o],zc[o]);let n=vs.length-1;for(;vs[n]>r;)n-=1;e.writeCode(n,5),Nc[n]>0&&e.writeBits(r-vs[n],Nc[n]);}i(af,"writeMatch");var lf=32768,ws=3,cf=258,Mc=15,df=64;function uf(e){let t=new Ss;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<Mc).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<Mc)-1,"hashAt"),l=i(c=>{if(c+ws>e.length)return;let s=n(c);o[c]=r[s],r[s]=c;},"insert"),a=0;for(;a<e.length;){let c=0,s=0;if(a+ws<=e.length){let d=r[n(a)],u=0,m=Math.min(cf,e.length-a);for(;d>=0&&u<df&&a-d<=lf;){let y=0;for(;y<m&&e[d+y]===e[a+y];)y+=1;if(y>c&&(c=y,s=a-d,y===m))break;d=o[d],u+=1;}}if(c>=ws){af(t,c,s);for(let d=0;d<c;d+=1)l(a+d);a+=c;}else Ts(t,e[a]),l(a),a+=1;}return Ts(t,256),t.finish()}i(uf,"deflate");function pf(e){let t=1,r=0;for(let o of e)t=(t+o)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(pf,"adler32");var Io=null;function mf(e){if(Io===null){Io=new Uint32Array(256);for(let r=0;r<256;r+=1){let o=r;for(let n=0;n<8;n+=1)o=o&1?3988292384^o>>>1:o>>>1;Io[r]=o>>>0;}}let t=4294967295;for(let r of e)t=Io[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(mf,"crc32");function zn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(zn,"u32");function xs(e,t){let r=Uint8Array.from([...e].map(n=>n.charCodeAt(0))),o=new Uint8Array(r.length+t.length);return o.set(r,0),o.set(t,r.length),[...zn(t.length),...o,...zn(mf(o))]}i(xs,"chunk");var Do="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function yf(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,l=r+2<e.length?e[r+2]:0,a=o<<16|n<<8|l;t+=Do.charAt(a>>18&63)+Do.charAt(a>>12&63),t+=r+1<e.length?Do.charAt(a>>6&63):"=",t+=r+2<e.length?Do.charAt(a&63):"=";}return t}i(yf,"toBase64");function ks(e){let{width:t,height:r,pixels:o}=e,n=Math.ceil(t/8)+1,l=new Uint8Array(n*r);for(let u=0;u<r;u+=1){let m=u*n;l[m]=0,l.fill(255,m+1,m+n);for(let y=0;y<t;y+=1)if(o[u*t+y]===1){let g=m+1+(y>>3);l[g]=l[g]&~(128>>(y&7));}}let a=uf(l),c=new Uint8Array(2+a.length+4);c[0]=120,c[1]=1,c.set(a,2),c.set(zn(pf(l)),2+a.length);let s=Uint8Array.from([...zn(t),...zn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...xs("IHDR",s),...xs("IDAT",c),...xs("IEND",new Uint8Array(0))]);return yf(d)}i(ks,"encodeSignaturePng");var Vo=2.6,Gc="#111111";function hf(e,t){let r=[];return e.forEach((o,n)=>{let l=i(a=>{let c=o[a];return [c[0]/t,c[1]/t]},"at");if(o.length===1){let[a,c]=l(0);r.push({key:`${n}-0`,cx:a,cy:c,length:0,angle:0});return}for(let a=1;a<o.length;a+=1){let[c,s]=l(a-1),[d,u]=l(a);r.push({key:`${n}-${a}`,cx:(c+d)/2,cy:(s+u)/2,length:Math.hypot(d-c,u-s),angle:Math.atan2(u-s,d-c)});}}),r}i(hf,"strokeSegments");var Rf=8,Yc=2;function $r({onChange:e,disabled:t=false}){let r=vf(),[o,n]=react.useState("draw"),[l,a]=react.useState(""),[c,s]=react.useState([]),[d,u]=react.useState(0),m=react.useRef([]),y=react.useRef(null),g=d>0?sn.width/d:1,w=react.useRef(g);w.current=g;let R=react.useRef(t);R.current=t,react.useEffect(()=>{if(o==="type"){so(e,l.trim().length>0?ks(jc(l)):null);return}let T=c.reduce((k,_)=>k+_.length,0);so(e,T>=Rf?ks(Uc(c)):null);},[o,l,c,e]);let v=i(T=>{let{locationX:k,locationY:_}=T.nativeEvent;return [k*w.current,_*w.current]},"point"),f=i(()=>{let T=m.current,k=y.current;m.current=[],y.current=null,s(_=>[..._.filter(E=>E!==k),T]);},"commitStroke"),b=react.useMemo(()=>reactNative.PanResponder.create({onStartShouldSetPanResponder:i(()=>!R.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!R.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(T=>{m.current=[v(T)];},"onPanResponderGrant"),onPanResponderMove:i(T=>{let k=v(T),_=m.current[m.current.length-1];if(_!==void 0&&Math.abs(_[0]-k[0])<Yc&&Math.abs(_[1]-k[1])<Yc)return;m.current=[...m.current,k];let E=y.current,B=m.current;y.current=B,s(x=>[...x.filter(A=>A!==E),B]);},"onPanResponderMove"),onPanResponderRelease:i(()=>f(),"onPanResponderRelease"),onPanResponderTerminate:i(()=>f(),"onPanResponderTerminate")}),[]),C=react.useCallback(()=>{R.current||(m.current=[],y.current=null,s([]),a(""));},[]),h=react.useCallback(()=>{C(),n(T=>T==="draw"?"type":"draw");},[C]),I=i(T=>u(T.nativeEvent.layout.width),"onLayout");return jsxRuntime.jsxs(reactNative.View,{style:r.container,testID:"records-signature-pad",children:[jsxRuntime.jsx(p,{style:r.label,children:o==="draw"?Z.draw:Z.type}),o==="type"?jsxRuntime.jsx(Qe,{accessibilityLabel:Z.type,style:r.input,value:l,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:T=>{R.current||a(T);}}):null,jsxRuntime.jsx(reactNative.View,{onLayout:I,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:Z.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?b.panHandlers:{},children:o==="type"?jsxRuntime.jsx(p,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:l.trim()}):hf(c,g).map(T=>{let k=T.length+Vo;return jsxRuntime.jsx(reactNative.View,{pointerEvents:"none",style:[r.segment,{width:k,left:T.cx-k/2,top:T.cy-Vo/2,transform:[{rotate:`${T.angle}rad`}]}]},T.key)})}),jsxRuntime.jsxs(reactNative.View,{style:r.actions,children:[jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:Z.clear,accessibilityState:{disabled:t},disabled:t,onPress:C,style:r.button,children:jsxRuntime.jsx(p,{style:r.buttonLabel,children:Z.clear})}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?Z.toType:Z.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:h,style:r.button,children:jsxRuntime.jsx(p,{style:r.buttonLabel,children:o==="draw"?Z.toType:Z.toDraw})})]})]})}i($r,"SignaturePad");function vf(){let e=V();return react.useMemo(()=>wf(e),[e])}i(vf,"useStyles");function wf(e){let{color:t,space:r,radius:o,type:n}=e;return reactNative.StyleSheet.create({container:{gap:r.sm},label:{...S(e,"regular"),fontSize:n.size.body,color:t.text.primary},input:{minHeight:44,padding:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,...S(e,"regular"),fontSize:n.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,overflow:"hidden",justifyContent:"center"},segment:{position:"absolute",height:Vo,borderRadius:Vo/2,backgroundColor:Gc},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:Gc,paddingHorizontal:r.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},button:{minHeight:44,paddingHorizontal:r.md,justifyContent:"center",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,backgroundColor:t.surface},buttonLabel:{...S(e,"regular"),fontSize:n.size.body,color:t.text.primary}})}i(wf,"makeStyles");function Is(e){let{userRef:t,scopeEpoch:r}=Te();return jsxRuntime.jsx(Ue,{capability:"recordsClinic",...$e(e.onClose,Z.cancel),children:t===null?jsxRuntime.jsx(p,{accessibilityRole:"alert",children:ve.sessionRequired}):jsxRuntime.jsx(Ef,{...Be(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(Is,"EverfurClinicRequestBatch");function Ef(e){let t=Zt(),r=ts(),o=e.controller??t,[n,l]=react.useState(null),a=react.useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=react.useCallback((v,f)=>bs(v,o,f),[o]),s=Fc(e,o,e.batchClient??r,e.onCaptureSignature??a,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=V(),m={minHeight:44,padding:u.space.sm,borderWidth:1,borderColor:u.color.borderHairlineGreen,borderRadius:u.radius.sm,color:u.color.text.primary,backgroundColor:u.color.surface},y={color:u.color.text.primary,fontSize:u.type.size.body},g={color:u.color.text.muted,fontSize:u.type.size.bodyTight},w=i((v,f,b=false,C=v)=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:C,accessibilityState:{disabled:b},disabled:b,onPress:f,style:[m,{justifyContent:"center",opacity:b?.5:1}],children:jsxRuntime.jsx(p,{style:y,children:v})}),"button"),R=s.busy?We.sending:s.drafts.length===0?We.addToContinue:s.error?We.tryAgain:We.send(s.drafts.length);return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:s.outcome?We.resultTitle:We.title,style:[{backgroundColor:u.color.surface,padding:u.space.lg,gap:u.space.md,borderRadius:u.radius.lg,minHeight:120},e.style],children:[jsxRuntime.jsx(p,{accessibilityRole:"header",style:[y,{...S(u,"bold"),fontSize:u.type.size.heading}],children:s.outcome?We.resultTitle:We.title}),jsxRuntime.jsx(p,{style:y,children:e.petName}),s.outcome?jsxRuntime.jsxs(reactNative.View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsxRuntime.jsx(p,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:y,children:s.outcome.createdCount===0?We.allFailed:s.outcome.failedCount>0?We.partial(s.outcome.createdCount,s.outcome.results.length,s.outcome.failedCount):We.allSent(s.outcome.createdCount)}),jsxRuntime.jsx(p,{accessibilityRole:"header",style:y,children:We.perClinic}),s.outcome.results.map((v,f)=>{let b=v.request?.clinicName??s.drafts[f]?.clinic?.name??v.clinicFreeText??"",C=v.created?We.sent:We.notSent;return jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${b}. ${C}.`,v.created?v.request?.statusLabel:v.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${v.created?"created":"failed"}`,children:[jsxRuntime.jsx(p,{style:y,children:b}),jsxRuntime.jsx(p,{style:g,children:C}),v.created&&v.request?.statusLabel?jsxRuntime.jsx(p,{style:g,children:v.request.statusLabel}):null,!v.created&&v.failureReason?jsxRuntime.jsx(p,{style:g,children:v.failureReason}):null]},v.idempotencyKey)}),s.group?jsxRuntime.jsx(p,{accessibilityLiveRegion:"polite",style:y,children:We.responded(s.group.responded,s.group.total)}):null,s.group?.members.map(v=>v.statusLabel?jsxRuntime.jsx(p,{style:g,children:[v.clinicName,v.statusLabel].filter(Boolean).join(": ")},v.id):null)]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(p,{style:y,children:Z.ownerName}),jsxRuntime.jsx(Qe,{accessibilityLabel:Z.ownerName,style:m,value:s.ownerName,maxLength:200,editable:!s.busy,autoComplete:"name",onChangeText:s.setOwnerName}),s.drafts.map(v=>jsxRuntime.jsxs(reactNative.View,{style:{gap:u.space.xs},testID:`records-batch-draft-${v.key}`,children:[jsxRuntime.jsx(p,{style:y,children:qn(v)}),Fn(v)?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(p,{style:g,children:v.email.trim()?v.email:We.emailToAdd}),jsxRuntime.jsx(Qe,{accessibilityLabel:Z.email,style:m,value:v.email,placeholder:Z.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!s.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:f=>s.setDraftEmail(v.key,f)})]}):null,w(We.remove(qn(v)),()=>s.removeDraft(v.key),s.busy)]},v.key)),jsxRuntime.jsx(p,{style:y,children:s.atCap?We.atCap:We.addClinic}),!s.atCap&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Qe,{accessibilityLabel:Z.clinic,style:m,value:s.query,placeholder:Z.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!s.busy,onChangeText:s.setQuery}),w(Z.search,()=>{s.search();},s.busy||s.searching||s.query.trim().length<2),s.query.trim().length>0&&s.clinics.length===0&&!s.searching&&w(We.addClinic,s.addFreeText,s.busy),s.searching&&jsxRuntime.jsx(p,{accessibilityLiveRegion:"polite",style:y,children:ve.loading}),s.recent.length>0&&jsxRuntime.jsx(p,{accessibilityRole:"header",style:y,children:Z.recentlyUsed}),s.recent.map(v=>jsxRuntime.jsx(reactNative.View,{children:w([v.name,v.address,v.phone].filter(Boolean).join(", "),()=>s.addClinic(v),s.busy)},`recent-${v.id}`)),s.visibleClinics.map(v=>jsxRuntime.jsx(reactNative.View,{children:w([v.name,v.address,v.phone].filter(Boolean).join(", "),()=>s.addClinic(v),s.busy)},v.id)),s.hasMoreClinics&&w(Z.moreClinics,s.showMoreClinics,s.busy)]}),jsxRuntime.jsx(p,{accessibilityRole:"header",style:y,children:Z.scopeHeading}),s.copy?jsxRuntime.jsx(p,{style:y,children:s.drafts.length>0&&s.ownerName.trim()?s.scopeText??W("internalError").displayMessage:ve.consentRequired}):!s.error&&jsxRuntime.jsx(p,{accessibilityLiveRegion:"polite",style:y,children:ve.loading}),!e.onCaptureSignature&&jsxRuntime.jsx($r,{onChange:l,disabled:s.busy}),!d&&s.ready&&jsxRuntime.jsx(p,{accessibilityRole:"alert",style:y,children:Z.missingSignature}),s.error&&jsxRuntime.jsx(p,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:y,children:s.error.displayMessage}),!s.copy&&s.error&&w(ve.retry,s.retryCopy),w(R,()=>{s.submit();},s.busy||!s.ready||!d,We.sendA11y(s.drafts.length))]}),e.onClose&&w(Z.cancel,e.onClose,s.busy),jsxRuntime.jsx(je,{})]})}i(Ef,"BatchBody");var me=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 ${ke(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 ${ke(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,t)=>`We don\u2019t have an email on file for ${t}. Add it so we can request ${ke(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 Sf="value_text",Jc=64,Zc=512;function ed(e){return e!==null&&e.httpStatus===409&&!ar(e)}i(ed,"isFactReviewerLocked");var Nn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:Sf}),td=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,rd=/^\d{4}-\d{2}-\d{2}$/;function nd(e){if(e==null)return "text";let t=e.trim();return td.test(t)?"num":rd.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(nd,"inferFactValueKind");function Ds(e,t){let r=t.trim(),o=nd(e);if(o==="num"&&td.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[Nn.num]:n})}return o==="date"&&rd.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Nn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[Nn.bool]:r==="true"}:{[Nn.text]:r})}i(Ds,"factCorrectionFor");var qe=zod.z.string().nullish(),Fo=zod.z.number().nullish(),Tf=zod.z.object({collected_at:qe,at:qe,value:Fo,unit:qe,qualitative_result:qe,ref_low:Fo,ref_high:Fo,status:qe,source_clinic:qe,source_doc_id:qe,doc_id:qe,reviewed:zod.z.boolean().nullish()}),kf=zod.z.object({collected_at:qe,at:qe,value:Fo,unit:qe,qualitative_result:qe,status:qe}),_f=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:kf.nullish(),trajectory:qe,points:zod.z.array(Tf).optional()}),Pf=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()}),If=zod.z.object({markers:zod.z.array(_f).optional(),summary:Pf.nullish(),disclaimer:zod.z.string().optional(),featured_marker_id:qe});function Df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Df,"isObject");function od(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(od,"withheldMarkers");function id(e,t){let r=Df(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return od(o);let n=If.safeParse(r);if(!n.success)return od(o);let l=n.data,a=i(s=>Object.freeze({at:s.collected_at??s.at??null,value:s.value??null,unit:s.unit??null,qualitativeResult:s.qualitative_result??null,refLow:s.ref_low??null,refHigh:s.ref_high??null,status:s.status??null,sourceClinic:s.source_clinic??null,docId:s.source_doc_id??s.doc_id??null,reviewed:s.reviewed===true}),"point"),c=(l.markers??[]).map(s=>Object.freeze({markerId:s.marker_id,name:s.canonical_name??s.name??s.marker_id,loincCode:s.loinc_code??null,unit:s.canonical_unit??s.unit??null,panel:s.panel_name??s.panel??null,meaning:s.meaning_text??s.meaning??null,latest:s.latest?Object.freeze({at:s.latest.collected_at??s.latest.at??null,value:s.latest.value??null,unit:s.latest.unit??null,qualitativeResult:s.latest.qualitative_result??null,status:s.latest.status??null}):null,trajectory:s.trajectory??null,points:Object.freeze((s.points??[]).map(a))}));return Object.freeze({petRef:o,withheld:false,markers:Object.freeze(c),summary:l.summary?Object.freeze({totalMarkers:l.summary.total_markers,inRangeCount:l.summary.in_range_count,outOfRangeCount:l.summary.out_of_range_count,unknownCount:l.summary.unknown_count}):null,disclaimer:l.disclaimer??"",featuredMarkerId:l.featured_marker_id??null})}i(id,"mapRecordMarkers");var Af=zod.z.string().min(1).refine(e=>e.startsWith("https://")),Of=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:Af,expires_in_seconds:zod.z.number().int().nonnegative().nullish()}),Lf=zod.z.object({items:zod.z.array(zod.z.unknown()).optional()});function sd(e){let t=Lf.safeParse(e);if(!t.success)return null;let r=[];for(let o of t.data.items??[]){let n=Of.safeParse(o);n.success&&r.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(r)}i(sd,"mapRequestDocuments");var Vf=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 t=Vf.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(ad,"mapSignatureSuggestions");var Q=zod.z.string().nullish(),Mn=zod.z.number().nullish(),Ff=zod.z.object({at:Q,value:Mn,unit:Q,qualitative_result:Q,ref_low:Mn,ref_high:Mn,status:Q,doc_id:Q}),qf=zod.z.object({marker_id:zod.z.string(),name:zod.z.string(),loinc_code:Q,unit:Q,panel:Q,meaning:Q,latest:zod.z.object({at:Q,value:Mn,unit:Q,qualitative_result:Q,status:Q}).nullish(),trajectory:Q,points:zod.z.array(Ff).optional()}),zf=zod.z.object({encounter_id:zod.z.string(),date:Q,type:Q,clinic_name:Q,veterinarian:Q,doc_id:Q}),Nf=zod.z.object({note_id:zod.z.string(),encounter_id:Q,observed_on:Q,sections:zod.z.array(zod.z.object({section:zod.z.string(),text:zod.z.string()})).optional()}),Mf=zod.z.object({exam_id:zod.z.string(),encounter_id:Q,observed_on:Q,doc_id:Q,systems:zod.z.record(zod.z.object({finding_status:Q,finding:Q})).optional()}),Hf=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:Q,latest_record_at:Q,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()}),Bf=zod.z.object({conflict_id:zod.z.string(),entity_type:zod.z.string(),field:Q,severity:Q,candidates:zod.z.array(zod.z.object({value:zod.z.string(),source_doc_id:Q,doc_id:Q,collected_at:Q})).optional()}),Uf=zod.z.object({lab_results:zod.z.array(qf).optional(),encounters:zod.z.array(zf).optional(),clinician_notes:zod.z.array(Nf).optional(),physical_exams:zod.z.array(Mf).optional(),completeness:Hf.nullish(),conflicts:zod.z.array(Bf).optional()}),jf=zod.z.object({visits:zod.z.array(zod.z.object({visit_id:zod.z.string(),visit_date:Q,veterinarian:Q,summary:Q,doc_id:Q})),vaccines:zod.z.array(zod.z.object({vaccine_id:zod.z.string(),product:Q,lot:Q,administered_on:Q,expires_on:Q,doc_id:Q})),weights:zod.z.array(zod.z.object({weight_id:zod.z.string(),observed_on:Q,weight_kg:Mn,doc_id:Q})),medications:zod.z.array(zod.z.object({medication_id:zod.z.string(),drug_name:Q,dose:Q,route:Q,frequency:Q,sig:Q,rx_number:Q,started_on:Q,stopped_on:Q,doc_id:Q})),disclaimer:zod.z.string().optional()}),$f=zod.z.object({document:Ti,contributions:zod.z.array(Si),contribution_count:zod.z.number().int().nonnegative().optional()});function Os(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Os,"isObject");function Ls(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Ls,"petOf");function As(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(As,"emptyDepth");function Wf(e,t){let r=Os(t)?t:{},o=Ls(r,e);if(r.withheld===true)return As(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(s=>s in r))return As(o,false);let l=Uf.safeParse(r);if(!l.success)return As(o,true);let a=l.data,c=i(s=>Object.freeze({at:s.at??null,value:s.value??null,unit:s.unit??null,qualitativeResult:s.qualitative_result??null,refLow:s.ref_low??null,refHigh:s.ref_high??null,status:s.status??null,docId:s.doc_id??null}),"point");return Object.freeze({petRef:o,available:true,withheld:false,labResults:Object.freeze((a.lab_results??[]).map(s=>Object.freeze({markerId:s.marker_id,name:s.name,loincCode:s.loinc_code??null,unit:s.unit??null,panel:s.panel??null,meaning:s.meaning??null,latest:Object.freeze({at:s.latest?.at??null,value:s.latest?.value??null,unit:s.latest?.unit??null,qualitativeResult:s.latest?.qualitative_result??null,status:s.latest?.status??null}),trajectory:s.trajectory??null,points:Object.freeze((s.points??[]).map(c))}))),encounters:Object.freeze((a.encounters??[]).map(s=>Object.freeze({encounterId:s.encounter_id,date:s.date??null,type:s.type??null,clinicName:s.clinic_name??null,veterinarian:s.veterinarian??null,docId:s.doc_id??null}))),clinicianNotes:Object.freeze((a.clinician_notes??[]).map(s=>Object.freeze({noteId:s.note_id,encounterId:s.encounter_id??null,observedOn:s.observed_on??null,sections:Object.freeze((s.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((a.physical_exams??[]).map(s=>Object.freeze({examId:s.exam_id,encounterId:s.encounter_id??null,observedOn:s.observed_on??null,docId:s.doc_id??null,systems:Object.freeze(Object.entries(s.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(s=>Object.freeze({conflictId:s.conflict_id,entityType:s.entity_type,field:s.field??null,severity:s.severity??"needs_review",candidates:Object.freeze((s.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(Wf,"mapRecordDepth");function ld(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(ld,"withheldTimeline");function Gf(e,t){let r=Os(t)?t:{},o=Ls(r,e);if(r.withheld===true)return ld(o);let n=jf.safeParse(r);if(!n.success)return ld(o);let l=n.data,a=l.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=l.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})),s=l.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=l.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&&s.length===0&&d.length===0,visits:Object.freeze(a),vaccines:Object.freeze(c),weights:Object.freeze(s),medications:Object.freeze(d),disclaimer:l.disclaimer??""})}i(Gf,"mapRecordsTimeline");function Yf(e,t){let r=Os(t)?t:{},o=Ls(r,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return n();let l=$f.safeParse(r);if(!l.success)return n();let a=Object.freeze(l.data.contributions.map(ki));return Object.freeze({petRef:o,withheld:false,document:_i(l.data.document),contributions:a,contributionCount:l.data.contribution_count??a.length})}i(Yf,"mapDocumentContributions");var Kf="/widget/v1/records/pets";function cd(e){let t=e.funnel??Dr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((s,d)=>typeof s=="string"&&s.length>0&&!br(s)&&[...s].length<=d,"segment"),o=i(async(s,d,u,m)=>{if(!r(d,Rt))return rr();let y=await t.send(s,{method:"GET",path:u});if(!y.ok)return y;let g=m(y.value);return g.petRef===d?Ve(g):te(W("internalError",{retryable:false}))},"read"),n=i(s=>`${Kf}/${encodeURIComponent(s)}`,"pet"),l=i(s=>`${n(s)}/everfur_record`,"record"),a=i(async(s,d,u)=>{let m=await t.send(s,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!m.ok)return m;let y=u(m.value);return y===null?te(W("internalError",{retryable:false})):Ve(y)},"parsed"),c=i((s,d)=>!r(s.entityType,Jc)||!r(s.canonicalKey,Zc)||s.idempotencyKey!==void 0&&!r(s.idempotencyKey,Rn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:s.entityType,canonical_key:s.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...s.idempotencyKey!==void 0?{idempotency_key:s.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(s=>o("records.depth.record",s,`${n(s)}/record`,d=>Wf(s,d)),"getRecordDepth"),getTimeline:i(s=>o("records.depth.timeline",s,`${n(s)}/timeline`,d=>Gf(s,d)),"getTimeline"),getDocumentContributions(s,d){return r(d,64)?o("records.depth.contributions",s,`${n(s)}/documents/${encodeURIComponent(d)}/contributions`,u=>Yf(s,u)):rr()},getMarkers:i(s=>o("records.depth.markers",s,`${n(s)}/markers`,d=>id(s,d)),"getMarkers"),createShare(s,d){if(!r(s,Rt))return rr();let u=d?.audience;return u!==void 0&&!Zr.includes(u)?rr():a("records.share.create",{method:"POST",path:`${l(s)}/share`,...u!==void 0?{body:{audience:u}}:{}},m=>Fa(m,e.apiBaseUrl))},emailShare(s,d){let u=d.recipientKind,m=typeof d.recipientEmail=="string"?d.recipientEmail.trim():"",y=u==="other"||Zr.includes(u);return !r(s,Rt)||!y||!Xn(m)||br(m)?rr():a("records.share.email",{method:"POST",path:`${l(s)}/share/email`,body:{recipient_email:m,recipient_kind:u}},za)},async readFeatures(){try{let s=await t.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return s.ok?Jn(s.value):Mt}catch{return Mt}},listShares(s){return r(s,Rt)?a("records.share.list",{method:"GET",path:`${l(s)}/shares`},qa):rr()},async revokeShare(s,d){if(!r(s,Rt)||!r(d,64))return rr();let u=await t.send("records.share.revoke",{method:"DELETE",path:`${l(s)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?Ve(void 0):u},getPdfLink(s){return r(s,Rt)?a("records.pdf.link",{method:"GET",path:`${l(s)}/pdf-link`},Na):rr()},async editFact(s,d){let u=r(s,Rt)?c(d,d.correctedFields):null;if(u===null)return rr();let m=await t.send("records.fact.edit",{method:"POST",path:`${l(s)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return m.ok?Ve(void 0):m},async removeFact(s,d){let u=r(s,Rt)?c(d):null;if(u===null)return rr();let m=await t.send("records.fact.remove",{method:"POST",path:`${l(s)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return m.ok?Ve(void 0):m},listRequestDocuments(s){return r(s,64)?a("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(s)}/documents`},sd):rr()},listAuthorizationSignatures:i(()=>a("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},ad),"listAuthorizationSignatures")}}i(cd,"createRecordsDepthClient");function rr(){return Promise.resolve(te(W("validationFailed",{retryable:false})))}i(rr,"invalid");function xr(){let{runtime:e,userRef:t,scopeEpoch:r}=Te();return react.useMemo(()=>{let{services:o}=e.registry;return cd({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(xr,"useEverfurRecordsDepthClient");function nr(e,t,r,o=""){let n=xr(),{userRef:l}=Te(),a=no(e),c=react.useMemo(()=>({}),[n,e,o,a]),[s,d]=react.useState({scope:c,value:null,error:null,loading:true}),u=react.useRef(0),m=react.useCallback(async()=>{let f=u.current+=1;if(d({scope:c,value:null,error:null,loading:true}),l===null){d({scope:c,value:null,error:null,loading:false});return}let b=await t(n,e);f===u.current&&(b.ok?d({scope:c,value:b.value,error:null,loading:false}):d({scope:c,value:null,error:b.error,loading:false}));},[n,e,t,c,l]);react.useEffect(()=>(m(),()=>{u.current+=1;}),[m]);let y=s.scope===c?s:{value:null,error:null,loading:true},g=react.useCallback(()=>{m();},[m]),w=y.error===null||y.error.httpStatus!==404,R=w?y.error:null,v=y.loading?"loading":R!==null?"error":y.value===null?"empty":y.value.withheld?"populated":r(y.value)?"empty":"populated";return react.useMemo(()=>({status:v,value:y.value,error:R,available:w,refresh:g}),[v,y.value,R,w,g])}i(nr,"useRecordsDepthRead");function Cr(e){return e!==null&&e.httpStatus===404}i(Cr,"isDarkRouteError");var eg=i((e,t)=>e.getMarkers(t),"readMarkers"),tg=i(e=>e.markers.length===0,"markersEmpty");function Fs(e){let t=nr(e,eg,tg);return react.useMemo(()=>{let r=t.available&&t.value!==null&&!t.value.withheld?t.value:null;return {status:t.status,markers:r,available:t.available,error:t.error,refresh:t.refresh}},[t])}i(Fs,"useRecordsMarkers");var rg=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function pd(e){let{clinic:t,controller:r,depthClient:o,capture:n,onCreated:l}=e,a=t.clinic?.name??t.freeText??"",c=t.clinic===null,[s,d]=react.useState(false),[u,m]=react.useState(e.ownerName),[y,g]=react.useState(t.email),[w,R]=react.useState(false),[v,f]=react.useState(null),[b,C]=react.useState(null),[h,I]=react.useState(0),[T,k]=react.useState(null),[_,E]=react.useState(false),[B,x]=react.useState(null),[A,z]=react.useState([]),[de,G]=react.useState(null),[ae,M]=react.useState(false),$=react.useRef(false),O=react.useRef(true),U=react.useRef(gr()),D=react.useRef(null);react.useEffect(()=>(O.current=true,()=>{O.current=false,D.current=null;}),[r]),react.useEffect(()=>{let Ee=true;return f(null),D.current=null,r.getAuthorizationCopy().then(Tt=>{Ee&&(Tt.ok?(f(Tt.value),C(null)):C(Tt.error));}).catch(()=>{Ee&&C(W("internalError"));}),()=>{Ee=false;}},[r,h]),react.useEffect(()=>{if(o===void 0)return;let Ee=true;return o.listAuthorizationSignatures().then(Tt=>{Ee&&(Tt.ok?z(Tt.value):Cr(Tt.error)||z([]));}).catch(()=>{}),()=>{Ee=false;}},[o]);let q=Vn(t.clinic),ee=y.trim().toLowerCase(),J=rg.test(ee),H=q&&(w||ee.length>0)&&!J?ee.length>0?me.emailInvalid:me.emailRequired:null,N=v?Ln(v,u.trim(),ke(e.petName),a):null,ie=e.hostCapture===true||ae||de!==null,Ce=!!(s&&v&&N&&u.trim()&&a&&ie&&(!q||J)),Le=react.useCallback(async()=>{if(!($.current||B!==null||!v||!N)){if(!a){k(me.missingDraftError);return}if(q&&!J){R(true),k(ee.length>0?me.emailInvalid:me.emailRequired);return}if(!(!s||!u.trim())){$.current=true,E(true),k(null);try{if(D.current===null){let Tt=de!==null?{signatureId:de}:await n();if(!O.current)return;if(Tt===null){k(me.missingSignatureError);return}let le=t.clinic&&(!q||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:a};D.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:v.authorizationVersion,...le,...q?{clinicEmail:ee}:{},...Tt.signatureId!==void 0?{signatureId:Tt.signatureId}:{signaturePngBase64:Tt.signaturePngBase64},idempotencyKey:U.current()};}let Ee=await r.createClinicRequest(D.current);if(!O.current)return;if(!Ee.ok){k(Ee.error.displayMessage);return}if(Ee.value.petRef!==e.petRef){k(W("internalError").displayMessage);return}x(Ee.value),D.current=null,l?.(Ee.value);}catch{O.current&&k(W("internalError").displayMessage);}finally{$.current=false,O.current&&E(false);}}}},[s,n,t.clinic,a,r,v,B,e.petRef,q,ee,l,u,de,N,J]),rt=react.useCallback(()=>{D.current=null,k(null);},[]);return {title:c?me.titleFreeText:me.titleDirectory,clinicName:a,isFreeText:c,authorized:s,ownerName:u,email:y,emailError:H,needsEmail:q,directoryClinicNoEmail:q&&t.clinic!==null,copy:v,copyError:b,scope:N,error:T,busy:_,created:B,ready:Ce,signatures:A,reuseSignatureId:de,hasSignature:ie,setAuthorized(Ee){$.current||(rt(),d(Ee));},setOwnerName(Ee){$.current||(rt(),m(Ee));},setEmail(Ee){$.current||(rt(),R(false),g(Ee));},setSigned(Ee){$.current||(rt(),M(Ee),Ee&&G(null));},pickReuseSignature(Ee){$.current||(rt(),G(Ee));},retryCopy(){C(null),I(Ee=>Ee+1);},submit:Le}}i(pd,"useRecordsConsentForm");function Ns(e){let{userRef:t,scopeEpoch:r}=Te();return jsxRuntime.jsx(Ue,{capability:"recordsClinic",style:e.style,...$e(e.onBack,ot),children:t===null?jsxRuntime.jsx(p,{accessibilityRole:"alert",children:ve.sessionRequired}):jsxRuntime.jsx(ag,{...Be(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(Ns,"EverfurRecordsConsent");function ag({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:l,controller:a,onNavigate:c,onBack:s,style:d}){let u=Re(),m=lg(),y=V(),g=Zt(),w=xr(),[R,v]=react.useState(null),[f,b]=react.useState("draw"),C=react.useCallback(async()=>R===null?null:{signaturePngBase64:R},[R]),h=pd({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:a??g,depthClient:w,capture:n?()=>n({petRef:e,petName:ke(t),ownerName:h.ownerName,clinicName:h.clinicName,authorizationVersion:h.copy?.authorizationVersion??"",scopeText:h.scope??"",signal:new AbortController().signal}):C,hostCapture:n!==void 0,onCreated:i(_=>{l?.(_),c?.({name:"dashboard"});},"onCreated")}),I=react.useRef(h);I.current=h;let T=react.useCallback(_=>{v(_),I.current.setSigned(_!==null);},[]),k=h.busy;return jsxRuntime.jsxs(reactNative.View,{style:[u.root,d],children:[jsxRuntime.jsx(it,{title:h.title,onBack:s,testID:"records-consent-header"}),jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:"padding",style:u.body,children:[jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:m.content,keyboardShouldPersistTaps:"handled",testID:"records-consent",children:[jsxRuntime.jsx(p,{style:m.lead,testID:"records-consent-lead",children:me.leadNative}),jsxRuntime.jsxs(reactNative.View,{style:m.scopeCard,accessibilityRole:"summary",children:[jsxRuntime.jsx(p,{style:m.scopeHeading,accessibilityRole:"header",children:me.scopeHeading}),jsxRuntime.jsx(p,{style:m.scopeBody,children:me.scopeBody}),jsxRuntime.jsx(reactNative.View,{style:m.bullets,children:me.whatWeDo.map(_=>jsxRuntime.jsxs(reactNative.View,{style:m.bulletRow,children:[jsxRuntime.jsx(p,{style:m.check,children:"\u2713"}),jsxRuntime.jsx(p,{style:m.bulletText,children:_})]},_))}),jsxRuntime.jsx(reactNative.View,{style:m.retentionRow,children:jsxRuntime.jsx(p,{style:m.retentionText,children:me.retentionNote})}),h.copy&&h.scope?jsxRuntime.jsx(p,{style:m.serverScope,testID:"records-consent-scope",children:h.scope}):h.copyError?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(p,{style:u.errorText,accessibilityRole:"alert",children:h.copyError.displayMessage}),jsxRuntime.jsx(X,{label:ve.retry,kind:"outline",onPress:h.retryCopy,testID:"records-consent-copy-retry"})]}):jsxRuntime.jsx(p,{style:u.muted,accessibilityLiveRegion:"polite",children:ve.loading})]}),jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>h.setAuthorized(!h.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:h.authorized},accessibilityLabel:me.authorizeLabel(t),hitSlop:6,style:[m.toggle,h.authorized?m.toggleChecked:null],testID:"records-authorize-toggle",children:[jsxRuntime.jsx(reactNative.View,{style:[m.box,h.authorized?m.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:h.authorized?jsxRuntime.jsx(p,{style:m.boxCheck,children:"\u2713"}):null}),jsxRuntime.jsx(p,{style:m.toggleLabel,children:me.authorizeLabel(t)})]}),jsxRuntime.jsxs(reactNative.View,{style:m.block,children:[jsxRuntime.jsx(p,{style:u.fieldLabel,children:me.fullName}),jsxRuntime.jsx(Qe,{accessibilityLabel:me.fullName,style:u.field,value:h.ownerName,placeholder:me.fullNamePlaceholder,placeholderTextColor:y.color.text.placeholder,maxLength:200,editable:!k,autoComplete:"name",autoCapitalize:"words",onChangeText:h.setOwnerName,testID:"records-consent-owner-name"})]}),h.needsEmail?jsxRuntime.jsxs(reactNative.View,{style:m.block,testID:"records-consent-email-block",children:[h.directoryClinicNoEmail?jsxRuntime.jsx(reactNative.View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsxRuntime.jsx(p,{style:u.cautionNoteText,children:me.noEmailNote(t,h.clinicName)})}):null,jsxRuntime.jsx(p,{style:u.fieldLabel,children:me.emailLabel}),jsxRuntime.jsx(Qe,{accessibilityLabel:me.emailLabel,style:u.field,value:h.email,placeholder:me.emailPlaceholder,placeholderTextColor:y.color.text.placeholder,maxLength:320,editable:!k,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:h.setEmail,testID:"records-consent-clinic-email"}),h.emailError?jsxRuntime.jsx(p,{style:u.errorText,accessibilityRole:"alert",children:h.emailError}):null,jsxRuntime.jsx(p,{style:u.muted,testID:"records-consent-review-note",children:me.newClinicDirectSendNote})]}):null,n?null:jsxRuntime.jsxs(reactNative.View,{style:m.signatureBlock,children:[h.signatures.length>0?jsxRuntime.jsxs(reactNative.View,{style:m.block,children:[jsxRuntime.jsx(p,{style:u.fieldLabel,children:me.reuseSignature}),jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:m.gallery,children:h.signatures.map(_=>{let E=h.reuseSignatureId===_.signatureId;return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>h.pickReuseSignature(E?null:_.signatureId),accessibilityRole:"button",accessibilityLabel:E?me.reuseTileSelectedA11y:me.reuseTileA11y,style:[m.tile,E?m.tileSelected:null],testID:`records-consent-reuse-${_.signatureId}`,children:jsxRuntime.jsx(reactNative.Image,{source:{uri:_.previewUrl},style:m.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},_.signatureId)})}),jsxRuntime.jsx(p,{style:u.muted,children:me.reuseHint})]}):null,jsxRuntime.jsx(reactNative.View,{style:m.signatureHeader,children:jsxRuntime.jsx(p,{style:u.fieldLabel,children:f==="type"?me.signType:me.signDraw})}),jsxRuntime.jsx($r,{onChange:T,disabled:k}),jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>b(_=>_==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:f==="draw"?me.toTypeA11y:me.toDraw,style:m.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsxRuntime.jsx(p,{style:m.modeToggleText,children:f==="draw"?me.toType:me.toDraw})}),jsxRuntime.jsx(p,{style:u.muted,children:me.signatureHint(h.clinicName)})]}),jsxRuntime.jsxs(reactNative.View,{style:m.nextCard,accessibilityRole:"summary",testID:"records-consent-next",children:[jsxRuntime.jsx(p,{style:m.scopeHeading,accessibilityRole:"header",children:me.whatHappensNext}),jsxRuntime.jsx(p,{style:m.scopeBody,children:me.whatHappensNextBody})]}),h.error?jsxRuntime.jsx(reactNative.View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsxRuntime.jsx(p,{style:u.errorText,children:h.error})}):null,h.created?jsxRuntime.jsx(p,{accessibilityLiveRegion:"polite",style:u.bodyText,children:h.created.statusLabel||ve.records}):null]}),jsxRuntime.jsx(reactNative.View,{style:m.footer,children:jsxRuntime.jsx(X,{label:k?me.submitting:me.submit,accessibilityLabel:me.submitA11y,disabled:!h.ready,busy:k,onPress:()=>{h.submit();},style:m.submit,testID:"records-consent-submit"})})]}),jsxRuntime.jsx(je,{})]})}i(ag,"ConsentBody");function lg(){let e=V();return react.useMemo(()=>cg(e),[e])}i(lg,"useLocalStyles");function cg(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,a=i((c,s,d,u="regular")=>({...S(e,u),fontSize:c,lineHeight:Math.round(c*s),color:d}),"text");return reactNative.StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xl+r.xs,gap:r.lg+r.xs/2},lead:a(n.size.body,n.lineHeight.normal,t.text.muted),scopeCard:{borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md},nextCard:{borderRadius:o.lg,backgroundColor:t.surfaceSubtle,padding:r.lg,gap:r.sm},scopeHeading:{...a(n.size.subtitle,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:-0.4},scopeBody:a(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),bullets:{gap:r.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:r.sm},check:{...a(n.size.body,n.lineHeight.normal,t.brandInk,"bold")},bulletText:{flex:1,...a(n.size.bodyTight,n.lineHeight.normal,t.text.primary)},retentionRow:{paddingTop:r.xs,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},retentionText:a(n.size.tiny,n.lineHeight.normal,t.text.muted),serverScope:{...a(n.size.bodyTight,n.lineHeight.relaxed,t.text.secondary),paddingTop:r.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:r.md,borderRadius:o.lg-r.xs,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2},toggleChecked:{borderColor:t.brandInk,backgroundColor:t.brandSoft},box:{width:r.xl,height:r.xl,borderRadius:o.xs+1,borderWidth:1.6,borderColor:t.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},boxChecked:{backgroundColor:t.brandInk},boxCheck:{...a(n.size.body,n.lineHeight.tight,t.surface,"bold")},toggleLabel:{flex:1,...a(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"bold")},block:{gap:r.sm},signatureBlock:{gap:r.sm},gallery:{gap:r.sm,paddingVertical:r.xs},tile:{width:r.xxl*3+r.lg,height:r.xxl+r.lg+r.sm,borderRadius:o.sm,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,overflow:"hidden"},tileSelected:{borderColor:t.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...a(n.size.bodyTight,n.lineHeight.snug,t.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:r.lg,paddingTop:r.md,paddingBottom:r.xxl,borderTopWidth:l,borderTopColor:t.borderHairlineGreen,backgroundColor:t.background},submit:{minHeight:r.xxl+r.lg+r.xs+r.xs/2}})}i(cg,"makeLocalStyles");function bd(e){let t={uri:e.uri,mimeType:e.mimeType},r=ug(e);return r!==null&&(t.sizeBytes=r),Object.freeze(t)}i(bd,"fileHandleFromMedia");function ug(e){let t=e.byteSize??e.sizeBytes;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}i(ug,"mediaByteSize");function hd(e,t){return Object.freeze(t===void 0?{mode:e}:{mode:e,maxDurationSeconds:t})}i(hd,"captureOptionsFor");function zo(e){return e!=null&&e.isAvailable===true}i(zo,"isCaptureAvailable");Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function No(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(No,"markerStatusTone");function pg(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(pg,"markerStatusSpoken");function mg(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(mg,"rangePhrase");function Mo(e,t){let r=t?` ${t}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${r}`:e.refLow!==null?`\u2265 ${e.refLow}${r}`:e.refHigh!==null?`\u2264 ${e.refHigh}${r}`:"-"}i(Mo,"formatReferenceRange");function Rd(e,t){let r=t.reviewed?", reviewed by our team":"",o=t.sourceClinic?`, from ${t.sourceClinic}`:"";return `${re(t.at)}: ${Vt(t.value,e.unit,t.qualitativeResult)}, ${pg(t.status)}${mg(t)}${o}${r}`}i(Rd,"markerPointSpoken");function at(e){return e?.trim()||"my pet"}i(at,"lead");function vd(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(vd,"clause");function wd(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${at(e)}'s ${r}`],n=[t.latestValueText?.trim(),t.statusText?.trim(),t.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",t.meaningText?.trim()&&o.push(vd(t.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${at(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:t.markerId,payload:{marker:r,...t.statusText?.trim()?{status:t.statusText.trim()}:{}}}}}i(wd,"buildMarkerAskPrompt");function xd(e,t,r){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:a}=t;if(o===0)return {prompt:`I'm looking at ${at(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${at(e)}?`,entityRef:{type:"marker_summary",id:r,payload:{total:0}}};let c=a>0?`, ${a} without a reference range`:"";return {prompt:`I'm looking at ${at(e)}'s lab markers: ${o} total, ${n} in range, ${l} out of range${c}. What should I focus on?`,entityRef:{type:"marker_summary",id:r,payload:{total:o,inRange:n,outOfRange:l,unknown:a}}}}i(xd,"buildMarkerSummaryAskPrompt");function Cd(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`${r}: ${t.valueText.trim()}`];t.collectedAt?.trim()&&o.push(`collected ${t.collectedAt.trim()}`),t.sourceClinic?.trim()&&o.push(`from ${t.sourceClinic.trim()}`),t.referenceText?.trim()&&o.push(`reference range ${t.referenceText.trim()}`),t.flagged&&o.push(`flagged ${t.flagged}`);let n={marker:r};return t.flagged&&(n.status=t.flagged),t.reviewed!==void 0&&(n.reviewed=t.reviewed),{prompt:`I'm looking at ${at(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:t.entityId,payload:n}}}i(Cd,"buildMarkerReadingAskPrompt");function Ho(e,t,r){let o=t.clinicName?.trim(),n=t.heldItemCount??0,l=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${at(e)}'s records request${o?` to ${o}`:""}, status: ${t.statusLabel.trim()}${l}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:r,payload:{status:t.status,held:n,...o?{clinic:o}:{}}}}}i(Ho,"buildRecordsRequestAskPrompt");var yg=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function Ms(e,t,r,o){let n=t.entityTypeLabel.trim()||"record",l=t.title.trim()||n,a=t.detail?.trim();return {prompt:`I'm looking at ${at(e)}'s ${n.toLowerCase()}: ${l}${a?`, ${a}`:""}. What does this mean, and what should I keep on top of for ${at(e)}?`,entityRef:{type:yg[r]??r,id:o,payload:{kind:n,title:l,...a?{detail:a}:{}}}}}i(Ms,"buildEntityRowAskPrompt");function Ed(e,t,r){let o=t.filter(a=>a.label.trim()),n={type:"upcoming_care",id:r};if(o.length===0)return {prompt:`I'm looking at ${at(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${at(e)} be on?`,entityRef:n};let l=[...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 ${at(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${at(e)}, and how do I stay on top of these?`,entityRef:n}}i(Ed,"buildUpcomingCareAskPrompt");function Sd(e,t,r){let o=[`I'm looking at ${at(e)}'s physical exam${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`],n=t.abnormal.filter(l=>l.system.trim());return n.length>0?(o.push(`Abnormal: ${n.slice(0,6).map(l=>`${l.system.trim()}: ${l.finding.trim()}`).join("; ")}.`),o.push(`What do these findings mean, and what should I follow up on for ${at(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${at(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:r}}}i(Sd,"buildPhysicalExamAskPrompt");function Td(e,t,r){let o=[`I'm looking at ${at(e)}'s visit notes${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`];for(let n of t.sections.filter(l=>l.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${vd(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${at(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:r}}}i(Td,"buildVisitNoteAskPrompt");function kd(e,t,r){let o=t.scopeLabel.trim()||"a detail",n=t.candidates.filter(a=>a.value.trim()),l=n.slice(0,3).map(a=>`"${a.value.trim()}"${a.clinicName?.trim()?` (${a.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${at(e)}'s documents disagree on ${o}: ${l}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:r,payload:{field:o,severity:t.severity,values:n.map(a=>a.value.trim()).join(" | ")}}}}i(kd,"buildConflictAskPrompt");var St=Object.freeze({title:"Medical records",subtitle:i(e=>{let t=e?.trim()??"";return t.length>0?`${t}\u2019s uploads and clinic requests`:"Every upload and clinic request"},"subtitle"),requestRecords:"Request records",requestRecordsA11y:"Request records from a clinic",uploadOwn:"I already have the records",uploadOwnA11y:"Upload records you already have",ownerUpload:"Records you uploaded",clinicRequest:"Clinic request",meta:i((e,t)=>`${e?"Uploaded":"Requested"} ${re(t)}`,"meta"),rowA11y:i((e,t,r)=>`${e}, ${t}, status ${r}`,"rowA11y"),askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),allRequests:"Your record requests"}),Bo=Object.freeze({preparing:"Preparing",sent:"Sent",processing:"Processing",done:"Ready"});function fg(e){switch(e){case "awaiting_clinic":return Bo.sent;case "received":case "parsing":case "in_review":return Bo.processing;case "published":return Bo.done;default:return Bo.preparing}}i(fg,"stepLabel");function _d(e){let t=e.source==="owner_provided",r=e.clinicName?.trim()||(t?St.ownerUpload:St.clinicRequest),o=e.statusLabel.trim()||fg(e.status),n=St.meta(t,e.createdAt);return Object.freeze({source:r,meta:n,status:o,ownerUpload:t,a11yLabel:St.rowA11y(r,n,o)})}i(_d,"requestRowView");var gg=new Set(["records_received","parsing","parsing_failed","in_review","review_email_failed"]),bg=new Set(["received","parsing","in_review"]);function hg(e){return e.wireStatus!==void 0?gg.has(e.wireStatus):bg.has(e.status)}i(hg,"isProcessing");function Pd(e,t,r={}){let o=e.filter(c=>!kr(c.status));if(e.length===0||r.activeOnly===true&&o.length===0)return null;let n=e.filter(hg).length,l=n>0?`${n} document${n===1?"":"s"} being read`:o.length>0?`${o.length} active record request${o.length===1?"":"s"}`:St.allRequests,a=n>0?`We\u2019ll add ${n===1?"it":"them"} to ${t}\u2019s records once ready.`:o.length>0?"See each clinic\u2019s status and what happens next.":"See the status of every upload and clinic request.";return Object.freeze({title:l,subtitle:a,processing:n>0,a11yLabel:`${l}. ${a}`})}i(Pd,"requestsStatusCardView");function Hn(e){return e!==void 0}i(Hn,"canUploadRecords");function Hs(e,t){return e??t?.version??""}i(Hs,"resolveConsentVersion");function Gr(e,t){return Hs(e,t).length>0}i(Gr,"canGrantConsent");function qr(e,t){return e.denialReason==="consent_required"?t?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:W("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:W("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(qr,"selectErrorView");function Uo(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?Id.ownerUpload:Id.clinicRequest}i(Uo,"selectRequestTitle");var Id=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function Bs(e,t){return t===null||t.status!=="awaiting_upload"?null:t}i(Bs,"selectResumableUploadRequest");function Us(e){let t=[...e].sort((r,o)=>r.updatedAt!==o.updatedAt?r.updatedAt>o.updatedAt?-1:1:r.createdAt!==o.createdAt?r.createdAt>o.createdAt?-1:1:0);return Object.freeze(t)}i(Us,"selectRequestList");function Yr(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(Yr,"selectPrimaryLabel");function jo(e){if(e.showClinicPhone!==true)return null;let t=e.clinicPhone?.trim()??"";return t.length===0?null:{phone:t,dial:`tel:${t.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(jo,"selectClinicCall");function Dd(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(Dd,"selectRequestStatusTone");var kt=200,Od=16;function vg(e,t){let r=e.inRangeCount+e.outOfRangeCount+e.unknownCount;if(!Number.isFinite(r)||r<=0)return [];let o=[{key:"in_range",color:t.inRange,count:e.inRangeCount},{key:"out_of_range",color:t.outOfRange,count:e.outOfRangeCount},{key:"unknown",color:t.unknown,count:e.unknownCount}],n=0,l=[];for(let a of o){if(!(a.count>0))continue;let c=a.count/r*360;if(!Number.isFinite(c))return null;l.push({key:a.key,color:a.color,startDeg:n,sweepDeg:c}),n+=c;}return l}i(vg,"buildRingSegments");function Vd({summary:e,onAsk:t,testID:r}){let o=xg(),n=V(),{totalMarkers:l,inRangeCount:a,outOfRangeCount:c,unknownCount:s}=e,d=react.useMemo(()=>vg(e,{inRange:n.color.success,outOfRange:n.color.danger,unknown:n.color.text.muted}),[e,n]),u=d!==null&&d.length>0;return jsxRuntime.jsxs(reactNative.View,{style:o.card,accessibilityRole:"summary",testID:r,children:[jsxRuntime.jsx(p,{style:o.title,children:Qt.title}),jsxRuntime.jsx(reactNative.View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:Qt.a11y(l,a,c,s),children:jsxRuntime.jsxs(reactNative.View,{style:o.ringWrap,children:[jsxRuntime.jsx(reactNative.View,{style:o.track}),d===null?null:d.map(m=>jsxRuntime.jsx(wg,{segment:m,styles:o},m.key)),jsxRuntime.jsxs(reactNative.View,{style:o.center,pointerEvents:"none",children:[jsxRuntime.jsx(p,{style:o.centerCount,children:l}),jsxRuntime.jsx(p,{style:o.centerLabel,children:l===1?Qt.marker:Qt.markers})]})]})}),u||d===null?jsxRuntime.jsxs(reactNative.View,{style:o.badges,children:[jsxRuntime.jsx(js,{count:c,label:Qt.outOfRange,color:n.color.danger,styles:o}),jsxRuntime.jsx(js,{count:a,label:Qt.inRange,color:n.color.success,styles:o}),s>0?jsxRuntime.jsx(js,{count:s,label:Qt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsxRuntime.jsx(p,{style:o.subtitle,children:Qt.subtitle}),t?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Qt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsxRuntime.jsx(p,{style:o.askLabel,children:Qt.ask})}):null]})}i(Vd,"MarkerSummaryCard");function wg({segment:e,styles:t}){return (e.sweepDeg<=180?[{start:e.startDeg,sweep:e.sweepDeg}]:[{start:e.startDeg,sweep:180},{start:e.startDeg+180,sweep:e.sweepDeg-180}]).map((o,n)=>jsxRuntime.jsx(reactNative.View,{style:[t.piece,{transform:[{rotate:`${o.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${e.key}`,children:jsxRuntime.jsx(reactNative.View,{style:t.window,children:jsxRuntime.jsx(reactNative.View,{style:[t.halfRing,{borderTopColor:e.color,borderRightColor:e.color,transform:[{rotate:`${o.sweep-135}deg`}]}]})})},n))}i(wg,"Arc");function js({count:e,label:t,color:r,styles:o}){return jsxRuntime.jsx(reactNative.View,{style:[o.badge,{borderColor:r}],children:jsxRuntime.jsx(p,{style:[o.badgeText,{color:r}],children:`${e} ${t}`})})}i(js,"Badge");function xg(){let e=V();return react.useMemo(()=>Cg(e),[e])}i(xg,"useStyles");function Cg(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,a=reactNative.StyleSheet.hairlineWidth,c=yt(l.recordCard);return reactNative.StyleSheet.create({card:{borderRadius:o.lg,backgroundColor:t.surfaceCream,borderWidth:1,borderColor:t.borderRingCream,padding:r.lg,gap:r.sm+r.xs/2,...dt(l.recordCard,1)},title:{...S(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),color:t.brandInk,letterSpacing:-0.4,...c},ringRow:{alignItems:"center"},ringWrap:{width:kt,height:kt,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:kt,height:kt,borderRadius:kt/2,borderWidth:Od,borderColor:t.surfaceSubtle},piece:{position:"absolute",width:kt,height:kt},window:{position:"absolute",left:kt/2,top:0,width:kt/2,height:kt,overflow:"hidden"},halfRing:{position:"absolute",left:-kt/2,top:0,width:kt,height:kt,borderRadius:kt/2,borderWidth:Od,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{...S(e,"medium"),fontSize:n.size.verdict*2,lineHeight:n.size.verdict*2+r.xs,color:t.text.primary,textAlign:"center",...c},centerLabel:{...S(e,"medium"),fontSize:n.size.heading-1,lineHeight:n.size.heading+r.xs/2,color:t.text.primary,textAlign:"center",...c},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:r.sm},badge:{borderWidth:1,borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs},badgeText:{...S(e,"mono"),fontSize:n.size.nano,lineHeight:n.size.tiny,letterSpacing:n.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{...S(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.relaxed),color:t.text.primary,...c},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.sm,marginTop:r.xs/2,paddingHorizontal:r.lg,borderRadius:o.pill,borderWidth:a,borderColor:t.borderRingCream,backgroundColor:t.surface},askLabel:{...S(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.primary,letterSpacing:n.letterSpacing.tight}})}i(Cg,"makeStyles");function Eg(e){return e.value!==null&&Number.isFinite(e.value)}i(Eg,"numeric");function Fd(e){let t=e.points.filter(Eg);if(t.length===0)return null;let r=e.points[e.points.length-1]??null,o=r?.refLow??null,n=r?.refHigh??null,l=t.map(f=>f.value),a=Math.min(...l,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...l,...o!==null?[o]:[],...n!==null?[n]:[]);a===c&&(a-=1,c+=1);let s=(c-a)*.18,d=a-s,u=c+s,m=u-d,y=i(f=>(u-f)/m*100,"y"),g=6,w=t.length,R=t.map((f,b)=>({index:b,xPct:w<=1?50:g+b/(w-1)*(100-2*g),yPct:y(f.value),status:f.status,point:f})),v=o!==null||n!==null?{topPct:n!==null?y(n):0,bottomPct:o!==null?y(o):100}:null;return {points:R,band:v,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Fd,"buildMarkerChart");var kg=416,_g=140;function Wo(e){return `${e}%`}i(Wo,"pct");function Pg({marker:e,width:t,onPointPress:r,onAsk:o}){let n=$s(),l=Re(),a=pr(e.latest?.status??null),c=No(e.latest?.status??null),s=nn(e.trajectory,e.points.length),d=react.useMemo(()=>Fd(e),[e]),u=e.latest?Vt(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsxRuntime.jsx(reactNative.View,{style:[n.page,t!==void 0?{width:t}:null],testID:`marker-card-${e.markerId}`,children:jsxRuntime.jsxs(reactNative.View,{style:n.card,children:[jsxRuntime.jsxs(reactNative.View,{style:n.headerRow,children:[jsxRuntime.jsxs(reactNative.View,{style:n.nameColumn,children:[jsxRuntime.jsx(p,{style:n.markerName,numberOfLines:2,children:e.name}),e.unit?jsxRuntime.jsx(p,{style:n.unit,children:e.unit}):null]}),jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:hr.status(a.label),children:jsxRuntime.jsx(Lt,{label:a.label,tone:c})})]}),e.latest&&u!==null?jsxRuntime.jsxs(reactNative.View,{style:n.latestRow,children:[jsxRuntime.jsx(p,{style:[n.latestValue,a.outOfRange?n.latestValueDanger:null],accessibilityLabel:hr.latestA11y(u,a.label,re(e.latest.at)),children:u}),jsxRuntime.jsx(p,{style:n.latestDate,children:re(e.latest.at)})]}):null,s?jsxRuntime.jsx(p,{style:n.trajectory,accessibilityRole:"text",children:s}):null,d!==null?jsxRuntime.jsxs(reactNative.View,{style:n.chartWrap,children:[jsxRuntime.jsxs(reactNative.View,{style:n.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[d.band?jsxRuntime.jsx(reactNative.View,{style:[n.band,{top:Wo(d.band.topPct),height:Wo(Math.max(0,d.band.bottomPct-d.band.topPct))}]}):null,d.points.map(m=>jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>r(e,m.point),hitSlop:12,style:[n.point,m.status==="above"||m.status==="below"?n.pointDanger:null,{left:Wo(m.xPct),top:Wo(m.yPct)}],testID:`marker-point-${e.markerId}-${m.index}`},m.index))]}),jsxRuntime.jsx(reactNative.View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:hr.readingsA11y(e.name),children:e.points.map((m,y)=>jsxRuntime.jsx(reactNative.View,{accessibilityRole:"text",accessibilityLabel:Rd(e,m)},y))}),jsxRuntime.jsx(p,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?hr.singleHint:hr.tapHint})]}):jsxRuntime.jsx(reactNative.View,{style:n.emptyBody,accessibilityRole:"text",children:jsxRuntime.jsx(p,{style:n.emptyText,children:hr.empty})}),o?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:hr.askA11y(e.name),style:[l.pill,l.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsxRuntime.jsx(p,{style:l.pillAskLabel,children:hr.askNamed(e.name)})}):null]})})}i(Pg,"MarkerTrendCard");function Md({markers:e,onPointPress:t,onAsk:r}){let o=$s(),[n,l]=react.useState(0),[a,c]=react.useState(0),s=i(m=>l(m.nativeEvent.layout.width),"onLayout"),d=i(m=>{if(n<=0)return;let y=Math.round(m.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(y,e.length-1)));},"onMomentumEnd"),u=e[a]??null;return jsxRuntime.jsxs(reactNative.View,{style:o.carousel,onLayout:s,testID:"marker-carousel",children:[jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:d,snapToAlignment:"start",children:e.map(m=>jsxRuntime.jsx(Pg,{marker:m,width:n>0?n:void 0,onPointPress:t,onAsk:r},m.markerId))}),jsxRuntime.jsxs(reactNative.View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:Yi.a11y(u?.name??null,a,e.length),children:[jsxRuntime.jsx(reactNative.View,{style:o.dots,children:e.map((m,y)=>jsxRuntime.jsx(reactNative.View,{style:[o.dot,y===a?o.dotActive:null]},m.markerId))}),jsxRuntime.jsx(p,{style:o.counter,children:Yi.counter(a,e.length)})]})]})}i(Md,"MarkerTrendCarousel");function Hd({marker:e,point:t,onClose:r,onAsk:o}){let n=$s(),l=Re();if(e===null||t===null)return null;let a=i((c,s)=>jsxRuntime.jsxs(reactNative.View,{style:n.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${c}: ${s}`,children:[jsxRuntime.jsx(p,{style:n.detailLabel,children:c}),jsxRuntime.jsx(p,{style:n.detailValue,children:s})]},c),"row");return jsxRuntime.jsxs(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:r,children:[jsxRuntime.jsx(reactNative.Pressable,{style:n.backdrop,onPress:r,accessibilityRole:"button",accessibilityLabel:At.close}),jsxRuntime.jsxs(reactNative.View,{style:n.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[jsxRuntime.jsx(reactNative.View,{style:n.handle}),jsxRuntime.jsxs(reactNative.View,{style:n.sheetHeader,children:[jsxRuntime.jsx(p,{style:n.sheetTitle,accessibilityRole:"header",children:At.title}),jsxRuntime.jsx(reactNative.Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:At.close,hitSlop:10,style:n.closeButton,testID:"marker-provenance-close",children:jsxRuntime.jsx(p,{style:n.closeGlyph,children:"\xD7"})})]}),jsxRuntime.jsxs(reactNative.View,{style:n.sheetBody,children:[jsxRuntime.jsxs(reactNative.View,{style:n.valueRow,children:[jsxRuntime.jsx(p,{style:n.sheetName,children:e.name}),jsxRuntime.jsx(p,{style:n.sheetValue,children:Vt(t.value,e.unit,t.qualitativeResult)})]}),t.reviewed?jsxRuntime.jsx(reactNative.View,{style:n.reviewed,accessibilityRole:"text",children:jsxRuntime.jsx(p,{style:n.reviewedText,children:At.reviewed})}):null,a(At.collected,re(t.at)),t.sourceClinic?a(At.clinic,t.sourceClinic):null,a(At.referenceRange,t.refLow!==null||t.refHigh!==null?Mo(t,e.unit):At.noRange),t.docId?a(At.sourceDocument,t.docId):null,t.reviewed?null:jsxRuntime.jsx(p,{style:n.unverified,accessibilityRole:"text",children:At.unverified}),o?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:At.askA11y,style:[l.pill,l.pillAsk],testID:"marker-provenance-ask",children:jsxRuntime.jsx(p,{style:l.pillAskLabel,children:At.ask})}):null]})]})]})}i(Hd,"MarkerProvenanceSheet");function $s(){let e=V();return react.useMemo(()=>Ig(e),[e])}i($s,"useStyles");function Ig(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,a=reactNative.StyleSheet.hairlineWidth,c=r.md,s=i((y,g,w,R="regular")=>({...S(e,R),fontSize:y,lineHeight:Math.round(y*g),color:w}),"text"),d=yt(l.recordCard),u=s(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),m=s(n.size.verdict+r.xs,n.lineHeight.tight,t.text.primary,"bold");return reactNative.StyleSheet.create({page:{paddingHorizontal:r.sm},card:{borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surface,padding:r.lg,gap:r.md,...dt(l.recordCard,1)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm+r.xs/2},nameColumn:{flex:1,gap:r.xs/2},markerName:{...u,...d},sheetName:u,unit:{...S(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted,...d},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},latestValue:{...m,...d},sheetValue:m,latestValueDanger:{color:t.danger},latestDate:{...s(n.size.caption,n.lineHeight.normal,t.text.muted),...d},trajectory:{...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted),...d},chartWrap:{gap:r.sm},plot:{height:_g,borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:t.badgeBgPositive},point:{position:"absolute",width:c,height:c,borderRadius:c/2,marginLeft:-c/2,marginTop:-c/2,backgroundColor:t.brand,borderWidth:2,borderColor:t.surface},pointDanger:{backgroundColor:t.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...s(n.size.tiny,n.lineHeight.normal,t.text.placeholder),textAlign:"center",...d},singleHint:{...s(n.size.caption,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},emptyBody:{alignItems:"center",justifyContent:"center",gap:r.sm,paddingVertical:r.xxl+r.xs},emptyText:{...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},carousel:{height:kg},footer:{alignItems:"center",gap:r.sm,paddingTop:r.md},dots:{flexDirection:"row",gap:r.xs+r.xs/2},dot:{width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs-1,backgroundColor:t.borderHairlineGreen},dotActive:{width:r.lg+r.xs/2,backgroundColor:t.brand},counter:{...S(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,letterSpacing:n.letterSpacing.eyebrow/3,color:t.text.muted},backdrop:{flex:1,backgroundColor:Ro},sheet:{backgroundColor:t.surfaceCream,borderTopLeftRadius:o.xl-r.xs,borderTopRightRadius:o.xl-r.xs,paddingHorizontal:r.lg+r.xs,paddingTop:r.sm,paddingBottom:r.xxl+r.xs,maxHeight:"80%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},sheetTitle:{flex:1,...s(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},closeButton:{width:r.xxl+r.md,height:r.xxl+r.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...s(n.size.verdict,n.lineHeight.tight,t.text.primary)},sheetBody:{gap:r.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs,backgroundColor:t.badgeBgPositive},reviewedText:{...s(n.size.tiny,n.lineHeight.normal,t.success,"medium")},detailRow:{gap:r.xs/2},detailLabel:{...s(n.size.caption,n.lineHeight.normal,t.text.muted,"medium")},detailValue:s(n.size.body,n.lineHeight.normal,t.text.primary),unverified:s(n.size.caption,n.lineHeight.normal,t.text.muted)})}i(Ig,"makeStyles");var gt=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 Bd(e,t){return ar(e)?t==="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.":ed(e)?t==="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.":t==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(Bd,"factEditErrorMessage");var Dg=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function Ws(e,t){if(Object.keys(t.edits).length===0&&t.removed.length===0)return e;let r=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&t.removed.includes(n))continue;let l=n!==null?t.edits[n]:void 0;r.push(l===void 0?o:Object.freeze({...o,value:l}));}return Object.freeze(r)}i(Ws,"applyFactOverlay");function Yo(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(Yo,"isFactEditable");function Ag(){return `records-fact-${Date.now().toString(36)}`}i(Ag,"defaultFactKey");function Gs(e,t={}){let r=xr(),{userRef:o}=Te(),[n,l]=react.useState(Dg),[a,c]=react.useState(false),[s,d]=react.useState(null),u=react.useMemo(()=>({}),[r,e,o]),[m,y]=react.useState(null),g=react.useCallback(()=>y(u),[u]),w=o!==null&&m!==u,R=react.useRef(false),v=react.useRef(t.newIdempotencyKey);v.current=t.newIdempotencyKey;let f=react.useCallback(()=>(v.current??Ag)(),[]),b=react.useCallback((T,k,_)=>{if(c(false),!T.ok){if(k(),Cr(T.error)){g();return}d(Bd(T.error,_));}},[g]),C=react.useCallback(async(T,k)=>{let _=T.canonicalKey??"",E=k.trim();if(R.current||_.length===0||E.length===0)return te(W("validationFailed",{retryable:false}));R.current=true,c(true),d(null);let B=n;l(A=>({...A,edits:{...A.edits,[_]:E}}));let x=await r.editFact(e,{entityType:T.category,canonicalKey:_,correctedFields:Ds(T.value,E),idempotencyKey:f()});return R.current=false,b(x,()=>l(B),"edit"),x},[r,e,n,b,f]),h=react.useCallback(async T=>{let k=T.canonicalKey??"";if(R.current||k.length===0)return te(W("validationFailed",{retryable:false}));R.current=true,c(true),d(null);let _=n;l(B=>({...B,removed:[...B.removed,k]}));let E=await r.removeFact(e,{entityType:T.category,canonicalKey:k,idempotencyKey:f()});return R.current=false,b(E,()=>l(_),"remove"),E},[r,e,n,b,f]),I=react.useCallback(()=>d(null),[]);return react.useMemo(()=>({overlay:n,busy:a,error:s,available:w,edit:C,remove:h,clearError:I}),[n,a,s,w,C,h,I])}i(Gs,"useRecordFactEdit");var Ys=Object.freeze(["vaccination","parasite_prevention"]),Ko="Undated",Og=Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),$d=Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function Qo(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(Qo,"toMillis");function Lg(e){let t=e.status?.toLowerCase()??"";return /overdue|lapsed|expired/.test(t)}i(Lg,"isLapsed");function Vg(e){return e.category==="parasite_prevention"?"prevention":Qo(e.observedAt)===null?"noDate":Lg(e)?"overdue":"given"}i(Vg,"vaccineTone");function Fg(e){let t=Qo(e);return t===null?Ko:String(new Date(t).getUTCFullYear())}i(Fg,"yearOf");function qg(e){let t=Vg(e),r=[e.value!==null&&e.value.length>0?e.value:null,e.observedAt!==null?re(e.observedAt):null].filter(o=>o!==null&&o.length>0);return {key:e.key,name:e.label,detail:r.length>0?r.join(" \xB7 "):null,statusLabel:Og[t],tone:t,entity:e}}i(qg,"buildRow");function Wd(e){let t=new Map;for(let o of e){if(!Ys.includes(o.category))continue;let n=Fg(o.observedAt),l=t.get(n),a={row:qg(o),at:o.observedAt};l===void 0?t.set(n,[a]):l.push(a);}let r=[...t.keys()].sort((o,n)=>o===Ko?1:n===Ko?-1:Number(n)-Number(o));return Object.freeze(r.map(o=>{let n=t.get(o)??[],l=o===Ko?n:[...n].sort((a,c)=>(Qo(c.at)??0)-(Qo(a.at)??0));return Object.freeze({year:o,items:Object.freeze(l.map(a=>a.row))})}))}i(Wd,"selectVaccineGroups");var Xo=Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function Ks({entity:e,factEdit:t,children:r}){let o=Gd(),[n,l]=react.useState(false),a=e.label.trim()||gt.detail;return jsxRuntime.jsxs(reactNative.View,{style:o.row,children:[jsxRuntime.jsx(reactNative.View,{style:o.main,children:r}),jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>l(true),accessibilityRole:"button",accessibilityLabel:gt.editA11y(a),hitSlop:6,style:o.editButton,testID:`fact-edit-open-${e.canonicalKey??e.key}`,children:jsxRuntime.jsx(reactNative.View,{style:o.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),n?jsxRuntime.jsx(Ug,{entity:e,title:a,factEdit:t,onClose:()=>l(false)}):null]})}i(Ks,"FactEditAffordance");function Ug({entity:e,title:t,factEdit:r,onClose:o}){let n=Gd(),l=Re(),a=V(),[c,s]=react.useState(e.value??""),[d,u]=react.useState(null),[m,y]=react.useState(false);react.useEffect(()=>{r.clearError();},[r]);let g=c.trim().length>0&&c.trim()!==(e.value??"").trim(),w=d??r.error,R=r.busy,v=i(()=>{if(!g){u(gt.noChange);return}u(null),r.edit(e,c).then(b=>{b.ok&&o();});},"submitEdit"),f=i(()=>{u(null),r.remove(e).then(b=>{b.ok?o():y(false);});},"submitRemove");return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:o,children:jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:"padding",style:n.backdrop,children:[jsxRuntime.jsx(reactNative.Pressable,{style:Xo,accessibilityRole:"button",accessibilityLabel:gt.closeEditorA11y,onPress:o}),jsxRuntime.jsxs(reactNative.View,{style:n.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[jsxRuntime.jsx(reactNative.View,{style:n.handle}),jsxRuntime.jsxs(reactNative.View,{style:n.header,children:[jsxRuntime.jsxs(reactNative.View,{style:n.headerText,children:[jsxRuntime.jsx(p,{style:n.title,accessibilityRole:"header",children:gt.title(t)}),jsxRuntime.jsx(p,{style:[n.helper,w?n.helperError:null],accessibilityLiveRegion:"polite",children:w??gt.helper})]}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:gt.close,onPress:o,hitSlop:12,style:n.closeButton,testID:"fact-edit-close",children:jsxRuntime.jsx(p,{style:n.closeGlyph,children:"\xD7"})})]}),jsxRuntime.jsx(p,{style:l.fieldLabel,children:e.label}),jsxRuntime.jsx(Qe,{accessibilityLabel:e.label,style:l.field,value:c,onChangeText:b=>{s(b),u(null);},editable:!R,maxLength:512,placeholderTextColor:a.color.text.placeholder,testID:"fact-edit-field"}),m?jsxRuntime.jsxs(reactNative.View,{style:n.confirmBlock,testID:"fact-edit-confirm-remove",children:[jsxRuntime.jsx(p,{style:n.confirmText,children:gt.confirmRemove}),jsxRuntime.jsxs(reactNative.View,{style:n.confirmRow,children:[jsxRuntime.jsx(X,{label:R?gt.removing:gt.removeConfirm,kind:"danger",busy:R,onPress:f,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsxRuntime.jsx(X,{label:gt.keep,kind:"outline",disabled:R,onPress:()=>y(false),style:n.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):jsxRuntime.jsxs(reactNative.View,{style:n.actions,children:[jsxRuntime.jsx(X,{label:R?gt.saving:gt.save,busy:R,disabled:!g,onPress:v,testID:"fact-edit-save"}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:gt.removeA11y(t),disabled:R,onPress:()=>{u(null),y(true);},style:[n.removeButton,R?n.removeDisabled:null],testID:"fact-edit-remove",children:jsxRuntime.jsx(p,{style:n.removeText,children:gt.remove})})]})]})]})})}i(Ug,"FactEditSheet");function Gd(){let e=V();return react.useMemo(()=>jg(e),[e])}i(Gd,"useStyles");function jg(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,a=e.brightness==="dark"?t.errorRed:t.danger,c=i((s,d,u,m="regular")=>({...S(e,m),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text");return reactNative.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:r.sm},main:{flex:1},editButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},pencil:{width:r.md+r.xs/2,height:r.xs/2,backgroundColor:t.brandInk,borderRadius:o.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:Ro},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),helperError:{color:a},closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),actions:{gap:r.sm},removeButton:{minHeight:l,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...c(n.size.bodyTight,n.lineHeight.snug,t.danger,"bold")},confirmBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.badgeBgCritical},confirmText:c(n.size.bodyTight,n.lineHeight.normal,t.text.primary),confirmRow:{flexDirection:"row",gap:r.sm},confirmButton:{flex:1}})}i(jg,"makeStyles");function ti({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:a,nowMs:c}){let s=Re(),d=$g(),u=c??Date.now(),m=react.useMemo(()=>a?Ws(e.entities,a.overlay):e.entities,[e.entities,a]),y=react.useMemo(()=>{let f=[],b=new Map;for(let C of m){let h=C.category.trim();if(h.length===0||Ys.includes(h))continue;let I=b.get(h);I===void 0?(f.push(h),b.set(h,[C])):I.push(C);}return {order:vo(f),groups:b}},[m]),g=react.useMemo(()=>Wd(m),[m]),w=Object.values(e.documents),R=i((f,b,C)=>l?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{let h=f();l(h.prompt,h.entityRef);},accessibilityRole:"button",accessibilityLabel:b,style:[s.pill,s.pillAsk,d.ask],testID:C,children:jsxRuntime.jsx(p,{style:s.pillAskLabel,children:b})}):null,"ask"),v=a!==void 0&&a.available;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(reactNative.View,{style:d.sections,children:[t&&t.conflicts.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-conflicts",children:[jsxRuntime.jsx(Bt,{title:ne.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((f,b)=>wo(f.severity).rank-wo(b.severity).rank).map(f=>{let b=wo(f.severity),C=Rr(f.field??f.entityType);return jsxRuntime.jsxs(reactNative.View,{style:[d.conflictCard,{borderColor:s.chipTones[b.tone].fg.color}],accessibilityRole:"summary",children:[jsxRuntime.jsxs(reactNative.View,{style:d.conflictHead,children:[jsxRuntime.jsx(p,{style:d.conflictTitle,children:b.label}),jsxRuntime.jsx(Lt,{label:C,tone:b.tone})]}),jsxRuntime.jsx(p,{style:s.rowDetail,children:ne.conflictSub}),f.candidates.map((h,I)=>jsxRuntime.jsxs(reactNative.View,{style:d.candidate,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:h.value}),jsxRuntime.jsx(p,{style:s.rowMuted,children:[h.docId?e.documents[h.docId]?.title??ne.uploadedDocument:ne.uploadedDocument,h.collectedAt?re(h.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},I)),R(()=>kd(r,{scopeLabel:C,severity:f.severity,candidates:f.candidates.map(h=>({value:h.value,clinicName:h.docId?e.documents[h.docId]?.title??null:null}))},f.conflictId),ne.askConflict,`records-ask-conflict-${f.conflictId}`)]},f.conflictId)})]}):null,t?.completeness?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-completeness",children:[jsxRuntime.jsx(Bt,{title:ne.whatsOnFile}),jsxRuntime.jsxs(reactNative.View,{style:s.card,children:[jsxRuntime.jsx(reactNative.View,{style:d.coverageRow,children:[[ne.coverage.labs,t.completeness.hasLabHistory],[ne.coverage.vaccines,t.completeness.hasVaccinationHistory],[ne.coverage.weight,t.completeness.hasWeightHistory],[ne.coverage.vitals,t.completeness.hasVitalsHistory],[ne.coverage.exams,t.completeness.hasPhysicalExamHistory],[ne.coverage.procedures,t.completeness.hasProcedureHistory],[ne.coverage.genetics,t.completeness.hasGeneticHistory],[ne.coverage.parasite,t.completeness.hasParasitePreventionHistory],[ne.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([f,b])=>jsxRuntime.jsx(reactNative.View,{style:[d.coveragePill,b?s.chipTones.positive.bg:s.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${f}: ${b?ne.onFile:ne.noneOnFile}`,children:jsxRuntime.jsx(p,{style:[d.coverageText,b?s.chipTones.positive.fg:{color:s.rowMuted.color}],children:f})},f))}),jsxRuntime.jsxs(reactNative.View,{style:d.metaRow,children:[jsxRuntime.jsx(p,{style:d.metaText,children:ne.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsxRuntime.jsx(Lt,{label:ne.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,Qs(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:ne.beingVerifiedA11y(Qs(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsxRuntime.jsx(Lt,{label:ne.beingVerified(Qs(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),t.completeness.earliestRecordAt||t.completeness.latestRecordAt?jsxRuntime.jsx(reactNative.View,{style:d.metaRow,children:jsxRuntime.jsx(p,{style:d.metaText,children:ne.dateRange(t.completeness.earliestRecordAt,t.completeness.latestRecordAt)})}):null,Object.entries(t.completeness.entitiesPendingReview).filter(([,f])=>f>0).length>0?jsxRuntime.jsxs(p,{style:d.pendingText,children:[ne.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,f])=>f>0).map(([f,b])=>`${vr(f)} (${b})`).join(", ")]}):null]})]}):null,w.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-documents",children:[jsxRuntime.jsx(Bt,{title:ne.documents,count:w.length}),jsxRuntime.jsx(reactNative.View,{style:s.card,children:w.map((f,b)=>{let C=f.title?.trim()||ne.uploadedDocument,h=ne.documentMeta(f.pageCount,f.receivedAt),I=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(reactNative.View,{style:s.rowMain,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:C}),h?jsxRuntime.jsx(p,{style:s.rowDetail,children:h}):null]}),n?jsxRuntime.jsx(er,{}):null]});return n?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>n({name:"contributions",docId:f.docId}),accessibilityRole:"button",accessibilityLabel:ne.documentRowA11y(C),style:[s.row,b>0?s.rowDivider:null],testID:`records-document-row-${f.docId}`,children:I},f.docId):jsxRuntime.jsx(reactNative.View,{style:[s.row,b>0?s.rowDivider:null],children:I},f.docId)})})]}):null,e.identity.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-identity",children:[jsxRuntime.jsx(Bt,{title:ne.identity}),jsxRuntime.jsx(reactNative.View,{style:s.card,children:e.identity.map((f,b)=>jsxRuntime.jsxs(reactNative.View,{style:[s.row,b>0?s.rowDivider:null],children:[jsxRuntime.jsx(p,{style:d.identityLabel,children:f.label}),jsxRuntime.jsx(p,{style:d.identityValue,children:Rc(f.value)})]},`${b}:${f.label}`))})]}):null,e.forwardLooking.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-upcoming",children:[jsxRuntime.jsx(Bt,{title:ne.upcomingCare,count:e.forwardLooking.length}),jsxRuntime.jsx(reactNative.View,{style:s.card,children:e.forwardLooking.map((f,b)=>{let C=Dn(f.dueAt,u);return jsxRuntime.jsxs(reactNative.View,{style:[s.row,b>0?s.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:s.rowMain,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:f.title}),f.detail?jsxRuntime.jsx(p,{style:s.rowDetail,children:f.detail}):null]}),C?jsxRuntime.jsx(Lt,{label:C.label,tone:C.overdue?"critical":"info"}):null]},`${f.title}-${b}`)})}),R(()=>Ed(r,e.forwardLooking.map(f=>{let b=Dn(f.dueAt,u);return {label:f.title,relativeText:b?.label??"",tone:b?.overdue?"overdue":"upcoming"}}),e.petRef),ne.askUpcomingCare,"records-ask-upcoming-care")]}):null,g.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-vaccination",children:[jsxRuntime.jsx(Bt,{title:vr("vaccination"),count:g.reduce((f,b)=>f+b.items.length,0)}),g.map(f=>jsxRuntime.jsxs(reactNative.View,{style:d.vaccineGroup,testID:`records-vaccine-group-${f.year}`,children:[jsxRuntime.jsx(p,{style:d.vaccineYear,accessibilityRole:"header",children:f.year.toUpperCase()}),jsxRuntime.jsx(reactNative.View,{style:s.card,children:f.items.map((b,C)=>{let h=jsxRuntime.jsxs(reactNative.View,{style:[s.row,C>0?s.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:s.rowMain,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:b.name}),b.detail?jsxRuntime.jsx(p,{style:s.rowDetail,children:b.detail}):null,R(()=>Ms(r,{entityTypeLabel:vr(b.entity.category),title:b.name,detail:b.detail},b.entity.category,b.key),ne.askEverfur,`records-ask-entity-${b.key}`)]}),jsxRuntime.jsx(Lt,{label:b.statusLabel,tone:$d[b.tone]})]});return v&&Yo(b.entity)&&a?jsxRuntime.jsx(Ks,{entity:b.entity,factEdit:a,children:h},b.key):jsxRuntime.jsx(reactNative.View,{children:h},b.key)})})]},f.year))]}):null,y.order.map(f=>{let b=y.groups.get(f)??[];if(b.length===0)return null;let C=vr(f);return jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:`record-section-${f}`,children:[jsxRuntime.jsx(Bt,{title:C,count:b.length}),jsxRuntime.jsx(reactNative.View,{style:s.card,children:b.map((h,I)=>{let k=[rn(h.value,h.unit),h.observedAt?re(h.observedAt):null].filter(E=>E&&E.length>0).join(" \xB7 "),_=jsxRuntime.jsxs(reactNative.View,{style:[s.row,I>0?s.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:s.rowMain,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:h.label}),k?jsxRuntime.jsx(p,{style:s.rowDetail,children:k}):null,R(()=>Ms(r,{entityTypeLabel:C,title:h.label,detail:k||null},f,h.key),ne.askEverfur,`records-ask-entity-${h.key}`)]}),h.status?jsxRuntime.jsx(Lt,{label:Rr(h.status)}):null]});return v&&Yo(h)&&a?jsxRuntime.jsx(Ks,{entity:h,factEdit:a,children:_},h.key):jsxRuntime.jsx(reactNative.View,{children:_},h.key)})})]},f)}),t&&t.physicalExams.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-exams",children:[jsxRuntime.jsx(Bt,{title:ne.physicalExams,count:t.physicalExams.length}),t.physicalExams.map(f=>jsxRuntime.jsxs(reactNative.View,{style:s.card,children:[jsxRuntime.jsx(p,{style:[s.rowTitle,d.cardTitle],accessibilityRole:"header",children:f.observedOn?re(f.observedOn):be.exam}),f.systems.map((b,C)=>{let h=b.findingStatus==="abnormal",I=h?be.abnormal:b.findingStatus==="not_examined"?be.notExamined:be.normal;return jsxRuntime.jsxs(reactNative.View,{style:[s.row,C>0?s.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[Hr(b.system),I,h?b.finding:null].filter(Boolean).join(", "),children:[jsxRuntime.jsxs(reactNative.View,{style:s.rowMain,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:Hr(b.system)}),h&&b.finding?jsxRuntime.jsx(p,{style:s.rowDetail,children:b.finding}):null]}),jsxRuntime.jsx(Lt,{label:I,tone:h?"warning":b.findingStatus==="not_examined"?"neutral":"positive"})]},b.system)}),R(()=>Sd(r,{observedOn:f.observedOn?re(f.observedOn):null,abnormal:f.systems.filter(b=>b.findingStatus==="abnormal").map(b=>({system:Hr(b.system),finding:b.finding??""}))},f.examId),ne.askExam,`records-ask-exam-${f.examId}`)]},f.examId))]}):null,t&&t.clinicianNotes.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-notes",children:[jsxRuntime.jsx(Bt,{title:ne.visitNotes,count:t.clinicianNotes.length}),t.clinicianNotes.map(f=>jsxRuntime.jsxs(reactNative.View,{style:s.card,children:[jsxRuntime.jsx(p,{style:[s.rowTitle,d.cardTitle],accessibilityRole:"header",children:f.observedOn?re(f.observedOn):be.visitNote}),f.sections.map((b,C)=>jsxRuntime.jsxs(reactNative.View,{style:[d.noteSection,C>0?s.rowDivider:null],children:[jsxRuntime.jsx(p,{style:d.noteLabel,children:on(b.section)}),jsxRuntime.jsx(p,{style:b.text?d.noteBody:d.noteBodyMuted,children:b.text||be.notRecorded})]},`${b.section}:${C}`)),R(()=>Td(r,{observedOn:f.observedOn?re(f.observedOn):null,sections:f.sections.map(b=>({label:on(b.section),text:b.text}))},f.noteId),ne.askVisit,`records-ask-note-${f.noteId}`)]},f.noteId))]}):null,o&&t&&t.labResults.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-labs",children:[jsxRuntime.jsx(Bt,{title:ne.labResults,count:t.labResults.length}),jsxRuntime.jsx(reactNative.View,{style:s.card,children:t.labResults.map((f,b)=>{let C=pr(f.latest.status),h=ds(f.latest.at,f.trajectory,f.points.length);return jsxRuntime.jsxs(reactNative.View,{style:[s.row,b>0?s.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:s.rowMain,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:f.name}),jsxRuntime.jsx(p,{style:s.rowValue,children:Vt(f.latest.value,f.latest.unit,f.latest.qualitativeResult)}),h?jsxRuntime.jsx(p,{style:s.rowDetail,children:h}):null]}),jsxRuntime.jsx(Lt,{label:C.label,tone:No(f.latest.status)})]},f.markerId)})})]}):null,t&&t.encounters.length>0?jsxRuntime.jsxs(reactNative.View,{style:s.section,testID:"record-section-visits",children:[jsxRuntime.jsx(Bt,{title:ne.visits,count:t.encounters.length}),jsxRuntime.jsx(reactNative.View,{style:s.card,children:t.encounters.map((f,b)=>{let C=[f.date?re(f.date):null,f.clinicName,f.veterinarian].filter(h=>h&&h!=="-").join(" \xB7 ");return jsxRuntime.jsx(reactNative.View,{style:[s.row,b>0?s.rowDivider:null],children:jsxRuntime.jsxs(reactNative.View,{style:s.rowMain,children:[jsxRuntime.jsx(p,{style:s.rowTitle,children:f.type?Rr(f.type):be.visit}),C?jsxRuntime.jsx(p,{style:s.rowDetail,children:C}):null]})},f.encounterId)})})]}):null]}),jsxRuntime.jsx(Fr,{disclaimer:e.disclaimer})]})}i(ti,"RecordSections");function Qs(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(Qs,"heldCount");function $g(){let e=V();return react.useMemo(()=>Wg(e),[e])}i($g,"useLocalStyles");function Wg(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:r.lg+r.xs},vaccineGroup:{gap:r.xs+1,marginBottom:r.sm},vaccineYear:{...S(e,"monoMedium"),fontSize:n.size.micro,lineHeight:n.size.micro+r.xs,color:t.text.muted,letterSpacing:n.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:r.xs+2},ask:{marginTop:r.lg},conflictCard:{borderRadius:o.md,borderWidth:1,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},conflictHead:{flexDirection:"row",alignItems:"center",gap:r.sm},conflictTitle:{flex:1,...S(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},candidate:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen,paddingTop:r.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,paddingVertical:r.md},coveragePill:{borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs+1},coverageText:{...S(e,"medium"),fontSize:n.size.caption,lineHeight:n.size.caption+r.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingBottom:r.md},metaText:{flex:1,...S(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},pendingText:{...S(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted,paddingBottom:r.md},identityLabel:{...S(e,"medium"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...S(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},cardTitle:{paddingTop:r.sm},noteSection:{paddingVertical:r.md,gap:r.xs},noteLabel:{...S(e,"bold"),fontSize:n.size.bodyTight,color:t.text.secondary,textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},noteBody:{...S(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.primary},noteBodyMuted:{...S(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.muted,fontStyle:"italic"}})}i(Wg,"makeLocalStyles");var Un=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 Gg=Math.round(Pr/(1024*1024)),Me=Object.freeze({title:i(e=>`Upload ${ke(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 ${ke(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 ${Gg} 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,t)=>`Uploading ${Math.min(e+1,t)} of ${t}\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."})}),or=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."});function Xd(e,t){return `${e} ${t}`}i(Xd,"uploadActionA11y");var Xs=Math.round(Pr/(1024*1024)),Kr=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,t)=>`Uploading ${Math.min(e+1,t)} of ${t} records`,"uploading"),uploaded:i((e,t)=>`${e} of ${t} records uploaded`,"uploaded")});function Jd(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return Kr.done;case "failed":return Kr.failed;case "uploading":return e.progress>=1?Kr.verifying:`${t}%`;case "queued":return Kr.queued;default:return null}}i(Jd,"uploadItemStatusLabel");function ri(e,t=false){if(e.length===0)return null;let r=i(a=>{let c=a.map(s=>s.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(t){let a=[];return n.length>0&&a.push(or.unreadable),o.length>0&&a.push(`Didn\u2019t upload: ${r(o)} ${o.length>1?"are":"is"} over ${Xs} MB.`),a.join(" ")}let l=[];return n.length>0&&l.push(`${r(n)} ${n.length>1?"are not PDFs":"is not a PDF"}`),o.length>0&&l.push(`${r(o)} ${o.length>1?"are":"is"} over ${Xs} MB`),`Didn\u2019t upload: ${l.join("; ")}. We can only read PDFs up to ${Xs} MB right now.`}i(ri,"skippedFilesMessage");function Zd(e){let t=[];for(let r of e)r.status==="skipped"&&r.skipReason!==null&&t.push({name:r.name,reason:r.skipReason});return t}i(Zd,"skippedOf");var Wt=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 eu({request:e,onRecovered:t,canUpload:r=false},o){let[n,l]=react.useState(""),[a,c]=react.useState(false),[s,d]=react.useState(null),[u,m]=react.useState(false),[y,g]=react.useState(null),w=react.useRef(false),R=react.useRef(false),v=react.useRef(0);react.useEffect(()=>(R.current=true,()=>{R.current=false,v.current+=1;}),[o]);let f=y!==null&&y.before===e.updatedAt?{...y.value,canRetrySend:e.canRetrySend===true&&y.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&y.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&y.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&y.value.canConvertToUpload===true}:e,b=n.trim(),C=b.length<=320&&!Array.from(b).some(E=>E.charCodeAt(0)<=32||E.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(b),h=f.canUpdateClinicEmail===true&&b.length>0,I=f.canRetrySend===true&&!a&&!h,T=f.canUpdateClinicEmail===true&&!a&&C,k=f.canConvertToUpload===true&&r,_=i(async E=>{let B={retry:I,email:T,revoke:f.canRevoke===true&&u,convert:k};if(w.current||!R.current||!B[E])return;w.current=true,c(true),d(null);let x=v.current,A=i(()=>R.current&&x===v.current,"live");try{let z=E==="retry"?await o.retryRequest(e.id):E==="email"?await o.updateClinicEmail(e.id,b):E==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!A())return;if(!z.ok){d(z.error);return}if(z.value.id!==e.id||z.value.petRef!==e.petRef){d(W("internalError"));return}g({before:e.updatedAt,value:z.value}),l(""),m(!1),t();}catch{A()&&d(W("internalError"));}finally{w.current=false,A()&&c(false);}},"run");return {request:f,email:n,busy:a,error:s,canRetry:I,canUpdateEmail:T,canConvert:k,hasEmailEdit:h,confirmingRevoke:u&&f.canRevoke===true,emailInvalid:b.length>0&&!C,setEmail(E){w.current||(l(E),d(null));},retry:i(()=>_("retry"),"retry"),updateEmail:i(()=>_("email"),"updateEmail"),revoke:i(()=>_("revoke"),"revoke"),convert:i(()=>_("convert"),"convert"),askRevoke(){!w.current&&f.canRevoke===true&&m(true);},keepRequest(){w.current||m(false);}}}i(eu,"useRecordsRecovery");var Kg=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],Qg=["requested","awaiting_upload","records_received","processing","ready"],Xg=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],dn=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"}),Jg=Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records\u2026"}),Zs=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")}),qt=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"}),Zg=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"}),eb=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 tb(e){return e.wireStatus??eb[e.status]??"sent"}i(tb,"wireStatusOf");function rb(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(rb,"reminderProgressLabel");function nb(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(nb,"reachedRailIndex");function ob(e){switch(e.dispatchStatus){case "sent":return qt.delivered;case "preparing":case "queued":case "sending":return qt.emailing;case "failed":return qt.bounced;default:return null}}i(ob,"deliveryDetail");function ib(e,t){return rb(t,e.reminderCount??0)??qt.waiting}i(ib,"awaitingDetail");function ni(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(ni,"isOwnerSourcedRequest");function sb(e,t,r){let o=ni(t);switch(e){case "sent_to_clinic":return ob(t);case "awaiting_clinic":return ib(t,r);case "awaiting_upload":return qt.upload;case "records_received":return o?qt.ownerAdded:qt.clinicSent;case "processing":return qt.preparing;case "ready":return qt.ready;default:return null}}i(sb,"railDetail");function ab(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(ab,"tookReviewBranch");function lb(e,t,r){if(e.key!=="processing"||!ab(t,r))return [e];let o=r==="parsing_failed",n=r==="published",l=n?"done":o?"current":"done",a=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:dn.parsing_failed,detail:qt.parsingFailed,at:null,state:l},{key:"manual_review",title:dn.manual_review,detail:qt.manualReview,at:t.reviewStartedAt??null,state:a}]}i(lb,"expandProcessingPhase");function cb(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(cb,"convertedReachedIndex");function tu(e){return {key:"awaiting_clinic",title:qt.switchedTitle,detail:qt.switched,at:e.convertedToUploadAt??null,state:"done"}}i(tu,"convertedClinicSwitchEvent");function db(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(db,"ownerReachedIndex");function ub(e,t,r){switch(e){case "requested":return t.createdAt||null;case "awaiting_clinic":return t.lastReminderAt??null;case "processing":return t.parsingStartedAt??t.reviewStartedAt??null;case "ready":return r==="published"&&t.updatedAt||null;default:return null}}i(ub,"railTimestamp");function ru(e,t,r,o){return {key:e,title:dn[e],detail:sb(e,t,r),at:ub(e,t,r),state:o}}i(ru,"railEvent");function Er(e,t){return {key:e,title:dn[e],detail:Zg[e]??null,at:t.updatedAt||null,state:"failed"}}i(Er,"terminalEvent");function ea(e,t,r,o,n){return e.map((l,a)=>{let c=n?.(l)??null;if(c!==null)return c;let s=o==="published"||a<t?"done":a===t?"current":"upcoming";return ru(l,r,o,s)}).flatMap(l=>lb(l,r,o))}i(ea,"walkRail");function ta(e,t={}){return pb(mb(e),e,t.petName??null)}i(ta,"buildRequestTimeline");function pb(e,t,r){let o=t.source!=="owner_provided"&&!e.some(l=>l.key==="delivery_failed"),n=t.clinicEmail?.trim()??"";return e.map(l=>{if(l.title!==dn[l.key])return l;if(l.key==="ready")return {...l,title:Zs.added(ke(r))};if(!o)return l;let a=Jg[l.key]??l.title;return l.key==="sent_to_clinic"&&t.dispatchStatus==="sent"&&n.length>0?{...l,title:a,detail:Zs.notified(n)}:l.key==="records_received"&&!ni(t)?{...l,title:a,detail:Zs.received}:{...l,title:a}})}i(pb,"inArtifactWords");function mb(e){let t=tb(e),r=i(n=>ru(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),Er("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),tu(e),r("awaiting_upload"),r("records_received"),Er("processing_failed",e)]:ea(Xg,cb(t),e,t,n=>n==="awaiting_clinic"?tu(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),Er("processing_failed",e)];let n=db(t);return ea(Qg,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),Er("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),Er("clinic_no_records",e)];if(t==="failed"){let n=e.failureCode??null;return n==="no_response"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),Er("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),Er("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),Er("processing_failed",e)]:[r("requested"),Er("delivery_failed",e)]}let o=nb(t);return ea(Kg,o<0?1:o,e,t)}i(mb,"buildRailEvents");var gb=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),oi=28,bb="Now",ra=10;function si({request:e,petName:t}){let r=vb(),o=ta(e,{petName:t??null});return jsxRuntime.jsx(reactNative.View,{style:r.container,accessibilityRole:"summary",children:o.map((n,l)=>jsxRuntime.jsx(hb,{event:n,isLast:l===o.length-1,styles:r},n.key))})}i(si,"RequestTimeline");function hb({event:e,isLast:t,styles:r}){let o=e.at?re(e.at):null,n=[e.title,e.detail,o,gb[e.state]].filter(Boolean);return jsxRuntime.jsxs(reactNative.View,{style:r.row,accessible:true,accessibilityRole:"text",accessibilityLabel:n.join(", "),testID:`records-timeline-${e.key}`,children:[jsxRuntime.jsxs(reactNative.View,{style:r.railColumn,children:[jsxRuntime.jsx(Rb,{state:e.state,styles:r}),t?null:jsxRuntime.jsx(reactNative.View,{style:[r.connector,e.state==="done"&&r.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),jsxRuntime.jsxs(reactNative.View,{style:r.body,children:[jsxRuntime.jsxs(reactNative.View,{style:r.titleRow,children:[jsxRuntime.jsx(p,{style:[r.title,e.state==="current"&&r.titleCurrent,e.state==="failed"&&r.titleFailed,e.state==="upcoming"&&r.titleUpcoming],children:e.title}),e.state==="current"?jsxRuntime.jsx(reactNative.View,{style:r.now,children:jsxRuntime.jsx(p,{tier:"badge",style:r.nowText,children:bb})}):null,o?jsxRuntime.jsx(p,{style:r.date,children:o}):null]}),e.detail?jsxRuntime.jsx(p,{style:[r.detail,e.state==="upcoming"&&r.detailUpcoming],children:e.detail}):null]})]})}i(hb,"TimelineRow");function Rb({state:e,styles:t}){return e==="done"?jsxRuntime.jsx(reactNative.View,{style:[t.dot,t.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(p,{tier:"badge",style:[t.glyph,t.glyphOnBrand],children:"\u2713"})}):e==="failed"?jsxRuntime.jsx(reactNative.View,{style:[t.dot,t.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(p,{tier:"badge",style:t.glyph,children:"!"})}):e==="current"?jsxRuntime.jsx(reactNative.View,{style:[t.dot,t.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(reactNative.View,{style:t.dotCurrentCore})}):jsxRuntime.jsx(reactNative.View,{style:[t.dot,t.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Rb,"TimelineDot");function vb(){let e=V();return react.useMemo(()=>wb(e),[e])}i(vb,"useStyles");function wb(e){let{color:t,type:r}=e,{size:o}=r;return reactNative.StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:oi},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",gap:8},dot:{width:oi,height:oi,borderRadius:oi/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brandInk,backgroundColor:t.surface},dotCurrentCore:{width:ra,height:ra,borderRadius:ra/2,backgroundColor:t.success},now:{borderRadius:e.radius.pill,backgroundColor:t.scanButtonPink,paddingHorizontal:e.space.sm,paddingVertical:e.space.xs/2},nowText:{...S(e,"monoBold"),fontSize:o.tiny,lineHeight:o.tiny+4,letterSpacing:.6,color:t.onBubbleVet,textTransform:"uppercase"},dotUpcoming:{borderWidth:2,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},glyph:{...S(e,"bold"),fontSize:o.caption,lineHeight:o.caption+2,color:t.surface},glyphOnBrand:{color:t.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:t.borderHairlineGreen,marginVertical:2},connectorDone:{backgroundColor:t.brand},title:{flexShrink:1,...S(e,"bold"),fontSize:o.bodyTight,lineHeight:o.bodyTight+4,color:t.text.primary},titleCurrent:{color:t.brandInk},titleFailed:{color:t.danger},titleUpcoming:{color:t.text.muted,...S(e,"regular")},date:{marginLeft:"auto",...S(e,"regular"),fontSize:o.caption,lineHeight:o.caption+4,color:t.text.muted},detail:{...S(e,"regular"),fontSize:o.caption,lineHeight:o.caption+5,color:t.text.muted},detailUpcoming:{color:t.text.muted,opacity:.7}})}i(wb,"makeStyles");function pn(e,t,r){let o=qr(e,r);switch(o.kind){case "consent_required":return jsxRuntime.jsx(Eb,{onGrant:t});case "consent_unavailable":return jsxRuntime.jsx(Sb,{});case "session_required":return jsxRuntime.jsx(Tb,{});case "withheld":return jsxRuntime.jsx(kb,{});case "pet_not_found":case "error":return jsxRuntime.jsx(_b,{error:o.error,onRetry:e.refresh});default:return Ir(o)}}i(pn,"renderErrorFamily");function mn(e,t){return ()=>{let r=Hs(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(mn,"makeGrantHandler");function iu({records:e}){let t=$n(),r=e.uploadQueue;if(r.length===0)return null;let o=r.filter(a=>a.status!=="skipped"),n=o.filter(a=>a.status==="done").length,l=ri(Zd(r));return jsxRuntime.jsxs(reactNative.View,{style:t.timeline,testID:"records-upload-queue",children:[l!==null?jsxRuntime.jsx(p,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:t.errorText,children:l}):null,o.length>0?jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",accessibilityLabel:e.isUploading?Kr.uploading(n,o.length):Kr.uploaded(n,o.length),children:o.map(a=>{let c=Math.round(a.progress*100);return jsxRuntime.jsxs(reactNative.View,{style:t.uploadRow,testID:`records-upload-file-${a.status}`,children:[jsxRuntime.jsxs(reactNative.View,{style:t.uploadRowHead,children:[jsxRuntime.jsx(p,{style:t.rowLabel,children:a.name??""}),jsxRuntime.jsx(p,{style:t.rowValue,children:Jd(a)})]}),a.status==="uploading"?jsxRuntime.jsx(reactNative.View,{style:t.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:c},children:jsxRuntime.jsx(reactNative.View,{style:[t.progressFill,{width:`${c}%`}]})}):null,a.status==="failed"&&a.error?jsxRuntime.jsx(p,{style:t.timelineMeta,children:a.error.displayMessage}):null]},a.key)})}):null]})}i(iu,"UploadQueue");function Eb({onGrant:e}){let t=$n();return jsxRuntime.jsx(reactNative.View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:ve.consentRequired,children:jsxRuntime.jsx(reactNative.Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:ve.allow,style:t.primaryButton,children:jsxRuntime.jsx(p,{style:t.primaryLabel,children:ve.allow})})})}i(Eb,"ConsentRequiredState");function ia({label:e,glyph:t}){let r=$n();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(e);},[e]),jsxRuntime.jsxs(reactNative.View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:e,children:[jsxRuntime.jsx(reactNative.View,{style:t==="withheld"?r.withheldGlyph:r.emptyGlyph}),jsxRuntime.jsx(p,{style:r.errorText,children:e})]})}i(ia,"AlertState");function Sb(){return jsxRuntime.jsx(ia,{label:ve.consentRequired,glyph:"empty"})}i(Sb,"ConsentUnavailableState");function Tb(){return jsxRuntime.jsx(ia,{label:ve.sessionRequired,glyph:"empty"})}i(Tb,"SessionRequiredState");function kb(){return jsxRuntime.jsx(ia,{label:ve.recordUnavailable,glyph:"withheld"})}i(kb,"WithheldState");function _b({error:e,onRetry:t}){let r=$n();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(e.displayMessage);},[e.displayMessage]),jsxRuntime.jsxs(reactNative.View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[jsxRuntime.jsx(p,{style:r.errorText,children:e.displayMessage}),e.retryable?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:ve.retry,style:r.primaryButton,children:jsxRuntime.jsx(p,{style:r.primaryLabel,children:ve.retry})}):null]})}i(_b,"ErrorState");function su({call:e,prompt:t}){let r=$n(),o=t.trim().length>0?t:Un.fallbackPrompt;return jsxRuntime.jsxs(reactNative.View,{style:r.callCard,accessibilityRole:"summary",children:[jsxRuntime.jsx(p,{style:r.timelineLabel,children:Un.heading}),jsxRuntime.jsx(p,{style:r.timelineMeta,children:o}),jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{reactNative.Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:Un.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsxRuntime.jsx(p,{style:r.linkLabel,children:Un.call})})]})}i(su,"ClinicCallCard");function $n(){let e=V();return react.useMemo(()=>Pb(e),[e])}i($n,"useStyles");function Pb(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:a,lineHeight:c,letterSpacing:s}=n,d=dt(l.recordCard,reactNative.StyleSheet.hairlineWidth),u=yt(l.recordCard),m=i((b,C)=>Math.round(b*C),"lh"),y=reactNative.StyleSheet.hairlineWidth,g=r.xxl*3+r.xl,w=r.xxl+r.md,R=r.xxl+r.sm,v=e.brightness==="dark"?t.errorRed:t.danger,f={shadowColor:t.brand,shadowOffset:{width:0,height:r.xs},shadowRadius:r.sm,shadowOpacity:.08,elevation:r.xs};return reactNative.StyleSheet.create({container:{flex:1,minHeight:g,backgroundColor:t.background},body:{flex:1},centered:{minHeight:g,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:R,height:R,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:y,borderColor:t.brandBorder},withheldGlyph:{width:R,height:R,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:y,borderColor:t.cautionAccent},errorText:{...S(e,"regular"),fontSize:a.subtitle,lineHeight:m(a.subtitle,c.snug),color:v,textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:w,minWidth:w,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...f,...dt(l.primaryButton)},primaryLabel:{...S(e,"bold"),color:t.onPrimary,fontSize:a.body,letterSpacing:s.tight,...yt(l.primaryButton)},linkButton:{minHeight:w,minWidth:w,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...f,...dt(l.primaryButton)},linkLabel:{...S(e,"bold"),color:t.onPrimary,fontSize:a.body,letterSpacing:s.tight,...yt(l.primaryButton)},disabledButton:{minHeight:w,minWidth:w,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.surfaceSubtle,borderWidth:y,borderColor:t.brandBorder},disabledLabel:{...S(e,"bold"),color:t.text.muted,fontSize:a.body,letterSpacing:s.tight},list:{flex:1},listContent:{padding:r.lg,gap:r.md},timeline:{paddingVertical:r.md,paddingHorizontal:r.lg,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:y,borderColor:t.brandBorder,gap:r.xs,...f,...d},timelineTitle:{...S(e,"bold"),fontSize:a.heading,lineHeight:m(a.heading,c.snug),color:t.text.primary,letterSpacing:s.tight,...u},timelineLabel:{...S(e,"bold"),fontSize:a.subtitle,lineHeight:m(a.subtitle,c.snug),color:t.text.secondary,letterSpacing:s.tight,...u},callCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:y,borderColor:t.brandBorder,...d},timelineMeta:{...S(e,"regular"),fontSize:a.bodyTight,lineHeight:m(a.bodyTight,c.normal),color:t.text.muted,...u},recordBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:y,borderColor:t.brandBorder,...f,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:y,borderBottomColor:t.borderHairlineGreen},rowLabel:{...S(e,"regular"),fontSize:a.body,lineHeight:m(a.body,c.normal),color:t.text.muted,flexShrink:1,...u},rowValue:{...S(e,"medium"),fontSize:a.body,lineHeight:m(a.body,c.normal),color:t.text.primary,textAlign:"right",flexShrink:1,...u},disclaimer:{...S(e,"regular"),fontSize:a.caption,lineHeight:m(a.caption,c.normal),color:t.text.muted,marginTop:r.md},uploadRow:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:y,borderBottomColor:t.borderHairlineGreen},uploadRowHead:{flexDirection:"row",justifyContent:"space-between",gap:r.md},progressTrack:{height:r.xs,borderRadius:o.pill,backgroundColor:t.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:t.brand}})}i(Pb,"makeStyles");function sa(e){let{style:t,renderPending:r,...o}=Be(e,["onNavigate","onBack","onAsk"]);return jsxRuntime.jsx(Ue,{capability:"records",style:t,...r?{renderPending:r}:{},...$e(o.onBack,ot),children:jsxRuntime.jsx(Ab,{...o,style:t})})}i(sa,"EverfurRecordsRequests");function Ab({petRef:e,petName:t,controller:r,onNavigate:o,onBack:n,onAsk:l,style:a}){let c=Re(),s=aa(),d=mt(r?{petRef:e,controller:r}:{petRef:e}),u=react.useMemo(()=>Us(d.requests.filter(g=>g.petRef===e)),[d.requests,e]),m=l?g=>{let w=Ho(t,{clinicName:g.clinicName??null,statusLabel:Yr(g),status:g.status,heldItemCount:g.heldItemCount},g.id);l(w.prompt,w.entityRef);}:void 0,y;return d.status==="loading"&&u.length===0?y=jsxRuntime.jsx(So,{testID:"records-list-loading"}):d.status==="error"&&u.length===0?y=jsxRuntime.jsx(Xe,{variant:wt(d.error),message:d.error?.displayMessage,onAction:d.error?.retryable?d.refresh:void 0,testID:"records-list-error"}):u.length===0?y=jsxRuntime.jsx(Xe,{variant:"no_requests",testID:"records-list-empty"}):y=jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:s.list,testID:"records-list-results",children:u.map(g=>jsxRuntime.jsx(Ob,{request:g,onOpen:o?()=>o({name:"request",requestId:g.id}):void 0,onAsk:m?()=>m(g):void 0},g.id))}),jsxRuntime.jsxs(reactNative.View,{style:[c.root,a],children:[jsxRuntime.jsx(it,{title:St.title,onBack:n,testID:"records-list-header"}),u.length>0?jsxRuntime.jsx(p,{style:s.subtitle,testID:"records-list-subtitle",children:St.subtitle(t)}):null,jsxRuntime.jsx(reactNative.View,{style:c.body,children:y}),o?jsxRuntime.jsxs(reactNative.View,{style:s.footer,children:[jsxRuntime.jsx(X,{label:St.requestRecords,accessibilityLabel:St.requestRecordsA11y,onPress:()=>o({name:"clinicPicker"}),testID:"records-list-new"}),jsxRuntime.jsx(X,{label:St.uploadOwn,kind:"outline",accessibilityLabel:St.uploadOwnA11y,onPress:()=>o({name:"upload"}),testID:"records-list-upload-own"})]}):null,jsxRuntime.jsx(je,{})]})}i(Ab,"RequestsBody");function Ob({request:e,onOpen:t,onAsk:r}){let o=Re(),n=aa(),l=_d(e),a=Dd(e),c=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(reactNative.View,{style:[n.bubble,o.chipTones[a].bg],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsxs(reactNative.View,{style:n.copy,children:[jsxRuntime.jsx(p,{style:n.source,numberOfLines:1,children:l.source}),jsxRuntime.jsx(p,{style:n.meta,numberOfLines:1,children:l.meta}),jsxRuntime.jsx(reactNative.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(Lt,{label:l.status,tone:a})})]}),t?jsxRuntime.jsx(er,{}):null]});return jsxRuntime.jsxs(reactNative.View,{style:n.row,testID:`records-request-row-${e.id}`,children:[t?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:l.a11yLabel,style:n.rowInner,testID:`records-request-open-${e.id}`,children:c}):jsxRuntime.jsx(reactNative.View,{style:n.rowInner,accessible:true,accessibilityLabel:l.a11yLabel,children:c}),t&&Bs(null,e)!==null?jsxRuntime.jsx(X,{label:Me.cardTitle,onPress:t,testID:`records-request-resume-upload-${e.id}`}):null,r?jsxRuntime.jsx(X,{label:Xt.ask,kind:"ask",accessibilityLabel:St.askA11y(l.source),onPress:r,testID:`records-request-ask-${e.id}`}):null]})}i(Ob,"RequestRow");function Wn({requests:e,petName:t,activeOnly:r=false,onOpen:o}){let n=aa(),l=Pd(e,ke(t),{activeOnly:r});return l===null||o===void 0?null:jsxRuntime.jsxs(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:l.a11yLabel,style:n.card,testID:"records-requests-status",children:[jsxRuntime.jsx(reactNative.View,{style:[n.cardBubble,l.processing?n.cardBubbleProcessing:null],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsxs(reactNative.View,{style:n.cardText,children:[jsxRuntime.jsx(p,{style:n.cardTitle,children:l.title}),jsxRuntime.jsx(p,{style:n.cardSubtitle,children:l.subtitle})]}),jsxRuntime.jsx(er,{})]})}i(Wn,"RecordsRequestsStatusCard");function aa(){let e=V();return react.useMemo(()=>Lb(e),[e])}i(aa,"useLocalStyles");function Lb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((c,s)=>Math.round(c*s),"lh"),a=r.xxl+r.xs/2;return reactNative.StyleSheet.create({subtitle:{...S(e,"regular"),fontSize:n.size.caption,lineHeight:l(n.size.caption,n.lineHeight.normal),color:t.text.muted,paddingHorizontal:r.lg,paddingBottom:r.md},list:{paddingHorizontal:r.lg,paddingBottom:r.xl,gap:r.md},row:{borderRadius:o.lg,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},rowInner:{flexDirection:"row",alignItems:"center",gap:r.md},bubble:{width:a,height:a,borderRadius:a/2},copy:{flex:1,gap:r.xs+1},source:{...S(e,"bold"),fontSize:n.size.body,lineHeight:l(n.size.body,n.lineHeight.snug),color:t.text.primary},meta:{...S(e,"regular"),fontSize:n.size.tiny,lineHeight:l(n.size.tiny,n.lineHeight.normal),color:t.text.muted},footer:{paddingHorizontal:r.lg,paddingTop:r.sm+r.xs/2,paddingBottom:r.lg,gap:r.sm+r.xs/2,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},card:{flexDirection:"row",alignItems:"center",gap:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs,paddingVertical:r.md},cardBubble:{width:r.xl+r.xs/2,height:r.xl+r.xs/2,borderRadius:o.pill,borderWidth:2,borderColor:t.brandInk},cardBubbleProcessing:{borderColor:t.warningStrong,backgroundColor:t.badgeBgCaution},cardText:{flex:1,gap:2},cardTitle:{...S(e,"bold"),fontSize:n.size.bodyTight,lineHeight:l(n.size.bodyTight,n.lineHeight.snug),color:t.brandInk},cardSubtitle:{...S(e,"regular"),fontSize:n.size.caption,lineHeight:l(n.size.caption,n.lineHeight.normal),color:t.text.muted}})}i(Lb,"makeLocalStyles");var zb=i((e,t)=>e.getRecordDepth(t),"readDepth"),Nb=i(e=>!e.available,"depthEmpty");function ca(e){let{style:t,renderPending:r,...o}=Be(e,["onNavigate","onBack","onAsk"]);return jsxRuntime.jsx(Ue,{capability:"records",style:t,...r?{renderPending:r}:{},...$e(o.onBack,ot),children:jsxRuntime.jsx(Mb,{...o,style:t})})}i(ca,"EverfurRecordsDashboard");function Mb({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:a,style:c}){let s=Re(),d=di(),u=mt(r?{petRef:e,controller:r,readUploadFeatures:true}:{petRef:e,readUploadFeatures:true}),{runtime:m}=Te(),y=hn(u.uploadContentTypes)&&zo(m.registry.services.camera),g=Fs(e),w=nr(e,zb,Nb),[R,v]=react.useState(null),f=react.useCallback((H,N)=>v({marker:H,point:N}),[]),b=react.useMemo(()=>Gr(o,u.consent),[o,u.consent]),C=react.useMemo(()=>mn(u,o),[u,o]),h=Tn("recordsClinic"),I=h.enabled||h.isPending,T=g.markers?.markers??[],k=T.length>0,_=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,E=mo(u.requests,e),B=u.requests.filter(H=>H.petRef===e),x=n?()=>n({name:"requests"}):void 0,A=Ki({hasMarkers:k,requests:u.requests,petRef:e}),z=Qi({recordLoading:u.status==="loading",hasFullRecord:_,recordError:u.status==="error",markersLoading:g.status==="loading",markersError:g.status==="error",hasMarkers:k,requestsLoading:u.status==="loading",dashboardState:A,drivingRequest:E}),de=g.markers?.disclaimer??u.record?.disclaimer??"",G=i(()=>{u.refresh(),g.refresh(),w.refresh();},"retryAll"),ae=w.value!==null&&!w.value.withheld&&w.value.available?w.value:null,M=ke(t),$=a&&g.markers?.summary?()=>{let H=xd(t,g.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);a(H.prompt,H.entityRef);}:void 0,O=a?H=>{let N=wd(t,{canonicalName:H.name,markerId:H.markerId,latestValueText:H.latest?Vt(H.latest.value,H.unit,H.latest.qualitativeResult):null,statusText:H.latest?pr(H.latest.status).label:null,trajectoryText:nn(H.trajectory,H.points.length),meaningText:H.meaning});a(N.prompt,N.entityRef);}:void 0,U=a&&R?()=>{let{marker:H,point:N}=R,ie=Cd(t,{canonicalName:H.name,valueText:Vt(N.value,H.unit,N.qualitativeResult),collectedAt:re(N.at),sourceClinic:N.sourceClinic,referenceText:N.refLow!==null||N.refHigh!==null?Mo(N,H.unit):null,flagged:N.status==="above"?"above":N.status==="below"?"below":null,reviewed:N.reviewed,entityId:N.docId??H.markerId});v(null),a(ie.prompt,ie.entityRef);}:void 0,D=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[g.markers?.summary?jsxRuntime.jsx(reactNative.View,{style:s.inset,children:jsxRuntime.jsx(Vd,{summary:g.markers.summary,onAsk:$,testID:"dashboard-marker-summary"})}):null,jsxRuntime.jsx(p,{style:s.lead,children:vt.lead(t)}),jsxRuntime.jsx(Md,{markers:T,onPointPress:f,onAsk:O})]}),q=i(H=>n?jsxRuntime.jsxs(reactNative.View,{style:[s.inset,d.actions],children:[H?jsxRuntime.jsx(li,{label:vt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsxRuntime.jsx(li,{label:vt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"}),jsxRuntime.jsx(li,{label:St.allRequests,onPress:()=>n({name:"requests"}),testID:"dashboard-requests-action"})]}):null,"actions"),ee=i(H=>n?jsxRuntime.jsxs(reactNative.View,{style:[H?s.inset:null,d.addActions],testID:"dashboard-actions",children:[I?jsxRuntime.jsx(X,{label:Ot.requestFromClinic,accessibilityLabel:Ot.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.addCta,testID:"dashboard-actions-clinic"}):null,jsxRuntime.jsx(X,{label:Ot.uploadDocument,kind:"outline",accessibilityLabel:Ot.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.addCta,testID:"dashboard-actions-upload"})]}):null,"addActions"),J;if(u.status==="error"){let H=qr(u,b);J=H.kind==="error"||H.kind==="pet_not_found"?jsxRuntime.jsx(Xe,{variant:wt(H.error),message:H.error.displayMessage,onAction:H.error.retryable?G:void 0,testID:"dashboard-error"}):pn(u,C,b);}else switch(z){case "loading":J=jsxRuntime.jsx(Eo,{testID:"dashboard-loading"});break;case "record":J=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:s.contentTight,testID:"dashboard-record",children:[k?D:g.status==="error"?jsxRuntime.jsx(reactNative.View,{style:[s.inset,d.actions],children:jsxRuntime.jsx(li,{label:vt.retryMarkers,onPress:G,testID:"dashboard-markers-retry"})}):null,jsxRuntime.jsx(reactNative.View,{style:s.inset,children:u.record?jsxRuntime.jsx(ti,{record:u.record,depth:ae,petName:t,showLabs:!k,onNavigate:n,onAsk:a}):null}),jsxRuntime.jsx(reactNative.View,{style:s.inset,children:jsxRuntime.jsx(Wn,{requests:B,petName:t,activeOnly:true,onOpen:x})}),ee(true),q(true)]});break;case "error":J=jsxRuntime.jsx(Xe,{variant:wt(g.error??u.error),message:(g.error??u.error)?.displayMessage,onAction:(g.error??u.error)?.retryable?G:void 0,testID:"dashboard-error"});break;case "in_progress":J=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:s.content,testID:"dashboard-in-progress",children:[E?jsxRuntime.jsx(Hb,{request:E,petName:M,onOpen:n?()=>n({name:"request",requestId:E.id}):void 0,onAsk:a?()=>{let H=Ho(t,{clinicName:E.clinicName??null,statusLabel:Yr(E),status:E.status,heldItemCount:E.heldItemCount},E.id);a(H.prompt,H.entityRef);}:void 0}):null,jsxRuntime.jsx(Wn,{requests:B,petName:t,onOpen:x}),n?jsxRuntime.jsxs(reactNative.View,{style:d.ways,testID:"dashboard-ways",children:[I?jsxRuntime.jsx(du,{title:Xt.anotherClinic,sub:Xt.anotherClinicSub,onPress:()=>n({name:"clinicPicker"}),testID:"dashboard-way-clinic"}):null,jsxRuntime.jsx(du,{title:Ot.uploadDocument,...y?{sub:Xt.uploadDocumentPhotoSub}:{},accessibilityLabel:Ot.uploadDocumentA11y(t),dashed:true,onPress:()=>n({name:"upload"}),testID:"dashboard-way-upload"})]}):null,jsxRuntime.jsx(Fr,{disclaimer:de})]});break;case "none":J=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:s.content,testID:"dashboard-request-prompt",children:[jsxRuntime.jsxs(reactNative.View,{style:d.promptCard,children:[jsxRuntime.jsxs(reactNative.View,{style:d.promptHeader,children:[jsxRuntime.jsx(reactNative.View,{style:d.promptGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(p,{style:d.promptTitle,children:Ot.title(t)})]}),jsxRuntime.jsx(p,{style:d.promptBody,children:Ot.body}),n?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(X,{label:Ot.requestFromClinic,accessibilityLabel:Ot.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsxRuntime.jsx(X,{label:Ot.uploadDocument,kind:"outline",accessibilityLabel:Ot.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsxRuntime.jsx(Wn,{requests:B,petName:t,onOpen:x}),jsxRuntime.jsx(Fr,{disclaimer:de})]});break;case "labs_only":J=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:s.contentTight,testID:"dashboard-labs-only",children:[D,jsxRuntime.jsx(reactNative.View,{style:s.inset,children:jsxRuntime.jsx(Wn,{requests:B,petName:t,activeOnly:true,onOpen:x})}),ee(true),jsxRuntime.jsx(reactNative.View,{style:s.inset,children:jsxRuntime.jsx(Fr,{disclaimer:de})}),q(false)]});break;default:J=Ir(z);}return jsxRuntime.jsxs(reactNative.View,{style:[s.root,c],children:[jsxRuntime.jsx(it,{title:vt.titleNative(t),onBack:l,testID:"dashboard-header",right:n?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>n({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:vt.openTimeline,hitSlop:12,style:d.headerButton,testID:"dashboard-timeline-link",children:jsxRuntime.jsx(mc,{})}):void 0}),jsxRuntime.jsx(reactNative.View,{style:s.body,children:J}),jsxRuntime.jsx(Hd,{marker:R?.marker??null,point:R?.point??null,onClose:()=>v(null),onAsk:U}),jsxRuntime.jsx(je,{})]})}i(Mb,"DashboardBody");function li({label:e,onPress:t,testID:r}){let o=di();return jsxRuntime.jsxs(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:e,style:o.actionRow,testID:r,children:[jsxRuntime.jsxs(reactNative.View,{style:o.actionLeft,children:[jsxRuntime.jsx(reactNative.View,{style:o.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(p,{style:o.actionLabel,children:e})]}),jsxRuntime.jsx(er,{})]})}i(li,"ActionRow");function Hb({request:e,petName:t,onOpen:r,onAsk:o}){let n=Re(),l=di(),a=Xt.title(t),c=e.clinicName?.trim()??"",s=Yr(e),d=jsxRuntime.jsxs(reactNative.View,{style:l.inProgressInner,children:[jsxRuntime.jsxs(reactNative.View,{style:l.inProgressHead,children:[jsxRuntime.jsxs(reactNative.View,{style:l.inProgressHeadText,children:[jsxRuntime.jsx(p,{style:l.inProgressTitle,children:a}),c.length>0?jsxRuntime.jsx(p,{style:n.rowDetail,children:c}):null]}),r?jsxRuntime.jsx(er,{}):null]}),jsxRuntime.jsx(si,{request:e,petName:t}),s.length>0?jsxRuntime.jsx(reactNative.View,{style:n.statusCard,children:jsxRuntime.jsx(p,{style:n.statusText,children:s})}):null]});return jsxRuntime.jsxs(reactNative.View,{style:l.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:r?false:void 0,accessibilityLabel:r?void 0:Xt.a11y(t),children:[r?jsxRuntime.jsx(reactNative.Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Xt.openA11y(t,s),testID:"dashboard-in-progress-open",children:d}):d,o?jsxRuntime.jsx(X,{label:Xt.ask,kind:"ask",accessibilityLabel:Xt.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(Hb,"InProgressCard");function du({title:e,sub:t,accessibilityLabel:r,dashed:o=false,onPress:n,testID:l}){let a=di(),s=V().motion.reducedMotion;return jsxRuntime.jsxs(reactNative.Pressable,{onPress:n,accessibilityRole:"button",accessibilityLabel:r??(t?`${e}. ${t}`:e),style:({pressed:d})=>[a.way,o?a.wayDashed:null,d&&!s?{transform:[{scale:ho.pressScale}]}:null],testID:l,children:[jsxRuntime.jsxs(reactNative.View,{style:a.wayText,children:[jsxRuntime.jsx(p,{style:a.wayTitle,children:e}),t?jsxRuntime.jsx(p,{style:a.waySub,children:t}):null]}),jsxRuntime.jsx(er,{})]})}i(du,"WayCard");function di(){let e=V();return react.useMemo(()=>Bb(e),[e])}i(di,"useLocalStyles");function Bb(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,a=r.xxl+r.md;return reactNative.StyleSheet.create({headerButton:{width:a,height:a,alignItems:"center",justifyContent:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},actionIcon:{width:r.lg+r.xs/2,height:r.lg+r.xs/2,borderRadius:o.xs,backgroundColor:t.brandSoft,borderWidth:l,borderColor:t.brandBorder},actionLabel:{flex:1,...S(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},inProgressCard:{borderRadius:o.lg,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,padding:r.lg,gap:r.lg},inProgressHeadText:{flex:1,gap:r.xs/2},ways:{gap:r.sm},way:{flexDirection:"row",alignItems:"center",gap:r.md,borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surface,padding:r.lg},wayDashed:{borderStyle:"dashed",borderColor:t.brandBorderStrong},wayText:{flex:1,gap:r.xs/2},wayTitle:{...S(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},waySub:{...S(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted},inProgressInner:{gap:r.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},inProgressTitle:{...S(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),letterSpacing:-0.4,color:t.brandInk},promptCard:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.borderRingCream,paddingHorizontal:r.lg+r.xs,paddingVertical:r.lg+r.xs/2},promptHeader:{flexDirection:"row",alignItems:"center",gap:r.xs+1},promptGlyph:{width:r.xl+1,height:r.xl+1,borderRadius:o.xs,borderWidth:2,borderColor:t.warningStrong},promptTitle:{flex:1,...S(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),letterSpacing:n.letterSpacing.headerBrand,color:t.brandInk},promptBody:{marginTop:r.sm-1,...S(e,"regular"),fontSize:n.size.bodyTight,lineHeight:r.lg+r.xs,color:t.text.primary},promptCta:{marginTop:r.sm-1,minHeight:r.xxl+r.sm},promptCtaSecondary:{marginTop:r.sm,minHeight:r.xxl+r.sm},addActions:{gap:r.sm},addCta:{minHeight:r.xxl+r.sm}})}i(Bb,"makeLocalStyles");var ui=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function pu(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(pu,"toMillis");function mu(e){let t=[...e.visits.map((r,o)=>({key:`visit-${o}-${r.visitId}`,kind:"visit",kindLabel:be.kind.visit,at:r.visitDate,date:re(r.visitDate),title:r.summary??be.clinicVisit,detail:r.veterinarian?be.doctor(r.veterinarian):null,docId:r.docId})),...e.vaccines.map((r,o)=>{let n=[];return r.lot&&n.push(be.lot(r.lot)),r.expiresOn&&n.push(be.expires(re(r.expiresOn))),{key:`vaccine-${o}-${r.vaccineId}`,kind:"vaccine",kindLabel:be.kind.vaccine,at:r.administeredOn,date:re(r.administeredOn),title:r.product||be.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}}),...e.weights.map((r,o)=>({key:`weight-${o}-${r.weightId}`,kind:"weight",kindLabel:be.kind.weight,at:r.observedOn,date:re(r.observedOn),title:xc(r.weightKg),detail:null,docId:r.docId})),...e.medications.map((r,o)=>{let n=[r.dose,r.route,r.frequency].filter(l=>!!l);return {key:`medication-${o}-${r.medicationId}`,kind:"medication",kindLabel:be.kind.medication,at:r.startedOn,date:re(r.startedOn),title:r.drugName||be.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}})];return Object.freeze(t.sort((r,o)=>{let n=pu(r.at),l=pu(o.at);return n===null&&l===null?ui[r.kind]-ui[o.kind]:n===null?1:l===null?-1:l!==n?l-n:ui[r.kind]-ui[o.kind]}))}i(mu,"buildTimelineRows");var Yb=300,Kb=i((e,t)=>e.getTimeline(t),"readTimeline"),Qb=i(e=>e.isEmpty,"timelineEmpty");var Xb=i(e=>e.contributions.length===0,"contributionsEmpty");function gu({petRef:e,style:t,onBack:r}){let o=nr(e,Kb,Qb);return jsxRuntime.jsx(hu,{state:o,style:t,onBack:r,header:jsxRuntime.jsx(it,{title:be.timeline,onBack:En(r),testID:"timeline-header"}),loading:jsxRuntime.jsx(Dc,{testID:"timeline-loading"}),empty:jsxRuntime.jsx(Xe,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsxRuntime.jsx(eh,{timeline:n})})}i(gu,"EverfurRecordsTimeline");function bu({petRef:e,docId:t,style:r,onBack:o}){let n=react.useCallback((c,s)=>c.getDocumentContributions(s,t),[t]),l=nr(e,n,Xb,t),a=l.value?.document?.title?.trim()||be.uploadedDocument;return jsxRuntime.jsx(hu,{state:l,style:r,onBack:o,header:jsxRuntime.jsx(it,{title:a,onBack:En(o),testID:"contributions-header"}),empty:jsxRuntime.jsx(Xe,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsxRuntime.jsx(th,{view:c})})}i(bu,"EverfurDocumentContributions");function hu({state:e,style:t,header:r,loading:o,empty:n,render:l,onBack:a}){let c=da();return jsxRuntime.jsx(Ue,{capability:"records",style:t,...$e(En(a),ot),children:jsxRuntime.jsxs(reactNative.View,{style:[c.container,t],children:[r??null,jsxRuntime.jsx(reactNative.View,{style:c.body,children:Jb(e,l,c,o,n)}),jsxRuntime.jsx(je,{})]})})}i(hu,"DepthSurface");function Jb(e,t,r,o,n){switch(e.status){case "loading":return o??jsxRuntime.jsx(Zb,{styles:r});case "empty":return n??jsxRuntime.jsx(reactNative.View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:ve.empty,children:jsxRuntime.jsx(reactNative.View,{style:r.emptyGlyph})});case "error":return e.error?jsxRuntime.jsx(Xe,{variant:wt(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:t(e.value);default:return null}}i(Jb,"renderState");function Zb({styles:e}){let[t,r]=react.useState(false);return react.useEffect(()=>{let o=setTimeout(()=>r(true),Yb);return ()=>clearTimeout(o)},[]),jsxRuntime.jsx(reactNative.View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:ve.loading,children:t?jsxRuntime.jsx(reactNative.ActivityIndicator,{}):null})}i(Zb,"LoadingState");function eh({timeline:e}){let t=da(),r=mu(e);return jsxRuntime.jsxs(reactNative.ScrollView,{style:t.list,contentContainerStyle:t.timelineContent,accessibilityLabel:be.timeline,children:[e.disclaimer.length>0?jsxRuntime.jsx(reactNative.View,{style:t.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:vt.important(e.disclaimer),children:jsxRuntime.jsx(p,{style:t.timelineBandText,children:e.disclaimer})}):null,r.map((o,n)=>jsxRuntime.jsxs(reactNative.View,{children:[n>0?jsxRuntime.jsx(reactNative.View,{style:t.timelineSeparator}):null,jsxRuntime.jsxs(reactNative.View,{style:t.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${o.kind}`,children:[jsxRuntime.jsx(reactNative.View,{style:t.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsxs(reactNative.View,{style:t.timelineBody,children:[jsxRuntime.jsxs(reactNative.View,{style:t.topLine,children:[jsxRuntime.jsx(p,{style:t.timelineKind,children:o.kindLabel}),jsxRuntime.jsx(p,{style:t.date,children:o.date})]}),jsxRuntime.jsx(p,{style:t.timelineTitle,children:o.title}),o.detail?jsxRuntime.jsx(p,{style:t.rowDetail,children:o.detail}):null]})]})]},o.key))]})}i(eh,"TimelineBody");function th({view:e}){let t=da();return jsxRuntime.jsxs(reactNative.ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:ve.records,children:[e.document?.receivedAt?jsxRuntime.jsx(p,{style:t.rowDetail,children:re(e.document.receivedAt)}):null,jsxRuntime.jsx(reactNative.View,{style:t.card,children:e.contributions.map(r=>jsxRuntime.jsxs(reactNative.View,{style:t.row,accessible:true,accessibilityRole:"text",children:[jsxRuntime.jsx(p,{style:t.rowTitle,children:r.label}),jsxRuntime.jsx(p,{style:t.rowValue,children:rn(r.value,r.unit)}),r.observedAt?jsxRuntime.jsx(p,{style:t.rowDetail,children:re(r.observedAt)}):null]},r.key))})]})}i(th,"ContributionsBody");function da(){let e=V();return react.useMemo(()=>rh(e),[e])}i(da,"useStyles");function rh(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:a,lineHeight:c}=n,s=i((v,f)=>Math.round(v*f),"lh"),d=reactNative.StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,m=r.xxl+r.md,y=e.brightness==="dark"?t.errorRed:t.danger,g=yt(l.recordCard),w=i((v,f,b,C="regular")=>({...S(e,C),fontSize:v,lineHeight:s(v,f),color:b}),"text"),R=i((v,f,b,C="regular")=>({...w(v,f,b,C),...g}),"inCard");return reactNative.StyleSheet.create({container:{flex:1,minHeight:u,backgroundColor:t.background},body:{flex:1},centered:{minHeight:u,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:r.xxl+r.sm,height:r.xxl+r.sm,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},errorText:{...w(a.subtitle,c.snug,y),textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:m,minWidth:m,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...dt(l.primaryButton)},primaryLabel:{...S(e,"bold"),color:t.onPrimary,fontSize:a.body,...yt(l.primaryButton)},list:{flex:1},listContent:{padding:r.lg,gap:r.md},section:{gap:r.sm},heading:{...w(a.heading,c.snug,t.text.primary,"bold")},card:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:d,borderColor:t.brandBorder,...dt(l.recordCard,d)},row:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:d,borderBottomColor:t.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:r.md},kindLabel:{...R(a.caption,c.normal,t.text.muted,"medium")},date:R(a.caption,c.normal,t.text.muted),rowTitle:{...R(a.body,c.normal,t.text.primary,"bold")},rowValue:{...R(a.body,c.normal,t.text.primary,"medium")},rowDetail:R(a.bodyTight,c.normal,t.text.muted),rowMuted:{...R(a.bodyTight,c.normal,t.text.muted),opacity:.7},chip:{...w(a.caption,c.normal,t.text.primary),alignSelf:"flex-start",paddingHorizontal:r.sm,paddingVertical:r.xs,borderRadius:o.pill},chipNeutral:{backgroundColor:t.badgeBgNeutral},chipCaution:{backgroundColor:t.badgeBgCaution},chipCritical:{backgroundColor:t.badgeBgCritical},disclaimer:{...w(a.caption,c.normal,t.text.muted),marginTop:r.md},timelineContent:{paddingBottom:r.xxl},timelineBand:{flexDirection:"row",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft,marginHorizontal:r.lg,marginTop:r.xs,marginBottom:r.md},timelineBandText:{flex:1,...w(a.caption,c.normal,t.text.secondary)},timelineSeparator:{height:d,backgroundColor:t.brandBorder,marginLeft:ms},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBubble:{width:r.xxl+r.xs/2,height:r.xxl+r.xs/2,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},timelineBody:{flex:1,gap:r.xs-1},timelineKind:{...S(e,"mono"),fontSize:a.micro,lineHeight:a.bodyTight,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:t.text.secondary},timelineTitle:{...w(a.body,c.normal,t.text.primary,"medium")}})}i(rh,"makeStyles");function ua(e,t={}){let r=xr(),{userRef:o}=Te(),n=t.now??Date.now,[l,a]=react.useState(null),[c,s]=react.useState(true),[d,u]=react.useState(null),[m,y]=react.useState(null),g=m===true,[w,R]=react.useState({}),[v,f]=react.useState(false),[b,C]=react.useState(null),[h,I]=react.useState(false),[T,k]=react.useState(false),[_,E]=react.useState(false),[B,x]=react.useState(null),A=B!==null&&B.client===r?B.value:Mt,z=A.shareAudiences,de=no(e),G=react.useRef(0),ae=react.useRef(true),M=react.useCallback(async()=>{let ie=G.current+=1;if(s(true),u(null),o===null){a(null),s(false);return}let Ce=await r.listShares(e);ie!==G.current||!ae.current||(Ce.ok?(a(Ce.value),y(true)):Cr(Ce.error)?(a(null),y(false)):(a(null),u(Ce.error),Ru(Ce)&&y(true)),s(false));},[r,e,o]);react.useEffect(()=>(ae.current=true,M(),()=>{ae.current=false,G.current+=1;}),[M]),react.useEffect(()=>{if(o===null||r.readFeatures===void 0)return;let ie=true;return r.readFeatures().then(Ce=>{ie&&x({client:r,value:Ce});},()=>{}),()=>{ie=false;}},[r,o]);let $=react.useRef(de);react.useEffect(()=>{$.current!==de&&($.current=de,R({}),k(true),M());},[de,M]);let O=react.useCallback(async ie=>{f(true);let Le=await(ie!==void 0&&z.some(rt=>rt.audience===ie)?r.createShare(e,{audience:ie}):r.createShare(e));return ae.current&&(f(false),Le.ok?(R(rt=>({...rt,[Le.value.shareId]:Le.value.shareUrl})),M()):Cr(Le.error)?y(false):ar(Le.error)&&k(true)),Le},[r,e,M,z]),U=react.useCallback(async ie=>{E(true);let Ce=await r.emailShare(e,ie);return ae.current&&(E(false),Ce.ok?M():Cr(Ce.error)?y(false):ar(Ce.error)?k(true):Ce.error.httpStatus===502&&M()),Ce},[r,e,M]),D=react.useCallback(async ie=>{C(ie);let Ce=await r.revokeShare(e,ie);return ae.current&&(C(null),M()),Ce},[r,e,M]),q=react.useCallback(async()=>{I(true);let ie=await r.getPdfLink(e);return ae.current&&(I(false),!ie.ok&&ar(ie.error)&&k(true)),ie},[r,e]),ee=react.useCallback(()=>{k(false),M();},[M]),J=react.useMemo(()=>kc(l??[],w,n()),[l,w,n]),H=c?"loading":d!==null?"error":J.length===0?"empty":"populated",N=A.features;return react.useMemo(()=>({status:H,rows:J,available:g,consentRequired:T,error:d,creating:v,revokingId:b,preparingPdf:h,shareAudiences:z,features:N,sending:_,createLink:O,sendEmail:U,revoke:D,pdfLink:q,refresh:ee}),[H,J,g,T,d,v,b,h,z,N,_,O,U,D,q,ee])}i(ua,"useRecordShares");function Ru(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(Ru,"answeredBehindGate");function vu(e){return e.available||e.status!=="empty"}i(vu,"sharesListShown");function pa(e){let t=xr(),{userRef:r}=Te(),o=react.useMemo(()=>({}),[t,e,r]),[n,l]=react.useState({scope:o,lit:null});react.useEffect(()=>{if(r===null)return;let c=true;return t.listShares(e).then(s=>{c&&(!s.ok&&Cr(s.error)?l({scope:o,lit:false}):Ru(s)&&l({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[t,e,r,o]);let a=n.scope===o?n.lit:null;return react.useMemo(()=>({lit:a}),[a])}i(pa,"useRecordsDepthProbe");function ma(e){let t=xr(),o=pa(e).lit===true,[n,l]=react.useState(false),[a,c]=react.useState(null),s=react.useRef(true);react.useEffect(()=>(s.current=true,()=>{s.current=false;}),[]);let d=react.useCallback(async()=>{l(true),c(null);let u=await t.getPdfLink(e);return s.current&&(l(false),u.ok||c(u.error)),u},[t,e]);return react.useMemo(()=>({preparing:n,available:o,error:a,pdfLink:d}),[n,o,a,d])}i(ma,"useRecordPdfLink");async function xu(e){await reactNative.Share.share({message:j.shareMessage(e),url:e});}i(xu,"shareLinkViaOs");async function mi(e){await reactNative.Share.share(reactNative.Platform.OS==="ios"?{url:e}:{message:e});}i(mi,"shareFileLinkViaOs");var zt=ne.document,Su=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),ah=i((e,t)=>e.getRecordDepth(t),"readDepth"),lh=i(e=>!e.available,"depthEmpty");function ya(e){let{style:t,renderPending:r,...o}=Be(e,["onBack"]);return jsxRuntime.jsx(Ue,{capability:"records",style:t,...r?{renderPending:r}:{},...$e(o.onBack,ot),children:jsxRuntime.jsx(dh,{...o,style:t})})}i(ya,"EverfurRecordDocument");function ch(e,t){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(t===null||t.labResults.length===0&&t.physicalExams.length===0&&t.clinicianNotes.length===0)}i(ch,"documentIsEmpty");function dh({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:l,style:a}){let c=Re(),s=Tu(),d=V(),u=mt(r?{petRef:e,controller:r}:{petRef:e}),m=nr(e,ah,lh),y=ma(e),g=react.useMemo(()=>Gr(o,u.consent),[o,u.consent]),w=react.useMemo(()=>mn(u,o),[u,o]),R=m.value!==null&&!m.value.withheld&&m.value.available?m.value:null,v=u.record,[f,b]=react.useState(false),C=i(()=>{b(false),y.pdfLink().then(T=>{if(!T.ok)return;Ar(l??(_=>mi(_)),T.value.downloadUrl,"record_pdf").then(_=>{!_.ok&&!l&&b(true);});});},"download"),h,I=false;if(u.status==="loading"||m.status==="loading"&&v!==null)h=jsxRuntime.jsx(reactNative.View,{style:s.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:vt.loading,testID:"record-document-loading",children:jsxRuntime.jsx(reactNative.ActivityIndicator,{color:d.color.brandInk})});else if(u.status==="error"){let T=qr(u,g);h=T.kind==="error"||T.kind==="pet_not_found"?jsxRuntime.jsx(Xe,{variant:wt(T.error),message:T.error.displayMessage,onAction:T.error.retryable?()=>{u.refresh(),m.refresh();}:void 0,testID:"record-document-error"}):pn(u,w,g);}else v===null||ch(v,R)?h=jsxRuntime.jsx(reactNative.View,{style:s.centered,testID:"record-document-empty",children:jsxRuntime.jsx(p,{style:s.emptyText,children:zt.empty})}):(I=true,h=jsxRuntime.jsx(uh,{record:v,depth:R,petName:t,wordmark:d.meta.displayName}));return jsxRuntime.jsxs(reactNative.View,{style:[c.root,s.root,a],children:[jsxRuntime.jsx(it,{title:zt.titleFor(t),variant:"document",onBack:n,testID:"record-document-header",right:y.available&&I?jsxRuntime.jsx(reactNative.Pressable,{onPress:C,disabled:y.preparing,accessibilityRole:"button",accessibilityLabel:zt.download,accessibilityState:{disabled:y.preparing,busy:y.preparing},hitSlop:8,style:s.download,testID:"record-document-download",children:y.preparing?jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:d.color.brandInk}):jsxRuntime.jsx(gc,{})}):void 0}),y.error?jsxRuntime.jsx(p,{style:[c.errorText,s.inset],accessibilityRole:"alert",children:y.error.displayMessage}):f?jsxRuntime.jsx(p,{style:[c.errorText,s.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:j.toasts.pdfShareSheet}):null,jsxRuntime.jsx(reactNative.View,{style:c.body,children:h}),jsxRuntime.jsx(je,{})]})}i(dh,"DocumentBody");function uh({record:e,depth:t,petName:r,wordmark:o}){let n=Tu(),l=react.useMemo(()=>{let s=[],d=new Map;for(let y of e.entities){let g=y.category.trim();if(g.length===0)continue;let w=d.get(g);w===void 0?(s.push(g),d.set(g,[y])):w.push(y);}let u=Su.filter(y=>s.includes(y)),m=s.filter(y=>!Su.includes(y));return [...u,...m].map(y=>({type:y,rows:d.get(y)??[]}))},[e.entities]),a=Date.now(),c=i((s,d,u)=>jsxRuntime.jsxs(reactNative.View,{style:n.section,testID:u,children:[jsxRuntime.jsxs(reactNative.View,{style:n.sectionHeader,children:[jsxRuntime.jsx(p,{style:n.sectionTitle,accessibilityRole:"header",children:s}),jsxRuntime.jsx(reactNative.View,{style:n.rule})]}),jsxRuntime.jsx(reactNative.View,{children:d})]},u),"section");return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:n.page,showsVerticalScrollIndicator:false,testID:"record-document",children:[jsxRuntime.jsxs(reactNative.View,{style:n.letterhead,children:[jsxRuntime.jsx(p,{style:n.wordmark,children:o}),jsxRuntime.jsx(p,{style:n.docTitle,children:zt.docTitle}),jsxRuntime.jsx(p,{style:n.petName,children:r?.trim()||zt.namelessPet}),jsxRuntime.jsx(p,{style:n.generated,children:zt.generated(e.generatedAt)})]}),e.identity.length>0?c(zt.identity,e.identity.map((s,d)=>jsxRuntime.jsxs(reactNative.View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxRuntime.jsx(p,{style:n.rowLabel,children:s.label}),jsxRuntime.jsx(p,{style:n.rowValue,children:s.value})]},`${d}:${s.label}`)),"record-document-identity"):null,t&&t.labResults.length>0?c(zt.labs,t.labResults.map((s,d)=>{let u=pr(s.latest.status),m=Sc(s.points[s.points.length-1]??null),y=Vt(s.latest.value,s.latest.unit??s.unit,s.latest.qualitativeResult);return jsxRuntime.jsxs(reactNative.View,{style:[n.row,u.outOfRange?n.rowFlag:null,d>0?n.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:n.rowMain,children:[jsxRuntime.jsx(p,{style:n.rowLabel,children:s.name}),jsxRuntime.jsxs(p,{style:n.rowMeta,children:[m?zt.ref(m):zt.noRange,s.latest.at?` \xB7 ${re(s.latest.at)}`:""]})]}),jsxRuntime.jsxs(reactNative.View,{style:n.rowRight,children:[y!=="-"?jsxRuntime.jsx(p,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:y}):null,jsxRuntime.jsx(p,{style:[n.markerStatus,u.outOfRange?n.rowValueAlert:null],children:u.label})]})]},s.markerId)}),"record-document-labs"):null,l.map(({type:s,rows:d})=>c(vr(s),d.map((u,m)=>{let y=[rn(u.value,u.unit),u.observedAt?re(u.observedAt):null].filter(g=>g&&g.length>0).join(" \xB7 ");return jsxRuntime.jsx(reactNative.View,{style:[n.row,m>0?n.rowDivider:null],children:jsxRuntime.jsxs(reactNative.View,{style:n.rowMain,children:[jsxRuntime.jsx(p,{style:n.rowLabel,children:u.label}),y?jsxRuntime.jsx(p,{style:n.rowMeta,children:y}):null]})},u.key)}),`record-document-${s}`)),e.forwardLooking.length>0?c(zt.upcomingCare,e.forwardLooking.map((s,d)=>{let u=Dn(s.dueAt,a);return jsxRuntime.jsxs(reactNative.View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:n.rowMain,children:[jsxRuntime.jsx(p,{style:n.rowLabel,children:s.title}),s.detail?jsxRuntime.jsx(p,{style:n.rowMeta,children:s.detail}):null]}),u?jsxRuntime.jsx(p,{style:[n.rowValue,u.overdue?n.rowValueAlert:null],children:u.label}):null]},`${s.title}-${d}`)}),"record-document-upcoming"):null,t&&t.physicalExams.length>0?c(zt.physicalExams,t.physicalExams.map((s,d)=>jsxRuntime.jsxs(reactNative.View,{style:[n.block,d>0?n.rowDivider:null],children:[s.observedOn?jsxRuntime.jsx(p,{style:n.blockDate,children:re(s.observedOn)}):null,s.systems.filter(u=>u.finding).map(u=>jsxRuntime.jsxs(reactNative.View,{style:n.fieldRow,children:[jsxRuntime.jsx(p,{style:n.fieldLabel,children:Hr(u.system)}),jsxRuntime.jsx(p,{style:n.fieldValue,children:u.finding})]},u.system))]},s.examId)),"record-document-exams"):null,t&&t.clinicianNotes.length>0?c(zt.clinicianNotes,t.clinicianNotes.map((s,d)=>jsxRuntime.jsxs(reactNative.View,{style:[n.block,d>0?n.rowDivider:null],children:[s.observedOn?jsxRuntime.jsx(p,{style:n.blockDate,children:re(s.observedOn)}):null,s.sections.filter(u=>u.text).map((u,m)=>jsxRuntime.jsxs(reactNative.View,{style:n.noteSection,children:[jsxRuntime.jsx(p,{style:n.noteLabel,children:on(u.section)}),jsxRuntime.jsx(p,{style:n.noteBody,children:u.text})]},`${u.section}-${m}`))]},s.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsxRuntime.jsx(reactNative.View,{style:n.disclaimer,children:jsxRuntime.jsx(p,{style:n.disclaimerText,children:e.disclaimer})}):null]})}i(uh,"RecordDocument");function Tu(){let e=V();return react.useMemo(()=>ph(e),[e])}i(Tu,"useLocalStyles");function ph(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,a=i((s,d,u,m="regular")=>({...S(e,m),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text"),c=i((s,d)=>({...S(e,"mono"),fontSize:s,lineHeight:s+r.xs-1,color:d,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"mono");return reactNative.StyleSheet.create({root:{backgroundColor:t.surface},inset:{paddingHorizontal:r.lg},download:{width:r.xxl+r.xs+r.xs/2,height:r.xxl+r.xs+r.xs/2,borderRadius:o.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xxl,minHeight:r.xxl*3+r.xl},emptyText:{...a(n.size.body,n.lineHeight.normal,t.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:r.lg+r.xs,paddingBottom:r.xxl+r.lg},letterhead:{alignItems:"center",paddingTop:r.md,paddingBottom:r.lg+r.xs+r.xs/2,borderBottomWidth:2,borderBottomColor:t.brandInk,gap:r.xs+r.xs/2,marginBottom:r.sm},wordmark:{...a(n.size.heading,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...c(n.size.caption,t.brandInk),marginTop:r.sm+r.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:a(n.size.verdict+r.xs/2,n.lineHeight.tight,t.text.primary),generated:{...c(n.size.tiny,t.text.muted),textTransform:"none"},section:{marginTop:r.lg+r.xs+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2,marginBottom:r.sm},sectionTitle:c(n.size.tiny,t.brandInk),rule:{flex:1,height:l,backgroundColor:t.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.md+r.xs/2,paddingVertical:r.sm+1},rowDivider:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen},rowFlag:{backgroundColor:t.badgeBgCritical,marginHorizontal:-r.sm,paddingHorizontal:r.sm,borderRadius:o.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:r.xs/2},rowLabel:{flexShrink:1,...a(n.size.body,n.lineHeight.normal,t.text.primary,"medium")},rowValue:{...a(n.size.body,n.lineHeight.normal,t.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:t.danger},rowMeta:{marginTop:r.xs/2,...S(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},markerStatus:c(n.size.micro,t.text.muted),block:{paddingVertical:r.sm+r.xs/2},blockDate:{...c(n.size.tiny,t.text.muted),marginBottom:r.xs+r.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md+r.xs/2,paddingVertical:r.xs-1},fieldLabel:{width:120,...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted,"medium")},fieldValue:{flex:1,...a(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")},noteSection:{marginTop:r.sm},noteLabel:{...c(n.size.tiny,t.brandInk),marginBottom:r.xs/2},noteBody:a(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),disclaimer:{marginTop:o.xl,paddingTop:r.md+r.xs/2,borderTopWidth:l,borderTopColor:t.borderHairlineGreen},disclaimerText:a(n.size.tiny,n.lineHeight.relaxed,t.text.muted)})}i(ph,"makeLocalStyles");function _u({petRef:e,petName:t,onClose:r,onNavigate:o,onOpenUrl:n,onCopy:l}){let a=bh(),c=Re(),s=ua(e),[d,u]=react.useState(null),[m,y]=react.useState(null),[g,w]=react.useState("vet"),[R,v]=react.useState(""),f=s.available&&!s.consentRequired,b=s.shareAudiences.length>0,C=s.shareAudiences.find(x=>x.audience===g)??null,h=C!==null?Tc(C,s.features):[],I=i((x,A)=>{let z=n??((G,ae)=>ae==="share_link"?xu(G):mi(G)),de=A==="share_link"?j.toasts.shareSheet:j.toasts.pdfShareSheet;Ar(z,x,A).then(G=>{G.ok||u(de);});},"open"),T=i(()=>{u(null),s.createLink(b?g:void 0).then(x=>{x.ok?I(x.value.shareUrl,"share_link"):u(An(x.error,"create"));});},"onCreateLink"),k=i(()=>{if(s.sending)return;u(null);let x=R.trim();if(x.length===0){u(j.addEmailFor(t));return}if(!Xn(x)){u(j.emailInvalid);return}s.sendEmail({recipientEmail:x,recipientKind:g}).then(A=>{A.ok?(v(""),u(j.toasts.sentTo(x))):u(An(A.error,"email"));});},"onSend"),_=i(()=>{u(null),s.pdfLink().then(x=>{x.ok?I(x.value.downloadUrl,"record_pdf"):u(An(x.error,"download"));});},"onDownload"),E=i(x=>{if(!l||x.shareUrl===null)return;let A=x.shareUrl;Ar(l,A).then(z=>u(z.ok?j.toasts.copiedNative:j.toasts.copyFailedNative(A)));},"onCopyRow"),B=i(x=>{s.revoke(x).then(A=>{y(null),u(A.ok?j.toasts.turnedOff:An(A.error,"revoke"));});},"onConfirmRevoke");return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:r,children:jsxRuntime.jsxs(reactNative.View,{style:a.backdrop,children:[jsxRuntime.jsx(reactNative.Pressable,{style:Xo,accessibilityRole:"button",accessibilityLabel:j.closeSheetA11y,onPress:r}),jsxRuntime.jsxs(reactNative.View,{style:a.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[jsxRuntime.jsx(reactNative.View,{style:a.handle}),jsxRuntime.jsxs(reactNative.View,{style:a.header,children:[jsxRuntime.jsxs(reactNative.View,{style:a.headerText,children:[jsxRuntime.jsx(p,{style:a.title,accessibilityRole:"header",children:j.titleFor(t)}),jsxRuntime.jsx(p,{style:a.helper,children:b?j.leadNative:j.helper})]}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:j.close,onPress:r,hitSlop:12,style:a.closeButton,testID:"share-record-close",children:jsxRuntime.jsx(p,{style:a.closeGlyph,children:"\xD7"})})]}),jsxRuntime.jsxs(reactNative.ScrollView,{style:a.scroll,contentContainerStyle:a.body,showsVerticalScrollIndicator:false,children:[jsxRuntime.jsxs(reactNative.View,{style:a.actions,children:[f?jsxRuntime.jsxs(reactNative.View,{style:a.form,testID:"share-email-form",children:[jsxRuntime.jsx(p,{style:a.fieldLabel,children:j.audienceLabel}),jsxRuntime.jsx(reactNative.View,{style:a.choices,accessibilityRole:"radiogroup",accessibilityLabel:j.audienceLabel,children:Zr.map(x=>{let A=g===x;return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>w(x),accessibilityRole:"radio",accessibilityLabel:j.audiences[x],accessibilityState:{checked:A,selected:A},style:[a.choice,A?a.choiceOn:null],testID:`share-audience-${x}`,children:jsxRuntime.jsx(p,{style:A?a.choiceTitleOn:a.choiceTitle,children:j.audiences[x]})},x)})}),b&&h.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.included,testID:"share-included",children:[jsxRuntime.jsx(p,{style:a.fieldLabel,children:j.included}),h.map(x=>jsxRuntime.jsxs(reactNative.View,{style:a.includedRow,children:[jsxRuntime.jsx(p,{style:a.includedLine,accessibilityElementsHidden:true,importantForAccessibility:"no",children:"\u2022"}),jsxRuntime.jsx(p,{style:[a.includedLine,a.includedText],testID:`share-included-line-${x}`,children:x})]},x))]}):null,o?jsxRuntime.jsx(X,{label:j.previewNative,onPress:()=>{r(),o({name:"document"});},testID:"share-view-document"}):null,jsxRuntime.jsx(p,{style:a.fieldLabel,children:j.sendTo}),jsxRuntime.jsx(reactNative.TextInput,{accessibilityLabel:j.sendTo,style:a.field,value:R,placeholder:j.sendToPlaceholder,placeholderTextColor:a.placeholder.color,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,autoComplete:"email",maxLength:wi,editable:!s.sending,returnKeyType:"send",onChangeText:v,onSubmitEditing:k,testID:"share-email-input"}),jsxRuntime.jsx(X,{label:s.sending?j.sending:j.send,busy:s.sending,onPress:k,testID:"share-email-send"})]}):o?jsxRuntime.jsx(X,{label:j.previewNative,onPress:()=>{r(),o({name:"document"});},testID:"share-view-document"}):null,f?jsxRuntime.jsx(X,{label:s.creating?j.creatingLink:j.shareLinkNative,kind:"outline",busy:s.creating,onPress:T,testID:"share-create-link"}):null,f?jsxRuntime.jsx(X,{label:s.preparingPdf?j.preparingPdf:j.downloadPdf,kind:"outline",busy:s.preparingPdf,onPress:_,testID:"share-download-pdf"}):null,f?jsxRuntime.jsx(p,{style:a.terms,testID:"share-link-terms",children:j.linkTerms}):null]}),s.consentRequired?jsxRuntime.jsxs(reactNative.View,{style:a.stateCard,testID:"share-consent-off",children:[jsxRuntime.jsx(p,{style:a.stateTitle,accessibilityRole:"header",children:j.consentOffTitle}),jsxRuntime.jsx(p,{style:a.stateBody,children:j.consentOffBody}),jsxRuntime.jsx(X,{label:j.retry,kind:"outline",onPress:s.refresh,testID:"share-consent-retry"})]}):null,d?jsxRuntime.jsx(p,{style:a.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:d}):null,vu(s)?jsxRuntime.jsxs(reactNative.View,{style:a.section,children:[jsxRuntime.jsx(p,{style:a.sectionLabel,accessibilityRole:"header",children:j.activeLinks}),s.status==="loading"?jsxRuntime.jsx(Oc,{testID:"share-record-loading"}):s.status==="error"?jsxRuntime.jsxs(reactNative.View,{style:a.stateCard,testID:"share-record-error",children:[jsxRuntime.jsx(p,{style:a.stateTitle,children:j.errorTitle}),jsxRuntime.jsx(p,{style:a.stateBody,children:j.errorBody}),jsxRuntime.jsx(X,{label:j.retry,kind:"outline",onPress:s.refresh,testID:"share-record-retry"})]}):s.rows.length===0?jsxRuntime.jsxs(reactNative.View,{style:a.stateCard,testID:"share-record-empty",children:[jsxRuntime.jsx(p,{style:a.stateTitle,children:j.emptyTitle}),jsxRuntime.jsx(p,{style:a.stateBody,children:j.emptyBody})]}):jsxRuntime.jsx(reactNative.View,{style:a.list,children:s.rows.map(x=>jsxRuntime.jsxs(reactNative.View,{style:a.row,testID:`share-row-${x.shareId}`,children:[jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:x.a11yLabel,children:[jsxRuntime.jsxs(reactNative.View,{style:a.statusLine,children:[jsxRuntime.jsx(reactNative.View,{style:[a.statusDot,{backgroundColor:x.active?a.active.color:a.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(p,{style:a.status,children:x.statusLabel}),jsxRuntime.jsx(p,{style:a.expiry,children:x.expiryLabel})]}),x.createdLabel?jsxRuntime.jsx(p,{style:a.created,children:x.createdLabel}):null]}),x.shareUrl!==null&&!l?jsxRuntime.jsx(p,{selectable:true,style:a.url,testID:`share-url-${x.shareId}`,children:x.shareUrl}):null,m===x.shareId?jsxRuntime.jsxs(reactNative.View,{style:a.confirm,testID:`share-revoke-confirm-${x.shareId}`,children:[jsxRuntime.jsx(p,{style:a.confirmText,children:j.confirmTurnOff}),jsxRuntime.jsxs(reactNative.View,{style:a.rowActions,children:[jsxRuntime.jsx(X,{label:s.revokingId===x.shareId?j.turningOff:j.turnOff,kind:"danger",busy:s.revokingId===x.shareId,onPress:()=>B(x.shareId),testID:`share-revoke-do-${x.shareId}`}),jsxRuntime.jsx(X,{label:j.keep,kind:"outline",disabled:s.revokingId===x.shareId,onPress:()=>y(null),testID:`share-revoke-cancel-${x.shareId}`})]})]}):jsxRuntime.jsxs(reactNative.View,{style:a.rowActions,children:[l?jsxRuntime.jsx(X,{label:j.copyLink,kind:"outline",disabled:x.shareUrl===null,accessibilityLabel:j.copyLinkA11y(x.actionContext),onPress:()=>E(x),testID:`share-copy-${x.shareId}`}):null,jsxRuntime.jsx(X,{label:j.turnOff,kind:"danger",accessibilityLabel:j.turnOffA11y(x.actionContext),onPress:()=>y(x.shareId),testID:`share-ask-revoke-${x.shareId}`})]})]},x.shareId))})]}):null]}),jsxRuntime.jsx(reactNative.View,{style:c.inset})]})]})})}i(_u,"ShareSheet");function bh(){let e=V();return react.useMemo(()=>hh(e),[e])}i(bh,"useStyles");function hh(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,a=reactNative.StyleSheet.hairlineWidth,c=i((s,d,u,m="regular")=>({...S(e,m),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text");return reactNative.StyleSheet.create({active:{color:t.success},inactive:{color:t.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),terms:{...c(n.size.caption,n.lineHeight.normal,t.text.muted),textAlign:"center"},closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),scroll:{flexGrow:0},body:{gap:r.lg,paddingBottom:r.sm},actions:{gap:r.sm},form:{gap:r.sm,paddingBottom:r.sm},fieldLabel:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.secondary,"medium")},choices:{flexDirection:"row",gap:r.sm},choice:{flex:1,minHeight:l,alignItems:"center",justifyContent:"center",paddingHorizontal:r.sm,borderRadius:o.md,borderWidth:a,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},choiceOn:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:t.brandSoft},choiceTitle:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"medium")},choiceTitleOn:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},included:{gap:r.xs},includedRow:{flexDirection:"row",gap:r.sm},includedLine:c(n.size.bodyTight,n.lineHeight.normal,t.text.primary),includedText:{flex:1},field:{...c(n.size.body,n.lineHeight.normal,t.text.primary),minHeight:l,paddingHorizontal:r.md,borderRadius:o.sm,borderWidth:a,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},placeholder:{color:t.text.placeholder},notice:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.secondary),padding:r.md,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft},section:{gap:r.sm},sectionLabel:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},stateCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.brandBorder},stateTitle:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},stateBody:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),list:{gap:r.md},row:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.brandBorder},statusLine:{flexDirection:"row",alignItems:"center",gap:r.sm},statusDot:{width:r.sm,height:r.sm,borderRadius:r.xs},status:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.primary,"bold")},expiry:{...c(n.size.caption,n.lineHeight.normal,t.text.muted)},created:c(n.size.tiny,n.lineHeight.normal,t.text.muted),url:{...c(n.size.caption,n.lineHeight.normal,t.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},confirm:{gap:r.sm},confirmText:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")}})}i(hh,"makeStyles");var wh=i((e,t)=>e.getRecordDepth(t),"readDepth"),xh=i(e=>!e.available,"depthEmpty");function ha(e){let{style:t,renderPending:r,...o}=Be(e,["onNavigate","onBack","onAsk"]);return jsxRuntime.jsx(Ue,{capability:"records",style:t,...r?{renderPending:r}:{},...$e(o.onBack,ot),children:jsxRuntime.jsx(Ch,{...o,style:t})})}i(ha,"EverfurRecordDetail");function Ch({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:a,onOpenUrl:c,onCopy:s,style:d}){let u=Re(),m=Eh(),y=mt(r?{petRef:e,controller:r}:{petRef:e}),g=nr(e,wh,xh),w=Gs(e),R=pa(e),[v,f]=react.useState(false),b=react.useMemo(()=>Gr(o,y.consent),[o,y.consent]),C=react.useMemo(()=>mn(y,o),[y,o]),h=g.value!==null&&!g.value.withheld&&g.value.available?g.value:null,I=y.record,T=i(()=>{y.refresh(),g.refresh();},"retry"),k=n!==void 0||R.lit===true,_;if(y.status==="loading"||g.status==="loading"&&I!==null&&!I.isEmpty)_=jsxRuntime.jsx(Eo,{testID:"everfur-record-loading"});else if(y.status==="error"){let E=qr(y,b);_=E.kind==="error"||E.kind==="pet_not_found"?jsxRuntime.jsx(Xe,{variant:wt(E.error),message:E.error.displayMessage,onAction:E.error.retryable?T:void 0,testID:"everfur-record-error"}):pn(y,C,b);}else if(I===null||I.isEmpty){let E=h?.completeness?.documentsInReview??0;_=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsxRuntime.jsx(Xe,{variant:"no_records",message:E>0?ne.inReview(E):void 0}),jsxRuntime.jsx(Fr,{disclaimer:I?.disclaimer??""})]});}else _=jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:m.content,testID:"everfur-record",children:jsxRuntime.jsx(ti,{record:I,depth:h,petName:t,onNavigate:n,onAsk:a,factEdit:w})});return jsxRuntime.jsxs(reactNative.View,{style:[u.root,d],children:[jsxRuntime.jsx(it,{title:ne.title,onBack:l,testID:"everfur-record-header",right:k||n?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[n?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>n({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:ne.requestClinicsA11y,hitSlop:8,style:m.share,testID:"everfur-record-request-clinics",children:jsxRuntime.jsx(fc,{})}):null,k?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>f(true),accessibilityRole:"button",accessibilityLabel:j.openA11yFor(t),hitSlop:8,style:m.share,testID:"everfur-record-share",children:jsxRuntime.jsx(yc,{})}):null]}):void 0}),jsxRuntime.jsx(reactNative.View,{style:u.body,children:_}),v?jsxRuntime.jsx(_u,{petRef:e,petName:t,onClose:()=>f(false),onNavigate:n,...c?{onOpenUrl:c}:{},...s?{onCopy:s}:{}}):null,jsxRuntime.jsx(je,{})]})}i(Ch,"RecordBody");function Eh(){let e=V();return react.useMemo(()=>Sh(e),[e])}i(Eh,"useLocalStyles");function Sh(e){let{space:t,radius:r}=e;return reactNative.StyleSheet.create({content:{paddingHorizontal:t.lg,paddingBottom:t.xxl+t.sm,gap:t.lg+t.xs},share:{width:t.xxl+t.sm,height:t.xxl+t.sm,borderRadius:r.pill,alignItems:"center",justifyContent:"center"}})}i(Sh,"makeLocalStyles");function Au(e,t){let r=V(),[o,n]=react.useState(false),l=react.useCallback(()=>{n(true),e().finally(()=>n(false));},[e]);return jsxRuntime.jsx(reactNative.RefreshControl,{refreshing:o,onRefresh:l,tintColor:r.color.brandInk,colors:[r.color.brandInk],testID:t})}i(Au,"useRecordsPullToRefresh");function Ra(e){let{style:t,renderPending:r,...o}=Be(e,["onNavigate","onBack"]);return jsxRuntime.jsx(Ue,{capability:"records",style:t,...r?{renderPending:r}:{},...$e(o.onBack,ot),children:jsxRuntime.jsx(Oh,{...o,style:t})})}i(Ra,"EverfurRecordsUpload");function Oh({petRef:e,petName:t,controller:r,onPickDocument:o,onPickPhotos:n,uploadTransport:l,onNavigate:a,onBack:c,style:s}){let d=Re(),u=Fu(),{runtime:m}=Te(),y=mt(r?{petRef:e,controller:r,readUploadFeatures:true}:l?{petRef:e,uploadTransport:l,readUploadFeatures:true}:{petRef:e,readUploadFeatures:true}),g=Hn(o)&&(r!==void 0||l!==void 0||to(m.registry.services.uploadTransport));return jsxRuntime.jsxs(reactNative.View,{style:[d.root,s],children:[jsxRuntime.jsx(it,{title:"",onBack:c,testID:"upload-header"}),jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:u.content,testID:"upload-screen",children:[jsxRuntime.jsxs(reactNative.View,{style:u.header,children:[jsxRuntime.jsx(reactNative.View,{style:u.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(p,{style:u.title,accessibilityRole:"header",children:Me.screenTitle}),jsxRuntime.jsx(p,{style:u.subtitle,children:Me.subtitle(t)})]}),jsxRuntime.jsx(va,{records:y,requestId:null,onPickDocument:o,onPickPhotos:n,canUpload:g,onDone:a?w=>a({name:"request",requestId:w}):void 0})]}),jsxRuntime.jsx(je,{})]})}i(Oh,"UploadBody");function va({records:e,requestId:t,onPickDocument:r,onPickPhotos:o,canUpload:n,onDone:l}){let a=Re(),c=Fu(),{runtime:s}=Te(),d=s.registry.services.camera,u=e.uploadContentTypes,m=hn(u),y=m&&zo(d),g=m&&o!==void 0,w=y||g,[R,v]=react.useState(null),[f,b]=react.useState(0),C=react.useRef(t),h=react.useRef([]),I=e.uploadQueue.filter(G=>G.status!=="skipped"),T=I.filter(G=>G.status==="done").length,k=I.filter(G=>G.status==="failed").length,_=!e.isUploading&&f>0,E=react.useCallback(async G=>{let{uploadable:ae,skipped:M}=gl(G,u),$=ri(M,w);if(ae.length===0){$!==null&&v($);return}v($);let O=C.current;if(O===null){let D=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!D.ok){v(Me.errors.start);return}O=D.value.id,C.current=O;}b(D=>D+1);let U=await e.uploadDocuments(O,ae);h.current=U.flatMap((D,q)=>D.status==="failed"&&ae[q]!==void 0?[ae[q]]:[]);},[e,u,w]),B=react.useCallback(G=>{!G||!n||Ar(G).then(ae=>{if(!ae.ok){v(Me.errors.startPlain);return}let M=ae.value;M!==null&&E(Array.isArray(M)?M:[M]);});},[n,E]),x=react.useCallback(()=>{B(r);},[B,r]),A=react.useCallback(()=>{B(o);},[B,o]),z=react.useCallback(()=>{!y||!n||Ar(()=>d.capture(hd("photo"))).then(G=>{if(!G.ok)return;let ae=bd(G.value);if(ae.sizeBytes===void 0){v(Me.errors.startPlain);return}E([ae]);});},[d,y,n,E]),de=react.useCallback(()=>{E(h.current);},[E]);return jsxRuntime.jsxs(reactNative.View,{style:c.card,testID:"records-upload-card",children:[jsxRuntime.jsx(p,{style:c.cardTitle,accessibilityRole:"header",children:Me.cardTitle}),jsxRuntime.jsx(p,{style:c.cardSubtitle,children:w?or.note:Me.cardSubtitle}),R?jsxRuntime.jsx(reactNative.View,{style:a.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(p,{style:a.errorText,children:R})}):null,jsxRuntime.jsx(iu,{records:e}),e.isUploading?jsxRuntime.jsx(reactNative.View,{style:c.uploadingRow,children:jsxRuntime.jsx(p,{style:c.progressText,children:Me.uploading(T,I.length)})}):_?jsxRuntime.jsxs(reactNative.View,{style:c.settled,children:[T>0?jsxRuntime.jsx(p,{style:c.success,accessibilityRole:"alert",children:Me.received(T)}):null,k>0?jsxRuntime.jsx(X,{label:Me.retryFailed(k),kind:"link",accessibilityLabel:Me.retryFailedA11y(k),onPress:de,testID:"records-upload-retry-failed"}):null,jsxRuntime.jsx(p,{style:c.cardTitle,accessibilityRole:"header",children:Me.haveMore}),w?jsxRuntime.jsx(p,{style:c.cardSubtitle,children:or.haveMoreLead}):null,jsxRuntime.jsxs(reactNative.View,{style:c.settledActions,children:[jsxRuntime.jsx(X,{label:Me.addMore,kind:"link",accessibilityLabel:Me.addMoreA11y,disabled:!n,onPress:x,testID:"records-upload-another"}),l&&C.current!==null&&T>0?jsxRuntime.jsx(X,{label:Me.done,accessibilityLabel:Me.doneA11y,onPress:()=>l(C.current),testID:"records-upload-done"}):null]})]}):w?jsxRuntime.jsxs(reactNative.View,{style:c.actions,children:[y?jsxRuntime.jsxs(reactNative.View,{style:c.action,children:[jsxRuntime.jsx(X,{label:or.takePhoto,kind:"outline",accessibilityLabel:Xd(or.takePhoto,or.takePhotoMeta),disabled:!n,onPress:z,testID:"records-upload-take-photo"}),jsxRuntime.jsx(p,{style:c.actionMeta,children:or.takePhotoMeta})]}):null,g?jsxRuntime.jsx(reactNative.View,{style:c.action,children:jsxRuntime.jsx(X,{label:or.choosePhotos,kind:"outline",disabled:!n,onPress:A,testID:"records-upload-choose-photos"})}):null,jsxRuntime.jsxs(reactNative.View,{style:c.action,children:[jsxRuntime.jsx(X,{label:Me.chooseFiles,accessibilityLabel:Me.chooseFilesA11y,disabled:!n,onPress:x,testID:"records-upload-choose"}),jsxRuntime.jsx(p,{style:c.actionMeta,children:or.chooseFileMeta})]})]}):jsxRuntime.jsx(X,{label:Me.chooseFiles,accessibilityLabel:Me.chooseFilesA11y,disabled:!n,onPress:x,testID:"records-upload-choose"})]})}i(va,"UploadRecordCard");function Fu(){let e=V();return react.useMemo(()=>Lh(e),[e])}i(Fu,"useLocalStyles");function Lh(e){let{color:t,space:r,radius:o,type:n}=e,l=i((a,c,s,d="regular")=>({...S(e,d),fontSize:a,lineHeight:Math.round(a*c),color:s}),"text");return reactNative.StyleSheet.create({content:{padding:r.lg+r.xs,gap:r.lg+r.xs},header:{gap:r.sm,alignItems:"center"},iconBubble:{width:r.xxl+r.lg+r.xs,height:r.xxl+r.lg+r.xs,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...l(n.size.heading+r.xs/2,n.lineHeight.snug,t.brandInk,"bold"),textAlign:"center"},subtitle:{...l(n.size.body,n.lineHeight.normal,t.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:o.lg,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,padding:r.lg,gap:r.md},cardTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},cardSubtitle:l(n.size.bodyTight,n.lineHeight.normal,t.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:r.sm},progressText:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.secondary)},settled:{gap:r.sm},success:l(n.size.bodyTight,n.lineHeight.normal,t.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:r.sm},actions:{gap:r.md},action:{gap:r.xs},actionMeta:l(n.size.bodyTight,n.lineHeight.normal,t.text.muted)})}i(Lh,"makeLocalStyles");function xa(e){let{style:t,renderPending:r,...o}=Be(e,["onNavigate","onBack"]);return jsxRuntime.jsx(Ue,{capability:"records",style:t,...r?{renderPending:r}:{},...$e(o.onBack,ot),children:jsxRuntime.jsx(Hh,{...o,style:t})})}i(xa,"EverfurRecordsRequest");function Hh({petRef:e,petName:t,requestId:r,controller:o,onPickDocument:n,onPickPhotos:l,uploadTransport:a,onNavigate:c,onBack:s,style:d,nowMs:u}){let m=Re(),{runtime:y,userRef:g,scopeEpoch:w}=Te(),R=mt(o?{petRef:e,controller:o,readUploadFeatures:true}:a?{petRef:e,uploadTransport:a,readUploadFeatures:true}:{petRef:e,readUploadFeatures:true}),v=R.requests.find(I=>I.id===r)??null,f=Hn(n)&&(o!==void 0||a!==void 0||to(y.registry.services.uploadTransport)),b=v?Uo(v):"",C=Au(R.refresh,"records-request-refresh"),h;return R.status==="loading"&&v===null?h=jsxRuntime.jsx(So,{testID:"records-request-loading"}):R.status==="error"&&R.error?h=jsxRuntime.jsx(Xe,{variant:wt(R.error),message:R.error.displayMessage,onAction:R.error.retryable?R.refresh:void 0,testID:"records-request-error"}):v===null?h=jsxRuntime.jsx(Xe,{variant:"no_requests",testID:"records-request-missing"}):g===null?h=jsxRuntime.jsx(Xe,{variant:"error",testID:"records-request-error"}):h=jsxRuntime.jsx(Bh,{petName:t,request:v,records:R,canUpload:f,onPickDocument:n,onPickPhotos:l,onNavigate:c,nowMs:u,refreshControl:C},JSON.stringify([g,w,v.id])),jsxRuntime.jsxs(reactNative.View,{style:[m.root,d],children:[jsxRuntime.jsx(it,{title:b,onBack:s,testID:"records-request-header"}),jsxRuntime.jsx(reactNative.KeyboardAvoidingView,{behavior:"padding",style:m.body,children:h}),jsxRuntime.jsx(je,{})]})}i(Hh,"RequestBody");function Bh({petName:e,request:t,records:r,canUpload:o,onPickDocument:n,onPickPhotos:l,onNavigate:a,nowMs:c,refreshControl:s}){let d=Re(),u=Uh(),m=V(),y=eu({request:t,onRecovered:r.refresh,canUpload:o},Zt()),[g,w]=react.useState(null),[R,v]=react.useState(false),[f,b]=react.useState(null),C=react.useRef(true);react.useEffect(()=>(C.current=true,()=>{C.current=false;}),[]);let h=y.request,I=c??Date.now(),T=h.status==="published",k=h.status==="published"||h.status==="failed"||h.status==="revoked",_=Ji(h),E=h.wireStatus==="clinic_responded_no_records",B=zl(h,I),x=Xi(h,I),A=k?null:h.waitingExpectation?.trim()||null,z=jo(h),de=Nl(h),G=y.canConvert,ae=k&&!T,M=y.error!==null&&g!==null&&g!=="start"?g==="revoke"?fe.errors.cancel:fe.errors[g]:null,$=i((J,H)=>{w(J),H();},"run"),O=i(()=>{R||(v(true),b(null),r.createRequest(`records-upload-${Date.now().toString(36)}`).then(J=>{if(C.current){if(v(false),!J.ok){b(fe.errors.start);return}a?.({name:"request",requestId:J.value.id});}}));},"startFresh"),U=h.clinicName?.trim()??"",D=!ni(h)&&U.length>0,q=D&&(h.status==="requested"||h.status==="awaiting_clinic"),ee=re(h.createdAt);return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:u.content,keyboardShouldPersistTaps:"handled",refreshControl:s,testID:`records-request-${h.id}`,children:[q?jsxRuntime.jsxs(reactNative.View,{style:u.sent,testID:"records-request-sent",children:[jsxRuntime.jsx(p,{style:u.cardTitle,accessibilityRole:"header",children:fe.sentTitle}),jsxRuntime.jsx(p,{style:d.bodyText,children:fe.sentLeadNative(ke(e))})]}):null,jsxRuntime.jsxs(reactNative.View,{style:u.card,testID:"records-request-where",children:[jsxRuntime.jsx(p,{style:u.cardTitle,accessibilityRole:"header",children:fe.whereItStands}),jsxRuntime.jsx(si,{request:h,petName:e})]}),D?jsxRuntime.jsxs(reactNative.View,{style:u.card,testID:"records-request-details",children:[jsxRuntime.jsx(p,{style:u.cardTitle,accessibilityRole:"header",children:fe.details}),jsxRuntime.jsxs(reactNative.View,{style:u.detailRow,children:[jsxRuntime.jsx(p,{style:d.muted,children:fe.detailsClinic}),jsxRuntime.jsx(p,{style:u.detailValue,children:U})]}),ee!=="-"?jsxRuntime.jsxs(reactNative.View,{style:u.detailRow,children:[jsxRuntime.jsx(p,{style:d.muted,children:fe.detailsSent}),jsxRuntime.jsx(p,{style:u.detailValue,children:ee})]}):null]}):null,h.status==="awaiting_upload"?jsxRuntime.jsx(va,{records:r,requestId:h.id,onPickDocument:n,onPickPhotos:l,canUpload:o}):null,h.statusLabel.length>0?jsxRuntime.jsx(reactNative.View,{style:d.statusCard,accessibilityRole:"summary",children:jsxRuntime.jsx(p,{style:d.statusText,children:h.statusLabel})}):null,A&&!B?jsxRuntime.jsx(reactNative.View,{style:d.infoNote,accessibilityRole:"summary",children:jsxRuntime.jsx(p,{style:d.infoNoteText,children:A})}):h.wireStatus==="awaiting_response"&&!B?jsxRuntime.jsx(reactNative.View,{style:d.infoNote,accessibilityRole:"summary",children:jsxRuntime.jsx(p,{style:d.infoNoteText,children:fe.awaitingNote})}):null,B?jsxRuntime.jsx(reactNative.View,{style:d.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsxRuntime.jsx(p,{style:d.cautionNoteText,children:fe.waitingBanner(x)})}):null,T&&a?jsxRuntime.jsx(X,{label:fe.viewRecords,onPress:()=>a({name:"dashboard"}),style:u.readyCta,testID:"records-request-view-dashboard"}):null,de?jsxRuntime.jsxs(reactNative.View,{style:[u.failureCard,_?u.failureCritical:u.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsxRuntime.jsx(p,{style:[u.failureTitle,_?u.failureTitleCritical:u.failureTitleCaution],children:ql(h)}),h.canUpdateClinicEmail!==true&&h.canRetrySend!==true?jsxRuntime.jsx(p,{style:d.rowDetail,children:fe.nextStep}):null,h.canUpdateClinicEmail===true?jsxRuntime.jsxs(reactNative.View,{style:u.emailBlock,children:[jsxRuntime.jsx(p,{style:d.fieldLabel,children:Wt.email}),jsxRuntime.jsx(Qe,{style:d.field,accessibilityLabel:Wt.email,placeholder:Wt.emailPlaceholder,placeholderTextColor:m.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:y.email,editable:!y.busy,onChangeText:y.setEmail,testID:"records-failure-clinic-email"}),y.emailInvalid?jsxRuntime.jsx(p,{style:d.errorText,accessibilityRole:"alert",children:fe.errors.invalidEmail}):null,jsxRuntime.jsx(X,{label:Wt.updateEmail,accessibilityLabel:Wt.updateEmailA11y,disabled:!y.canUpdateEmail,busy:y.busy&&g==="email",onPress:()=>$("email",y.updateEmail),testID:"records-failure-update-email"})]}):null,h.canRetrySend===true?jsxRuntime.jsx(X,{label:Wt.retry,kind:"outline",accessibilityLabel:Wt.retryA11y,disabled:!y.canRetry,busy:y.busy&&g==="retry",onPress:()=>$("retry",y.retry),testID:"records-failure-retry-send"}):null,h.canRetrySend===true&&y.hasEmailEdit?jsxRuntime.jsx(p,{style:d.rowDetail,children:Wt.retryHint}):null,M&&(g==="email"||g==="retry")?jsxRuntime.jsx(reactNative.View,{style:d.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(p,{style:d.errorText,children:M})}):null]}):null,(_||E)&&a?jsxRuntime.jsx(X,{label:fe.tryAnotherClinic,kind:"outline",accessibilityLabel:fe.tryAnotherClinicA11y,onPress:()=>a({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,z!==null?jsxRuntime.jsxs(reactNative.View,{style:u.callBlock,children:[jsxRuntime.jsx(su,{call:z,prompt:h.statusLabel}),h.canRetrySend===true?jsxRuntime.jsx(X,{label:y.busy&&g==="retry"?fe.resending:fe.resend,kind:"outline",accessibilityLabel:y.busy&&g==="retry"?fe.resendingA11y:fe.resendA11y,disabled:!y.canRetry,onPress:()=>$("retry",y.retry),testID:"records-resend-authorization"}):null]}):null,G?jsxRuntime.jsxs(reactNative.View,{style:u.block,children:[jsxRuntime.jsx(X,{label:y.busy&&g==="convert"?fe.converting:fe.convert,busy:y.busy&&g==="convert",onPress:()=>$("convert",y.convert),testID:"records-convert-upload"}),jsxRuntime.jsx(p,{style:d.muted,children:fe.convertHint}),M&&g==="convert"?jsxRuntime.jsx(reactNative.View,{style:d.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(p,{style:d.errorText,children:M})}):null]}):null,ae?jsxRuntime.jsxs(reactNative.View,{style:u.block,children:[jsxRuntime.jsx(X,{label:R?fe.freshUploadStarting:fe.freshUpload,kind:_||E?"outline":"primary",busy:R,onPress:O,testID:"records-upload-own-fresh"}),f?jsxRuntime.jsx(reactNative.View,{style:d.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(p,{style:d.errorText,children:f})}):null]}):null,M&&g==="revoke"?jsxRuntime.jsx(reactNative.View,{style:d.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(p,{style:d.errorText,children:M})}):null,h.canRevoke===true?y.confirmingRevoke?jsxRuntime.jsxs(reactNative.View,{style:u.block,testID:"records-revoke-confirm",children:[jsxRuntime.jsx(p,{style:u.confirmTitle,accessibilityRole:"header",children:Wt.cancelQuestion}),jsxRuntime.jsx(p,{style:d.bodyText,children:Wt.cancelConsequence}),jsxRuntime.jsx(X,{label:y.busy&&g==="revoke"?fe.cancelling:fe.cancel,kind:"danger",accessibilityLabel:y.busy&&g==="revoke"?fe.cancellingA11y:fe.cancelA11y,busy:y.busy&&g==="revoke",onPress:()=>$("revoke",y.revoke),testID:"records-revoke-do"}),jsxRuntime.jsx(X,{label:Wt.keepRequest,kind:"outline",disabled:y.busy,onPress:y.keepRequest,testID:"records-revoke-keep"})]}):jsxRuntime.jsx(X,{label:fe.cancel,kind:"danger",accessibilityLabel:fe.cancelA11y,disabled:y.busy,onPress:y.askRevoke,testID:"records-revoke"}):null]})}i(Bh,"RequestDetail");function Uh(){let e=V();return react.useMemo(()=>jh(e),[e])}i(Uh,"useLocalStyles");function jh(e){let{color:t,space:r,radius:o,type:n}=e,l=i((a,c,s,d="regular")=>({...S(e,d),fontSize:a,lineHeight:Math.round(a*c),color:s}),"text");return reactNative.StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg+r.xs/2},readyCta:{minHeight:r.xxl+r.lg+r.xs/2},sent:{gap:r.xs},card:{borderRadius:o.lg,borderWidth:1,borderColor:t.borderRingCream,backgroundColor:t.surface,padding:r.lg,gap:r.md},cardTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:-0.4},detailRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.lg},detailValue:{flexShrink:1,textAlign:"right",...l(n.size.body,n.lineHeight.normal,t.text.primary)},failureCard:{borderRadius:o.lg-r.xs,borderWidth:1,padding:r.md+r.xs/2,gap:r.md},failureCritical:{borderColor:t.badgeBgCritical,backgroundColor:t.badgeBgCritical},failureCaution:{borderColor:t.badgeBgCaution,backgroundColor:t.badgeBgCaution},failureTitle:{...l(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},failureTitleCritical:{color:t.danger},failureTitleCaution:{color:t.warningStrong},emailBlock:{gap:r.sm},callBlock:{gap:r.sm},block:{gap:r.sm},confirmTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")}})}i(jh,"makeLocalStyles");function qu(e){let{petRef:t,petName:r,controller:o,clinicController:n,onPickDocument:l,onPickPhotos:a,uploadTransport:c,consentVersion:s,ownerName:d,onCaptureSignature:u,initialScreen:m,onExit:y,style:g,renderPending:w,onOpenUrl:R,onCopy:v,onAsk:f,location:b}=Be(e,["onExit"]),[C,h]=react.useReducer(Bi,m,ao),I=lo(C),T=C.stack.length;react.useEffect(()=>{let z=i(()=>T<=1?false:(h({type:"pop"}),true),"onBackPress"),de=reactNative.BackHandler.addEventListener("hardwareBackPress",z);return ()=>{de.remove();}},[T]);let k=react.useCallback(z=>h({type:"navigate",screen:z}),[]),_=react.useMemo(()=>co(C).handled?()=>h({type:"pop"}):y,[C,y]),E={onNavigate:k,..._?{onBack:_}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...f?{onAsk:f}:{},...b?{location:b}:{}},B={...o?{controller:o}:{},...s!==void 0?{consentVersion:s}:{}},x={...l?{onPickDocument:l}:{},...a?{onPickPhotos:a}:{},...c?{uploadTransport:c}:{}},A=w?{renderPending:w}:{};switch(I.name){case "dashboard":return jsxRuntime.jsx(ca,{petRef:t,...E,...B,...A,style:g});case "request":return jsxRuntime.jsx(xa,{petRef:t,requestId:I.requestId,...E,...B,...x,...A,style:g});case "timeline":return jsxRuntime.jsx(gu,{petRef:t,...E,style:g});case "record":return jsxRuntime.jsx(ha,{petRef:t,...E,...B,...A,style:g});case "document":return jsxRuntime.jsx(ya,{petRef:t,...E,...B,...A,style:g});case "contributions":return jsxRuntime.jsx(bu,{petRef:t,docId:I.docId,...E,style:g});case "clinicPicker":return jsxRuntime.jsx(ys,{petRef:t,...E,...n?{controller:n}:{},...o?{recordsController:o}:{},style:g});case "clinicBatch":return jsxRuntime.jsx(Is,{petRef:t,petName:r??"",ownerName:d??"",..._?{onClose:_}:{},onCreated:()=>h({type:"navigate",screen:{name:"dashboard"}}),...u?{onCaptureSignature:u}:{},...n?{controller:n}:{},style:g});case "consent":return jsxRuntime.jsx(Ns,{petRef:t,clinic:I.clinic,...E,...d!==void 0?{ownerName:d}:{},...u?{onCaptureSignature:u}:{},...n?{controller:n}:{},style:g});case "upload":return jsxRuntime.jsx(Ra,{petRef:t,...E,...o?{controller:o}:{},...x,...A,style:g});case "requests":return jsxRuntime.jsx(sa,{petRef:t,...E,...o?{controller:o}:{},...A,style:g});default:return Ir(I)}}i(qu,"EverfurRecordsFlow");var Qh=qu;function eR(e){let{userRef:t,scopeEpoch:r}=Te();return jsxRuntime.jsx(Ue,{capability:"recordsClinic",...$e(e.onClose,Z.cancel),children:t===null?jsxRuntime.jsx(p,{accessibilityRole:"alert",children:ve.sessionRequired}):jsxRuntime.jsx(tR,{...Be(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(eR,"EverfurClinicRequest");function tR(e){let t=Zt(),[r,o]=react.useState(null),n=react.useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),l=Vc(e,e.controller??t,e.onCaptureSignature??n),a=e.onCaptureSignature!==void 0||r!==null,c=V(),s={minHeight:44,padding:c.space.sm,borderWidth:1,borderColor:c.color.borderHairlineGreen,borderRadius:c.radius.sm,color:c.color.text.primary,backgroundColor:c.color.surface},d={color:c.color.text.primary,fontSize:c.type.size.body},u=i((m,y,g=false)=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:m,accessibilityState:{disabled:g},disabled:g,onPress:y,style:[s,{justifyContent:"center",opacity:g?.5:1}],children:jsxRuntime.jsx(p,{style:d,children:m})}),"button");return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:Z.title,style:[{backgroundColor:c.color.surface,padding:c.space.lg,gap:c.space.md,borderRadius:c.radius.lg,minHeight:120},e.style],children:[jsxRuntime.jsx(p,{accessibilityRole:"header",style:[d,{...S(c,"bold"),fontSize:c.type.size.heading}],children:Z.title}),jsxRuntime.jsx(p,{style:d,children:e.petName}),l.created?jsxRuntime.jsx(p,{accessibilityLiveRegion:"polite",style:d,children:l.created.statusLabel||ve.records}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(p,{style:d,children:Z.ownerName}),jsxRuntime.jsx(Qe,{accessibilityLabel:Z.ownerName,style:s,value:l.ownerName,maxLength:200,editable:!l.busy,autoComplete:"name",onChangeText:l.setOwnerName}),jsxRuntime.jsx(p,{style:d,children:Z.clinic}),jsxRuntime.jsx(Qe,{accessibilityLabel:Z.clinic,style:s,value:l.query,placeholder:Z.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!l.busy,onChangeText:l.setQuery}),u(Z.search,()=>{l.search();},l.busy||l.searching||l.query.trim().length<2),l.searching&&jsxRuntime.jsx(p,{accessibilityLiveRegion:"polite",style:d,children:ve.loading}),l.recent.length>0&&jsxRuntime.jsx(p,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:Z.recentlyUsed}),l.recent.map(m=>jsxRuntime.jsx(reactNative.View,{children:u([m.name,m.address,m.phone].filter(Boolean).join(", "),()=>l.selectClinic(m),l.busy)},`recent-${m.id}`)),l.visibleClinics.map(m=>jsxRuntime.jsx(reactNative.View,{children:u([m.name,m.address,m.phone].filter(Boolean).join(", "),()=>l.selectClinic(m),l.busy)},m.id)),l.hasMoreClinics&&u(Z.moreClinics,l.showMoreClinics,l.busy),l.needsEmail&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(p,{style:d,children:Z.email}),jsxRuntime.jsx(Qe,{accessibilityLabel:Z.email,style:s,value:l.email,placeholder:Z.emailPlaceholder,placeholderTextColor:c.color.text.placeholder,maxLength:320,editable:!l.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:l.setEmail})]}),jsxRuntime.jsx(p,{accessibilityRole:"header",style:d,children:Z.scopeHeading}),l.copy?jsxRuntime.jsx(p,{style:d,children:l.query.trim()&&l.ownerName.trim()?l.scope??W("internalError").displayMessage:ve.consentRequired}):!l.error&&jsxRuntime.jsx(p,{accessibilityLiveRegion:"polite",style:d,children:ve.loading}),!e.onCaptureSignature&&jsxRuntime.jsx($r,{onChange:o,disabled:l.busy}),!a&&l.ready&&jsxRuntime.jsx(p,{accessibilityRole:"alert",style:d,children:Z.missingSignature}),l.error&&jsxRuntime.jsx(p,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:l.error.displayMessage}),!l.copy&&l.error&&u(ve.retry,l.retryCopy),u(l.busy?Z.sending:Z.send,()=>{l.submit();},l.busy||!l.ready||!a)]}),e.onClose&&u(Z.cancel,e.onClose,l.busy),jsxRuntime.jsx(je,{})]})}i(tR,"ClinicRequestBody");
|
|
4
|
-
|
|
1
|
+
"use strict";var react=require("react"),zod=require("zod"),reactNative=require("react-native"),jsxRuntime=require("react/jsx-runtime"),reactNativeSafeAreaContext=require("react-native-safe-area-context");var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
2
|
+
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
3
|
+
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
4
|
+
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
5
|
+
/* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
6
|
+
/* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
7
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
8
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
9
|
+
/* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
10
|
+
/* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
|
|
11
|
+
/* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
|
|
12
|
+
/* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
|
|
13
|
+
/* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
14
|
+
/* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
15
|
+
/* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
16
|
+
/* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
17
|
+
/* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
18
|
+
/* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
19
|
+
/* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
20
|
+
/* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
21
|
+
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
22
|
+
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
23
|
+
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
24
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
25
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
26
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
27
|
+
/* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
28
|
+
/* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
29
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
30
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
31
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
32
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
33
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
34
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
35
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
36
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
37
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
38
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
39
|
+
/* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
40
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
41
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
|
|
42
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
43
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
44
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
45
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
46
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
47
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
48
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
49
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
50
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
51
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
52
|
+
/* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
53
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
54
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
55
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
56
|
+
/* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
|
|
57
|
+
/* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
58
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
59
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
60
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
61
|
+
/* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
62
|
+
/* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
63
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
64
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
65
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
66
|
+
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
67
|
+
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
68
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
69
|
+
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
70
|
+
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
72
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
73
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
74
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
75
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
76
|
+
/* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
77
|
+
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
78
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
79
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
80
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
81
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
82
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
84
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
85
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
86
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
87
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
88
|
+
/* @__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__ */
|
|
89
|
+
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
90
|
+
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 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__ */
|
|
91
|
+
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__ */
|
|
92
|
+
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__ */
|
|
93
|
+
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__ */
|
|
94
|
+
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__ */
|
|
95
|
+
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__ */
|
|
96
|
+
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__ */
|
|
97
|
+
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__ */
|
|
98
|
+
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;var 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__ */
|
|
99
|
+
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 stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({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(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
100
|
+
/* @__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__ */
|
|
101
|
+
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__ */
|
|
102
|
+
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 RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
|
|
103
|
+
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__ */
|
|
104
|
+
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
|
|
105
|
+
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}}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)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}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"});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 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.";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"});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 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,location){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=location?.latitude,lng=location?.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__ */
|
|
106
|
+
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 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 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__ */
|
|
107
|
+
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
108
|
+
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}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
109
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
110
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar2={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
|
|
111
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
|
|
112
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2}),
|
|
113
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2}),
|
|
114
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2})]})}function UploadGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),head=size*.34;/* @__PURE__ */
|
|
115
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
116
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.06,width:head,height:head,borderTopWidth:w,borderLeftWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}}),
|
|
117
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.1,width:w,height:size*.56,borderRadius:w,backgroundColor:color}}),
|
|
118
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",bottom:0,width:size*.84,height:size*.3,borderBottomWidth:w,borderLeftWidth:w,borderRightWidth:w,borderColor:color,borderBottomLeftRadius:w,borderBottomRightRadius:w}})]})}function SearchGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),unit=size/24,outer=16*unit+w,ringAt=11*unit-outer/2,start=11+8/Math.SQRT2,length=(21-start)*Math.SQRT2*unit,middle=(start+21)/2*unit;/* @__PURE__ */
|
|
119
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
120
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:ringAt,left:ringAt,width:outer,height:outer,borderRadius:outer,borderWidth:w,borderColor:color}}),
|
|
121
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:middle-w/2,left:middle-(length+w)/2,width:length+w,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"45deg"}]}})]})}function RecordsFootnote(props){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles2(theme),[theme]);/* @__PURE__ */
|
|
122
|
+
return jsxRuntime.jsx(Text,{style:[styles.footnote,props.style],accessibilityRole:"text",testID:"records-footnote",children:RECORDS_FOOTNOTE})}function makeStyles2(theme){let{color:color,space:space,type:type}=theme;return reactNative.StyleSheet.create({footnote:{...face(theme,"regular"),paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.lg,textAlign:"center",fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,backgroundColor:color.background}})}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}}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 HIDDEN2={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box2(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke2(size){return Math.max(1.5,Math.round(size/11*10)/10)}function bar(color,w,length,at,angle=0){return{position:"absolute",top:at.top-w/2,left:at.left-length/2,width:length,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:`${angle}deg`}]}}function FileTextGlyph({size:size,color:color}){let w=stroke2(size),line2=(top,width)=>({position:"absolute",top:size*top,left:size*.3,width:size*width,height:w,borderRadius:w,backgroundColor:color});/* @__PURE__ */
|
|
123
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box2(size),...HIDDEN2,children:[
|
|
124
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.06,left:size*.16,width:size*.68,height:size*.88,borderWidth:w,borderColor:color,borderRadius:size*.1}}),
|
|
125
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:line2(.36,.4)}),
|
|
126
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:line2(.54,.4)}),
|
|
127
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:line2(.72,.24)})]})}function ListGlyph({size:size,color:color}){/* @__PURE__ */
|
|
128
|
+
return jsxRuntime.jsx(MenuGlyph,{size:size,color:color})}function InboxGlyph({size:size,color:color}){let w=stroke2(size);/* @__PURE__ */
|
|
129
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box2(size),...HIDDEN2,children:[
|
|
130
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.2,left:size*.06,width:size*.88,height:size*.66,borderWidth:w,borderColor:color,borderRadius:size*.12}}),
|
|
131
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*.26,{top:size*.54,left:size*.2})}),
|
|
132
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*.26,{top:size*.54,left:size*.8})}),
|
|
133
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.54-w/2,left:size*.34,width:size*.32,height:size*.14,borderBottomWidth:w,borderLeftWidth:w,borderRightWidth:w,borderColor:color,borderBottomLeftRadius:w,borderBottomRightRadius:w}})]})}function ActivityGlyph({size:size,color:color}){let w=stroke2(size),mid=size*.5;/* @__PURE__ */
|
|
134
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box2(size),...HIDDEN2,children:[
|
|
135
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*.24,{top:mid,left:size*.12})}),
|
|
136
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*.42,{top:size*.32,left:size*.32},-68)}),
|
|
137
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*.62,{top:size*.5,left:size*.5},72)}),
|
|
138
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*.42,{top:size*.68,left:size*.68},-68)}),
|
|
139
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*.14,{top:mid,left:size*.9})})]})}function ClockGlyph({size:size,color:color}){let w=stroke2(size),c=size/2;/* @__PURE__ */
|
|
140
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box2(size),...HIDDEN2,children:[
|
|
141
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.04,left:size*.04,width:size*.92,height:size*.92,borderRadius:size,borderWidth:w,borderColor:color}}),
|
|
142
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.24,left:c-w/2,width:w,height:c-size*.24+w/2,borderRadius:w,backgroundColor:color}}),
|
|
143
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:c-w/2,left:c-w/2,width:size*.22,height:w,borderRadius:w,backgroundColor:color}})]})}function ToolGlyph({size:size,color:color}){let w=stroke2(size),ring=size*.42;/* @__PURE__ */
|
|
144
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box2(size),...HIDDEN2,children:[
|
|
145
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w*1.2,size*.62,{top:size*.62,left:size*.38},-45)}),
|
|
146
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.06,right:size*.06,width:ring,height:ring,borderRadius:ring,borderWidth:w,borderColor:color,borderTopColor:"transparent",transform:[{rotate:"45deg"}]}})]})}function WifiOffGlyph({size:size,color:color}){let w=stroke2(size),arc=(diameter,top)=>({position:"absolute",top:size*top,left:(size-diameter)/2,width:diameter,height:diameter,borderRadius:diameter,borderWidth:w,borderColor:"transparent",borderTopColor:color});/* @__PURE__ */
|
|
147
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box2(size),...HIDDEN2,children:[
|
|
148
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:arc(size*.96,.12)}),
|
|
149
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:arc(size*.56,.38)}),
|
|
150
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.78,left:size/2-w,width:w*2,height:w*2,borderRadius:w,backgroundColor:color}}),
|
|
151
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar(color,w,size*1.1,{top:size/2,left:size/2},45)})]})}function RefreshGlyph({size:size,color:color}){let w=stroke2(size),ring=size*.8,head=size*.26;/* @__PURE__ */
|
|
152
|
+
return jsxRuntime.jsxs(reactNative.View,{style:box2(size),...HIDDEN2,children:[
|
|
153
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.1,left:size*.1,width:ring,height:ring,borderRadius:ring,borderWidth:w,borderColor:color,borderRightColor:"transparent",transform:[{rotate:"-45deg"}]}}),
|
|
154
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.04,right:size*.06,width:head,height:head,borderTopWidth:w,borderRightWidth:w,borderColor:color}})]})}function UploadCloudGlyph({size:size,color:color}){/* @__PURE__ */
|
|
155
|
+
return jsxRuntime.jsx(UploadGlyph,{size:size,color:color})}function RecordsEmptyGlyph({variant:variant,size:size,color:color}){switch(variant){case"idle":/* @__PURE__ */
|
|
156
|
+
return jsxRuntime.jsx(SearchGlyph,{size:size,color:color});case"no_requests":/* @__PURE__ */
|
|
157
|
+
return jsxRuntime.jsx(InboxGlyph,{size:size,color:color});case"no_records":/* @__PURE__ */
|
|
158
|
+
return jsxRuntime.jsx(ActivityGlyph,{size:size,color:color});case"rate_limited":/* @__PURE__ */
|
|
159
|
+
return jsxRuntime.jsx(ClockGlyph,{size:size,color:color});case"service_unavailable":/* @__PURE__ */
|
|
160
|
+
return jsxRuntime.jsx(ToolGlyph,{size:size,color:color});case"error":/* @__PURE__ */
|
|
161
|
+
return jsxRuntime.jsx(WifiOffGlyph,{size:size,color:color});default:return null}}function RecordsEmptyState({variant:variant,onAction:onAction,message:message,testID:testID}){let styles=useStyles(),theme=useEverfurTheme(),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(s=>Math.max(0,s-1)),1e3);return()=>clearTimeout(handle)},[cooldown]);let cooling=variant==="rate_limited"&&cooldown>0,label=cooling?coolingActionLabel(cooldown):copy.action;/* @__PURE__ */
|
|
162
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.container,accessibilityRole:"summary",testID:testID,children:[
|
|
163
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"records-empty-glyph",children:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyGlyph,{variant:variant,size:GLYPH_SIZE,color:theme.color.brandInk})}),
|
|
164
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,children:copy.title}),
|
|
165
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...face(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}var BACK_LABEL="Back";function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let styles=useStyles2();/* @__PURE__ */
|
|
166
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.row,testID:testID,children:[onBack?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,hitSlop:12,style:styles.back,testID:testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back}),title.trim().length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:variant==="document"?styles.documentTitle:styles.title,accessibilityRole:"header",numberOfLines:1,children:title}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:testID?`${testID}-spacer`:void 0}),
|
|
167
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.right,children:right??/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back})})]})}function ListGlyph2(){let styles=useStyles2();/* @__PURE__ */
|
|
168
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
|
|
169
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.listBar}),
|
|
170
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.listBar}),
|
|
171
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.listBar})]})}function ShareGlyph(){let styles=useStyles2();/* @__PURE__ */
|
|
172
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.shareGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
|
|
173
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareDot,styles.shareDotTop]}),
|
|
174
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareDot,styles.shareDotLeft]}),
|
|
175
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareDot,styles.shareDotBottom]}),
|
|
176
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareStroke,styles.shareStrokeUp]}),
|
|
177
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareStroke,styles.shareStrokeDown]})]})}function SendGlyph(){let styles=useStyles2();/* @__PURE__ */
|
|
178
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
|
|
179
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.sendBody}),
|
|
180
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.sendFold})]})}function DownloadGlyph(){let styles=useStyles2();/* @__PURE__ */
|
|
181
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
|
|
182
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadStem}),
|
|
183
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadHead}),
|
|
184
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return reactNative.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,gap:space.sm},back:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},chevron:{width:chevron,height:chevron,borderLeftWidth:stroke3,borderBottomWidth:stroke3,borderColor:color.brandInk,transform:[{rotate:"45deg"}],marginLeft:space.xs},title:{flex:1,...face(theme,"bold"),fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.tight)+1,color:color.brandInk},spacer:{flex:1},documentTitle:{flex:1,textAlign:"center",...face(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.text.primary},right:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2},listGlyph:{width:glyph,height:glyph,justifyContent:"space-evenly"},listBar:{height:stroke3,borderRadius:stroke3,backgroundColor:color.brandInk},shareGlyph:{width:glyph-space.xs,height:glyph-space.xs},shareDot:{position:"absolute",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs,borderWidth:stroke3,borderColor:color.brandInk},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:space.xs+space.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:space.xs,top:space.sm,width:space.sm+space.xs/2,height:stroke3,backgroundColor:color.brandInk},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:glyph-space.xs,height:glyph-space.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:stroke3,borderColor:color.brandInk,transform:[{rotate:"45deg"}],borderRadius:stroke3},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:stroke3,backgroundColor:color.brandInk},downloadGlyph:{width:glyph-space.xs,height:glyph-space.xs,alignItems:"center"},downloadStem:{width:stroke3,height:space.sm+space.xs/2,backgroundColor:color.brandInk},downloadHead:{width:space.sm,height:space.sm,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:color.brandInk,transform:[{rotate:"45deg"}],marginTop:-space.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:space.xs+space.xs/2,borderLeftWidth:stroke3,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:color.brandInk}})}var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
|
|
185
|
+
return jsxRuntime.jsxs(reactNative.View,{testID:"records-gate-off",style:[{minHeight:MIN_HEIGHT,justifyContent:"center",gap:space.md,padding:space.lg,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surfaceCream},style],children:[reason.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
|
|
186
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});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 BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
|
|
187
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoGlyphText,children:"i"})}),
|
|
188
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,busy:busy=false,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID,style:style}){let styles=useScreenStyles(),theme=useEverfurTheme(),still=theme.motion.reducedMotion,box3=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink,text3=kind==="primary"?styles.pillPrimaryLabel:kind==="danger"?styles.pillDangerLabel:kind==="ask"?styles.pillAskLabel:kind==="link"?styles.pillLinkLabel:styles.pillOutlineLabel;/* @__PURE__ */
|
|
189
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,accessibilityHint:accessibilityHint,accessibilityState:{disabled:disabled||busy,busy:busy},style:({pressed:pressed})=>[styles.pill,box3,disabled?styles.pillDisabled:null,pressed&&!still?styles.pressed:null,style],testID:testID,children:[busy?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:kind==="primary"?theme.color.onPrimary:theme.color.brandInk}):null,
|
|
190
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:label})]})}function Chip({label:label,tone:tone="neutral",testID:testID}){let styles=useScreenStyles(),{bg:bg,fg:fg}=styles.chipTones[tone],sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
|
|
191
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.chip,sentence?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.chipText,sentence?styles.chipSentenceText:null,fg],children:label})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
|
|
192
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.sectionHeader,children:[
|
|
193
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:title}),count!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionCount,children:count}):null]})}function Chevron({direction:direction="right"}){let styles=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
|
|
194
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.chevron,{transform:[{rotate:rotate}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),cardText=slotText(slots.recordCard),errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({bg:{backgroundColor:bg,borderColor:"transparent"},fg:{color:fg}}),edge=(line2,fg)=>({bg:{backgroundColor:color.surface,borderColor:line2},fg:{color:fg}});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)},...reactNative.StyleSheet.create({root:{flex:1,backgroundColor:color.background},body:{flex:1},content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg},contentTight:{paddingHorizontal:space.sm,paddingBottom:space.xxl,gap:space.lg},inset:{paddingHorizontal:space.sm},section:{gap:space.sm+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.xs},sectionTitle:{...text3(size.subtitle,lineHeight.snug,color.text.primary,"bold"),letterSpacing:-.4},sectionCount:{...text3(size.bodyTight,lineHeight.snug,color.text.muted,"medium")},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.xs,...slotBox(slots.recordCard,hairline)},creamCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(slots.recordCard,hairline)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.md,paddingVertical:space.md},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text3(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(size.caption,lineHeight.normal,color.text.muted),...cardText},chip:{minHeight:24,justifyContent:"center",borderRadius:radius.pill,borderWidth:1.5,paddingHorizontal:space.sm+space.xs/2,alignSelf:"flex-start"},chipText:{...text3(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text3(size.caption,lineHeight.normal,color.text.primary,"medium"),letterSpacing:0,textTransform:"none"},pill:{minHeight:BUTTON_HEIGHT,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm},pillPrimary:{backgroundColor:color.brand,...slotBox(slots.primaryButton)},pillPrimaryLabel:{...text3(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text3(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text3(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text3(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text3(size.body,lineHeight.snug,color.linkInk,"bold")},pillDisabled:{opacity:.5},pressed:{transform:[{scale:RECORDS_MOTION.pressScale}]},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},infoNoteText:{flex:1,...text3(size.bodyTight,lineHeight.normal,color.text.primary)},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},cautionNoteText:{flex:1,...text3(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text3(size.bodyTight,lineHeight.relaxed,color.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md},errorText:{flex:1,...text3(size.bodyTight,lineHeight.normal,errorColor)},band:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft},bandText:{flex:1,...text3(size.caption,lineHeight.normal,color.text.secondary)},infoGlyph:{width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,borderWidth:1,borderColor:color.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...text3(size.small,lineHeight.tight,color.text.secondary,"bold")},chevron:{width:space.sm,height:space.sm,borderTopWidth:space.xs/2,borderRightWidth:space.xs/2,borderColor:color.text.muted},lead:{paddingHorizontal:space.sm,...text3(size.body+1,lineHeight.snug,color.text.primary,"bold")},field:{minHeight:touch,paddingHorizontal:space.md,paddingVertical:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:size.body},fieldLabel:{...text3(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text3(size.caption,lineHeight.normal,color.text.muted),bodyText:text3(size.body,lineHeight.normal,color.text.primary)})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}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 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__ */
|
|
195
|
+
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__ */
|
|
196
|
+
return jsxRuntime.jsx(reactNative.View,{style:[{width:width,height:height,borderRadius:radius??radii.xs,backgroundColor:color.skeleton},style],accessibilityElementsHidden:true,importantForAccessibility:"no"})}var DONUT=180,BADGE_W=70,BADGE_H=22,CAROUSEL_H=300,DISCLAIMER_H=44,RAIL_DOT=24,TIMELINE_BUBBLE=34,TIMELINE_ROWS=6,CLINIC_ROWS=5;function DashboardSkeleton({testID:testID}){let styles=useStyles3(),action=key=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionRow,children:[
|
|
197
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionLeft,children:[
|
|
198
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:18,height:18,radius:9}),
|
|
199
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"55%",height:14,radius:7})]}),
|
|
200
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:18,height:18,radius:9})]},key);/* @__PURE__ */
|
|
201
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:DASHBOARD_COPY.loading,testID:testID,children:[
|
|
202
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.summaryCard,children:[
|
|
203
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:DONUT,height:DONUT,radius:DONUT/2}),
|
|
204
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.badges,children:[
|
|
205
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:BADGE_W,height:BADGE_H,radius:BADGE_H/2}),
|
|
206
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:BADGE_W,height:BADGE_H,radius:BADGE_H/2})]})]})}),
|
|
207
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:150,height:16,radius:8,style:styles.inset}),
|
|
208
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.carouselCard,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:CAROUSEL_H,radius:14})}),
|
|
209
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.dots,children:[
|
|
210
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:6,height:6,radius:3}),
|
|
211
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:18,height:6,radius:3}),
|
|
212
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:6,height:6,radius:3})]}),
|
|
213
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:46,height:12,radius:6,style:styles.centered}),
|
|
214
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:DISCLAIMER_H,radius:12})}),
|
|
215
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,styles.actions],children:[action("a"),action("b")]})]})}function RequestSkeleton({testID:testID}){let styles=useStyles3();/* @__PURE__ */
|
|
216
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:REQUEST_SCREEN_COPY.loading,testID:testID,children:[
|
|
217
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:[0,1,2,3].map(index=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.railRow,children:[
|
|
218
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.railColumn,children:[
|
|
219
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:RAIL_DOT,height:RAIL_DOT,radius:RAIL_DOT/2}),index<3?/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:2,height:20,radius:1,style:styles.connector}):null]}),
|
|
220
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.railBody,children:[
|
|
221
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"55%",height:14,radius:7}),
|
|
222
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"75%",height:11,radius:6})]})]},index))}),
|
|
223
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.statusCard,children:[
|
|
224
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"90%",height:13,radius:6}),
|
|
225
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"60%",height:13,radius:6})]}),
|
|
226
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:50,radius:25})]})}function TimelineSkeleton({testID:testID}){let styles=useStyles3();/* @__PURE__ */
|
|
227
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:DEPTH_COPY.loadingTimeline,testID:testID,children:[
|
|
228
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineDisclaimer,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:DISCLAIMER_H,radius:12})}),Array.from({length:TIMELINE_ROWS},(_,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[index>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineSeparator}):null,
|
|
229
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.timelineRow,children:[
|
|
230
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:TIMELINE_BUBBLE,height:TIMELINE_BUBBLE,radius:TIMELINE_BUBBLE/2}),
|
|
231
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.timelineBody,children:[
|
|
232
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.timelineTop,children:[
|
|
233
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:44,height:10,radius:5}),
|
|
234
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:56,height:12,radius:6})]}),
|
|
235
|
+
/* @__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 styles=useStyles3();/* @__PURE__ */
|
|
236
|
+
return jsxRuntime.jsx(reactNative.View,{style:styles.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:CLINIC_PICKER_COPY.loading,testID:testID,children:Array.from({length:CLINIC_ROWS},(_,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.clinicRow,children:[
|
|
237
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"65%",height:14,radius:7}),
|
|
238
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"40%",height:11,radius:6})]},index))})}function SharesSkeleton({testID:testID}){let styles=useStyles3();/* @__PURE__ */
|
|
239
|
+
return jsxRuntime.jsx(reactNative.View,{style:styles.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:SHARE_COPY.loadingLinks,testID:testID,children:[0,1].map(index=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.shareRow,children:[
|
|
240
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"55%",height:13}),
|
|
241
|
+
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"40%",height:11})]},index))})}var TIMELINE_SEPARATOR_INSET=62;function useStyles3(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles5(theme),[theme])}function makeStyles5(theme){let{color:color,space:space,radius:radius}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({dashboard:{flex:1,paddingHorizontal:space.sm,paddingTop:space.xs,gap:space.lg,backgroundColor:color.background},inset:{paddingHorizontal:space.sm},summaryCard:{alignItems:"center",borderRadius:radius.lg-space.xs,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg+space.xs,gap:space.md+space.xs/2},badges:{flexDirection:"row",gap:space.md},carouselCard:{borderRadius:radius.lg-space.xs,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,padding:space.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.xs+space.xs/2},centered:{alignSelf:"center"},actions:{gap:space.sm+space.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:radius.md,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:space.md},request:{paddingHorizontal:space.lg,paddingTop:space.xs,gap:space.lg+space.xs/2,backgroundColor:color.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:space.md},railColumn:{alignItems:"center",width:RAIL_DOT},connector:{marginVertical:space.xs/2},railBody:{flex:1,paddingBottom:space.lg+space.xs/2,gap:space.xs+space.xs/2},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2,gap:space.sm},timeline:{flex:1,backgroundColor:color.background},timelineDisclaimer:{paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md},timelineRow:{flexDirection:"row",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md+space.xs/2},timelineBody:{flex:1,gap:space.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},timelineSeparator:{height:hairline,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},clinics:{gap:space.md},clinicRow:{borderRadius:radius.lg-space.xs/2,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md+space.xs/2,gap:space.sm},shares:{gap:space.md,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder},shareRow:{gap:space.xs+space.xs/2}})}var EMAIL=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function EverfurClinicPicker(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
242
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"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:location,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),picker=useClinicPicker(controller??runtimeController,location),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,onEndReached=event=>{let{layoutMeasurement:layoutMeasurement,contentOffset:contentOffset,contentSize:contentSize}=event.nativeEvent;layoutMeasurement.height+contentOffset.y>=contentSize.height-layoutMeasurement.height*.6&&picker.loadMore()},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";/* @__PURE__ */
|
|
243
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
244
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:CLINIC_PICKER_COPY.titleFor(petName),onBack:onBack,testID:"records-clinic-header"}),
|
|
245
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.lead,testID:"records-clinic-lead",children:CLINIC_PICKER_COPY.leadNative}),
|
|
246
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.searchBar,children:[
|
|
247
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{testID:"records-clinic-search-glyph",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsxRuntime.jsx(SearchGlyph,{size:theme.space.md,color:theme.color.text.muted,strokeWidth:2})}),
|
|
248
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{value:picker.query,onChangeText:picker.setQuery,placeholder:CLINIC_PICKER_COPY.placeholder,placeholderTextColor:theme.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:CLINIC_PICKER_COPY.searchA11y,style:local.searchInput,testID:"records-clinic-search-input"}),picker.query.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>picker.setQuery(""),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.clearGlyph,children:"×"})}):null]}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.uploadWrap,children:[startError?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:startError})}):null,
|
|
249
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:starting?CLINIC_PICKER_COPY.uploadOwnStarting:CLINIC_PICKER_COPY.uploadOwn,kind:"outline",busy:starting,onPress:startUpload,testID:"records-clinic-upload-own"})]}):null,
|
|
250
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.list,keyboardShouldPersistTaps:"handled",keyboardDismissMode:reactNative.Platform.OS==="ios"?"interactive":"on-drag",onScroll:picker.isSearchActive?onEndReached:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[picker.isSearchActive?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.fallbackCard,testID:"records-clinic-fallback-card",children:[
|
|
251
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>setFallbackOpen(open=>!open),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.fallback.title,accessibilityHint:CLINIC_PICKER_COPY.fallback.subtitle,accessibilityState:{expanded:fallbackOpen},style:local.fallbackHeader,testID:"records-clinic-fallback",children:[
|
|
252
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.fallbackCopy,children:[
|
|
253
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.fallbackTitle,numberOfLines:1,children:CLINIC_PICKER_COPY.fallback.title}),
|
|
254
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.fallbackSubtitle,numberOfLines:2,children:CLINIC_PICKER_COPY.fallback.subtitle})]}),
|
|
255
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{direction:fallbackOpen?"up":"down"})]}),fallbackOpen?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.fallbackForm,children:[
|
|
256
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:CLINIC_PICKER_COPY.fallback.nameLabel}),
|
|
257
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_PICKER_COPY.fallback.nameLabel,style:styles.field,value:displayName,onChangeText:value=>{setFallbackName(value),setFallbackNameDirty(true)},placeholder:CLINIC_PICKER_COPY.fallback.namePlaceholder,placeholderTextColor:theme.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),
|
|
258
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:CLINIC_PICKER_COPY.fallback.emailLabel}),
|
|
259
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_PICKER_COPY.fallback.emailLabel,style:styles.field,value:fallbackEmail,onChangeText:value=>{setFallbackEmail(value),setFallbackTouched(false)},onBlur:()=>setFallbackTouched(true),placeholder:CLINIC_PICKER_COPY.fallback.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),fallbackTouched&&fallbackEmail.trim().length>0&&!fallbackEmailValid?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",children:REQUEST_SCREEN_COPY.errors.invalidEmail}):null,
|
|
260
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:CLINIC_PICKER_COPY.fallback.reviewNote}),
|
|
261
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_PICKER_COPY.fallback.submit,disabled:!canContinue||!onNavigate,onPress:()=>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(Text,{style:local.sectionLabel,accessibilityRole:"header",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,listData.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(ClinicRow,{clinic:clinic,onSelect:select,styles:local},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,
|
|
262
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.footer,children:[picker.loadingMore?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.footerLoading,testID:"records-clinic-loading-more",children:[
|
|
263
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:theme.color.brandInk,size:"small"}),
|
|
264
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:CLINIC_PICKER_COPY.loadingMore})]}):null,picker.pageError?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:picker.loadMore,accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.loadMoreFailed,style:local.footerRetry,testID:"records-clinic-page-error-retry",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.footerRetryLabel,children:CLINIC_PICKER_COPY.loadMoreFailed})}):null]}),
|
|
265
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.howCard,accessibilityRole:"summary",testID:"records-clinic-how",children:[
|
|
266
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.howTitle,accessibilityRole:"header",children:CLINIC_PICKER_COPY.howItWorks}),CLINIC_PICKER_COPY.howSteps(petNameOr(petName)).map((step,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.howRow,children:[
|
|
267
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.howNumber,accessibilityElementsHidden:true,importantForAccessibility:"no",children:String(index+1).padStart(2,"0")}),
|
|
268
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.howText,children:[
|
|
269
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.howStepTitle,children:step.title}),
|
|
270
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.howStepBody,children:step.body})]})]},step.title))]})]}),
|
|
271
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function ClinicRow({clinic:clinic,onSelect:onSelect,styles:styles}){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(", ");/* @__PURE__ */
|
|
272
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>onSelect(clinic),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.selectA11y(summary),hitSlop:8,style:styles.item,testID:`records-clinic-${clinic.id}`,children:[
|
|
273
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.itemHeader,children:[
|
|
274
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemName,numberOfLines:1,children:clinic.name}),distance?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:distance}):null]}),clinic.address?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemAddress,numberOfLines:2,children:clinic.address}):null,clinic.phone?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:clinic.phone}):null,
|
|
275
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeLabel,badge.tone==="positive"?styles.badgePositiveText:badge.tone==="caution"?styles.badgeCautionText:styles.badgeNeutralText],children:badge.label})})]})}function useLocalStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({lead:{...text3(type.size.body,type.lineHeight.normal,color.text.muted),paddingHorizontal:space.lg,paddingBottom:space.md},howCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.md,marginTop:space.sm},howTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),letterSpacing:-.4},howRow:{flexDirection:"row",gap:space.md},howNumber:{...face(theme,"monoBold"),fontSize:type.size.caption,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.brandInk,minWidth:space.xl},howText:{flex:1,gap:space.xs/2},howStepTitle:text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),howStepBody:text3(type.size.caption,type.lineHeight.normal,color.text.secondary),searchBar:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.md+space.xs/2,height:space.xxl+space.md,marginHorizontal:space.lg,marginBottom:space.sm,borderRadius:radius.lg+space.xs/2,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.borderHairlineGreen},searchInput:{flex:1,...text3(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0},clearGlyph:text3(type.size.heading,type.lineHeight.tight,color.text.muted),uploadWrap:{paddingHorizontal:space.lg,paddingBottom:space.md,gap:space.sm},list:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.md},sectionLabel:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:radius.lg-space.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:color.brandBorder,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.md},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},fallbackSubtitle:text3(type.size.caption,type.lineHeight.normal,color.text.muted),fallbackForm:{gap:space.sm},item:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text3(type.size.body,type.lineHeight.snug,color.brandInk,"bold")},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:text3(type.size.caption,type.lineHeight.normal,color.text.primary),itemPhone:text3(type.size.caption,type.lineHeight.normal,color.text.muted),badge:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+1,paddingVertical:space.xs},badgePositive:{backgroundColor:color.badgeBgPositive},badgeCaution:{backgroundColor:color.badgeBgCaution},badgeNeutral:{backgroundColor:color.badgeBgNeutral},badgeLabel:{...text3(type.size.micro,type.lineHeight.snug,color.text.muted,"bold")},badgePositiveText:{color:color.success},badgeCautionText:{color:color.cautionAccent},badgeNeutralText:{color:color.text.muted},footer:{gap:space.sm,paddingTop:space.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.md},footerRetry:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...text3(type.size.bodyTight,type.lineHeight.snug,color.brandInk,"bold")}})}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}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 abort=captureAbort.current;try{let registered=await registerSignature(captured.signaturePngBase64,abort.signal);if(!current())return;signature.current={signatureId:registered.signatureId}}catch(registrationError){if(!isSignatureUploadLegFailure(registrationError)||abort.signal.aborted)throw registrationError;if(!current())return}}}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)}}}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number",probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function 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}}var FAILED="Signature upload failed",UPLOAD_TIMEOUT_MS=3e4;function base64ByteLength(base64){let padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;return Math.floor(base64.length*3/4)-padding}async function registerRnSignature(signaturePngBase64,controller,signal,fetchImpl){let fail=()=>new Error(FAILED),size=base64ByteLength(signaturePngBase64);if(size<=0||signal.aborted)throw fail();let initiated=await controller.initiateSignatureUpload(size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw fail();let form=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))form.append(key,value);form.append("file",{uri:`data:image/png;base64,${signaturePngBase64}`,name:"signature.png",type:"image/png"});let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,UPLOAD_TIMEOUT_MS);try{if(!(await(fetchImpl??fetch)(initiated.value.uploadUrl,{method:"POST",body:form,credentials:"omit",signal:uploadAbort.signal})).ok||signal.aborted)throw fail()}catch{throw signal.aborted?fail():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw fail();return{signatureId:completed.value}}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke3 of strokes){let points=[];for(let point of stroke3){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text3=name.trim();if(text3.length===0)return bitmap;let chars=[...text3],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count){for(this.acc|=value<<this.count,this.count+=count;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],LENGTH_EXTRA=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],DIST_BASE=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],DIST_EXTRA=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte of bytes)a=(a+byte)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n=0;n<256;n+=1){let c=n;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n]=c>>>0}}let crc=4294967295;for(let byte of bytes)crc=crcTable[(crc^byte)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}var SIGNATURE_STROKE_WIDTH=2.6,INK="#111111";function strokeSegments(strokes,scale){let segments=[];return strokes.forEach((stroke3,s)=>{let at=i=>{let p=stroke3[i];return[p[0]/scale,p[1]/scale]};if(stroke3.length===1){let[x,y]=at(0);segments.push({key:`${s}-0`,cx:x,cy:y,length:0,angle:0});return}for(let i=1;i<stroke3.length;i+=1){let[x0,y0]=at(i-1),[x1,y1]=at(i);segments.push({key:`${s}-${i}`,cx:(x0+x1)/2,cy:(y0+y1)/2,length:Math.hypot(x1-x0,y1-y0),angle:Math.atan2(y1-y0,x1-x0)})}}),segments}var MIN_DRAWN_POINTS=8,MIN_MOVE=2;function SignaturePad({onChange:onChange,disabled:disabled=false}){let styles=useStyles4(),[mode,setMode]=react.useState("draw"),[typed,setTyped]=react.useState(""),[strokes,setStrokes]=react.useState([]),[width,setWidth]=react.useState(0),current=react.useRef([]),drawing=react.useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=react.useRef(scale);scaleRef.current=scale;let disabledRef=react.useRef(disabled);disabledRef.current=disabled,react.useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n,stroke3)=>n+stroke3.length,0);callHost(onChange,points>=MIN_DRAWN_POINTS?encodeSignaturePng(rasterizeStrokes(strokes)):null)},[mode,typed,strokes,onChange]);let point=event=>{let{locationX:locationX,locationY:locationY}=event.nativeEvent;return[locationX*scaleRef.current,locationY*scaleRef.current]},commitStroke=()=>{let finished=current.current,inProgress=drawing.current;current.current=[],drawing.current=null,setStrokes(committed=>[...committed.filter(s=>s!==inProgress),finished])},responder=react.useMemo(()=>reactNative.PanResponder.create({onStartShouldSetPanResponder:()=>!disabledRef.current,onMoveShouldSetPanResponder:()=>!disabledRef.current,onPanResponderTerminationRequest:()=>false,onPanResponderGrant:event=>{current.current=[point(event)]},onPanResponderMove:event=>{let next=point(event),last=current.current[current.current.length-1];if(last!==void 0&&Math.abs(last[0]-next[0])<MIN_MOVE&&Math.abs(last[1]-next[1])<MIN_MOVE)return;current.current=[...current.current,next];let previous=drawing.current,trail=current.current;drawing.current=trail,setStrokes(committed=>[...committed.filter(s=>s!==previous),trail])},onPanResponderRelease:()=>commitStroke(),onPanResponderTerminate:()=>commitStroke()}),[]),clear=react.useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=react.useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
|
|
276
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.container,testID:"records-signature-pad",children:[
|
|
277
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.label,children:mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),mode==="type"?/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.type,style:styles.input,value:typed,maxLength:100,editable:!disabled,autoComplete:"off",autoCorrect:false,onChangeText:value=>{disabledRef.current||setTyped(value)}}):null,
|
|
278
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{onLayout:onLayout,style:[styles.canvas,{height:width>0?width/3:120}],accessible:true,accessibilityLabel:CLINIC_REQUEST_COPY.sign,accessibilityRole:"image",testID:"records-signature-canvas",...mode==="draw"?responder.panHandlers:{},children:mode==="type"?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:typed.trim()}):strokeSegments(strokes,scale).map(segment=>{let box3=segment.length+SIGNATURE_STROKE_WIDTH;/* @__PURE__ */
|
|
279
|
+
return jsxRuntime.jsx(reactNative.View,{pointerEvents:"none",style:[styles.segment,{width:box3,left:segment.cx-box3/2,top:segment.cy-SIGNATURE_STROKE_WIDTH/2,transform:[{rotate:`${segment.angle}rad`}]}]},segment.key)})}),
|
|
280
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actions,children:[
|
|
281
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CLINIC_REQUEST_COPY.clear,accessibilityState:{disabled:disabled},disabled:disabled,onPress:clear,style:styles.button,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.buttonLabel,children:CLINIC_REQUEST_COPY.clear})}),
|
|
282
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw,accessibilityState:{disabled:disabled},disabled:disabled,onPress:toggle,style:styles.button,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.buttonLabel,children:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw})})]})]})}function useStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles6(theme),[theme])}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({container:{gap:space.sm},label:{...face(theme,"regular"),fontSize:type.size.body,color:color.text.primary},input:{minHeight:44,padding:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:type.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,overflow:"hidden",justifyContent:"center"},segment:{position:"absolute",height:SIGNATURE_STROKE_WIDTH,borderRadius:SIGNATURE_STROKE_WIDTH/2,backgroundColor:INK},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:INK,paddingHorizontal:space.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},button:{minHeight:44,paddingHorizontal:space.md,justifyContent:"center",borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,backgroundColor:color.surface},buttonLabel:{...face(theme,"regular"),fontSize:type.size.body,color:color.text.primary}})}function EverfurClinicRequestBatch(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
283
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(BatchBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}var IOS=reactNative.Platform.OS==="ios";function clinicDetail(clinic){return[clinic.address,clinic.phone].filter(Boolean).join(", ")}function BatchBody(props){let runtimeController=useEverfurRecordsClinic(),runtimeBatch=useEverfurRecordsClinicBatch(),controller=props.controller??runtimeController,[png,setPng]=react.useState(null),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),register=react.useCallback((image,signal)=>registerRnSignature(image,controller,signal),[controller]),form=useClinicBatchForm(props,controller,props.batchClient??runtimeBatch,props.onCaptureSignature??padCapture,props.onCaptureSignature?void 0:register),signed=props.onCaptureSignature!==void 0||png!==null,theme=useEverfurTheme(),styles=useScreenStyles(),local=useLocalStyles2(),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),keyboard=useChatKeyboardOffset(void 0,IOS),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,canSearch=!form.busy&&!form.searching&&form.query.trim().length>=2,search=()=>{canSearch&&(reactNative.Keyboard.dismiss(),form.search())},option=(key,clinic)=>{let detail=clinicDetail(clinic);/* @__PURE__ */
|
|
284
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:[clinic.name,detail].filter(Boolean).join(", "),accessibilityState:{disabled:form.busy},disabled:form.busy,onPress:()=>form.addClinic(clinic),style:[local.option,form.busy?styles.pillDisabled:null],children:[
|
|
285
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.optionName,children:clinic.name}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:detail}):null]},key)};/* @__PURE__ */
|
|
286
|
+
return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:title,style:[styles.root,props.style],children:[
|
|
287
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.header,children:[
|
|
288
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.title,numberOfLines:2,children:title}),props.onClose?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CLINIC_REQUEST_COPY.cancel,accessibilityState:{disabled:form.busy},disabled:form.busy,onPress:props.onClose,hitSlop:8,style:[local.close,form.busy?styles.pillDisabled:null],testID:"records-batch-close",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.closeLabel,children:CLINIC_REQUEST_COPY.cancel})}):null]}),
|
|
289
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:IOS?"padding":void 0,style:styles.body,...keyboard.avoidingProps,children:[
|
|
290
|
+
/* @__PURE__ */jsxRuntime.jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),
|
|
291
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.content,keyboardShouldPersistTaps:"handled",keyboardDismissMode:IOS?"interactive":"on-drag",testID:"records-batch-scroll",children:[props.petName?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.lead,children:props.petName}):null,form.outcome?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,testID:"records-batch-result",children:[
|
|
292
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:styles.bodyText,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)}),
|
|
293
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:CLINIC_BATCH_COPY.perClinic}),form.outcome.results.map((row,index)=>{let name=row.request?.clinicName??form.drafts[index]?.clinic?.name??row.clinicFreeText??"",status=row.created?CLINIC_BATCH_COPY.sent:CLINIC_BATCH_COPY.notSent;/* @__PURE__ */
|
|
294
|
+
return jsxRuntime.jsxs(reactNative.View,{style:local.option,accessible:true,accessibilityRole:"text",accessibilityLabel:[`${name}. ${status}.`,row.created?row.request?.statusLabel:row.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${row.created?"created":"failed"}`,children:[
|
|
295
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.optionName,children:name}),
|
|
296
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:status}),row.created&&row.request?.statusLabel?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:row.request.statusLabel}):null,!row.created&&row.failureReason?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:row.failureReason}):null]},row.idempotencyKey)}),form.group?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.bodyText,children:CLINIC_BATCH_COPY.responded(form.group.responded,form.group.total)}):null,form.group?.members.map(member=>member.statusLabel?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:[member.clinicName,member.statusLabel].filter(Boolean).join(": ")},member.id):null)]}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
297
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
|
|
298
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:CLINIC_REQUEST_COPY.ownerName}),
|
|
299
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.ownerName,style:styles.field,value:form.ownerName,maxLength:200,editable:!form.busy,autoComplete:"name",autoCapitalize:"words",returnKeyType:"done",onChangeText:form.setOwnerName,testID:"records-batch-owner-name"})]}),form.drafts.map(draft=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.draft,testID:`records-batch-draft-${draft.key}`,children:[
|
|
300
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.optionName,children:draftName(draft)}),draftNeedsEmail(draft)?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
301
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:draft.email.trim()?draft.email:CLINIC_BATCH_COPY.emailToAdd}),
|
|
302
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.email,style:styles.field,value:draft.email,placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:320,editable:!form.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,returnKeyType:"done",onChangeText:value=>form.setDraftEmail(draft.key,value)})]}):null,
|
|
303
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_BATCH_COPY.remove(draftName(draft)),kind:"link",disabled:form.busy,onPress:()=>form.removeDraft(draft.key),style:local.remove})]},draft.key)),
|
|
304
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
|
|
305
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:form.atCap?CLINIC_BATCH_COPY.atCap:CLINIC_BATCH_COPY.addClinic}),!form.atCap&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
306
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:styles.field,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",onSubmitEditing:search,onChangeText:form.setQuery,testID:"records-batch-search-input"}),
|
|
307
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.search,kind:"outline",disabled:!canSearch,onPress:search,testID:"records-batch-search"}),form.query.trim().length>0&&form.clinics.length===0&&!form.searching?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_BATCH_COPY.addClinic,kind:"link",disabled:form.busy,onPress:form.addFreeText,testID:"records-batch-add-typed"}):null,form.searching?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading}):null,form.recent.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:styles.fieldLabel,children:CLINIC_REQUEST_COPY.recentlyUsed}):null,form.recent.map(clinic=>option(`recent-${clinic.id}`,clinic)),form.visibleClinics.map(clinic=>option(clinic.id,clinic)),form.hasMoreClinics?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.moreClinics,kind:"link",disabled:form.busy,onPress:form.showMoreClinics}):null]})]}),
|
|
308
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.scopeCard,accessibilityRole:"summary",testID:"records-batch-scope",children:[
|
|
309
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeText,testID:"records-batch-scope-text",children:form.drafts.length>0&&form.ownerName.trim()?form.scopeText??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading})]}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",style:styles.bodyText,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:form.error.displayMessage})}),!form.copy&&form.error&&/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onPress:form.retryCopy})]}),
|
|
310
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]}),form.outcome?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.footer,{paddingBottom:Math.max(insets.bottom,theme.space.md)}],testID:"records-batch-footer",children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:sendLabel,disabled:form.busy||!form.ready||!signed,busy:form.busy,onPress:()=>{reactNative.Keyboard.dismiss(),form.submit()},testID:"records-batch-send"})})]})]})}function useLocalStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles2(theme),[theme])}function makeLocalStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({header:{flexDirection:"row",alignItems:"center",gap:space.md,paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md},title:{flex:1,...text3(type.size.heading,type.lineHeight.snug,color.brandInk,"bold")},close:{minHeight:touch,minWidth:touch,alignItems:"center",justifyContent:"center"},closeLabel:text3(type.size.body,type.lineHeight.snug,color.linkInk,"bold"),content:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.lg},lead:text3(type.size.body,type.lineHeight.normal,color.text.muted),block:{gap:space.sm},sectionTitle:text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),option:{minHeight:touch,justifyContent:"center",gap:space.xs/2,borderRadius:radius.md,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},optionName:text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),draft:{gap:space.sm,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,padding:space.md},remove:{alignSelf:"flex-start",minHeight:touch,paddingHorizontal:0},scopeCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.sm},scopeText:text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.secondary),footer:{paddingHorizontal:space.lg,paddingTop:space.md,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background}})}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__ */
|
|
311
|
+
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__ */
|
|
312
|
+
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(
|
|
313
|
+
/* @__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__ */
|
|
314
|
+
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__ */
|
|
315
|
+
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__ */
|
|
316
|
+
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__ */
|
|
317
|
+
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__ */
|
|
318
|
+
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__ */
|
|
319
|
+
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__ */
|
|
320
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}var IOS2=reactNative.Platform.OS==="ios";function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles3(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),depthClient=useEverfurRecordsDepthClient(),[png,setPng]=react.useState(null),[mode,setMode]=react.useState("draw"),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:controller??runtimeController,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}):padCapture,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),formRef=react.useRef(form);formRef.current=form;let onPadChange=react.useCallback(next=>{setPng(next),formRef.current.setSigned(next!==null)},[]),busy=form.busy,keyboard=useChatKeyboardOffset(void 0,IOS2);/* @__PURE__ */
|
|
321
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
322
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:form.title,onBack:onBack,testID:"records-consent-header"}),
|
|
323
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:IOS2?"padding":void 0,style:styles.body,...keyboard.avoidingProps,children:[
|
|
324
|
+
/* @__PURE__ */jsxRuntime.jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),
|
|
325
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.content,keyboardShouldPersistTaps:"handled",keyboardDismissMode:IOS2?"interactive":"on-drag",testID:"records-consent",children:[
|
|
326
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.lead,testID:"records-consent-lead",children:RECORDS_CONSENT_COPY.leadNative}),
|
|
327
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.scopeCard,accessibilityRole:"summary",children:[
|
|
328
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeHeading,accessibilityRole:"header",children:RECORDS_CONSENT_COPY.scopeHeading}),
|
|
329
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeBody,children:RECORDS_CONSENT_COPY.scopeBody}),
|
|
330
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.bullets,children:RECORDS_CONSENT_COPY.whatWeDo.map(line2=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.bulletRow,children:[
|
|
331
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.check,children:"✓"}),
|
|
332
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.bulletText,children:line2})]},line2))}),
|
|
333
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.retentionRow,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.retentionText,children:RECORDS_CONSENT_COPY.retentionNote})}),form.copy&&form.scope?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.serverScope,testID:"records-consent-scope",children:form.scope}):form.scopeAwaitingName?null:form.copyError?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
334
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",children:form.copyError.displayMessage}),
|
|
335
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onPress:form.retryCopy,testID:"records-consent-copy-retry"})]}):/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,accessibilityLiveRegion:"polite",children:RECORDS_COPY.loading})]}),
|
|
336
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>form.setAuthorized(!form.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:form.authorized},accessibilityLabel:RECORDS_CONSENT_COPY.authorizeLabel(petName),hitSlop:6,style:[local.toggle,form.authorized?local.toggleChecked:null],testID:"records-authorize-toggle",children:[
|
|
337
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.box,form.authorized?local.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:form.authorized?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.boxCheck,children:"✓"}):null}),
|
|
338
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.toggleLabel,children:RECORDS_CONSENT_COPY.authorizeLabel(petName)})]}),
|
|
339
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
|
|
340
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.fullName}),
|
|
341
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:RECORDS_CONSENT_COPY.fullName,style:styles.field,value:form.ownerName,placeholder:RECORDS_CONSENT_COPY.fullNamePlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!busy,autoComplete:"name",autoCapitalize:"words",onChangeText:form.setOwnerName,testID:"records-consent-owner-name"})]}),form.needsEmail?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,testID:"records-consent-email-block",children:[form.directoryClinicNoEmail?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.cautionNote,testID:"records-consent-no-email-note",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.cautionNoteText,children:RECORDS_CONSENT_COPY.noEmailNote(petName,form.clinicName)})}):null,
|
|
342
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.emailLabel}),
|
|
343
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:RECORDS_CONSENT_COPY.emailLabel,style:styles.field,value:form.email,placeholder:RECORDS_CONSENT_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:320,editable:!busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:form.setEmail,testID:"records-consent-clinic-email"}),form.emailError?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",children:form.emailError}):null,
|
|
344
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,testID:"records-consent-review-note",children:RECORDS_CONSENT_COPY.newClinicDirectSendNote})]}):null,onCaptureSignature?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.signatureBlock,children:[form.signatures.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
|
|
345
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.reuseSignature}),
|
|
346
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:local.gallery,children:form.signatures.map(sig=>{let selected=form.reuseSignatureId===sig.signatureId;/* @__PURE__ */
|
|
347
|
+
return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>form.pickReuseSignature(selected?null:sig.signatureId),accessibilityRole:"button",accessibilityLabel:selected?RECORDS_CONSENT_COPY.reuseTileSelectedA11y:RECORDS_CONSENT_COPY.reuseTileA11y,style:[local.tile,selected?local.tileSelected:null],testID:`records-consent-reuse-${sig.signatureId}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:sig.previewUrl},style:local.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},sig.signatureId)})}),
|
|
348
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:RECORDS_CONSENT_COPY.reuseHint})]}):null,
|
|
349
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.signatureHeader,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:mode==="type"?RECORDS_CONSENT_COPY.signType:RECORDS_CONSENT_COPY.signDraw})}),
|
|
350
|
+
/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:onPadChange,disabled:busy}),
|
|
351
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setMode(m=>m==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:mode==="draw"?RECORDS_CONSENT_COPY.toType:RECORDS_CONSENT_COPY.toDraw,style:local.modeToggle,testID:"records-consent-sign-mode-toggle",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.modeToggleText,children:mode==="draw"?RECORDS_CONSENT_COPY.toType:RECORDS_CONSENT_COPY.toDraw})}),
|
|
352
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:RECORDS_CONSENT_COPY.signatureHint(form.clinicName)})]}),
|
|
353
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.nextCard,accessibilityRole:"summary",testID:"records-consent-next",children:[
|
|
354
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeHeading,accessibilityRole:"header",children:RECORDS_CONSENT_COPY.whatHappensNext}),
|
|
355
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeBody,children:RECORDS_CONSENT_COPY.whatHappensNextBody})]}),form.error?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:form.error})}):null,form.created?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.bodyText,children:form.created.statusLabel||RECORDS_COPY.records}):null]}),
|
|
356
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.footer,testID:"records-consent-footer",children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?RECORDS_CONSENT_COPY.submitting:RECORDS_CONSENT_COPY.submit,disabled:!form.ready,busy:busy,onPress:()=>{reactNative.Keyboard.dismiss(),form.submit()},style:local.submit,testID:"records-consent-submit"})})]}),
|
|
357
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function useLocalStyles3(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles3(theme),[theme])}function makeLocalStyles3(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xl+space.xs,gap:space.lg+space.xs/2},lead:text3(type.size.body,type.lineHeight.normal,color.text.muted),scopeCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md},nextCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.sm},scopeHeading:{...text3(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:-.4},scopeBody:text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),bullets:{gap:space.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},check:{...text3(type.size.body,type.lineHeight.normal,color.brandInk,"bold")},bulletText:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary)},retentionRow:{paddingTop:space.xs,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},retentionText:text3(type.size.tiny,type.lineHeight.normal,color.text.muted),serverScope:{...text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.secondary),paddingTop:space.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:space.md,borderRadius:radius.lg-space.xs,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md+space.xs/2},toggleChecked:{borderColor:color.brandInk,backgroundColor:color.brandSoft},box:{width:space.xl,height:space.xl,borderRadius:radius.xs+1,borderWidth:1.6,borderColor:color.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},boxChecked:{backgroundColor:color.brandInk},boxCheck:{...text3(type.size.body,type.lineHeight.tight,color.surface,"bold")},toggleLabel:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"bold")},block:{gap:space.sm},signatureBlock:{gap:space.sm},gallery:{gap:space.sm,paddingVertical:space.xs},tile:{width:space.xxl*3+space.lg,height:space.xxl+space.lg+space.sm,borderRadius:radius.sm,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,overflow:"hidden"},tileSelected:{borderColor:color.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...text3(type.size.bodyTight,type.lineHeight.snug,color.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.xxl,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background},submit:{minHeight:space.xxl+space.lg+space.xs+space.xs/2}})}function fileHandleFromMedia(source){let handle={uri:source.uri,mimeType:source.mimeType},size=mediaByteSize(source);return size!==null&&(handle.sizeBytes=size),/* @__PURE__ */Object.freeze(handle)}function mediaByteSize(source){let candidate=source.byteSize??source.sizeBytes;return typeof candidate=="number"&&Number.isFinite(candidate)&&candidate>=0?candidate:null}function captureOptionsFor(mode,maxDurationSeconds){/* @__PURE__ */
|
|
358
|
+
return Object.freeze({mode:mode})}function isCaptureAvailable(camera){return camera!=null&&camera.isAvailable===true}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 REQUEST_LIST_COPY=/* @__PURE__ */Object.freeze({title:"Medical records",subtitle:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s uploads and clinic requests`:"Every upload and clinic request"},requestRecords:"Request records",requestRecordsA11y:"Request records from a clinic",uploadOwn:"I already have the records",ownerUpload:"Records you uploaded",clinicRequest:"Clinic request",meta:(ownerUpload,createdAt)=>`${ownerUpload?"Uploaded":"Requested"} ${formatRecordsDate(createdAt)}`,rowA11y:(source,meta,status)=>`${source}, ${meta}, status ${status}`,allRequests:"Your record requests"}),STEP_LABELS=/* @__PURE__ */Object.freeze({preparing:"Preparing",sent:"Sent",processing:"Processing",done:"Ready"});function stepLabel(status){switch(status){case"awaiting_clinic":return STEP_LABELS.sent;case"received":case"parsing":case"in_review":return STEP_LABELS.processing;case"published":return STEP_LABELS.done;default:return STEP_LABELS.preparing}}function requestRowView(request){let ownerUpload=request.source==="owner_provided",source=request.clinicName?.trim()||(ownerUpload?REQUEST_LIST_COPY.ownerUpload:REQUEST_LIST_COPY.clinicRequest),status=request.statusLabel.trim()||stepLabel(request.status),meta=REQUEST_LIST_COPY.meta(ownerUpload,request.createdAt);/* @__PURE__ */
|
|
359
|
+
return Object.freeze({source:source,meta:meta,status:status,ownerUpload:ownerUpload,a11yLabel:REQUEST_LIST_COPY.rowA11y(source,meta,status)})}var PROCESSING_WIRE=/* @__PURE__ */new Set(["records_received","parsing","parsing_failed","in_review","review_email_failed"]),PROCESSING_FOLDED=/* @__PURE__ */new Set(["received","parsing","in_review"]);function isProcessing(request){return request.wireStatus!==void 0?PROCESSING_WIRE.has(request.wireStatus):PROCESSING_FOLDED.has(request.status)}function requestsStatusCardView(requests,petName,opts={}){let active=requests.filter(r=>!isTerminalStatus(r.status));if(requests.length===0||opts.activeOnly===true&&active.length===0)return null;let processing=requests.filter(isProcessing).length,title=processing>0?`${processing} document${processing===1?"":"s"} being read`:active.length>0?`${active.length} active record request${active.length===1?"":"s"}`:REQUEST_LIST_COPY.allRequests,subtitle=processing>0?`We’ll add ${processing===1?"it":"them"} to ${petName}’s records once ready.`:active.length>0?"See each clinic’s status and what happens next.":"See the status of every upload and clinic request.";/* @__PURE__ */
|
|
360
|
+
return Object.freeze({title:title,subtitle:subtitle,processing:processing>0,a11yLabel:`${title}. ${subtitle}`})}function canUploadRecords(onPickDocument){return onPickDocument!==void 0}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 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__ */
|
|
361
|
+
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 RING_SIZE=200,RING_STROKE=16;function buildRingSegments(summary,colors){let denominator=summary.inRangeCount+summary.outOfRangeCount+summary.unknownCount;if(!Number.isFinite(denominator)||denominator<=0)return[];let buckets=[{key:"in_range",color:colors.inRange,count:summary.inRangeCount},{key:"out_of_range",color:colors.outOfRange,count:summary.outOfRangeCount},{key:"unknown",color:colors.unknown,count:summary.unknownCount}],cumulative=0,out=[];for(let bucket of buckets){if(!(bucket.count>0))continue;let sweepDeg=bucket.count/denominator*360;if(!Number.isFinite(sweepDeg))return null;out.push({key:bucket.key,color:bucket.color,startDeg:cumulative,sweepDeg:sweepDeg}),cumulative+=sweepDeg}return out}function MarkerSummaryCard({summary:summary,onAsk:onAsk,testID:testID}){let styles=useStyles5(),theme=useEverfurTheme(),{totalMarkers:totalMarkers,inRangeCount:inRangeCount,outOfRangeCount:outOfRangeCount,unknownCount:unknownCount}=summary,segments=react.useMemo(()=>buildRingSegments(summary,{inRange:theme.color.success,outOfRange:theme.color.danger,unknown:theme.color.text.muted}),[summary,theme]),hasArcs=segments!==null&&segments.length>0;/* @__PURE__ */
|
|
362
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.card,accessibilityRole:"summary",testID:testID,children:[
|
|
363
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,children:MARKER_SUMMARY_COPY.title}),
|
|
364
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:MARKER_SUMMARY_COPY.a11y(totalMarkers,inRangeCount,outOfRangeCount,unknownCount),children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.ringWrap,children:[
|
|
365
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.track}),segments===null?null:segments.map(segment=>/* @__PURE__ */jsxRuntime.jsx(Arc,{segment:segment,styles:styles},segment.key)),
|
|
366
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.center,pointerEvents:"none",children:[
|
|
367
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.centerCount,children:totalMarkers}),
|
|
368
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.centerLabel,children:totalMarkers===1?MARKER_SUMMARY_COPY.marker:MARKER_SUMMARY_COPY.markers})]})]})}),hasArcs||segments===null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.badges,children:[
|
|
369
|
+
/* @__PURE__ */jsxRuntime.jsx(Badge,{count:outOfRangeCount,label:MARKER_SUMMARY_COPY.outOfRange,color:theme.color.danger,styles:styles}),
|
|
370
|
+
/* @__PURE__ */jsxRuntime.jsx(Badge,{count:inRangeCount,label:MARKER_SUMMARY_COPY.inRange,color:theme.color.success,styles:styles}),unknownCount>0?/* @__PURE__ */jsxRuntime.jsx(Badge,{count:unknownCount,label:MARKER_SUMMARY_COPY.noRange,color:theme.color.text.muted,styles:styles}):null]}):null,
|
|
371
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.subtitle,children:MARKER_SUMMARY_COPY.subtitle}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:MARKER_SUMMARY_COPY.ask,style:styles.ask,testID:"marker-summary-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.askLabel,children:MARKER_SUMMARY_COPY.ask})}):null]})}function Arc({segment:segment,styles:styles}){return(segment.sweepDeg<=180?[{start:segment.startDeg,sweep:segment.sweepDeg}]:[{start:segment.startDeg,sweep:180},{start:segment.startDeg+180,sweep:segment.sweepDeg-180}]).map((piece,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.piece,{transform:[{rotate:`${piece.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${segment.key}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.window,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.halfRing,{borderTopColor:segment.color,borderRightColor:segment.color,transform:[{rotate:`${piece.sweep-135}deg`}]}]})})},index))}function Badge({count:count,label:label,color:color,styles:styles}){/* @__PURE__ */
|
|
372
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.badge,{borderColor:color}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeText,{color:color}],children:`${count} ${label}`})})}function useStyles5(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles7(theme),[theme])}function makeStyles7(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=reactNative.StyleSheet.hairlineWidth,cardText=slotText(slots.recordCard);return reactNative.StyleSheet.create({card:{borderRadius:radius.lg,backgroundColor:color.surfaceCream,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.sm+space.xs/2,...slotBox(slots.recordCard,1)},title:{...face(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.brandInk,letterSpacing:-.4,...cardText},ringRow:{alignItems:"center"},ringWrap:{width:RING_SIZE,height:RING_SIZE,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:RING_SIZE,height:RING_SIZE,borderRadius:RING_SIZE/2,borderWidth:RING_STROKE,borderColor:color.surfaceSubtle},piece:{position:"absolute",width:RING_SIZE,height:RING_SIZE},window:{position:"absolute",left:RING_SIZE/2,top:0,width:RING_SIZE/2,height:RING_SIZE,overflow:"hidden"},halfRing:{position:"absolute",left:-RING_SIZE/2,top:0,width:RING_SIZE,height:RING_SIZE,borderRadius:RING_SIZE/2,borderWidth:RING_STROKE,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{...face(theme,"medium"),fontSize:type.size.verdict*2,lineHeight:type.size.verdict*2+space.xs,color:color.text.primary,textAlign:"center",...cardText},centerLabel:{...face(theme,"medium"),fontSize:type.size.heading-1,lineHeight:type.size.heading+space.xs/2,color:color.text.primary,textAlign:"center",...cardText},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:space.sm},badge:{borderWidth:1,borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs},badgeText:{...face(theme,"mono"),fontSize:type.size.nano,lineHeight:type.size.tiny,letterSpacing:type.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.relaxed),color:color.text.primary,...cardText},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.sm,marginTop:space.xs/2,paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},askLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.primary,letterSpacing:type.letterSpacing.tight}})}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 CAROUSEL_HEIGHT=416,PLOT_HEIGHT=140;function pct(value){return`${value}%`}function MarkerTrendCard({marker:marker,width:width,onPointPress:onPointPress,onAsk:onAsk}){let styles=useStyles6(),screen=useScreenStyles(),status=markerStatusLabel(marker.latest?.status??null),tone=markerStatusTone(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__ */
|
|
373
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.page,width!==void 0?{width:width}:null],testID:`marker-card-${marker.markerId}`,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
374
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.headerRow,children:[
|
|
375
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.nameColumn,children:[
|
|
376
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.markerName,numberOfLines:2,children:marker.name}),marker.unit?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.unit,children:marker.unit}):null]}),
|
|
377
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:MARKER_CARD_COPY.status(status.label),children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:status.label,tone:tone})})]}),marker.latest&&latestReading!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.latestRow,children:[
|
|
378
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.latestValue,status.outOfRange?styles.latestValueDanger:null],accessibilityLabel:MARKER_CARD_COPY.latestA11y(latestReading,status.label,formatRecordsDate(marker.latest.at)),children:latestReading}),
|
|
379
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.latestDate,children:formatRecordsDate(marker.latest.at)})]}):null,traj?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.trajectory,accessibilityRole:"text",children:traj}):null,chart!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.chartWrap,children:[
|
|
380
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[chart.band?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.band,{top:pct(chart.band.topPct),height:pct(Math.max(0,chart.band.bottomPct-chart.band.topPct))}]}):null,chart.points.map(p=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onPointPress(marker,p.point),hitSlop:12,style:[styles.point,p.status==="above"||p.status==="below"?styles.pointDanger:null,{left:pct(p.xPct),top:pct(p.yPct)}],testID:`marker-point-${marker.markerId}-${p.index}`},p.index))]}),
|
|
381
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.a11yTable,accessibilityRole:"summary",accessibilityLabel:MARKER_CARD_COPY.readingsA11y(marker.name),children:marker.points.map((point,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityRole:"text",accessibilityLabel:markerPointSpoken(marker,point)},index))}),
|
|
382
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:marker.points.length===1?styles.singleHint:styles.tapHint,children:marker.points.length===1?MARKER_CARD_COPY.singleHint:MARKER_CARD_COPY.tapHint})]}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.emptyBody,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.emptyText,children:MARKER_CARD_COPY.empty})}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onAsk(marker),accessibilityRole:"button",accessibilityLabel:MARKER_CARD_COPY.askNamed(marker.name),style:[screen.pill,screen.pillAsk],testID:`marker-ask-${marker.markerId}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:MARKER_CARD_COPY.askNamed(marker.name)})}):null]})})}function MarkerTrendCarousel({markers:markers,onPointPress:onPointPress,onAsk:onAsk}){let styles=useStyles6(),[width,setWidth]=react.useState(0),[activeIndex,setActiveIndex]=react.useState(0),onLayout=event=>setWidth(event.nativeEvent.layout.width),onMomentumEnd=event=>{if(width<=0)return;let next=Math.round(event.nativeEvent.contentOffset.x/width);setActiveIndex(Math.max(0,Math.min(next,markers.length-1)))},active=markers[activeIndex]??null;/* @__PURE__ */
|
|
383
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.carousel,onLayout:onLayout,testID:"marker-carousel",children:[
|
|
384
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:onMomentumEnd,snapToAlignment:"start",children:markers.map(marker=>/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCard,{marker:marker,width:width>0?width:void 0,onPointPress:onPointPress,onAsk:onAsk},marker.markerId))}),
|
|
385
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:MARKER_CAROUSEL_COPY.a11y(active?.name??null,activeIndex,markers.length),children:[
|
|
386
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dots,children:markers.map((marker,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,index===activeIndex?styles.dotActive:null]},marker.markerId))}),
|
|
387
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.counter,children:MARKER_CAROUSEL_COPY.counter(activeIndex,markers.length)})]})]})}function MarkerProvenanceSheet({marker:marker,point:point,onClose:onClose,onAsk:onAsk}){let styles=useStyles6(),screen=useScreenStyles();if(marker===null||point===null)return null;let row=(label,value)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${value}`,children:[
|
|
388
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailLabel,children:label}),
|
|
389
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailValue,children:value})]},label);/* @__PURE__ */
|
|
390
|
+
return jsxRuntime.jsxs(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:onClose,children:[
|
|
391
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:styles.backdrop,onPress:onClose,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.close}),
|
|
392
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[
|
|
393
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.handle}),
|
|
394
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheetHeader,children:[
|
|
395
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetTitle,accessibilityRole:"header",children:PROVENANCE_COPY.title}),
|
|
396
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onClose,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.close,hitSlop:10,style:styles.closeButton,testID:"marker-provenance-close",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.closeGlyph,children:"×"})})]}),
|
|
397
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheetBody,children:[
|
|
398
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.valueRow,children:[
|
|
399
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetName,children:marker.name}),
|
|
400
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.reviewedText,children:PROVENANCE_COPY.reviewed})}):null,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(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=reactNative.StyleSheet.hairlineWidth,dot=space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),cardText=slotText(slots.recordCard),nameText=text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),valueText=text3(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold");return reactNative.StyleSheet.create({page:{paddingHorizontal:space.sm},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(slots.recordCard,1)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,gap:space.xs/2},markerName:{...nameText,...cardText},sheetName:nameText,unit:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted,...cardText},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...valueText,...cardText},sheetValue:valueText,latestValueDanger:{color:color.danger},latestDate:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},trajectory:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...cardText},chartWrap:{gap:space.sm},plot:{height:PLOT_HEIGHT,borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:color.badgeBgPositive},point:{position:"absolute",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,borderWidth:2,borderColor:color.surface},pointDanger:{backgroundColor:color.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...text3(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center",...cardText},singleHint:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},emptyBody:{alignItems:"center",justifyContent:"center",gap:space.sm,paddingVertical:space.xxl+space.xs},emptyText:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},carousel:{height:CAROUSEL_HEIGHT},footer:{alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{flexDirection:"row",gap:space.xs+space.xs/2},dot:{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:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},backdrop:{flex:1,backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surfaceCream,borderTopLeftRadius:radius.xl-space.xs,borderTopRightRadius:radius.xl-space.xs,paddingHorizontal:space.lg+space.xs,paddingTop:space.sm,paddingBottom:space.xxl+space.xs,maxHeight:"80%",gap:space.md},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},sheetTitle:{flex:1,...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold")},closeButton:{width:space.xxl+space.md,height:space.xxl+space.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...text3(type.size.verdict,type.lineHeight.tight,color.text.primary)},sheetBody:{gap:space.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs,backgroundColor:color.badgeBgPositive},reviewedText:{...text3(type.size.tiny,type.lineHeight.normal,color.success,"medium")},detailRow:{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),unverified:text3(type.size.caption,type.lineHeight.normal,color.text.muted)})}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__ */
|
|
401
|
+
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 VACCINE_CATEGORIES=/* @__PURE__ */Object.freeze(["vaccination","parasite_prevention"]),VACCINE_UNDATED_GROUP="Undated",VACCINE_STATUS_LABEL=/* @__PURE__ */Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),VACCINE_CHIP_TONE=/* @__PURE__ */Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function toMillis(value){if(!value)return null;let ms=Date.parse(value);return Number.isNaN(ms)?null:ms}function isLapsed(entity){let status=entity.status?.toLowerCase()??"";return/overdue|lapsed|expired/.test(status)}function vaccineTone(entity){return entity.category==="parasite_prevention"?"prevention":toMillis(entity.observedAt)===null?"noDate":isLapsed(entity)?"overdue":"given"}function yearOf(at){let ms=toMillis(at);return ms===null?VACCINE_UNDATED_GROUP:String(new Date(ms).getUTCFullYear())}function buildRow(entity){let tone=vaccineTone(entity),parts=[entity.value!==null&&entity.value.length>0?entity.value:null,entity.observedAt!==null?formatRecordsDate(entity.observedAt):null].filter(part=>part!==null&&part.length>0);return{key:entity.key,name:entity.label,detail:parts.length>0?parts.join(" · "):null,statusLabel:VACCINE_STATUS_LABEL[tone],tone:tone,entity:entity}}function selectVaccineGroups(entities){let byYear=/* @__PURE__ */new Map;for(let entity of entities){if(!VACCINE_CATEGORIES.includes(entity.category))continue;let year=yearOf(entity.observedAt),bucket=byYear.get(year),item={row:buildRow(entity),at:entity.observedAt};bucket===void 0?byYear.set(year,[item]):bucket.push(item)}let years=[...byYear.keys()].sort((a,b)=>a===VACCINE_UNDATED_GROUP?1:b===VACCINE_UNDATED_GROUP?-1:Number(b)-Number(a));/* @__PURE__ */
|
|
402
|
+
return Object.freeze(years.map(year=>{let items=byYear.get(year)??[],ordered=year===VACCINE_UNDATED_GROUP?items:[...items].sort((a,b)=>(toMillis(b.at)??0)-(toMillis(a.at)??0));/* @__PURE__ */
|
|
403
|
+
return Object.freeze({year:year,items:/* @__PURE__ */Object.freeze(ordered.map(i=>i.row))})}))}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let styles=useStyles7(),[open,setOpen]=react.useState(false),label=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
|
|
404
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.row,children:[
|
|
405
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.main,children:children}),
|
|
406
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setOpen(true),accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.editA11y(label),hitSlop:6,style:styles.editButton,testID:`fact-edit-open-${entity.canonicalKey??entity.key}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),open?/* @__PURE__ */jsxRuntime.jsx(FactEditSheet,{entity:entity,title:label,factEdit:factEdit,onClose:()=>setOpen(false)}):null]})}function FactEditSheet({entity:entity,title:title,factEdit:factEdit,onClose:onClose}){let styles=useStyles7(),screen=useScreenStyles(),theme=useEverfurTheme(),[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)})};/* @__PURE__ */
|
|
407
|
+
return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:"padding",style:styles.backdrop,children:[
|
|
408
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.closeEditorA11y,onPress:onClose}),
|
|
409
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[
|
|
410
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.handle}),
|
|
411
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.header,children:[
|
|
412
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.headerText,children:[
|
|
413
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,accessibilityRole:"header",children:FACT_EDIT_COPY.title(title)}),
|
|
414
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.helper,error?styles.helperError:null],accessibilityLiveRegion:"polite",children:error??FACT_EDIT_COPY.helper})]}),
|
|
415
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.close,onPress:onClose,hitSlop:12,style:styles.closeButton,testID:"fact-edit-close",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.closeGlyph,children:"×"})})]}),
|
|
416
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.fieldLabel,children:entity.label}),
|
|
417
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:entity.label,style:screen.field,value:draft,onChangeText:value=>{setDraft(value),setLocalError(null)},editable:!busy,maxLength:512,placeholderTextColor:theme.color.text.placeholder,testID:"fact-edit-field"}),confirmingRemove?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.confirmBlock,testID:"fact-edit-confirm-remove",children:[
|
|
418
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.confirmText,children:FACT_EDIT_COPY.confirmRemove}),
|
|
419
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.confirmRow,children:[
|
|
420
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.removing:FACT_EDIT_COPY.removeConfirm,kind:"danger",busy:busy,onPress:submitRemove,style:styles.confirmButton,testID:"fact-edit-remove-confirm"}),
|
|
421
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:FACT_EDIT_COPY.keep,kind:"outline",disabled:busy,onPress:()=>setConfirmingRemove(false),style:styles.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actions,children:[
|
|
422
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.saving:FACT_EDIT_COPY.save,busy:busy,disabled:!changed,onPress:submitEdit,testID:"fact-edit-save"}),
|
|
423
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.remove,disabled:busy,onPress:()=>{setLocalError(null),setConfirmingRemove(true)},style:[styles.removeButton,busy?styles.removeDisabled:null],testID:"fact-edit-remove",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.removeText,children:FACT_EDIT_COPY.remove})})]})]})]})})}function useStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles9(theme),[theme])}function makeStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:space.sm},main:{flex:1},editButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},pencil:{width:space.md+space.xs/2,height:space.xs/2,backgroundColor:color.brandInk,borderRadius:radius.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surface,borderTopLeftRadius:radius.xl-1,borderTopRightRadius:radius.xl-1,paddingHorizontal:space.lg+space.xs+space.xs/2,paddingTop:space.md,paddingBottom:radius.xl,maxHeight:"88%",gap:space.md},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},headerText:{flex:1,gap:space.xs},title:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},helper:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),helperError:{color:errorColor},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:text3(type.size.verdict,type.lineHeight.tight,color.text.primary),actions:{gap:space.sm},removeButton:{minHeight:touch,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...text3(type.size.bodyTight,type.lineHeight.snug,color.danger,"bold")},confirmBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.badgeBgCritical},confirmText:text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),confirmRow:{flexDirection:"row",gap:space.sm},confirmButton:{flex:1}})}function RecordSections({record:record,depth:depth,petName:petName,showLabs:showLabs=true,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit,nowMs:nowMs}){let styles=useScreenStyles(),local=useLocalStyles4(),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||VACCINE_CATEGORIES.includes(category))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]),vaccineGroups=react.useMemo(()=>selectVaccineGroups(entities),[entities]),documents=Object.values(record.documents),ask=(build,label,testID)=>onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{let built=build();onAsk(built.prompt,built.entityRef)},accessibilityRole:"button",accessibilityLabel:label,style:[styles.pill,styles.pillAsk,local.ask],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.pillAskLabel,children:label})}):null,editable=factEdit!==void 0&&factEdit.available;/* @__PURE__ */
|
|
424
|
+
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
425
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.sections,children:[depth&&depth.conflicts.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-conflicts",children:[
|
|
426
|
+
/* @__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__ */
|
|
427
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[local.conflictCard,{borderColor:styles.chipTones[meta.tone].fg.color}],accessibilityRole:"summary",children:[
|
|
428
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.conflictHead,children:[
|
|
429
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.conflictTitle,children:meta.label}),
|
|
430
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:scope,tone:meta.tone})]}),
|
|
431
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:RECORD_SCREEN_COPY.conflictSub}),conflict.candidates.map((candidate,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.candidate,children:[
|
|
432
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:candidate.value}),
|
|
433
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{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(reactNative.View,{style:styles.section,testID:"record-section-completeness",children:[
|
|
434
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.whatsOnFile}),
|
|
435
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
436
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.coverageRow,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(reactNative.View,{style:[local.coveragePill,present?styles.chipTones.positive.bg:styles.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.coverageText,present?styles.chipTones.positive.fg:{color:styles.rowMuted.color}],children:label})},label))}),
|
|
437
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.metaRow,children:[
|
|
438
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,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(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel: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(reactNative.View,{style:local.metaRow,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,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(Text,{style:local.pendingText,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(reactNative.View,{style:styles.section,testID:"record-section-documents",children:[
|
|
439
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.documents,count:documents.length}),
|
|
440
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{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:[
|
|
441
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
442
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:title}),meta?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:meta}):null]}),onNavigate?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]});return onNavigate?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onNavigate({name:"contributions",docId:doc.docId}),accessibilityRole:"button",accessibilityLabel:RECORD_SCREEN_COPY.documentRowA11y(title),style:[styles.row,index>0?styles.rowDivider:null],testID:`records-document-row-${doc.docId}`,children:body},doc.docId):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:body},doc.docId)})})]}):null,record.identity.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-identity",children:[
|
|
443
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.identity}),
|
|
444
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:record.identity.map((field,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
445
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.identityLabel,children:field.label}),
|
|
446
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.identityValue,children:formatIdentityValue(field.value)})]},`${index}:${field.label}`))})]}):null,record.forwardLooking.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-upcoming",children:[
|
|
447
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.upcomingCare,count:record.forwardLooking.length}),
|
|
448
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:record.forwardLooking.map((item,index)=>{let badge=dueBadge(item.dueAt,now);/* @__PURE__ */
|
|
449
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
450
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
451
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:item.title}),item.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,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,vaccineGroups.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-vaccination",children:[
|
|
452
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:entityTypeLabel("vaccination"),count:vaccineGroups.reduce((n,g)=>n+g.items.length,0)}),vaccineGroups.map(group=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.vaccineGroup,testID:`records-vaccine-group-${group.year}`,children:[
|
|
453
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.vaccineYear,accessibilityRole:"header",children:group.year.toUpperCase()}),
|
|
454
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:group.items.map((row,index)=>{let body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
455
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
456
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:row.name}),row.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:row.detail}):null,ask(()=>buildEntityRowAskPrompt(petName,{entityTypeLabel:entityTypeLabel(row.entity.category),title:row.name,detail:row.detail},row.entity.category,row.key),RECORD_SCREEN_COPY.askEverfur,`records-ask-entity-${row.key}`)]}),
|
|
457
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:row.statusLabel,tone:VACCINE_CHIP_TONE[row.tone]})]});return editable&&isFactEditable(row.entity)&&factEdit?/* @__PURE__ */jsxRuntime.jsx(FactEditAffordance,{entity:row.entity,factEdit:factEdit,children:body},row.key):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:body},row.key)})})]},group.year))]}):null,byType.order.map(category=>{let rows=byType.groups.get(category)??[];if(rows.length===0)return null;let label=entityTypeLabel(category);/* @__PURE__ */
|
|
458
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:`record-section-${category}`,children:[
|
|
459
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:label,count:rows.length}),
|
|
460
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:rows.map((entity,index)=>{let detail=[formatEntityValue(entity.value,entity.unit),entity.observedAt?formatRecordsDate(entity.observedAt):null].filter(part=>part&&part.length>0).join(" · "),row=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
461
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
462
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:entity.label}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:detail}):null,ask(()=>buildEntityRowAskPrompt(petName,{entityTypeLabel:label,title:entity.label,detail:detail||null},category,entity.key),RECORD_SCREEN_COPY.askEverfur,`records-ask-entity-${entity.key}`)]}),entity.status?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:humanize(entity.status)}):null]});return editable&&isFactEditable(entity)&&factEdit?/* @__PURE__ */jsxRuntime.jsx(FactEditAffordance,{entity:entity,factEdit:factEdit,children:row},entity.key):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:row},entity.key)})})]},category)}),depth&&depth.physicalExams.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-exams",children:[
|
|
463
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.physicalExams,count:depth.physicalExams.length}),depth.physicalExams.map(exam=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
464
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.rowTitle,local.cardTitle],accessibilityRole:"header",children:exam.observedOn?formatRecordsDate(exam.observedOn):DEPTH_COPY.exam}),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__ */
|
|
465
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[bodySystemLabel(system.system),label,abnormal?system.finding:null].filter(Boolean).join(", "),children:[
|
|
466
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
467
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:bodySystemLabel(system.system)}),abnormal&&system.finding?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:system.finding}):null]}),
|
|
468
|
+
/* @__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(reactNative.View,{style:styles.section,testID:"record-section-notes",children:[
|
|
469
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.visitNotes,count:depth.clinicianNotes.length}),depth.clinicianNotes.map(note=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
470
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.rowTitle,local.cardTitle],accessibilityRole:"header",children:note.observedOn?formatRecordsDate(note.observedOn):DEPTH_COPY.visitNote}),note.sections.map((section,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.noteSection,index>0?styles.rowDivider:null],children:[
|
|
471
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteLabel,children:soapSectionLabel(section.section)}),
|
|
472
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:section.text?local.noteBody:local.noteBodyMuted,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(reactNative.View,{style:styles.section,testID:"record-section-labs",children:[
|
|
473
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.labResults,count:depth.labResults.length}),
|
|
474
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{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__ */
|
|
475
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
476
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
477
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:marker.name}),
|
|
478
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:formatMarkerReading(marker.latest.value,marker.latest.unit,marker.latest.qualitativeResult)}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:detail}):null]}),
|
|
479
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:status.label,tone:markerStatusTone(marker.latest.status)})]},marker.markerId)})})]}):null,depth&&depth.encounters.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-visits",children:[
|
|
480
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.visits,count:depth.encounters.length}),
|
|
481
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{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__ */
|
|
482
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
483
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:encounter.type?humanize(encounter.type):DEPTH_COPY.visit}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:detail}):null]})},encounter.encounterId)})})]}):null]}),
|
|
484
|
+
/* @__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 useLocalStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...face(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}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,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!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,isDevelopment3){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=reactNative.Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}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."});function uploadActionA11y(label,meta){return`${label} ${meta}`}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 pct2=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:`${pct2}%`;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 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",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),events=buildRequestTimeline(request,{petName:petName??null});/* @__PURE__ */
|
|
485
|
+
return jsxRuntime.jsx(reactNative.View,{style:styles.container,accessibilityRole:"summary",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,a11yParts=[event.title,event.detail,date,A11Y_STATE[event.state]].filter(Boolean);/* @__PURE__ */
|
|
486
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.row,accessible:true,accessibilityRole:"text",accessibilityLabel:a11yParts.join(", "),testID:`records-timeline-${event.key}`,children:[
|
|
487
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.railColumn,children:[
|
|
488
|
+
/* @__PURE__ */jsxRuntime.jsx(TimelineDot,{state:event.state,styles:styles}),isLast?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.connector,event.state==="done"&&styles.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),
|
|
489
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.body,children:[
|
|
490
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.titleRow,children:[
|
|
491
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.title,event.state==="current"&&styles.titleCurrent,event.state==="failed"&&styles.titleFailed,event.state==="upcoming"&&styles.titleUpcoming],children:event.title}),event.state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.now,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.nowText,children:NOW})}):null,date?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.date,children:date}):null]}),event.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.detail,event.state==="upcoming"&&styles.detailUpcoming],children:event.detail}):null]})]})}function TimelineDot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:[styles.glyph,styles.glyphOnBrand],children:"✓"})}):state==="failed"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.glyph,children:"!"})}):state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dotCurrentCore})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function useStyles8(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles10(theme),[theme])}function makeStyles10(theme){let{color:color,type:type}=theme,{size:size}=type;return reactNative.StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:DOT_SIZE},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",gap:8},dot:{width:DOT_SIZE,height:DOT_SIZE,borderRadius:DOT_SIZE/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:color.brand,borderWidth:2,borderColor:color.primaryEdge},dotFailed:{backgroundColor:color.danger},dotCurrent:{borderWidth:2,borderColor:color.brandInk,backgroundColor:color.surface},dotCurrentCore:{width:DOT_CORE_SIZE,height:DOT_CORE_SIZE,borderRadius:DOT_CORE_SIZE/2,backgroundColor:color.mark},now:{borderRadius:theme.radius.pill,backgroundColor:color.highlight,paddingHorizontal:theme.space.sm,paddingVertical:theme.space.xs/2},nowText:{...face(theme,"monoBold"),fontSize:size.tiny,lineHeight:size.tiny+4,letterSpacing:.6,color:color.onHighlight,textTransform:"uppercase"},dotUpcoming:{borderWidth:2,borderColor:color.structureEdge,backgroundColor:color.surface},glyph:{...face(theme,"bold"),fontSize:size.caption,lineHeight:size.caption+2,color:color.surface},glyphOnBrand:{color:color.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:color.structureEdge,marginVertical:2},connectorDone:{backgroundColor:color.primaryEdge},title:{flexShrink:1,...face(theme,"bold"),fontSize:size.bodyTight,lineHeight:size.bodyTight+4,color:color.text.primary},titleCurrent:{color:color.brandInk},titleFailed:{color:color.danger},titleUpcoming:{color:color.text.muted,...face(theme,"regular")},date:{marginLeft:"auto",...face(theme,"regular"),fontSize:size.caption,lineHeight:size.caption+4,color:color.text.muted},detail:{...face(theme,"regular"),fontSize:size.caption,lineHeight:size.caption+5,color:color.text.muted},detailUpcoming:{color:color.text.muted,opacity:.7}})}function renderErrorFamily(records,onGrant,canGrant,consentText){let errorView=selectErrorView(records,canGrant);switch(errorView.kind){case"consent_required":/* @__PURE__ */
|
|
492
|
+
return jsxRuntime.jsx(ConsentRequiredState,{onGrant:onGrant,consentText:consentText});case"consent_unavailable":/* @__PURE__ */
|
|
493
|
+
return jsxRuntime.jsx(ConsentUnavailableState,{});case"session_required":/* @__PURE__ */
|
|
494
|
+
return jsxRuntime.jsx(SessionRequiredState,{});case"withheld":/* @__PURE__ */
|
|
495
|
+
return jsxRuntime.jsx(WithheldState,{});case"pet_not_found":case"error":/* @__PURE__ */
|
|
496
|
+
return jsxRuntime.jsx(ErrorState,{error:errorView.error,onRetry:records.refresh});default:return assertNever(errorView)}}function makeGrantHandler(records,consentVersion){return()=>{let version=resolveConsentVersion(consentVersion,records.consent);if(version.length===0)return;let key=`records-consent-${Date.now().toString(36)}`;records.grantConsent(version,key)}}function UploadQueue({records:records}){let styles=useStyles9(),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__ */
|
|
497
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.timeline,testID:"records-upload-queue",children:[skipped!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:styles.errorText,children:skipped}):null,rows.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",accessibilityLabel:records.isUploading?UPLOAD_QUEUE_COPY.uploading(done,rows.length):UPLOAD_QUEUE_COPY.uploaded(done,rows.length),children:rows.map(item=>{let pct2=Math.round(item.progress*100);
|
|
498
|
+
/* @__PURE__ */
|
|
499
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRow,testID:`records-upload-file-${item.status}`,children:[
|
|
500
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRowHead,children:[
|
|
501
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowLabel,children:item.name??""}),
|
|
502
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:uploadItemStatusLabel(item)})]}),item.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:pct2},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.progressFill,{width:`${pct2}%`}]})}):null,item.status==="failed"&&item.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:item.error.displayMessage}):null]},item.key)})}):null]})}function ConsentRequiredState({onGrant:onGrant,consentText:consentText}){let styles=useStyles9(),text3=presentConsentText(consentText);return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(RECORDS_COPY.consentRequired)},[]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,testID:"records-consent-gate",children:[
|
|
503
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:RECORDS_COPY.consentRequired}),text3!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.disclaimer,testID:"records-consent-gate-body",children:text3}):null,
|
|
504
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onGrant,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.allow,style:styles.primaryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.primaryLabel,children:RECORDS_COPY.allow})})]})}function AlertState({label:label,glyph:glyph}){let styles=useStyles9();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(label)},[label]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:label,children:[
|
|
505
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:glyph==="withheld"?styles.withheldGlyph:styles.emptyGlyph}),
|
|
506
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:label})]})}function ConsentUnavailableState(){/* @__PURE__ */
|
|
507
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.consentRequired,glyph:"empty"})}function SessionRequiredState(){/* @__PURE__ */
|
|
508
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}function WithheldState(){/* @__PURE__ */
|
|
509
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.recordUnavailable,glyph:"withheld"})}function ErrorState({error:error,onRetry:onRetry}){let styles=useStyles9();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(error.displayMessage)},[error.displayMessage]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[
|
|
510
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:error.displayMessage}),error.retryable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onRetry,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.retry,style:styles.primaryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.primaryLabel,children:RECORDS_COPY.retry})}):null]})}function ClinicCallCard({call:call,prompt:prompt}){let styles=useStyles9(),intro=prompt.trim().length>0?prompt:CALL_CLINIC_COPY.fallbackPrompt;/* @__PURE__ */
|
|
511
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.callCard,accessibilityRole:"summary",children:[
|
|
512
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineLabel,children:CALL_CLINIC_COPY.heading}),
|
|
513
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:intro}),
|
|
514
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{reactNative.Linking?.openURL?.(call.dial)},accessibilityRole:"button",accessibilityLabel:CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,testID:"records-call-clinic",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.linkLabel,children:CALL_CLINIC_COPY.call})})]})}function useStyles9(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles11(theme),[theme])}function makeStyles11(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight,letterSpacing:letterSpacing}=type,card=slotBox(slots.recordCard,reactNative.StyleSheet.hairlineWidth),cardText=slotText(slots.recordCard),lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,glyphSize=space.xxl+space.sm,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,softShadow={shadowColor:color.brand,shadowOffset:{width:0,height:space.xs},shadowRadius:space.sm,shadowOpacity:.08,elevation:space.xs};return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},withheldGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.sm,backgroundColor:color.badgeBgCaution,borderWidth:hairline,borderColor:color.cautionAccent},errorText:{...face(theme,"regular"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:errorColor,textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},linkButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},linkLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},disabledButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.brandBorder},disabledLabel:{...face(theme,"bold"),color:color.text.muted,fontSize:size.body,letterSpacing:letterSpacing.tight},list:{flex:1},listContent:{padding:space.lg,gap:space.md},timeline:{paddingVertical:space.md,paddingHorizontal:space.lg,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,gap:space.xs,...softShadow,...card},timelineTitle:{...face(theme,"bold"),fontSize:size.heading,lineHeight:lh(size.heading,lineHeight.snug),color:color.text.primary,letterSpacing:letterSpacing.tight,...cardText},timelineLabel:{...face(theme,"bold"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:color.text.secondary,letterSpacing:letterSpacing.tight,...cardText},callCard:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...card},timelineMeta:{...face(theme,"regular"),fontSize:size.bodyTight,lineHeight:lh(size.bodyTight,lineHeight.normal),color:color.text.muted,...cardText},recordBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...softShadow,...card},row:{flexDirection:"row",justifyContent:"space-between",gap:space.md,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},rowLabel:{...face(theme,"regular"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.muted,flexShrink:1,...cardText},rowValue:{...face(theme,"medium"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.primary,textAlign:"right",flexShrink:1,...cardText},disclaimer:{...face(theme,"regular"),fontSize:size.caption,lineHeight:lh(size.caption,lineHeight.normal),color:color.text.muted,marginTop:space.md},uploadRow:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},uploadRowHead:{flexDirection:"row",justifyContent:"space-between",gap:space.md},progressTrack:{height:space.xs,borderRadius:radius.pill,backgroundColor:color.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:color.brand}})}function EverfurRecordsRequests(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
515
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RequestsBody,{...rest,style:style})})}function RequestsBody({petRef:petRef,petName:petName,controller:controller,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,style:style}){let styles=useScreenStyles(),local=useLocalStyles5(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),requests=react.useMemo(()=>selectRequestList(records.requests.filter(r=>r.petRef===petRef)),[records.requests,petRef]),ask=onAsk?request=>{let built=buildRecordsRequestAskPrompt(petName,{clinicName:request.clinicName??null,statusLabel:selectPrimaryLabel(request),status:request.status,heldItemCount:request.heldItemCount},request.id);onAsk(built.prompt,built.entityRef)}:void 0,body;return records.status==="loading"&&requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-list-loading"}):records.status==="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-list-error"}):requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-list-empty"}):body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:local.list,testID:"records-list-results",children:requests.map(request=>/* @__PURE__ */jsxRuntime.jsx(RequestRow,{request:request,onOpen:onNavigate?()=>onNavigate({name:"request",requestId:request.id}):void 0,onAsk:ask?()=>ask(request):void 0},request.id))}),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
516
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:REQUEST_LIST_COPY.title,onBack:onBack,testID:"records-list-header"}),requests.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.subtitle,testID:"records-list-subtitle",children:REQUEST_LIST_COPY.subtitle(petName)}):null,
|
|
517
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.footer,children:[
|
|
518
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_LIST_COPY.requestRecords,accessibilityLabel:REQUEST_LIST_COPY.requestRecordsA11y,onPress:()=>onNavigate({name:"clinicPicker"}),testID:"records-list-new"}),
|
|
519
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_LIST_COPY.uploadOwn,kind:"outline",onPress:()=>onNavigate({name:"upload"}),testID:"records-list-upload-own"})]}):null,
|
|
520
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RequestRow({request:request,onOpen:onOpen,onAsk:onAsk}){let styles=useScreenStyles(),local=useLocalStyles5(),row=requestRowView(request),tone=selectRequestStatusTone(request),content=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
521
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.bubble,styles.chipTones[tone].bg],accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
522
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.copy,children:[
|
|
523
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.source,numberOfLines:1,children:row.source}),
|
|
524
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.meta,numberOfLines:1,children:row.meta}),
|
|
525
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:row.status,tone:tone})})]}),onOpen?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]});/* @__PURE__ */
|
|
526
|
+
return jsxRuntime.jsxs(reactNative.View,{style:local.row,testID:`records-request-row-${request.id}`,children:[onOpen?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:row.a11yLabel,style:local.rowInner,testID:`records-request-open-${request.id}`,children:content}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.rowInner,accessible:true,accessibilityLabel:row.a11yLabel,children:content}),onOpen&&selectResumableUploadRequest(null,request)!==null?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.cardTitle,onPress:onOpen,testID:`records-request-resume-upload-${request.id}`}):null,onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",accessibilityHint:row.source,onPress:onAsk,testID:`records-request-ask-${request.id}`}):null]})}function RecordsRequestsStatusCard({requests:requests,petName:petName,activeOnly:activeOnly=false,onOpen:onOpen}){let local=useLocalStyles5(),view=requestsStatusCardView(requests,petNameOr(petName),{activeOnly:activeOnly});return view===null||onOpen===void 0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:view.a11yLabel,style:local.card,testID:"records-requests-status",children:[
|
|
527
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.cardBubble,view.processing?local.cardBubbleProcessing:null],accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
528
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.cardText,children:[
|
|
529
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,children:view.title}),
|
|
530
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardSubtitle,children:view.subtitle})]}),
|
|
531
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function useLocalStyles5(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles5(theme),[theme])}function makeLocalStyles5(theme){let{color:color,space:space,radius:radius,type:type}=theme,lh=(size,m)=>Math.round(size*m),bubble=space.xxl+space.xs/2;return reactNative.StyleSheet.create({subtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted,paddingHorizontal:space.lg,paddingBottom:space.md},list:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.md},row:{borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm},rowInner:{flexDirection:"row",alignItems:"center",gap:space.md},bubble:{width:bubble,height:bubble,borderRadius:bubble/2},copy:{flex:1,gap:space.xs+1},source:{...face(theme,"bold"),fontSize:type.size.body,lineHeight:lh(type.size.body,type.lineHeight.snug),color:color.text.primary},meta:{...face(theme,"regular"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny,type.lineHeight.normal),color:color.text.muted},footer:{paddingHorizontal:space.lg,paddingTop:space.sm+space.xs/2,paddingBottom:space.lg,gap:space.sm+space.xs/2,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},card:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs,paddingVertical:space.md},cardBubble:{width:space.xl+space.xs/2,height:space.xl+space.xs/2,borderRadius:radius.pill,borderWidth:2,borderColor:color.brandInk},cardBubbleProcessing:{borderColor:color.warningStrong,backgroundColor:color.badgeBgCaution},cardText:{flex:1,gap:2},cardTitle:{...face(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:lh(type.size.bodyTight,type.lineHeight.snug),color:color.brandInk},cardSubtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted}})}var readDepth=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty=value=>!value.available;function EverfurRecordsDashboard(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
532
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(DashboardBody,{...rest,style:style})})}function DashboardBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,style:style}){let styles=useScreenStyles(),local=useLocalStyles6(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),{runtime:runtime}=useEverfurContext(),photoWay=acceptsPhotos(records.uploadContentTypes)&&isCaptureAvailable(runtime.registry.services.camera),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth,depthEmpty),[provenance,setProvenance]=react.useState(null),onPointPress=react.useCallback((marker,point)=>setProvenance({marker:marker,point:point}),[]);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),clinicDecision=useCapability("recordsClinic"),canRequestFromClinic=clinicDecision.enabled||clinicDecision.isPending,markerList=markers.markers?.markers??[],hasMarkers=markerList.length>0,hasFullRecord=records.record!==null&&!records.record.isEmpty&&!records.record.withheld,drivingRequest=pickPetRecordsRequest(records.requests,petRef),petRequests=records.requests.filter(r=>r.petRef===petRef),openRequests=onNavigate?()=>onNavigate({name:"requests"}):void 0,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),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,labs=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[markers.markers?.summary?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(MarkerSummaryCard,{summary:markers.markers.summary,onAsk:askSummary,testID:"dashboard-marker-summary"})}):null,
|
|
533
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.lead,children:DASHBOARD_COPY.lead(petName)}),
|
|
534
|
+
/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCarousel,{markers:markerList,onPointPress:onPointPress,onAsk:askMarker})]}),actions=withRecord=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,local.actions],children:[withRecord?/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"record",label:DASHBOARD_COPY.viewFullRecord,onPress:()=>onNavigate({name:"record"}),testID:"dashboard-full-record-action"}):null,
|
|
535
|
+
/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"timeline",label:DASHBOARD_COPY.viewTimeline,onPress:()=>onNavigate({name:"timeline"}),testID:"dashboard-timeline-action"}),
|
|
536
|
+
/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"requests",label:REQUEST_LIST_COPY.allRequests,onPress:()=>onNavigate({name:"requests"}),testID:"dashboard-requests-action"})]}):null,addActions=inset=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,local.addActions],testID:"dashboard-actions",children:[canRequestFromClinic?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.requestFromClinic,onPress:()=>onNavigate({name:"clinicPicker"}),style:local.addCta,testID:"dashboard-actions-clinic"}):null,
|
|
537
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.uploadDocument,kind:"outline",onPress:()=>onNavigate({name:"upload"}),style:local.addCta,testID:"dashboard-actions-upload"})]}):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(reactNative.ScrollView,{contentContainerStyle:styles.contentTight,testID:"dashboard-record",children:[hasMarkers?labs:markers.status==="error"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.inset,local.actions],children:/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"retry",label:DASHBOARD_COPY.retryMarkers,onPress:retryAll,testID:"dashboard-markers-retry"})}):null,
|
|
538
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:records.record?/* @__PURE__ */jsxRuntime.jsx(RecordSections,{record:records.record,depth:depthView,petName:petName,showLabs:!hasMarkers,onNavigate:onNavigate,onAsk:onAsk}):null}),
|
|
539
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,activeOnly:true,onOpen:openRequests})}),addActions(),actions(true)]});break;case"error":body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(markers.error??records.error),message:(markers.error??records.error)?.displayMessage,onAction:(markers.error??records.error)?.retryable?retryAll:void 0,testID:"dashboard-error"});break;case"in_progress":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.content,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,
|
|
540
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,onOpen:openRequests}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.ways,testID:"dashboard-ways",children:[canRequestFromClinic?/* @__PURE__ */jsxRuntime.jsx(WayCard,{title:IN_PROGRESS_COPY.anotherClinic,sub:IN_PROGRESS_COPY.anotherClinicSub,onPress:()=>onNavigate({name:"clinicPicker"}),testID:"dashboard-way-clinic"}):null,
|
|
541
|
+
/* @__PURE__ */jsxRuntime.jsx(WayCard,{title:REQUEST_PROMPT_COPY.uploadDocument,...photoWay?{sub:IN_PROGRESS_COPY.uploadDocumentPhotoSub}:{},dashed:true,onPress:()=>onNavigate({name:"upload"}),testID:"dashboard-way-upload"})]}):null,
|
|
542
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"none":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.content,testID:"dashboard-request-prompt",children:[
|
|
543
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.promptCard,children:[
|
|
544
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.promptHeader,children:[
|
|
545
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.promptGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
546
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.promptTitle,children:REQUEST_PROMPT_COPY.title(petName)})]}),
|
|
547
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.promptBody,children:REQUEST_PROMPT_COPY.body}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
548
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.requestFromClinic,onPress:()=>onNavigate({name:"clinicPicker"}),style:local.promptCta,testID:"dashboard-request-prompt-clinic"}),
|
|
549
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.uploadDocument,kind:"outline",onPress:()=>onNavigate({name:"upload"}),style:local.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),
|
|
550
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,onOpen:openRequests}),
|
|
551
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"labs_only":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.contentTight,testID:"dashboard-labs-only",children:[labs,
|
|
552
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,activeOnly:true,onOpen:openRequests})}),addActions(),
|
|
553
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})}),actions(false)]});break;default:body=assertNever(view)}/* @__PURE__ */
|
|
554
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
555
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DASHBOARD_COPY.titleNative(petName),onBack:onBack,testID:"dashboard-header",right:onNavigate?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onNavigate({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:DASHBOARD_COPY.openTimeline,hitSlop:12,style:local.headerButton,testID:"dashboard-timeline-link",children:/* @__PURE__ */jsxRuntime.jsx(ListGlyph2,{})}):void 0}),
|
|
556
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),
|
|
557
|
+
/* @__PURE__ */jsxRuntime.jsx(MarkerProvenanceSheet,{marker:provenance?.marker??null,point:provenance?.point??null,onClose:()=>setProvenance(null),onAsk:askReading}),
|
|
558
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var ACTION_GLYPH_SIZE=18;function ActionRow({glyph:glyph,label:label,onPress:onPress,testID:testID}){let local=useLocalStyles6(),ink=useEverfurTheme().color.brandInk,icon=glyph==="record"?/* @__PURE__ */jsxRuntime.jsx(FileTextGlyph,{size:ACTION_GLYPH_SIZE,color:ink}):glyph==="timeline"?/* @__PURE__ */jsxRuntime.jsx(ListGlyph,{size:ACTION_GLYPH_SIZE,color:ink}):glyph==="requests"?/* @__PURE__ */jsxRuntime.jsx(InboxGlyph,{size:ACTION_GLYPH_SIZE,color:ink}):/* @__PURE__ */jsxRuntime.jsx(RefreshGlyph,{size:ACTION_GLYPH_SIZE,color:ink});/* @__PURE__ */
|
|
559
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,style:local.actionRow,testID:testID,children:[
|
|
560
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.actionLeft,children:[
|
|
561
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:testID?`${testID}-glyph`:void 0,children:icon}),
|
|
562
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionLabel,children:label})]}),
|
|
563
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function InProgressCard({request:request,petName:petName,onOpen:onOpen,onAsk:onAsk}){let styles=useScreenStyles(),local=useLocalStyles6(),title=IN_PROGRESS_COPY.title(petName),clinic=request.clinicName?.trim()??"",status=selectPrimaryLabel(request),content=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.inProgressInner,children:[
|
|
564
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.inProgressHead,children:[
|
|
565
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.inProgressHeadText,children:[
|
|
566
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.inProgressTitle,children:title}),clinic.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:clinic}):null]}),onOpen?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]}),
|
|
567
|
+
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:request,petName:petName}),status.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.statusCard,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.statusText,children:status})}):null]});/* @__PURE__ */
|
|
568
|
+
return jsxRuntime.jsxs(reactNative.View,{style:local.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:onOpen?false:void 0,accessibilityLabel:onOpen?void 0:IN_PROGRESS_COPY.a11y(petName),children:[onOpen?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:[title,clinic,status].filter(part=>part.length>0).join(". "),testID:"dashboard-in-progress-open",children:content}):content,onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",onPress:onAsk,testID:"dashboard-in-progress-ask"}):null]})}function WayCard({title:title,sub:sub,accessibilityLabel:accessibilityLabel,dashed:dashed=false,onPress:onPress,testID:testID}){let local=useLocalStyles6(),still=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
569
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??(sub?`${title}. ${sub}`:title),style:({pressed:pressed})=>[local.way,dashed?local.wayDashed:null,pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],testID:testID,children:[
|
|
570
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.wayText,children:[
|
|
571
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.wayTitle,children:title}),sub?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.waySub,children:sub}):null]}),
|
|
572
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function useLocalStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles6(theme),[theme])}function makeLocalStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md;return reactNative.StyleSheet.create({headerButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},actions:{gap:space.sm+space.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:space.md},actionIcon:{width:ACTION_GLYPH_SIZE,height:ACTION_GLYPH_SIZE,alignItems:"center",justifyContent:"center"},actionLabel:{flex:1,...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},inProgressCard:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.lg},inProgressHeadText:{flex:1,gap:space.xs/2},ways:{gap:space.sm},way:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg},wayDashed:{borderStyle:"dashed",borderColor:color.brandBorderStrong},wayText:{flex:1,gap:space.xs/2},wayTitle:{...face(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},waySub:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted},inProgressInner:{gap:space.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},inProgressTitle:{...face(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:-.4,color:color.brandInk},promptCard:{borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderRingCream,paddingHorizontal:space.lg+space.xs,paddingVertical:space.lg+space.xs/2},promptHeader:{flexDirection:"row",alignItems:"center",gap:space.xs+1},promptGlyph:{width:space.xl+1,height:space.xl+1,borderRadius:radius.xs,borderWidth:2,borderColor:color.warningStrong},promptTitle:{flex:1,...face(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:type.letterSpacing.headerBrand,color:color.brandInk},promptBody:{marginTop:space.sm-1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:space.lg+space.xs,color:color.text.primary},promptCta:{marginTop:space.sm-1,minHeight:space.xxl+space.sm},promptCtaSecondary:{marginTop:space.sm,minHeight:space.xxl+space.sm},addActions:{gap:space.sm},addCta:{minHeight:space.xxl+space.sm}})}var KIND_ORDER=/* @__PURE__ */Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function toMillis2(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__ */
|
|
573
|
+
return Object.freeze(rows.sort((a,b)=>{let am=toMillis2(a.at),bm=toMillis2(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,readTimeline=(client,petRef)=>client.getTimeline(petRef),timelineEmpty=value=>value.isEmpty;var contributionsEmpty=value=>value.contributions.length===0;function EverfurRecordsTimeline({petRef:petRef,style:style,onBack:onBack}){let state=useRecordsDepthRead(petRef,readTimeline,timelineEmpty);/* @__PURE__ */
|
|
574
|
+
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,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,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__ */
|
|
575
|
+
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,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,header:header,loading:loading,empty:empty,render:render,onBack:onBack}){let styles=useStyles10();/* @__PURE__ */
|
|
576
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...recordsGateExit(guardHost(onBack),BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.container,style],children:[header??null,
|
|
577
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:renderState(state,render,styles,loading,empty)}),
|
|
578
|
+
/* @__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(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:RECORDS_COPY.empty,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{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(reactNative.View,{style:styles.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:RECORDS_COPY.loading,children:visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{}):null})}function TimelineBody({timeline:timeline}){let styles=useStyles10(),rows=buildTimelineRows(timeline);/* @__PURE__ */
|
|
579
|
+
return jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.list,contentContainerStyle:styles.timelineContent,accessibilityLabel:DEPTH_COPY.timeline,children:[timeline.disclaimer.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(timeline.disclaimer),children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineBandText,children:timeline.disclaimer})}):null,rows.map((row,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[index>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineSeparator}):null,
|
|
580
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[row.kindLabel,row.date,row.title,row.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${row.kind}`,children:[
|
|
581
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
582
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.timelineBody,children:[
|
|
583
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.topLine,children:[
|
|
584
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineKind,children:row.kindLabel}),
|
|
585
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.date,children:row.date})]}),
|
|
586
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineTitle,children:row.title}),row.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:row.detail}):null]})]})]},row.key))]})}function ContributionsBody({view:view}){let styles=useStyles10();/* @__PURE__ */
|
|
587
|
+
return jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.list,contentContainerStyle:styles.listContent,accessibilityLabel:RECORDS_COPY.records,children:[view.document?.receivedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(view.document.receivedAt)}):null,
|
|
588
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:view.contributions.map(entity=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.row,accessible:true,accessibilityRole:"text",children:[
|
|
589
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:entity.label}),
|
|
590
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles12(theme),[theme])}function makeStyles12(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,cardText=slotText(slots.recordCard),text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),inCard=(fontSize,multiplier,fg,weight="regular")=>({...text3(fontSize,multiplier,fg,weight),...cardText});return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},errorText:{...text3(size.subtitle,lineHeight.snug,errorColor),textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,...slotText(slots.primaryButton)},list:{flex:1},listContent:{padding:space.lg,gap:space.md},section:{gap:space.sm},heading:{...text3(size.heading,lineHeight.snug,color.text.primary,"bold")},card:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(slots.recordCard,hairline)},row:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(size.caption,lineHeight.normal,color.text.muted,"medium")},date:inCard(size.caption,lineHeight.normal,color.text.muted),rowTitle:{...inCard(size.body,lineHeight.normal,color.text.primary,"bold")},rowValue:{...inCard(size.body,lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(size.bodyTight,lineHeight.normal,color.text.muted),rowMuted:{...inCard(size.bodyTight,lineHeight.normal,color.text.muted),opacity:.7},chip:{...text3(size.caption,lineHeight.normal,color.text.primary),alignSelf:"flex-start",paddingHorizontal:space.sm,paddingVertical:space.xs,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:{...text3(size.caption,lineHeight.normal,color.text.muted),marginTop:space.md},timelineContent:{paddingBottom:space.xxl},timelineBand:{flexDirection:"row",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,marginHorizontal:space.lg,marginTop:space.xs,marginBottom:space.md},timelineBandText:{flex:1,...text3(size.caption,lineHeight.normal,color.text.secondary)},timelineSeparator:{height:hairline,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},timelineRow:{flexDirection:"row",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md+space.xs/2},timelineBubble:{width:space.xxl+space.xs/2,height:space.xxl+space.xs/2,borderRadius:radius.pill,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},timelineBody:{flex:1,gap:space.xs-1},timelineKind:{...face(theme,"mono"),fontSize:size.micro,lineHeight:size.bodyTight,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text3(size.body,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])}async function shareLinkViaOs(url){await reactNative.Share.share({message:SHARE_COPY.shareMessage(url),url:url})}async function shareFileLinkViaOs(url){await reactNative.Share.share(reactNative.Platform.OS==="ios"?{url:url}:{message:url})}var COPY=RECORD_SCREEN_COPY.document,DOCUMENT_ENTITY_ORDER=/* @__PURE__ */Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),readDepth2=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty2=value=>!value.available;function EverfurRecordDocument(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onBack"]);/* @__PURE__ */
|
|
591
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(DocumentBody,{...rest,style:style})})}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 DocumentBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onBack:onBack,onOpenUrl:onOpenUrl,style:style}){let styles=useScreenStyles(),local=useLocalStyles7(),theme=useEverfurTheme(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth2,depthEmpty2),pdf=useRecordPdfLink(petRef);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,[shareFailed,setShareFailed]=react.useState(false),download=()=>{setShareFailed(false),pdf.pdfLink().then(result=>{if(!result.ok)return;callHostAsync(onOpenUrl??(target=>shareFileLinkViaOs(target)),result.value.downloadUrl,"record_pdf").then(outcome=>{!outcome.ok&&!onOpenUrl&&setShareFailed(true)})})},body,documentShown=false;if(records.status==="loading"||depth.status==="loading"&&record!==null)body=/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:DASHBOARD_COPY.loading,testID:"record-document-loading",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:theme.color.brandInk})});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(reactNative.View,{style:local.centered,testID:"record-document-empty",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.emptyText,children:COPY.empty})}):(documentShown=true,body=/* @__PURE__ */jsxRuntime.jsx(RecordDocument,{record:record,depth:depthView,petName:petName,wordmark:theme.meta.displayName})/* @__PURE__ */);return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,local.root,style],children:[
|
|
592
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:download,disabled:pdf.preparing,accessibilityRole:"button",accessibilityLabel:COPY.download,accessibilityState:{disabled:pdf.preparing,busy:pdf.preparing},hitSlop:8,style:local.download,testID:"record-document-download",children:pdf.preparing?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:theme.color.brandInk}):/* @__PURE__ */jsxRuntime.jsx(DownloadGlyph,{})}):void 0}),pdf.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",children:pdf.error.displayMessage}):shareFailed?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:SHARE_COPY.toasts.pdfShareSheet}):null,
|
|
593
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),
|
|
594
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RecordDocument({record:record,depth:depth,petName:petName,wordmark:wordmark}){let local=useLocalStyles7(),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(reactNative.View,{style:local.section,testID:testID,children:[
|
|
595
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.sectionHeader,children:[
|
|
596
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.sectionTitle,accessibilityRole:"header",children:title}),
|
|
597
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.rule})]}),
|
|
598
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:children})]},testID);/* @__PURE__ */
|
|
599
|
+
return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.page,showsVerticalScrollIndicator:false,testID:"record-document",children:[
|
|
600
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.letterhead,children:[
|
|
601
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.wordmark,children:wordmark}),
|
|
602
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.docTitle,children:COPY.docTitle}),
|
|
603
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.petName,children:petName?.trim()||COPY.namelessPet}),
|
|
604
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.generated,children:COPY.generated(record.generatedAt)})]}),record.identity.length>0?section(COPY.identity,record.identity.map((field,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.row,index>0?local.rowDivider:null],children:[
|
|
605
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.rowLabel,children:field.label}),
|
|
606
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.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__ */
|
|
607
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[local.row,status.outOfRange?local.rowFlag:null,index>0?local.rowDivider:null],children:[
|
|
608
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.rowMain,children:[
|
|
609
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.rowLabel,children:marker.name}),
|
|
610
|
+
/* @__PURE__ */jsxRuntime.jsxs(Text,{style:local.rowMeta,children:[band?COPY.ref(band):COPY.noRange,marker.latest.at?` · ${formatRecordsDate(marker.latest.at)}`:""]})]}),
|
|
611
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.rowRight,children:[value!=="-"?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.rowValue,status.outOfRange?local.rowValueAlert:null],children:value}):null,
|
|
612
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.markerStatus,status.outOfRange?local.rowValueAlert:null],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__ */
|
|
613
|
+
return jsxRuntime.jsx(reactNative.View,{style:[local.row,index>0?local.rowDivider:null],children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.rowMain,children:[
|
|
614
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.rowLabel,children:entity.label}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.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__ */
|
|
615
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[local.row,index>0?local.rowDivider:null],children:[
|
|
616
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.rowMain,children:[
|
|
617
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.rowLabel,children:item.title}),item.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.rowMeta,children:item.detail}):null]}),badge?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.rowValue,badge.overdue?local.rowValueAlert:null],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(reactNative.View,{style:[local.block,index>0?local.rowDivider:null],children:[exam.observedOn?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.blockDate,children:formatRecordsDate(exam.observedOn)}):null,exam.systems.filter(system=>system.finding).map(system=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.fieldRow,children:[
|
|
618
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.fieldLabel,children:bodySystemLabel(system.system)}),
|
|
619
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.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(reactNative.View,{style:[local.block,index>0?local.rowDivider:null],children:[note.observedOn?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.blockDate,children:formatRecordsDate(note.observedOn)}):null,note.sections.filter(s=>s.text).map((s,i)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.noteSection,children:[
|
|
620
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteLabel,children:soapSectionLabel(s.section)}),
|
|
621
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteBody,children:s.text})]},`${s.section}-${i}`))]},note.noteId)),"record-document-notes"):null,disclaimerRepeatsFootnote(record.disclaimer)?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.disclaimer,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.disclaimerText,children:record.disclaimer})})]})}function useLocalStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles7(theme),[theme])}function makeLocalStyles7(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),mono=(fontSize,fg)=>({...face(theme,"mono"),fontSize:fontSize,lineHeight:fontSize+space.xs-1,color:fg,letterSpacing:type.letterSpacing.eyebrow/2,textTransform:"uppercase"});return reactNative.StyleSheet.create({root:{backgroundColor:color.surface},inset:{paddingHorizontal:space.lg},download:{width:space.xxl+space.xs+space.xs/2,height:space.xxl+space.xs+space.xs/2,borderRadius:radius.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xxl,minHeight:space.xxl*3+space.xl},emptyText:{...text3(type.size.body,type.lineHeight.normal,color.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:space.lg+space.xs,paddingBottom:space.xxl+space.lg},letterhead:{alignItems:"center",paddingTop:space.md,paddingBottom:space.lg+space.xs+space.xs/2,borderBottomWidth:2,borderBottomColor:color.brandInk,gap:space.xs+space.xs/2,marginBottom:space.sm},wordmark:{...text3(type.size.heading,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:type.letterSpacing.headerBrand},docTitle:{...mono(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:{...mono(type.size.tiny,color.text.muted),textTransform:"none"},section:{marginTop:space.lg+space.xs+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2,marginBottom:space.sm},sectionTitle:mono(type.size.tiny,color.brandInk),rule:{flex:1,height:hairline,backgroundColor:color.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.md+space.xs/2,paddingVertical:space.sm+1},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowFlag:{backgroundColor:color.badgeBgCritical,marginHorizontal:-space.sm,paddingHorizontal:space.sm,borderRadius:radius.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:space.xs/2},rowLabel:{flexShrink:1,...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"},rowValueAlert:{color:color.danger},rowMeta:{marginTop:space.xs/2,...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},markerStatus:mono(type.size.micro,color.text.muted),block:{paddingVertical:space.sm+space.xs/2},blockDate:{...mono(type.size.tiny,color.text.muted),marginBottom:space.xs+space.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:space.md+space.xs/2,paddingVertical:space.xs-1},fieldLabel:{width:120,...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:{...mono(type.size.tiny,color.brandInk),marginBottom:space.xs/2},noteBody:text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),disclaimer:{marginTop:radius.xl,paddingTop:space.md+space.xs/2,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},disclaimerText:text3(type.size.tiny,type.lineHeight.relaxed,color.text.muted)})}function ShareSheet({petRef:petRef,petName:petName,onClose:onClose,onNavigate:onNavigate,onOpenUrl:onOpenUrl,onCopy:onCopy}){let styles=useStyles11(),screen=useScreenStyles(),shares=useRecordShares(petRef),[notice,setNotice]=react.useState(null),[pendingRevokeId,setPendingRevokeId]=react.useState(null),[audience,setAudience]=react.useState("vet"),[email2,setEmail]=react.useState(""),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)=>{let opener=onOpenUrl??((target,what)=>what==="share_link"?shareLinkViaOs(target):shareFileLinkViaOs(target)),failure=kind==="share_link"?SHARE_COPY.toasts.shareSheet:SHARE_COPY.toasts.pdfShareSheet;callHostAsync(opener,url,kind).then(outcome=>{outcome.ok||setNotice(failure)})},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=()=>{if(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=>{if(!onCopy||row.shareUrl===null)return;let url=row.shareUrl;callHostAsync(onCopy,url).then(outcome=>setNotice(outcome.ok?SHARE_COPY.toasts.copiedNative:SHARE_COPY.toasts.copyFailedNative(url)))},onConfirmRevoke=shareId=>{shares.revoke(shareId).then(result=>{setPendingRevokeId(null),setNotice(result.ok?SHARE_COPY.toasts.turnedOff:shareErrorMessage(result.error,"revoke"))})};/* @__PURE__ */
|
|
622
|
+
return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.backdrop,children:[
|
|
623
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,accessibilityRole:"button",accessibilityLabel:SHARE_COPY.closeSheetA11y,onPress:onClose}),
|
|
624
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[
|
|
625
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.handle}),
|
|
626
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.header,children:[
|
|
627
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.headerText,children:[
|
|
628
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,accessibilityRole:"header",children:SHARE_COPY.titleFor(petName)}),
|
|
629
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.helper,children:armed?SHARE_COPY.leadNative:SHARE_COPY.helper})]}),
|
|
630
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:SHARE_COPY.close,onPress:onClose,hitSlop:12,style:styles.closeButton,testID:"share-record-close",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.closeGlyph,children:"×"})})]}),
|
|
631
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.scroll,contentContainerStyle:styles.body,showsVerticalScrollIndicator:false,children:[
|
|
632
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actions,children:[mintable?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.form,testID:"share-email-form",children:[
|
|
633
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:SHARE_COPY.audienceLabel}),
|
|
634
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.choices,accessibilityRole:"radiogroup",accessibilityLabel:SHARE_COPY.audienceLabel,children:RECORD_SHARE_AUDIENCES.map(option=>{let selected=audience===option;/* @__PURE__ */
|
|
635
|
+
return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setAudience(option),accessibilityRole:"radio",accessibilityLabel:SHARE_COPY.audiences[option],accessibilityState:{checked:selected,selected:selected},style:[styles.choice,selected?styles.choiceOn:null],testID:`share-audience-${option}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:selected?styles.choiceTitleOn:styles.choiceTitle,children:SHARE_COPY.audiences[option]})},option)})}),armed&&included.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.included,testID:"share-included",children:[
|
|
636
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:SHARE_COPY.included}),included.map(line2=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.includedRow,children:[
|
|
637
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.includedLine,accessibilityElementsHidden:true,importantForAccessibility:"no",children:"•"}),
|
|
638
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.includedLine,styles.includedText],testID:`share-included-line-${line2}`,children:line2})]},line2))]}):null,onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.previewNative,onPress:()=>{onClose(),onNavigate({name:"document"})},testID:"share-view-document"}):null,
|
|
639
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:SHARE_COPY.sendTo}),
|
|
640
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.TextInput,{accessibilityLabel:SHARE_COPY.sendTo,style:styles.field,value:email2,placeholder:SHARE_COPY.sendToPlaceholder,placeholderTextColor:styles.placeholder.color,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,autoComplete:"email",maxLength:SHARE_RECIPIENT_EMAIL_MAX,editable:!shares.sending,returnKeyType:"send",onChangeText:setEmail,onSubmitEditing:onSend,testID:"share-email-input"}),
|
|
641
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.sending?SHARE_COPY.sending:SHARE_COPY.send,busy:shares.sending,onPress:onSend,testID:"share-email-send"})]}):onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.previewNative,onPress:()=>{onClose(),onNavigate({name:"document"})},testID:"share-view-document"}):null,mintable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.creating?SHARE_COPY.creatingLink:SHARE_COPY.shareLinkNative,kind:"outline",busy:shares.creating,onPress: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,onPress:onDownload,testID:"share-download-pdf"}):null,mintable?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.terms,testID:"share-link-terms",children:SHARE_COPY.linkTerms}):null]}),shares.consentRequired?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.stateCard,testID:"share-consent-off",children:[
|
|
642
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateTitle,accessibilityRole:"header",children:SHARE_COPY.consentOffTitle}),
|
|
643
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateBody,children:SHARE_COPY.consentOffBody}),
|
|
644
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.retry,kind:"outline",onPress:shares.refresh,testID:"share-consent-retry"})]}):null,notice?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:notice}):null,sharesListShown(shares)?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,children:[
|
|
645
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionLabel,accessibilityRole:"header",children:SHARE_COPY.activeLinks}),shares.status==="loading"?/* @__PURE__ */jsxRuntime.jsx(SharesSkeleton,{testID:"share-record-loading"}):shares.status==="error"?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.stateCard,testID:"share-record-error",children:[
|
|
646
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateTitle,children:SHARE_COPY.errorTitle}),
|
|
647
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateBody,children:SHARE_COPY.errorBody}),
|
|
648
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.retry,kind:"outline",onPress:shares.refresh,testID:"share-record-retry"})]}):shares.rows.length===0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.stateCard,testID:"share-record-empty",children:[
|
|
649
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateTitle,children:SHARE_COPY.emptyTitle}),
|
|
650
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateBody,children:SHARE_COPY.emptyBody})]}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.list,children:shares.rows.map(row=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.row,testID:`share-row-${row.shareId}`,children:[
|
|
651
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:row.a11yLabel,children:[
|
|
652
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.statusLine,children:[
|
|
653
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.statusDot,{backgroundColor:row.active?styles.active.color:styles.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
654
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.status,children:row.statusLabel}),
|
|
655
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.expiry,children:row.expiryLabel})]}),row.createdLabel?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.created,children:row.createdLabel}):null]}),row.shareUrl!==null&&!onCopy?/* @__PURE__ */jsxRuntime.jsx(Text,{selectable:true,style:styles.url,testID:`share-url-${row.shareId}`,children:row.shareUrl}):null,pendingRevokeId===row.shareId?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.confirm,testID:`share-revoke-confirm-${row.shareId}`,children:[
|
|
656
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.confirmText,children:SHARE_COPY.confirmTurnOff}),
|
|
657
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowActions,children:[
|
|
658
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.revokingId===row.shareId?SHARE_COPY.turningOff:SHARE_COPY.turnOff,kind:"danger",busy:shares.revokingId===row.shareId,onPress:()=>onConfirmRevoke(row.shareId),testID:`share-revoke-do-${row.shareId}`}),
|
|
659
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.keep,kind:"outline",disabled:shares.revokingId===row.shareId,onPress:()=>setPendingRevokeId(null),testID:`share-revoke-cancel-${row.shareId}`})]})]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowActions,children:[onCopy?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.copyLink,kind:"outline",disabled:row.shareUrl===null,accessibilityHint:row.a11yLabel,onPress:()=>onCopyRow(row),testID:`share-copy-${row.shareId}`}):null,
|
|
660
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.turnOff,kind:"danger",accessibilityLabel:SHARE_COPY.turnOffA11y(row.actionContext),onPress:()=>setPendingRevokeId(row.shareId),testID:`share-ask-revoke-${row.shareId}`})]})]},row.shareId))})]}):null]}),
|
|
661
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:screen.inset})]})]})})}function useStyles11(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles13(theme),[theme])}function makeStyles13(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,hairline=reactNative.StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({active:{color:color.success},inactive:{color:color.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:color.surface,borderTopLeftRadius:radius.xl-1,borderTopRightRadius:radius.xl-1,paddingHorizontal:space.lg+space.xs+space.xs/2,paddingTop:space.md,paddingBottom:radius.xl,maxHeight:"88%",gap:space.md},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},headerText:{flex:1,gap:space.xs},title:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},helper:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),terms:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:text3(type.size.verdict,type.lineHeight.tight,color.text.primary),scroll:{flexGrow:0},body:{gap:space.lg,paddingBottom:space.sm},actions:{gap:space.sm},form:{gap:space.sm,paddingBottom:space.sm},fieldLabel:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary,"medium")},choices:{flexDirection:"row",gap:space.sm},choice:{flex:1,minHeight:touch,alignItems:"center",justifyContent:"center",paddingHorizontal:space.sm,borderRadius:radius.md,borderWidth:hairline,borderColor:color.borderHairlineGreen,backgroundColor:color.surface},choiceOn:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:color.brandSoft},choiceTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"medium")},choiceTitleOn:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},included:{gap:space.xs},includedRow:{flexDirection:"row",gap:space.sm},includedLine:text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),includedText:{flex:1},field:{...text3(type.size.body,type.lineHeight.normal,color.text.primary),minHeight:touch,paddingHorizontal:space.md,borderRadius:radius.sm,borderWidth:hairline,borderColor:color.borderHairlineGreen,backgroundColor:color.surface},placeholder:{color:color.text.placeholder},notice:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary),padding:space.md,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft},section:{gap:space.sm},sectionLabel:{...text3(type.size.bodyTight,type.lineHeight.snug,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},stateCard:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder},stateTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},stateBody:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),list:{gap:space.md},row:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder},statusLine:{flexDirection:"row",alignItems:"center",gap:space.sm},statusDot:{width:space.sm,height:space.sm,borderRadius:space.xs},status:{...text3(type.size.bodyTight,type.lineHeight.snug,color.text.primary,"bold")},expiry:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted)},created:text3(type.size.tiny,type.lineHeight.normal,color.text.muted),url:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},confirm:{gap:space.sm},confirmText:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"medium")}})}var readDepth3=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty3=value=>!value.available;function EverfurRecordDetail(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
662
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RecordBody,{...rest,style:style})})}function RecordBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,onOpenUrl:onOpenUrl,onCopy:onCopy,style:style}){let styles=useScreenStyles(),local=useLocalStyles8(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth3,depthEmpty3),factEdit=useRecordFactEdit(petRef),shareProbe=useRecordsDepthProbe(petRef),[sharing,setSharing]=react.useState(false);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),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(reactNative.ScrollView,{contentContainerStyle:styles.content,testID:"everfur-record-empty",children:[
|
|
663
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",message:inReview>0?RECORD_SCREEN_COPY.inReview(inReview):void 0}),
|
|
664
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record?.disclaimer??""})]})}else body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:local.content,testID:"everfur-record",children:/* @__PURE__ */jsxRuntime.jsx(RecordSections,{record:record,depth:depthView,petName:petName,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit})});/* @__PURE__ */
|
|
665
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
666
|
+
/* @__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(reactNative.Pressable,{onPress:()=>onNavigate({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:RECORD_SCREEN_COPY.requestClinicsA11y,hitSlop:8,style:local.share,testID:"everfur-record-request-clinics",children:/* @__PURE__ */jsxRuntime.jsx(SendGlyph,{})}):null,shareable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setSharing(true),accessibilityRole:"button",accessibilityLabel:SHARE_COPY.openA11yFor(petName),hitSlop:8,style:local.share,testID:"everfur-record-share",children:/* @__PURE__ */jsxRuntime.jsx(ShareGlyph,{})}):null]}):void 0}),
|
|
667
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),sharing?/* @__PURE__ */jsxRuntime.jsx(ShareSheet,{petRef:petRef,petName:petName,onClose:()=>setSharing(false),onNavigate:onNavigate,...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{}}):null,
|
|
668
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function useLocalStyles8(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles8(theme),[theme])}function makeLocalStyles8(theme){let{space:space,radius:radius}=theme;return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xxl+space.sm,gap:space.lg+space.xs},share:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.pill,alignItems:"center",justifyContent:"center"}})}function useRecordsPullToRefresh(refresh,testID){let theme=useEverfurTheme(),[refreshing,setRefreshing]=react.useState(false),onRefresh=react.useCallback(()=>{setRefreshing(true),refresh().finally(()=>setRefreshing(false))},[refresh]);/* @__PURE__ */
|
|
669
|
+
return jsxRuntime.jsx(reactNative.RefreshControl,{refreshing:refreshing,onRefresh:onRefresh,tintColor:theme.color.brandInk,colors:[theme.color.brandInk],testID:testID})}function EverfurRecordsUpload(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]);/* @__PURE__ */
|
|
670
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(UploadBody,{...rest,style:style})})}function UploadBody({petRef:petRef,petName:petName,controller:controller,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles9(),theme=useEverfurTheme(),{runtime:runtime}=useEverfurContext(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:uploadTransport?{petRef:petRef,uploadTransport:uploadTransport,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),canUpload=canUploadRecords(onPickDocument)&&(controller!==void 0||uploadTransport!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport));/* @__PURE__ */
|
|
671
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
672
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:"",onBack:onBack,testID:"upload-header"}),
|
|
673
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.content,testID:"upload-screen",children:[
|
|
674
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.header,children:[
|
|
675
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"upload-glyph",children:/* @__PURE__ */jsxRuntime.jsx(UploadCloudGlyph,{size:UPLOAD_GLYPH,color:theme.color.brandInk})}),
|
|
676
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.title,accessibilityRole:"header",children:UPLOAD_COPY.screenTitle}),
|
|
677
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.subtitle,children:UPLOAD_COPY.subtitle(petName)})]}),
|
|
678
|
+
/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:null,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onNavigate?requestId2=>onNavigate({name:"request",requestId:requestId2}):void 0})]}),
|
|
679
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function UploadRecordCard({records:records,requestId:requestId2,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onDone}){let styles=useScreenStyles(),local=useLocalStyles9(),{runtime:runtime}=useEverfurContext(),camera=runtime.registry.services.camera,types=records.uploadContentTypes,photosLive=acceptsPhotos(types),canTakePhoto=photosLive&&isCaptureAvailable(camera),canChoosePhotos=photosLive&&onPickPhotos!==void 0,photoCopy=canTakePhoto||canChoosePhotos,[pickError,setPickError]=react.useState(null),[batchCount,setBatchCount]=react.useState(0),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&&batchCount>0,run=react.useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photoCopy);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal);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]]:[])},[records,types,photoCopy]),pickFrom=react.useCallback(picker=>{!picker||!canUpload||callHostAsync(picker).then(outcome=>{if(!outcome.ok){setPickError(UPLOAD_COPY.errors.startPlain);return}let picked=outcome.value;picked!==null&&run(Array.isArray(picked)?picked:[picked])})},[canUpload,run]),pick=react.useCallback(()=>{pickFrom(onPickDocument)},[pickFrom,onPickDocument]),pickPhotos=react.useCallback(()=>{pickFrom(onPickPhotos)},[pickFrom,onPickPhotos]),takePhoto=react.useCallback(()=>{!canTakePhoto||!canUpload||callHostAsync(()=>camera.capture(captureOptionsFor("photo"))).then(outcome=>{if(!outcome.ok)return;let handle=fileHandleFromMedia(outcome.value);if(handle.sizeBytes===void 0){setPickError(UPLOAD_COPY.errors.startPlain);return}run([handle])})},[camera,canTakePhoto,canUpload,run]),retryFailed=react.useCallback(()=>{run(failedFiles.current)},[run]);/* @__PURE__ */
|
|
680
|
+
return jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-upload-card",children:[
|
|
681
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:UPLOAD_COPY.cardTitle}),
|
|
682
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardSubtitle,children:photoCopy?UPLOAD_PHOTO_COPY.note:UPLOAD_COPY.cardSubtitle}),pickError?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:pickError})}):null,
|
|
683
|
+
/* @__PURE__ */jsxRuntime.jsx(UploadQueue,{records:records}),records.isUploading?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.uploadingRow,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.progressText,children:UPLOAD_COPY.uploading(done,rows.length)})}):settled?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.settled,children:[done>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.success,accessibilityRole:"alert",children:UPLOAD_COPY.received(done)}):null,failed>0?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.retryFailed(failed),kind:"link",onPress:retryFailed,testID:"records-upload-retry-failed"}):null,
|
|
684
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:UPLOAD_COPY.haveMore}),photoCopy?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardSubtitle,children:UPLOAD_PHOTO_COPY.haveMoreLead}):null,
|
|
685
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.settledActions,children:[
|
|
686
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.addMore,kind:"link",accessibilityLabel:UPLOAD_COPY.addMoreA11y,disabled:!canUpload,onPress:pick,testID:"records-upload-another"}),onDone&&resolvedId.current!==null&&done>0?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.done,accessibilityLabel:UPLOAD_COPY.doneA11y,onPress:()=>onDone(resolvedId.current),testID:"records-upload-done"}):null]})]}):photoCopy?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.actions,children:[canTakePhoto?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.action,children:[
|
|
687
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_PHOTO_COPY.takePhoto,kind:"outline",accessibilityLabel:uploadActionA11y(UPLOAD_PHOTO_COPY.takePhoto,UPLOAD_PHOTO_COPY.takePhotoMeta),disabled:!canUpload,onPress:takePhoto,testID:"records-upload-take-photo"}),
|
|
688
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.takePhotoMeta})]}):null,canChoosePhotos?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.action,children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_PHOTO_COPY.choosePhotos,kind:"outline",disabled:!canUpload,onPress:pickPhotos,testID:"records-upload-choose-photos"})}):null,
|
|
689
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.action,children:[
|
|
690
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick,testID:"records-upload-choose"}),
|
|
691
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.chooseFileMeta})]})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick,testID:"records-upload-choose"})]})}function useLocalStyles9(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles9(theme),[theme])}var UPLOAD_GLYPH=24;function makeLocalStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{padding:space.lg+space.xs,gap:space.lg+space.xs},header:{gap:space.sm,alignItems:"center"},iconBubble:{width:space.xxl+space.lg+space.xs,height:space.xxl+space.lg+space.xs,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...text3(type.size.heading+space.xs/2,type.lineHeight.snug,color.brandInk,"bold"),textAlign:"center"},subtitle:{...text3(type.size.body,type.lineHeight.normal,color.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.md},cardTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold")},cardSubtitle:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:space.sm},progressText:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary)},settled:{gap:space.sm},success:text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:space.sm},actions:{gap:space.md},action:{gap:space.xs},actionMeta:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted)})}function EverfurRecordsRequest(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]);/* @__PURE__ */
|
|
692
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RequestBody,{...rest,style:style})})}function RequestBody({petRef:petRef,petName:petName,requestId:requestId2,controller:controller,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,onNavigate:onNavigate,onBack:onBack,style:style,nowMs:nowMs}){let styles=useScreenStyles(),{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:uploadTransport?{petRef:petRef,uploadTransport:uploadTransport,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),request=records.requests.find(r=>r.id===requestId2)??null,canUpload=canUploadRecords(onPickDocument)&&(controller!==void 0||uploadTransport!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport)),title=request?selectRequestTitle(request):"",refreshControl=useRecordsPullToRefresh(records.refresh,"records-request-refresh"),body;return records.status==="loading"&&request===null?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"}):userRef===null?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"error",testID:"records-request-error"}):body=/* @__PURE__ */jsxRuntime.jsx(RequestDetail,{petName:petName,request:request,records:records,canUpload:canUpload,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,onNavigate:onNavigate,nowMs:nowMs,refreshControl:refreshControl},JSON.stringify([userRef,scopeEpoch,request.id])),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
693
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:title,onBack:onBack,testID:"records-request-header"}),
|
|
694
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.KeyboardAvoidingView,{behavior:"padding",style:styles.body,children:body}),
|
|
695
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RequestDetail({petName:petName,request:request,records:records,canUpload:canUpload,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,onNavigate:onNavigate,nowMs:nowMs,refreshControl:refreshControl}){let styles=useScreenStyles(),local=useLocalStyles10(),theme=useEverfurTheme(),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),elapsedDays=requestElapsedDays(current,now),expectation=terminal?null:current.waitingExpectation?.trim()||null,call=selectClinicCall(current),showRecovery=shouldOfferRecovery(current),canConvert=form.canConvert,canStartFresh=terminal&&!published,actionError=form.error!==null&&lastAction!==null&&lastAction!=="start"?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})}}))},clinicName=current.clinicName?.trim()??"",clinicRequest=!isOwnerSourcedRequest(current)&&clinicName.length>0,awaitingClinic=clinicRequest&&(current.status==="requested"||current.status==="awaiting_clinic"),sentDate=formatRecordsDate(current.createdAt);/* @__PURE__ */
|
|
696
|
+
return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.content,keyboardShouldPersistTaps:"handled",refreshControl:refreshControl,testID:`records-request-${current.id}`,children:[awaitingClinic?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.sent,testID:"records-request-sent",children:[
|
|
697
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:REQUEST_SCREEN_COPY.sentTitle}),
|
|
698
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bodyText,children:REQUEST_SCREEN_COPY.sentLeadNative(petNameOr(petName))})]}):null,
|
|
699
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-request-where",children:[
|
|
700
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:REQUEST_SCREEN_COPY.whereItStands}),
|
|
701
|
+
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:current,petName:petName})]}),clinicRequest?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-request-details",children:[
|
|
702
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:REQUEST_SCREEN_COPY.details}),
|
|
703
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.detailRow,children:[
|
|
704
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:REQUEST_SCREEN_COPY.detailsClinic}),
|
|
705
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.detailValue,children:clinicName})]}),sentDate!=="-"?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.detailRow,children:[
|
|
706
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:REQUEST_SCREEN_COPY.detailsSent}),
|
|
707
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.detailValue,children:sentDate})]}):null]}):null,current.status==="awaiting_upload"?/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:current.id,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload}):null,current.statusLabel.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.statusCard,accessibilityRole:"summary",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.statusText,children:current.statusLabel})}):null,expectation&&!waitingTooLong?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoNote,accessibilityRole:"summary",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoNoteText,children:expectation})}):current.wireStatus==="awaiting_response"&&!waitingTooLong?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoNote,accessibilityRole:"summary",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoNoteText,children:REQUEST_SCREEN_COPY.awaitingNote})}):null,waitingTooLong?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.cautionNoteText,children:REQUEST_SCREEN_COPY.waitingBanner(elapsedDays)})}):null,published&&onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.viewRecords,onPress:()=>onNavigate({name:"dashboard"}),style:local.readyCta,testID:"records-request-view-dashboard"}):null,showRecovery?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.failureCard,failed?local.failureCritical:local.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[
|
|
708
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.failureTitle,failed?local.failureTitleCritical:local.failureTitleCaution],children:failureTitle(current)}),current.canUpdateClinicEmail!==true&¤t.canRetrySend!==true?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:REQUEST_SCREEN_COPY.nextStep}):null,current.canUpdateClinicEmail===true?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.emailBlock,children:[
|
|
709
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:RECORDS_RECOVERY_COPY.email}),
|
|
710
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{style:styles.field,accessibilityLabel:RECORDS_RECOVERY_COPY.email,placeholder:RECORDS_RECOVERY_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:form.email,editable:!form.busy,onChangeText:form.setEmail,testID:"records-failure-clinic-email"}),form.emailInvalid?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",children:REQUEST_SCREEN_COPY.errors.invalidEmail}):null,
|
|
711
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.updateEmail,disabled:!form.canUpdateEmail,busy:form.busy&&lastAction==="email",onPress:()=>run("email",form.updateEmail),testID:"records-failure-update-email"})]}):null,current.canRetrySend===true?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.retry,kind:"outline",accessibilityLabel:RECORDS_RECOVERY_COPY.retryA11y,disabled:!form.canRetry,busy:form.busy&&lastAction==="retry",onPress:()=>run("retry",form.retry),testID:"records-failure-retry-send"}):null,current.canRetrySend===true&&form.hasEmailEdit?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:RECORDS_RECOVERY_COPY.retryHint}):null,actionError&&(lastAction==="email"||lastAction==="retry")?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:actionError})}):null]}):null,(failed||clinicNoRecords)&&onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.tryAnotherClinic,kind:"outline",onPress:()=>onNavigate({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,call!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.callBlock,children:[
|
|
712
|
+
/* @__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,onPress:()=>run("retry",form.retry),testID:"records-resend-authorization"}):null]}):null,canConvert?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
|
|
713
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:form.busy&&lastAction==="convert"?REQUEST_SCREEN_COPY.converting:REQUEST_SCREEN_COPY.convert,busy:form.busy&&lastAction==="convert",onPress:()=>run("convert",form.convert),testID:"records-convert-upload"}),
|
|
714
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:REQUEST_SCREEN_COPY.convertHint}),actionError&&lastAction==="convert"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:actionError})}):null]}):null,canStartFresh?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
|
|
715
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:starting?REQUEST_SCREEN_COPY.freshUploadStarting:REQUEST_SCREEN_COPY.freshUpload,kind:failed||clinicNoRecords?"outline":"primary",busy:starting,onPress:startFresh,testID:"records-upload-own-fresh"}),startError?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:startError})}):null]}):null,actionError&&lastAction==="revoke"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:actionError})}):null,current.canRevoke===true?form.confirmingRevoke?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,testID:"records-revoke-confirm",children:[
|
|
716
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.confirmTitle,accessibilityRole:"header",children:RECORDS_RECOVERY_COPY.cancelQuestion}),
|
|
717
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bodyText,children:RECORDS_RECOVERY_COPY.cancelConsequence}),
|
|
718
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:form.busy&&lastAction==="revoke"?REQUEST_SCREEN_COPY.cancelling:REQUEST_SCREEN_COPY.cancel,kind:"danger",busy:form.busy&&lastAction==="revoke",onPress:()=>run("revoke",form.revoke),testID:"records-revoke-do"}),
|
|
719
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function useLocalStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles10(theme),[theme])}function makeLocalStyles10(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg+space.xs/2},readyCta:{minHeight:space.xxl+space.lg+space.xs/2},sent:{gap:space.xs},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md},cardTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:-.4},detailRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.lg},detailValue:{flexShrink:1,textAlign:"right",...text3(type.size.body,type.lineHeight.normal,color.text.primary)},failureCard:{borderRadius:radius.lg-space.xs,borderWidth:1,padding:space.md+space.xs/2,gap:space.md},failureCritical:{borderColor:color.badgeBgCritical,backgroundColor:color.badgeBgCritical},failureCaution:{borderColor:color.badgeBgCaution,backgroundColor:color.badgeBgCaution},failureTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},failureTitleCritical:{color:color.danger},failureTitleCaution:{color:color.warningStrong},emailBlock:{gap:space.sm},callBlock:{gap:space.sm},block:{gap:space.sm},confirmTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold")}})}function EverfurRecordsFlow(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,initialScreen:initialScreen,onExit:onExit,style:style,renderPending:renderPending,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location}=guardHostProps(props,["onExit"]),[nav,dispatch]=react.useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length;react.useEffect(()=>{let onBackPress=()=>depth<=1?false:(dispatch({type:"pop"}),true),subscription=reactNative.BackHandler.addEventListener("hardwareBackPress",onBackPress);return()=>{subscription.remove()}},[depth]);let onNavigate=react.useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=react.useMemo(()=>popRecordsNav(nav).handled?()=>dispatch({type:"pop"}):onExit,[nav,onExit]),seams={onNavigate:onNavigate,...onBack?{onBack:onBack}:{},...petName!==void 0?{petName:petName}:{},...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location?{location:location}:{}},records={...controller?{controller:controller}:{},...consentVersion!==void 0?{consentVersion:consentVersion}:{},...consentText!==void 0?{consentText:consentText}:{}},uploads={...onPickDocument?{onPickDocument:onPickDocument}:{},...onPickPhotos?{onPickPhotos:onPickPhotos}:{},...uploadTransport?{uploadTransport:uploadTransport}:{}},pending=renderPending?{renderPending:renderPending}:{};switch(screen.name){case"dashboard":/* @__PURE__ */
|
|
720
|
+
return jsxRuntime.jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,style:style});case"request":/* @__PURE__ */
|
|
721
|
+
return jsxRuntime.jsx(EverfurRecordsRequest,{petRef:petRef,requestId:screen.requestId,...seams,...records,...uploads,...pending,style:style});case"timeline":/* @__PURE__ */
|
|
722
|
+
return jsxRuntime.jsx(EverfurRecordsTimeline,{petRef:petRef,...seams,style:style});case"record":/* @__PURE__ */
|
|
723
|
+
return jsxRuntime.jsx(EverfurRecordDetail,{petRef:petRef,...seams,...records,...pending,style:style});case"document":/* @__PURE__ */
|
|
724
|
+
return jsxRuntime.jsx(EverfurRecordDocument,{petRef:petRef,...seams,...records,...pending,style:style});case"contributions":/* @__PURE__ */
|
|
725
|
+
return jsxRuntime.jsx(EverfurDocumentContributions,{petRef:petRef,docId:screen.docId,...seams,style:style});case"clinicPicker":/* @__PURE__ */
|
|
726
|
+
return jsxRuntime.jsx(EverfurClinicPicker,{petRef:petRef,...seams,...clinicController?{controller:clinicController}:{},...controller?{recordsController:controller}:{},style:style});case"clinicBatch":/* @__PURE__ */
|
|
727
|
+
return 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}:{},style:style});case"consent":/* @__PURE__ */
|
|
728
|
+
return jsxRuntime.jsx(EverfurRecordsConsent,{petRef:petRef,clinic:screen.clinic,...seams,...ownerName!==void 0?{ownerName:ownerName}:{},...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},style:style});case"upload":/* @__PURE__ */
|
|
729
|
+
return jsxRuntime.jsx(EverfurRecordsUpload,{petRef:petRef,...seams,...controller?{controller:controller}:{},...uploads,...pending,style:style});case"requests":/* @__PURE__ */
|
|
730
|
+
return jsxRuntime.jsx(EverfurRecordsRequests,{petRef:petRef,...seams,...controller?{controller:controller}:{},...pending,style:style});default:return assertNever(screen)}}var EverfurRecords=EverfurRecordsFlow;function EverfurClinicRequest(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
731
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"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(),[png,setPng]=react.useState(null),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useClinicRequestForm(props,props.controller??runtimeController,props.onCaptureSignature??padCapture),signed=props.onCaptureSignature!==void 0||png!==null,theme=useEverfurTheme(),field={minHeight:44,padding:theme.space.sm,borderWidth:1,borderColor:theme.color.borderHairlineGreen,borderRadius:theme.radius.sm,color:theme.color.text.primary,backgroundColor:theme.color.surface},text3={color:theme.color.text.primary,fontSize:theme.type.size.body},button=(label,action,disabled=false)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{disabled:disabled},disabled:disabled,onPress:action,style:[field,{justifyContent:"center",opacity:disabled?.5:1}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:label})});/* @__PURE__ */
|
|
732
|
+
return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:CLINIC_REQUEST_COPY.title,style:[{backgroundColor:theme.color.surface,padding:theme.space.lg,gap:theme.space.md,borderRadius:theme.radius.lg,minHeight:120},props.style],children:[
|
|
733
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:[text3,{...face(theme,"bold"),fontSize:theme.type.size.heading}],children:CLINIC_REQUEST_COPY.title}),
|
|
734
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:props.petName}),form.created?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text3,children:form.created.statusLabel||RECORDS_COPY.records}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
735
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:CLINIC_REQUEST_COPY.ownerName}),
|
|
736
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.ownerName,style:field,value:form.ownerName,maxLength:200,editable:!form.busy,autoComplete:"name",onChangeText:form.setOwnerName}),
|
|
737
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:CLINIC_REQUEST_COPY.clinic}),
|
|
738
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:field,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,onChangeText:form.setQuery}),button(CLINIC_REQUEST_COPY.search,()=>{form.search()},form.busy||form.searching||form.query.trim().length<2),form.searching&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text3,children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:text3,testID:"records-clinic-recent-label",children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},`recent-${clinic.id}`)),form.visibleClinics.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},clinic.id)),form.hasMoreClinics&&button(CLINIC_REQUEST_COPY.moreClinics,form.showMoreClinics,form.busy),form.needsEmail&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
739
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:CLINIC_REQUEST_COPY.email}),
|
|
740
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.email,style:field,value:form.email,placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:320,editable:!form.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:form.setEmail})]}),
|
|
741
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:text3,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:form.query.trim()&&form.ownerName.trim()?form.scope??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text3,children:RECORDS_COPY.loading}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",style:text3,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:text3,children:form.error.displayMessage}),!form.copy&&form.error&&button(RECORDS_COPY.retry,form.retryCopy),button(form.busy?CLINIC_REQUEST_COPY.sending:CLINIC_REQUEST_COPY.send,()=>{form.submit()},form.busy||!form.ready||!signed)]}),props.onClose&&button(CLINIC_REQUEST_COPY.cancel,props.onClose,form.busy),
|
|
742
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}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.EverfurRecordsRequest=EverfurRecordsRequest;exports.EverfurRecordsRequests=EverfurRecordsRequests;exports.EverfurRecordsUpload=EverfurRecordsUpload;exports.RECORDS_CLINIC_BATCH_MAX=RECORDS_CLINIC_BATCH_MAX;exports.RECORDS_TERMINAL=RECORDS_TERMINAL;exports.REQUEST_TIMELINE_TITLES=REQUEST_TIMELINE_TITLES;exports.SignaturePad=SignaturePad;exports.acceptsPhotos=acceptsPhotos;exports.applyFactOverlay=applyFactOverlay;exports.buildRequestTimeline=buildRequestTimeline;exports.currentRecordsScreen=currentRecordsScreen;exports.deriveRecordsDashboardState=deriveRecordsDashboardState;exports.initialRecordsNav=initialRecordsNav;exports.isFactEditable=isFactEditable;exports.isTerminalStatus=isTerminalStatus;exports.pickPetRecordsRequest=pickPetRecordsRequest;exports.popRecordsNav=popRecordsNav;exports.pushRecordsNav=pushRecordsNav;exports.recordsDenialReasonOf=recordsDenialReasonOf;exports.recordsNavReducer=recordsNavReducer;exports.registerRnSignature=registerRnSignature;exports.replaceRecordsNav=replaceRecordsNav;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;
|