@everfur/sdk 0.1.0 → 0.3.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.
Files changed (187) hide show
  1. package/CHANGELOG.md +648 -1
  2. package/README.md +58 -23
  3. package/consent/package.json +8 -0
  4. package/dist/Chat-DPUD6dnc.d.cts +128 -0
  5. package/dist/Chat-DwAC2vhB.d.ts +128 -0
  6. package/dist/DepthViews-DNEM96Se.d.ts +16 -0
  7. package/dist/DepthViews-DP0R-DhB.d.cts +19 -0
  8. package/dist/DepthViews-D_3hl4xk.d.ts +19 -0
  9. package/dist/DepthViews-DbFhR4Du.d.cts +16 -0
  10. package/dist/ErrorPolicyPort-CNf4uQZP.d.cts +22 -0
  11. package/dist/ErrorPolicyPort-CwbfmxzJ.d.ts +22 -0
  12. package/dist/{EverfurResult-D92-uL82.d.cts → EverfurResult-DN9pL2Ab.d.cts} +11 -10
  13. package/dist/{EverfurResult-D92-uL82.d.ts → EverfurResult-DN9pL2Ab.d.ts} +11 -10
  14. package/dist/{PhotoController-BItt5M7u.d.cts → PhotoController-3l7MT9jA.d.cts} +1 -1
  15. package/dist/{PhotoController-D8zMTdcW.d.ts → PhotoController-vzY5bfY_.d.ts} +1 -1
  16. package/dist/animations/index.cjs +1 -1997
  17. package/dist/animations/index.d.cts +35 -35
  18. package/dist/animations/index.d.ts +35 -35
  19. package/dist/animations/index.js +1 -1972
  20. package/dist/attachments-5NeobOCd.d.ts +256 -0
  21. package/dist/attachments-Bw3iMQgu.d.ts +146 -0
  22. package/dist/attachments-CQgFrEQ7.d.cts +146 -0
  23. package/dist/attachments-D8T5re7e.d.cts +256 -0
  24. package/dist/casesRepository-ClLv6qMl.d.ts +188 -0
  25. package/dist/casesRepository-DHwtGRYY.d.cts +188 -0
  26. package/dist/chat/index.cjs +1 -1170
  27. package/dist/chat/index.d.cts +31 -53
  28. package/dist/chat/index.d.ts +31 -53
  29. package/dist/chat/index.js +1 -1167
  30. package/dist/client/index.cjs +9 -2315
  31. package/dist/client/index.d.cts +77 -15
  32. package/dist/client/index.d.ts +77 -15
  33. package/dist/client/index.js +9 -2215
  34. package/dist/{config-CiJ0PVBB.d.ts → config-CzTZGlfF.d.cts} +63 -25
  35. package/dist/{config-BSjBdxrZ.d.cts → config-DW60uRb9.d.ts} +63 -25
  36. package/dist/consent/index.cjs +1 -0
  37. package/dist/consent/index.d.cts +33 -0
  38. package/dist/consent/index.d.ts +33 -0
  39. package/dist/consent/index.js +1 -0
  40. package/dist/context-DXhqHlPU.d.ts +159 -0
  41. package/dist/context-XvTzq1tE.d.cts +159 -0
  42. package/dist/copy-Mjoo91aS.d.ts +198 -0
  43. package/dist/copy-bKDNigLb.d.cts +198 -0
  44. package/dist/core/index.cjs +13 -3175
  45. package/dist/core/index.d.cts +58 -12
  46. package/dist/core/index.d.ts +58 -12
  47. package/dist/core/index.js +13 -3163
  48. package/dist/depth-CErXCU8J.d.cts +502 -0
  49. package/dist/depth-DjDcJ6kH.d.ts +502 -0
  50. package/dist/entitlementRepository-DKdXFgTo.d.cts +698 -0
  51. package/dist/entitlementRepository-DSbzuyAW.d.ts +698 -0
  52. package/dist/{identity-DK9zORrG.d.ts → identity-BMx2SUOM.d.ts} +19 -6
  53. package/dist/{identity-Brl-lDd6.d.cts → identity-DI4eVx9S.d.cts} +19 -6
  54. package/dist/{ids-CJ1S6adf.d.cts → ids-B2GAAifq.d.cts} +1 -1
  55. package/dist/{ids-CJ1S6adf.d.ts → ids-B2GAAifq.d.ts} +1 -1
  56. package/dist/index.cjs +12 -4488
  57. package/dist/index.d.cts +29 -121
  58. package/dist/index.d.ts +29 -121
  59. package/dist/index.js +12 -4464
  60. package/dist/models-B-Uh2LTf.d.ts +214 -0
  61. package/dist/models-D2EUxPZY.d.cts +214 -0
  62. package/dist/notifications/index.cjs +2 -0
  63. package/dist/notifications/index.d.cts +17 -0
  64. package/dist/notifications/index.d.ts +17 -0
  65. package/dist/notifications/index.js +2 -0
  66. package/dist/pets-CtQdRpWo.d.ts +92 -0
  67. package/dist/pets-aB8q0JyX.d.cts +92 -0
  68. package/dist/photo/index.cjs +1 -2189
  69. package/dist/photo/index.d.cts +6 -6
  70. package/dist/photo/index.d.ts +6 -6
  71. package/dist/photo/index.js +1 -2186
  72. package/dist/ports-BN6RHF9W.d.cts +48 -0
  73. package/dist/ports-BN6RHF9W.d.ts +48 -0
  74. package/dist/ports-DEBzEhbp.d.cts +386 -0
  75. package/dist/ports-DMolTRzU.d.ts +386 -0
  76. package/dist/profile-CSs1wlXT.d.cts +93 -0
  77. package/dist/profile-CSs1wlXT.d.ts +93 -0
  78. package/dist/records/depth/index.cjs +2 -0
  79. package/dist/records/depth/index.d.cts +13 -0
  80. package/dist/records/depth/index.d.ts +13 -0
  81. package/dist/records/depth/index.js +2 -0
  82. package/dist/records/index.cjs +3 -2839
  83. package/dist/records/index.d.cts +137 -203
  84. package/dist/records/index.d.ts +137 -203
  85. package/dist/records/index.js +3 -2833
  86. package/dist/requestFunnel-CjW7uDuA.d.ts +87 -0
  87. package/dist/requestFunnel-L-BQfi0z.d.cts +87 -0
  88. package/dist/{resolve-Dq_4_agU.d.ts → resolve-D4Ywz5OS.d.cts} +10 -4
  89. package/dist/{resolve-Dq_4_agU.d.cts → resolve-D4Ywz5OS.d.ts} +10 -4
  90. package/dist/{runtime-BgQnA594.d.cts → runtime-B8s-_hv8.d.cts} +134 -59
  91. package/dist/{runtime-CBA-LvdM.d.ts → runtime-BR9ysG0J.d.ts} +134 -59
  92. package/dist/server/events/index.cjs +2 -0
  93. package/dist/server/events/index.d.cts +550 -0
  94. package/dist/server/events/index.d.ts +550 -0
  95. package/dist/server/events/index.js +2 -0
  96. package/dist/server/index.cjs +2 -533
  97. package/dist/server/index.d.cts +73 -18
  98. package/dist/server/index.d.ts +73 -18
  99. package/dist/server/index.js +2 -530
  100. package/dist/species-BXAIMh7I.d.cts +9 -0
  101. package/dist/species-BXAIMh7I.d.ts +9 -0
  102. package/dist/televet/index.cjs +1 -0
  103. package/dist/televet/index.d.cts +60 -0
  104. package/dist/televet/index.d.ts +60 -0
  105. package/dist/televet/index.js +1 -0
  106. package/dist/testing/index.cjs +5 -823
  107. package/dist/testing/index.d.cts +17 -3
  108. package/dist/testing/index.d.ts +17 -3
  109. package/dist/testing/index.js +5 -820
  110. package/dist/testing/rn/index.cjs +1 -449
  111. package/dist/testing/rn/index.d.cts +17 -29
  112. package/dist/testing/rn/index.d.ts +17 -29
  113. package/dist/testing/rn/index.js +1 -444
  114. package/dist/testing/web/index.cjs +1 -0
  115. package/dist/testing/web/index.d.cts +131 -0
  116. package/dist/testing/web/index.d.ts +131 -0
  117. package/dist/testing/web/index.js +1 -0
  118. package/dist/timelineRows-CaohZzXS.d.cts +19 -0
  119. package/dist/timelineRows-DZed6dAM.d.ts +19 -0
  120. package/dist/typeStyle-0TydiZ1w.d.cts +19 -0
  121. package/dist/typeStyle-CWMsoe6b.d.ts +19 -0
  122. package/dist/uploadTransport-D0M0T4hN.d.ts +38 -0
  123. package/dist/uploadTransport-DKJHs3Yj.d.cts +38 -0
  124. package/dist/useRecordsDepth-BHBzJ76R.d.cts +237 -0
  125. package/dist/useRecordsDepth-BU-OhzH6.d.ts +237 -0
  126. package/dist/useVetVisit-Bc84hWUU.d.cts +187 -0
  127. package/dist/useVetVisit-CjmMa896.d.ts +187 -0
  128. package/dist/video/index.cjs +1 -1941
  129. package/dist/video/index.d.cts +4 -4
  130. package/dist/video/index.d.ts +4 -4
  131. package/dist/video/index.js +1 -1938
  132. package/dist/view-C3qPIXGX.d.cts +310 -0
  133. package/dist/view-DtSPYpKa.d.ts +310 -0
  134. package/dist/visitIntent-D7_yVp1I.d.cts +8 -0
  135. package/dist/visitIntent-D7_yVp1I.d.ts +8 -0
  136. package/dist/web/consent/index.cjs +1 -0
  137. package/dist/web/consent/index.d.cts +34 -0
  138. package/dist/web/consent/index.d.ts +34 -0
  139. package/dist/web/consent/index.js +1 -0
  140. package/dist/web/index.cjs +14 -0
  141. package/dist/web/index.d.cts +217 -0
  142. package/dist/web/index.d.ts +217 -0
  143. package/dist/web/index.js +14 -0
  144. package/dist/web/notifications/index.cjs +2 -0
  145. package/dist/web/notifications/index.d.cts +213 -0
  146. package/dist/web/notifications/index.d.ts +213 -0
  147. package/dist/web/notifications/index.js +2 -0
  148. package/dist/web/records/depth/index.cjs +2 -0
  149. package/dist/web/records/depth/index.d.cts +12 -0
  150. package/dist/web/records/depth/index.d.ts +12 -0
  151. package/dist/web/records/depth/index.js +2 -0
  152. package/dist/web/records/index.cjs +4 -0
  153. package/dist/web/records/index.d.cts +194 -0
  154. package/dist/web/records/index.d.ts +194 -0
  155. package/dist/web/records/index.js +4 -0
  156. package/dist/web/televet/index.cjs +1 -0
  157. package/dist/web/televet/index.d.cts +50 -0
  158. package/dist/web/televet/index.d.ts +50 -0
  159. package/dist/web/televet/index.js +1 -0
  160. package/notifications/package.json +8 -0
  161. package/package.json +197 -9
  162. package/records/depth/package.json +8 -0
  163. package/server/events/device-blocked.cjs +15 -0
  164. package/server/events/package.json +9 -0
  165. package/televet/package.json +8 -0
  166. package/testing/web/native-blocked.cjs +12 -0
  167. package/testing/web/package.json +8 -0
  168. package/web/consent/native-blocked.cjs +12 -0
  169. package/web/consent/package.json +8 -0
  170. package/web/native-blocked.cjs +12 -0
  171. package/web/notifications/native-blocked.cjs +12 -0
  172. package/web/notifications/package.json +8 -0
  173. package/web/package.json +8 -0
  174. package/web/records/depth/native-blocked.cjs +12 -0
  175. package/web/records/depth/package.json +8 -0
  176. package/web/records/native-blocked.cjs +12 -0
  177. package/web/records/package.json +8 -0
  178. package/web/televet/native-blocked.cjs +12 -0
  179. package/web/televet/package.json +8 -0
  180. package/dist/ChatController-CKdBvPj2.d.ts +0 -146
  181. package/dist/ChatController-CpUMvvZf.d.cts +0 -146
  182. package/dist/FilePort-BabWrv7I.d.cts +0 -22
  183. package/dist/FilePort-BabWrv7I.d.ts +0 -22
  184. package/dist/petsRepository-BEGb97M9.d.cts +0 -326
  185. package/dist/petsRepository-Bu18r2kK.d.ts +0 -326
  186. package/dist/requestFunnel-DuUH-kAe.d.cts +0 -28
  187. package/dist/requestFunnel-dio5OmR9.d.ts +0 -28
@@ -1,2840 +1,4 @@
1
- 'use strict';
1
+ 'use strict';var react=require('react'),zod=require('zod'),reactNative=require('react-native'),jsxRuntime=require('react/jsx-runtime');var qd=Object.defineProperty;var i=(e,t)=>qd(e,"name",{value:t,configurable:true});var Lo=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(Lo.map(e=>e.wireCode));var Fd=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"}),Fa=Object.freeze(Lo.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Fd[e.wireCode]}))),zd=new Map(Fa.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Nd=Object.freeze(["http_envelope",...[...new Set(Fa.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Ln(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...Nd]){let n=zd.get(o+r);if(n)return n}}i(Ln,"contractErrorFor");function Md(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Md,"contractDocUrl");function za(e){return null}i(za,"publishedDocUrl");var Bd=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 Na(e){return Bd[e]}i(Na,"categoryFor");function Ma(e){let t=Ln(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":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(Ma,"fromWire");var Hd=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Vo(e){return Hd.has(e)}i(Vo,"isAutoRetryable");var Ud=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Ba(e){return Vo(e)||Ud.has(e)}i(Ba,"isRetryableCode");var jd=500,qo=8e3,Ha=4;function Ua(e,t=Math.random){let r=Math.max(0,e),o=Math.min(jd*2**r,qo);return Math.floor(t()*o)}i(Ua,"backoffDelayMs");var $d=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 Fo(e){return $d[e]}i(Fo,"userFacingError");function ja(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(ja,"defineHidden");var Wd=/^[a-z][a-z0-9_]{0,63}$/;function q(e,t){let r=Ln(t?.wireCode,t?.wireEnvelope),o={code:e,category:Na(e),retryable:t?.retryable??Ba(e),displayMessage:Fo(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&Wd.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&ja(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ja(o,"raw",t.raw),Object.freeze(o)}i(q,"makeEverfurError");function _e(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_e,"ok");function B(e){return Object.freeze({ok:false,error:e})}i(B,"err");var Vn=class Vn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Vn.prototype);}};i(Vn,"EverfurConfigError");var en=Vn;var Ka=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),$a=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 Gd(e){let t=Object.prototype.hasOwnProperty.call($a,e)?$a[e]:void 0;if(t!==void 0)return t;let r=e;return Ka.has(r)?r:"parsing"}i(Gd,"normalizeStatus");function Qa(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Qa,"normalizeOrigin");var Yd=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 cr(e){let t=Yd.safeParse(e);if(!t.success)return null;let r=t.data,o=Qd(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??Gd(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:Ga(r.document_count,0),heldItemCount:Ga(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(cr,"mapRequestView");var Kd=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 Xa(e){let t=Kd.safeParse(e);if(!t.success)return null;let r=t.data,o=zo(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(Xa,"mapRequestGroup");function Qd(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Ka.has(e)?e:null}i(Qd,"normalizeSimpleStatus");function zo(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=cr(o);n!==null&&r.push(n);}return Object.freeze(r)}i(zo,"mapRequestList");var Xd=zod.z.object({source_doc_id:zod.z.string().min(1),request_id:zod.z.string().min(1)});function Ja(e){let t=Xd.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(Ja,"mapUploadedDocument");var Jd=zod.z.object({label:zod.z.string(),value:zod.z.string()}),No=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()}),Zd=zod.z.object({at:zod.z.string(),value:zod.z.number().nullish(),display:zod.z.string().nullish(),origin:zod.z.string().nullish()}),eu=zod.z.object({key:zod.z.string(),label:zod.z.string().optional(),points:zod.z.array(Zd).optional()}),tu=zod.z.object({title:zod.z.string(),detail:zod.z.string().nullish(),due_at:zod.z.string().nullish()}),Mo=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 Bo(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:Qa(e.origin),canonicalKey:e.canonical_key??null})}i(Bo,"mapEntityRow");function Ho(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Ho,"mapDocumentRow");var ru=zod.z.object({identity:zod.z.array(Jd).optional(),entities:zod.z.array(No).optional(),entity_series:zod.z.array(eu).optional(),forward_looking:zod.z.array(tu).optional(),documents:zod.z.array(Mo).optional()});function Za(e,t){let r=ou(t)?t:{},o=Ya(r.schema_version,"epdf/1.0"),n=Ya(r.disclaimer,""),l=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Wa(l,o,n);let s=ru.safeParse(r);if(!s.success)return Wa(l,o,n);let c=s.data,a=(c.identity??[]).map(R=>Object.freeze({label:R.label,value:R.value})),d=(c.entities??[]).map(Bo),u=(c.entity_series??[]).map(R=>Object.freeze({key:R.key,label:R.label??R.key,points:Object.freeze((R.points??[]).map(v=>Object.freeze({at:v.at,value:v.value??null,display:v.display??null,origin:Qa(v.origin)})))})),p=(c.forward_looking??[]).map(R=>Object.freeze({title:R.title,detail:R.detail??null,dueAt:R.due_at??null})),f={};for(let R of c.documents??[])f[R.doc_id]=Ho(R);let h=r.is_empty===true||a.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(f).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:h,withheld:false,generatedAt:iu(r.generated_at),identity:Object.freeze(a),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(f),disclaimer:n})}i(Za,"mapRecordView");function Wa(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(Wa,"withheldView");var nu=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 qn(e,t){let r=nu.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(qn,"mapConsent");function ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ou,"isObject");function Ga(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Ga,"numberOr");function Ya(e,t){return typeof e=="string"&&e.length>0?e:t}i(Ya,"strOr");function iu(e){return typeof e=="string"&&e.length>0?e:null}i(iu,"strOrNull");var es=Object.freeze(["published","failed","revoked"]);function zr(e){return es.includes(e)}i(zr,"isTerminalStatus");function dr(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(dr,"recordsDenialReasonOf");var au="records_consent_required";function su(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(su,"recordsWireCodeOf");function tr(e){return e===null||e.httpStatus!==409?false:su(e)===au}i(tr,"isRecordsConsentRequired");var lu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Fn(e){return e!==lu}i(Fn,"isUploadTransportAvailable");var ts=Object.freeze({record(){}}),ur=25*1024*1024,rs=64,tn=128,mt=128,rn="application/pdf",ns=9e4;function is(e){return new Uo(e)}i(is,"createRecordsController");var jo=class jo{constructor(t){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.repository=t.repository,this.uploads=t.uploads,this.telemetry=t.telemetry??ts,this.newIdempotencyKey=t.newIdempotencyKey??mu(),this.timers=t.timers??uu,this.uploadDeadlineMs=t.uploadDeadlineMs??ns;}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=cr(r.value);return o===null?B(zn()):(this.observeRequest(o),_e(o))}async getRequest(t){let r=await this.repository.getRequest(t);if(!r.ok)return this.onRequestError(r.error);let o=cr(r.value);return o===null?B(zn()):(this.observeRequest(o),_e(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=zo(t.value);for(let o of r)this.observeRequest(o);return _e(r)}async uploadDocument(t){let{requestId:r,file:o}=t,n=cu(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),B(os(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(r,{content_type:rn,file_size:o.sizeBytes});if(!l.ok)return this.onRequestError(l.error);let s=await this.postToS3(l.value,o,t);if(!s.ok)return this.telemetry.record("records.upload.failed",{reason:s.reason}),B(os(s.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:du(c.error)??"corrupt"}),this.onRequestError(c.error);let a=Ja(c.value);return a===null?B(zn()):_e(a)}async postToS3(t,r,o){let n=new AbortController,l=pu(n.signal,o.signal),s=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(s);}}async getRecord(t){let r=this.consentEpoch.get(t)??0,o=await this.repository.getRecord(t);if(r!==(this.consentEpoch.get(t)??0))return B(Object.freeze({...q("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=dr(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}),B(o.error)}let n=Za(t,o.value);return n.petRef!==t?B(zn()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:t}),this.recordCache.delete(t),_e(n)):(this.recordCache.set(t,n),_e(n))}peekCachedRecord(t){return this.recordCache.get(t)??null}async getConsent(t){let r=await this.repository.getConsent(t);return r.ok?_e(qn(t,r.value)):B(r.error)}async grantConsent(t){let r=await this.repository.putConsent(t.petRef,{consent_version:t.consentVersion,idempotency_key:t.idempotencyKey});return r.ok?_e(qn(t.petRef,r.value)):(dr(r.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t.petRef}),B(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),_e(qn(t,r.value))):B(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 dr(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),B(t)}};i(jo,"RecordsControllerImpl");var Uo=jo;function cu(e){if(e.mimeType!==rn)return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>ur?"oversize":null}i(cu,"validateFile");function du(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(du,"reasonFromWire");function os(e){return q("mediaUploadFailed",{retryable:false,wireMessage:e})}i(os,"uploadFailed");function zn(){return q("internalError",{retryable:true})}i(zn,"internal");var uu={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function pu(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(pu,"mergeSignals");function mu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(mu,"defaultIdempotencyFactory");function pr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(pr,"assertNever");function as(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(as,"errorFrame");function gu(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(gu,"authHeaders");function nn(e,t){return {...e,headers:{...bu(e.headers),...gu(t)}}}i(nn,"withAuthHeaders");function bu(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(bu,"stripAuthHeaders");async function ss(e,t){if(t.mode==="anonymous")return t.transport.request(nn(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return B($o())}let o=await t.transport.request(nn(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 B($o())}let l=await t.transport.request(nn(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?B($o(l.error.httpStatus)):l}i(ss,"authedSend");function $o(e){return q("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i($o,"authRejectedError");function ls(e){return q("internalError",{retryable:true,wireMessage:hu(e)})}i(ls,"networkError");function hu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(hu,"describeCause");var Ru=3e4,vu=qo*2,xu="idempotency-key",wu=new Set(["POST","PUT","PATCH","DELETE"]),Cu=Object.freeze({onEvent(){}}),Eu=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function mr(e){let t=e.observer??Cu,r=e.timers??Eu,o=e.rng??Math.random,n=e.sleep??((f,h)=>qu(f,r,h)),l=e.maxAttempts??Ha,s=e.unaryTimeoutMs??Ru,c=e.newIdempotencyKey??rr(),a=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,h,R){let v=R?.maxAttempts,y=Math.max(1,v??l),b=R?.idempotent??wu.has(h.method)?c():null,w=Su(h,b),x=0;for(;;){let E=i($=>Object.freeze({call:f,method:h.method,path:h.path,attempt:x,...b?{idempotencyKey:b}:{},...$}),"stamp");a(E({phase:"attempt"}));let D=Lu(s,r),k=Vu(D.signal,h.signal),S;try{S=await ss({...w,signal:k.signal},e.auth);}catch($){S=B(ls($));}finally{k.dispose(),D.cancel();}if(S.ok)return a(E({phase:"settled",ok:true,reason:"ok"})),S;let I=S.error,Y=Tu(I,x,{maxAttempts:y,rng:o,now:r.now(),aborted:h.signal?.aborted===true,...v!==void 0?{perCallMaxAttempts:v}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),z={ok:false,code:I.code,reason:Y.reason,...I.httpStatus!==void 0?{httpStatus:I.httpStatus}:{},...I.requestId!==void 0?{requestId:I.requestId}:{}};if(!Y.retry)return a(E({phase:"settled",...z})),B(I);if(a(E({phase:"retry",...z,delayMs:Y.delayMs})),await n(Y.delayMs,h.signal),h.signal?.aborted===true)return a(E({phase:"settled",...z,reason:"aborted"})),B(I);x+=1;}}i(d,"send");async function u(f){return nn(f,await Ou(e.auth))}i(u,"authorize");async function*p(f,h,R){a(Object.freeze({call:f,phase:"stream.open",method:h.method,path:h.path,attempt:0}));try{yield*e.auth.transport.stream(h,R);}catch{yield as({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:u,stream:p})}i(mr,"createRequestFunnel");function Su(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==xu&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Su,"assembleHeaders");function rr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(rr,"defaultIdempotencyKeyFactory");var ku=10;function Tu(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=_u(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Vo(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 s=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(ku,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??s()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let a=Pu(e,r.now);return a!==null?a>vu?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:a}:{retry:true,reason:n,delayMs:Ua(t,r.rng)}}i(Tu,"decideRetry");function _u(e){let t=e.code==="unknown"?Ma(Au(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(_u,"throttleKind");function Pu(e,t){let r=Iu(e.raw);if(r===null)return null;let o=r-t;return o>0?o:0}i(Pu,"retryOverrideMs");function Iu(e){for(let t of ds(e)){let r=t.resets_at,o=Du(r);if(o!==null)return o}return null}i(Iu,"findResetsAt");function ds(e){if(!cs(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];cs(o)&&t.push(o);}return t}i(ds,"candidateScopes");function Du(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(Du,"parseInstantMs");function Au(e){for(let t of ds(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Au,"rawWireCode");function cs(e){return typeof e=="object"&&e!==null}i(cs,"isRecord");async function Ou(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(Ou,"resolveDeviceAuth");function Lu(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(Lu,"boundedSignal");function Vu(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(Vu,"mergeSignals");function qu(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(qu,"delayAbortable");function yr(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(yr,"hasLoneSurrogate");var nr="/widget/v1/records";function ps(e){let{auth:t}=e,r=t.mode,o=e.funnel??mr({auth:t,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(a,d,u)=>{let p=await o.send(a,d);return p.ok?p:B(Nu(p.error,r,u))},"send"),l=i((a,d)=>typeof d!="string"||d.length===0?q("validationFailed",{retryable:false,wireMessage:`${a} is required and must be a non-empty string`}):yr(d)?q("validationFailed",{retryable:false,wireMessage:`${a} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),s=i((a,d,u)=>{let p=l(a,d);if(p!==null)return p;let h=[...d].length;return h>u?q("validationFailed",{retryable:false,wireMessage:`${a} is ${h} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...a)=>a.find(d=>d!==null)??null,"firstError");return {createRequest:i(a=>{let d=c(s("idempotency_key",a.idempotency_key,tn),s("pet_ref",a.pet_ref,mt));return d?Promise.resolve(B(d)):n("records.createRequest",Wo(`${nr}/requests`,a),"request")},"createRequest"),initiateUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.initiateUpload",Wo(`${nr}/requests/${encodeURIComponent(a)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.completeUpload",Wo(`${nr}/requests/${encodeURIComponent(a)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(a=>{let d=l("request_id",a);return d?Promise.resolve(B(d)):n("records.getRequest",Nn(`${nr}/requests/${encodeURIComponent(a)}`),"request")},"getRequest"),listRequests:i(async()=>{let a=await n("records.listRequests",Nn(`${nr}/requests`),"request");if(!a.ok)return a;let d=a.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getRecord",Nn(`${nr}/pets/${encodeURIComponent(a)}/record`),"content")},"getRecord"),getConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getConsent",Nn(`${nr}/pets/${encodeURIComponent(a)}/consent`),"consent")},"getConsent"),putConsent:i((a,d)=>{let u=c(s("consent_version",d.consent_version,rs),s("idempotency_key",d.idempotency_key,tn),s("pet_ref",a,mt));return u?Promise.resolve(B(u)):n("records.putConsent",Mu(`${nr}/pets/${encodeURIComponent(a)}/consent`,d),"consent")},"putConsent"),deleteConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.deleteConsent",Bu(`${nr}/pets/${encodeURIComponent(a)}/consent`),"consent")},"deleteConsent")}}i(ps,"createHttpRecordsRepository");function us(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(us,"withReason");var Fu="pet_not_registered";function zu(e){return e.httpStatus!==404?null:e.reasonCode===Fu?"pet_not_found":"entitlement"}i(zu,"recordsErrorReasonFor");function Nu(e,t,r){let o=zu(e);return o!==null?us(e,o):e.code!=="accessDenied"?e:us(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(Nu,"tagReason");function Nn(e){return {method:"GET",path:e}}i(Nn,"get");function Wo(e,t){return {method:"POST",path:e,body:t}}i(Wo,"post");function Mu(e,t){return {method:"PUT",path:e,body:t}}i(Mu,"put");function Bu(e){return {method:"DELETE",path:e}}i(Bu,"del");var ms=Symbol.for("@everfur/sdk#EverfurContext@v1"),ys=globalThis,fs=ys[ms]??(ys[ms]=react.createContext(null));fs.displayName??="EverfurContext";function ke(){let e=react.useContext(fs);if(e===null)throw new en("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ke,"useEverfurContext");var Go=new Map,Yo=new Set;function gs(e){Go.set(e,(Go.get(e)??0)+1);for(let t of [...Yo])t();}i(gs,"notifyRecordsConsentWithdrawn");function Wu(e){return Go.get(e)??0}i(Wu,"recordsConsentEpochOf");function Gu(e){return Yo.add(e),()=>{Yo.delete(e);}}i(Gu,"subscribe");function Mn(e){let t=react.useCallback(()=>Wu(e),[e]);return react.useSyncExternalStore(Gu,t,t)}i(Mn,"useRecordsConsentEpoch");var Qo={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},hs=4e3,Ku=30;function yt(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:s}=ke(),c=react.useMemo(()=>({}),[n,l,t,s,e.controller]),a=react.useRef(c),[d,u]=react.useState({scope:c,controller:e.controller??null}),p=e.controller??(d.scope===c?d.controller:null),[f,h]=react.useState({scope:c,value:Qo}),R=f.scope===c?f.value:Qo,v=react.useCallback(C=>{h(T=>T.scope===c?{scope:c,value:C(T.value)}:T);},[c]),y=react.useRef(0);react.useEffect(()=>(a.current=c,h({scope:c,value:Qo}),()=>{a.current=null,y.current+=1;}),[c]),react.useEffect(()=>{if(e.controller)return;let{services:C}=n.registry,T={record:i((M,K)=>C.telemetry.track(M,K),"record")},A=n.registry.acquire("records",`${l??""}|${t}${o?"|own-upload":""}`,()=>is({repository:ps({auth:C.authFor(l),...C.errorPolicy?{errorPolicy:C.errorPolicy}:{}}),uploads:o?{postMultipart:i((M,K,ye)=>(r.current??C.uploadTransport).postMultipart(M,K,ye),"postMultipart")}:C.uploadTransport,telemetry:T}),()=>{});return u({scope:c,controller:A}),()=>{n.registry.release(A);}},[n,l,t,e.controller,s,c,o]);let g=react.useCallback(C=>{v(T=>({...T,...C}));},[v]),b=react.useCallback(async()=>{if(!p||a.current!==c)return;let C=y.current+=1;D.current=0,I(),g({loading:true,error:null,denialReason:null,withheld:false});let[T,A]=await Promise.all([p.getConsent(t),p.listRequests()]);if(C!==y.current)return;let M=T.ok?T.value:null,K=A.ok?A.value.filter(Ve=>Ve.petRef===t):[],ye=A.ok?null:A.error;if(M&&M.granted){let Ve=await p.getRecord(t);if(C!==y.current)return;if(Ve.ok){g({consent:M,requests:K,record:Ve.value,withheld:Ve.value.withheld,error:Ve.value.withheld?ep():ye,denialReason:null,loading:false});return}g({consent:M,requests:K,record:null,error:Ve.error,denialReason:dr(Ve.error),withheld:false,loading:false});return}g({consent:M,requests:K,record:null,error:T.ok?ye:T.error,denialReason:M?"consent_required":Zu(T),withheld:false,loading:false});},[p,t,g,c]);react.useEffect(()=>(b(),()=>{y.current+=1;}),[b]);let w=react.useMemo(()=>Ju(R.requests),[R.requests]),x=w?.id??null,E=w?.status??null,D=react.useRef(0),k=react.useRef(null),[S,I]=react.useReducer(C=>C+1,0);react.useEffect(()=>{if(!p||x===null||E===null||zr(E)||E==="in_review")return;k.current!==String(x)&&(k.current=String(x),D.current=0);let C=false,T=i(async()=>{if(C||D.current>=Ku)return;D.current+=1;let M=await p.getRequest(x);if(!C){if(M.ok&&M.value.petRef===t){if(v(K=>({...K,requests:Hn(K.requests,M.value)})),zr(M.value.status)){M.value.status==="published"&&b();return}if(M.value.status==="in_review")return}A=setTimeout(()=>{T();},hs);}},"tick"),A=setTimeout(()=>{T();},hs);return ()=>{C=true,clearTimeout(A);}},[p,x,E,b,S,t,v]);let Y=react.useCallback(async C=>{if(!p||a.current!==c)return Un();let T=await p.createUploadRequest({petRef:t,idempotencyKey:C});return a.current===c&&T.ok&&T.value.petRef===t&&v(A=>({...A,requests:Hn(A.requests,T.value)})),T},[p,t,c,v]),z=react.useCallback((C,T)=>{v(A=>({...A,uploadQueue:A.uploadQueue.map(M=>M.key===C?T(M):M)}));},[v]),$=react.useCallback(async(C,T)=>{let A=Date.now().toString(36),M=T.map((ye,Ve)=>{let ie=Qu(ye);return {key:`${A}-${Ve}`,name:ye.name??null,status:ie===null?"queued":"skipped",progress:0,skipReason:ie,error:null}}),K=[...M];if(!p||a.current!==c)return Object.freeze(K);v(ye=>({...ye,uploadQueue:M,isUploading:true,uploadProgress:0}));for(let[ye,Ve]of T.entries()){let ie=M[ye];if(ie.status==="skipped")continue;if(a.current!==c)break;z(ie.key,Xe=>({...Xe,status:"uploading",progress:0})),g({uploadProgress:0});let we=await p.uploadDocument({requestId:C,file:Ve,onProgress:i(Xe=>{if(a.current!==c)return;let Vt=Math.min(1,Math.max(0,Xe));z(ie.key,qt=>({...qt,progress:Math.max(qt.progress,Vt)})),g({uploadProgress:Vt});},"onProgress")});if(a.current!==c)break;let vt=we.ok?{...ie,status:"done",progress:1}:{...ie,status:"failed",error:we.error};if(K[ye]=vt,z(ie.key,()=>vt),we.ok){let Xe=await p.getRequest(C);a.current===c&&Xe.ok&&Xe.value.petRef===t&&v(Vt=>({...Vt,requests:Hn(Vt.requests,Xe.value)}));}}return a.current===c&&g({isUploading:false,uploadProgress:null}),Object.freeze(K)},[p,g,z,t,c,v]),G=react.useCallback(async(C,T)=>{if(!p||a.current!==c)return Un();let A=`${Date.now().toString(36)}-0`;v(K=>({...K,isUploading:true,uploadProgress:0,uploadQueue:[{key:A,name:T.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let M=await p.uploadDocument({requestId:C,file:T,onProgress:i(K=>{a.current===c&&(g({uploadProgress:K}),z(A,ye=>({...ye,progress:Math.max(ye.progress,Math.min(1,K))})));},"onProgress")});if(a.current!==c)return M;if(g({isUploading:false,uploadProgress:null}),z(A,K=>M.ok?{...K,status:"done",progress:1}:{...K,status:"failed",error:M.error}),M.ok){let K=await p.getRequest(C);a.current===c&&K.ok&&K.value.petRef===t&&v(ye=>({...ye,requests:Hn(ye.requests,K.value)}));}return M},[p,g,z,t,c,v]),Z=react.useCallback(async(C,T)=>{if(!p||a.current!==c)return Un();let A=await p.grantConsent({petRef:t,consentVersion:C,idempotencyKey:T});return A.ok&&a.current===c&&b(),A},[p,t,b,c]),oe=react.useCallback(async()=>{if(!p||a.current!==c)return Un();let C=await p.revokeConsent(t);return C.ok&&gs(t),C.ok&&a.current===c&&(y.current+=1,g({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:C.value})),C},[p,t,g,c]),Ee=react.useCallback(()=>{b();},[b]),H=Xu(R,p!==null);return react.useMemo(()=>({status:H,record:R.record,requests:R.requests,activeRequest:w,consent:R.consent,error:R.error,denialReason:R.denialReason,withheld:R.withheld,isUploading:R.isUploading,uploadProgress:R.uploadProgress,uploadQueue:R.uploadQueue,createRequest:Y,uploadDocument:G,uploadDocuments:$,grantConsent:Z,revokeConsent:oe,refresh:Ee}),[H,R,w,Y,G,$,Z,oe,Ee])}i(yt,"useEverfurRecords");function Qu(e){if(e.mimeType!==rn)return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>ur?"too_large":null}i(Qu,"skipReasonFor");function Xu(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(Xu,"selectStatus");function Ju(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(Ju,"newestRequest");function Hn(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(Hn,"replaceRequest");function Zu(e){return e.ok?"consent_required":dr(e.error)??"consent_required"}i(Zu,"consentDenial");function ep(){return q("internalError",{retryable:false})}i(ep,"withheldSentinel");function Un(){return {ok:false,error:q("internalError",{retryable:true})}}i(Un,"notReady");function Xo(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Xo,"reportHostFailure");function tp(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(tp,"isThenable");function jn(e,...t){if(typeof e=="function")try{let r=e(...t);return tp(r)&&Promise.resolve(r).then(void 0,Xo),r}catch(r){Xo(r);return}}i(jn,"callHost");var Rs=new WeakMap;function an(e){if(typeof e!="function")return;let t=Rs.get(e);if(t!==void 0)return t;let r=i((...o)=>{jn(e,...o);},"guarded");return Rs.set(e,r),r}i(an,"guardHost");function Fe(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=an(n));}return r??e}i(Fe,"guardHostProps");function kr(e,...t){let r;try{r=e(...t);}catch(o){return Xo(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(kr,"callHostAsync");var vs=Object.freeze({name:"dashboard"});function $n(e=vs){return Object.freeze({stack:Object.freeze([e])})}i($n,"initialRecordsNav");function Wn(e){return e.stack[e.stack.length-1]??vs}i(Wn,"currentRecordsScreen");function Jo(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(Jo,"pushRecordsNav");function Zo(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(Zo,"replaceRecordsNav");function ei(e){return $n(e)}i(ei,"resetRecordsNav");function Gn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(Gn,"popRecordsNav");function xs(e,t){return t.name==="dashboard"?ei(t):Wn(e).name==="upload"&&t.name==="request"?Zo(e,t):Jo(e,t)}i(xs,"transitionRecordsNav");function ti(e,t){switch(t.type){case "push":return Jo(e,t.screen);case "pop":return Gn(e).state;case "replace":return Zo(e,t.screen);case "reset":return ei(t.screen);case "navigate":return xs(e,t.screen);default:return e}}i(ti,"recordsNavReducer");function oi(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))oi(e[t]);}return e}i(oi,"deepFreeze");var rp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Cs={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Es={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},ws={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},np={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},op={regular:"400",medium:"500",bold:"700"},ip={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},ap=0,Yn="System",Kn="monospace",sp=["content","heading","control","compact","badge"];function lp(e){let t={};for(let r of sp)t[r]=e;return t}i(lp,"authoredTierSizes");function Ss(){return {family:Yn,mono:Kn,fontUrl:null,families:{regular:Yn,medium:Yn,bold:Yn,mono:Kn,monoMedium:Kn,monoBold:Kn},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:ws,tierSizes:lp(ws),lineHeight:np,weight:op,letterSpacing:ip,scale:1,maxScale:ap,scaleCaps:rp}}i(Ss,"baseType");var ks={},ri=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function ni(e){return `cubic-bezier(${e.join(", ")})`}i(ni,"cssCubicBezier");var Ts={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:ni(ri.standard),emphasized:ni(ri.emphasized),exit:ni(ri.exit)},reducedMotion:false},cp={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:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",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:"#B91C1C",errorRed:"#FF1B00",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(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},_s=oi({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:cp,space:Cs,radius:Es,type:Ss(),motion:Ts,slots:ks}),dp={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:"#9A938C",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",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",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};oi({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:dp,space:Cs,radius:Es,type:Ss(),motion:Ts,slots:ks});var Ps=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Is=globalThis,ii=Is[Ps]??(Is[Ps]=react.createContext(_s));ii.displayName??="EverfurThemeContext";function L(){return react.useContext(ii)}i(L,"useEverfurTheme");function gp(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(gp,"tierMultiplier");function m({tier:e="content",...t}){let{type:r}=L(),o=gp(r,e);return react.createElement(reactNative.Text,o===void 0?t:{maxFontSizeMultiplier:o,...t})}i(m,"Text");var qe=react.forwardRef(i(function(t,r){return react.createElement(reactNative.TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var bp=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function _(e,t){let r=e.type,o=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:o}:{fontFamily:o,fontWeight:r.weight[bp[t]]}}i(_,"face");var U=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",missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used"});var xe=Object.freeze({title:U.title,placeholder:U.placeholder,searchA11y:U.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:U.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 As(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(As,"clinicEmailStatusBadge");function Os(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Os,"formatClinicDistanceLabel");function Ls(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Ls,"formatClinicDistanceForA11y");var Vs=300,ai=2;var ce=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"});function qs(e){return !zr(e.status)}i(qs,"isRecordsInProgress");function Qn(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(qs).sort((l,s)=>s.updatedAt.localeCompare(l.updatedAt))[0]??null}i(Qn,"pickPetRecordsRequest");function si(e){if(e.hasMarkers)return "published";let t=Qn(e.requests,e.petRef);return t===null?"none":t.status==="published"||qs(t)?"in_progress":"none"}i(si,"deriveRecordsDashboardState");function hp(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(hp,"selectDashboardLoading");function li(e){return hp(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(li,"selectDashboardView");function wt(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(wt,"recordsEmptyVariantForError");var ge=Object.freeze({loading:"Loading record request",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 Rp(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(Rp,"fallbackFailureTitle");function Fs(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Rp(e)}i(Fs,"failureTitle");var vp=1440*60*1e3;function ci(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/vp)}i(ci,"requestElapsedDays");var xp=7;function zs(e,t){return e.wireStatus!=="awaiting_response"?false:ci(e,t)>=xp}i(zs,"requestWaitingTooLong");function di(e){return e.status==="failed"}i(di,"isTerminalFailure");function Ns(e){return di(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(Ns,"shouldOfferRecovery");function Hs(e,t){let[r,o]=react.useState(""),[n,l]=react.useState(""),[s,c]=react.useState([]),[a,d]=react.useState(null),[u,p]=react.useState([]),[f,h]=react.useState(true),[R,v]=react.useState(false),[y,g]=react.useState(false),[b,w]=react.useState(null),[x,E]=react.useState(null),[D,k]=react.useState(0),S=react.useRef(0),I=react.useRef(true),Y=t?.latitude,z=t?.longitude,$=react.useMemo(()=>Y!==void 0&&z!==void 0?{latitude:Y,longitude:z}:void 0,[Y,z]);react.useEffect(()=>(I.current=true,()=>{I.current=false,S.current+=1;}),[e]),react.useEffect(()=>{let H=true;return h(true),e.recentClinics({limit:5}).then(C=>{H&&(C.ok&&p(C.value.clinics),h(false));}).catch(()=>{H&&h(false);}),()=>{H=false;}},[e]),react.useEffect(()=>{let H=r.trim();if(H.length<ai){l("");return}let C=setTimeout(()=>l(H),Vs);return ()=>clearTimeout(C)},[r]);let G=n.length>=ai;react.useEffect(()=>{let H=S.current+=1;if(c([]),d(null),w(null),E(null),!G){v(false);return}v(true),e.searchClinics({query:n,limit:25,...$?{location:$}:{}}).then(C=>{!I.current||H!==S.current||(C.ok?(c(C.value.clinics),d(C.value.nextCursor)):w(C.error),v(false));}).catch(()=>{I.current&&H===S.current&&v(false);});},[e,n,G,$,D]);let Z=react.useCallback(()=>{if(!G||a===null||y)return;let H=S.current;g(true),E(null),e.searchClinics({query:n,limit:25,cursor:a,...$?{location:$}:{}}).then(C=>{!I.current||H!==S.current||(C.ok?(c(T=>[...T,...C.value.clinics]),d(C.value.nextCursor)):E(C.error),g(false));}).catch(()=>{I.current&&H===S.current&&g(false);});},[e,a,n,G,y,$]),oe=react.useCallback(H=>o(H),[]),Ee=react.useCallback(()=>k(H=>H+1),[]);return react.useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:G,clinics:s,recent:u,recentLoading:f,initialLoading:R,loadingMore:y,hasNextPage:a!==null,error:b,pageError:x,setQuery:oe,loadMore:Z,retry:Ee}),[r,n,G,s,u,f,R,y,a,b,x,oe,Z,Ee])}i(Hs,"useClinicPicker");function pi(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(pi,"clinicDraftFor");var Nr=10,Jn=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=>!yr(r)&&[...r].length>=t&&[...r].length<=e),"text"),js=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),wp=zod.z.object({clinicId:Jn.optional(),clinicFreeText:sn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:sn(320,3).refine(e=>!js(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Jn.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)),Cp=zod.z.object({petRef:sn(128),ownerName:sn(200).refine(e=>e.trim().length>0&&!js(e)),authorizationVersion:sn(64),clinics:zod.z.array(wp).min(1).max(Nr)}).strict(),Ep=zod.z.object({request_group_id:Jn,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:Jn.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 $s(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Cp.safeParse(r).success)return B(q("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(s=>({...s.clinicId!==void 0?{clinic_id:s.clinicId}:{clinic_free_text:s.clinicFreeText},...s.clinicEmail!==void 0?{clinic_email:s.clinicEmail}:{},...s.signatureId!==void 0?{signature_id:s.signatureId}:{signature_png_base64:s.signaturePngBase64},idempotency_key:s.idempotencyKey}))}});if(!o.ok)return o;let n=Ep.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return Us();let l=[];for(let s of n.data.results){let c=s.request===void 0||s.request===null?null:cr(s.request);if(s.created!==(c!==null))return Us();l.push(Object.freeze({idempotencyKey:s.idempotency_key,clinicId:s.clinic_id??null,clinicFreeText:s.clinic_free_text??null,created:s.created,request:c,failureCode:s.failure_code??null,failureReason:s.failure_reason??null}));}return _e(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($s,"createRecordsClinicBatchClient");function Us(){return B(q("internalError",{retryable:false}))}i(Us,"malformed");var Ws=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),Sp=zod.z.object({clinics:zod.z.array(zod.z.object({clinic_id:Ws,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()}),kp=zod.z.object({authorization_version:zod.z.string().min(1),scope_template:zod.z.string().min(1),authorization_template:zod.z.string().min(1)}),Tp=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 Gs(e){let{repository:t}=e,r=i(async n=>{let l=await n;if(!l.ok)return l;let s=cr(l.value);return s===null?Tr():_e(s)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let s=Sp.safeParse(l.value);return s.success?_e(Object.freeze({clinics:Object.freeze(s.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:s.data.next_cursor??null})):Tr()},"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 s=Xa(l.value);return s===null?Tr():_e(s)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let l=kp.safeParse(n.value);return l.success?_e(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):Tr()},async createClinicRequest(n){let l=await r(t.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?Tr():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 s=Tp.safeParse(l.value);return s.success?_e(Object.freeze({uploadId:s.data.upload_id,uploadUrl:s.data.upload_url,uploadFields:Object.freeze(s.data.upload_fields)})):Tr()},async completeSignatureUpload(n){let l=await t.completeSignatureUpload(n);if(!l.ok)return l;let s=zod.z.object({signature_id:Ws}).safeParse(l.value);return s.success?_e(s.data.signature_id):Tr()}}}i(Gs,"createRecordsClinicController");function Tr(){return B(q("internalError",{retryable:false}))}i(Tr,"malformed");var fr="/widget/v1/records",Ys=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),br=i((e,t=1)=>zod.z.string().refine(r=>!yr(r)&&[...r].length>=t&&[...r].length<=e),"text"),Qs=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Xs=br(320,3).refine(e=>!Qs(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),Ks=br(64),_p=zod.z.object({limit:zod.z.number().int().min(1).max(25).optional()}).strict(),Pp=zod.z.object({query:br(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:br(512,0).optional()}).strict(),Ip=zod.z.object({petRef:br(128),ownerName:br(200).refine(e=>e.trim().length>0&&!Qs(e)),authorizationVersion:br(64),clinicId:Ys.optional(),clinicFreeText:br(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Xs.optional(),signatureId:Ys.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 Js(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((n,l,s=false)=>t.send(`records.clinic.${n}`,l,l.method==="GET"||s?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,l,s)=>Ks.safeParse(n).success?r(l,{method:"POST",path:`${fr}/requests/${encodeURIComponent(n)}/${l}`,...s?{body:s}:{}}):gr(),"recover");return {searchClinics(n){return Pp.safeParse(n).success?r("search",{method:"GET",path:`${fr}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):gr()},recentClinics(n){return _p.safeParse(n).success?r("recent",{method:"GET",path:`${fr}/clinics/recent`,query:{limit:n.limit}}):gr()},getRequestGroup(n){return Ks.safeParse(n).success?r("requestGroup",{method:"GET",path:`${fr}/request-groups/${encodeURIComponent(n)}`}):gr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${fr}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Ip.safeParse(n).success?r("create",{method:"POST",path:`${fr}/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):gr()},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 Xs.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):gr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?gr():r("signatureInitiate",{method:"POST",path:`${fr}/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:`${fr}/signatures/complete`,body:{upload_id:n}}):gr()}}}i(Js,"createHttpRecordsClinicRepository");function gr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(gr,"invalid");function Nt(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=react.useMemo(()=>{let{services:l}=e.registry;return Gs({repository:Js({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 s=>{if(t===null||n.current!==o)return B(q("accessDenied"));let c=await s();return n.current===o?c:B(q("accessDenied"))},"run");return {searchClinics:i(s=>l(()=>o.searchClinics(s)),"searchClinics"),recentClinics:i(s=>l(()=>o.recentClinics(s)),"recentClinics"),getRequestGroup:i(s=>l(()=>o.getRequestGroup(s)),"getRequestGroup"),getAuthorizationCopy:i(()=>l(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(s=>l(()=>o.createClinicRequest(s)),"createClinicRequest"),retryRequest:i(s=>l(()=>o.retryRequest(s)),"retryRequest"),revokeRequest:i(s=>l(()=>o.revokeRequest(s)),"revokeRequest"),updateClinicEmail:i((s,c)=>l(()=>o.updateClinicEmail(s,c)),"updateClinicEmail"),convertToUpload:i(s=>l(()=>o.convertToUpload(s)),"convertToUpload"),initiateSignatureUpload:i(s=>l(()=>o.initiateSignatureUpload(s)),"initiateSignatureUpload"),completeSignatureUpload:i(s=>l(()=>o.completeSignatureUpload(s)),"completeSignatureUpload")}},[o,t])}i(Nt,"useEverfurRecordsClinic");function mi(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=react.useMemo(()=>{let{services:l}=e.registry;return $s({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 B(q("accessDenied"));let s=await o.createClinicRequestBatch(l);return n.current===o?s:B(q("accessDenied"))}}),[o,t])}i(mi,"useEverfurRecordsClinicBatch");var gi=class gi 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(gi,"HostRenderBoundary");var yi=gi;function Ap({render:e}){return e()}i(Ap,"RenderHost");function fi({render:e,fallback:t,resetKey:r}){return react.createElement(yi,{fallback:t,resetKey:r,children:react.createElement(Ap,{render:e})})}i(fi,"HostRender");var Op=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 Lp(e){return Op[e]}i(Lp,"requires");function rl(e,t,r){let o=Lp(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 bi({name:e,enabled:false,isPending:true,limits:{}});let l=Vp(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?bi({name:e,enabled:true,isPending:false,limits:l}):bi({name:e,enabled:false,isPending:false,limits:l,disabled:qp(o,n)})}i(rl,"decideCapability");function Vp(e,t){let r={};for(let o of e){let n=t.get(o)?.limits;if(n)for(let[l,s]of Object.entries(n)){let c=r[l];r[l]=c===void 0?s:Math.min(c,s);}}return r}i(Vp,"mergeLimits");function qp(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:Fo("accessDenied"),level:"user_entitlement",recoverable:false})}i(qp,"disabledFor");function bi(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(bi,"freezeDecision");function hi(e){let{runtime:t}=ke(),r=t.entitlements,o=react.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return react.useMemo(()=>rl(e,o.decisions,{isPending:o.isPending}),[e,o])}i(hi,"useCapability");var Np=48;function Mp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Mp,"selectView");function Ne(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:l}=e,s=hi(t),c=react.useMemo(()=>Mp(s),[s]);switch(c){case "enabled":return r;case "pending":return n?jsxRuntime.jsx(fi,{render:n,fallback:jsxRuntime.jsx(ol,{capability:t,style:l})}):jsxRuntime.jsx(ol,{capability:t,style:l});case "disabled":return o?jsxRuntime.jsx(fi,{render:()=>o(s),fallback:jsxRuntime.jsx(il,{decision:s,style:l}),resetKey:s}):jsxRuntime.jsx(il,{decision:s,style:l});default:return pr(c)}}i(Ne,"CapabilityGate");function ol({capability:e,style:t}){let r=L(),o=react.useMemo(()=>al(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(ol,"PendingSkeleton");function il({decision:e,style:t}){let r=L(),o=react.useMemo(()=>al(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(m,{style:o.offstateText,children:n}):null})}i(il,"OffState");function al(e){let{color:t,space:r,radius:o,type:n}=e;return reactNative.StyleSheet.create({offstate:{minHeight:Np,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:o.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{..._(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(al,"makeStyles");var ln=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function Me(e){let t=L(),r=react.useMemo(()=>Up(t),[t]);return jsxRuntime.jsxs(reactNative.View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${ln.title}. ${ln.body}`,children:[jsxRuntime.jsx(m,{style:r.title,children:ln.title}),jsxRuntime.jsx(m,{style:r.body,children:ln.body})]})}i(Me,"ClinicalDisclaimer");function Up(e){let{color:t,space:r,type:o}=e;return reactNative.StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:reactNative.StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{..._(e,"bold"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{..._(e,"regular"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.muted}})}i(Up,"makeStyles");function Je(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(Je,"slotBox");function ot(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(ot,"slotText");var cl=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"})}),xi=60;function dl(e){return `Try again in ${e}s`}i(dl,"coolingActionLabel");var ul="Try again, available shortly";function Qe({variant:e,onAction:t,message:r,testID:o}){let n=Yp(),l=cl[e],[s,c]=react.useState(e==="rate_limited"?xi:0);react.useEffect(()=>{e==="rate_limited"&&c(xi);},[e]),react.useEffect(()=>{if(s<=0)return;let u=setTimeout(()=>c(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[s]);let a=e==="rate_limited"&&s>0,d=a?dl(s):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(m,{style:n.title,children:l.title}),jsxRuntime.jsx(m,{style:n.body,children:r??l.body}),d!==null&&t?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,disabled:a,accessibilityRole:"button",accessibilityLabel:a?ul:d,accessibilityState:{disabled:a},style:[n.action,a?n.actionDisabled:null],testID:o?`${o}-action`:`records-empty-${e}-action`,children:jsxRuntime.jsx(m,{style:n.actionLabel,children:d})}):null]})}i(Qe,"RecordsEmptyState");function Yp(){let e=L();return react.useMemo(()=>Kp(e),[e])}i(Yp,"useStyles");function Kp(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=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:s,height:s,borderRadius:s/2,backgroundColor:t.brandSoft,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug)-1,color:t.brandInk,textAlign:"center"},body:{..._(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",...Je(l.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug)-1,...ot(l.primaryButton)}})}i(Kp,"makeStyles");var Ze="Back";function et({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let l=dn();return jsxRuntime.jsxs(reactNative.View,{style:l.row,testID:o,children:[t?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Ze,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}),jsxRuntime.jsx(m,{style:n==="document"?l.documentTitle:l.title,accessibilityRole:"header",numberOfLines:1,children:e}),jsxRuntime.jsx(reactNative.View,{style:l.right,children:r??jsxRuntime.jsx(reactNative.View,{style:l.back})})]})}i(et,"ScreenHeader");function fl(){let e=dn();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(fl,"ListGlyph");function gl(){let e=dn();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(gl,"ShareGlyph");function bl(){let e=dn();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(bl,"SendGlyph");function hl(){let e=dn();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(hl,"DownloadGlyph");function dn(){let e=L();return react.useMemo(()=>em(e),[e])}i(dn,"useStyles");function em(e){let{color:t,space:r,type:o}=e,n=r.xxl+r.md,l=r.md,s=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:s,borderBottomWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginLeft:r.xs},title:{flex:1,..._(e,"bold"),fontSize:o.size.heading,lineHeight:Math.round(o.size.heading*o.lineHeight.tight)+1,color:t.brandInk},documentTitle:{flex:1,textAlign:"center",..._(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:s,borderRadius:s,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:s,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:s,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:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],borderRadius:s},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:s,backgroundColor:t.brandInk},downloadGlyph:{width:c-r.xs,height:c-r.xs,alignItems:"center"},downloadStem:{width:s,height:r.sm+r.xs/2,backgroundColor:t.brandInk},downloadHead:{width:r.sm,height:r.sm,borderRightWidth:s,borderBottomWidth:s,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:s,borderRightWidth:s,borderBottomWidth:s,borderColor:t.brandInk}})}i(em,"makeStyles");var nm=120,om=44;function im({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:l,radius:s,type:c}=L();return jsxRuntime.jsxs(reactNative.View,{testID:"records-gate-off",style:[{minHeight:nm,justifyContent:"center",gap:l.md,padding:l.lg,borderRadius:s.md,borderWidth:1,borderColor:n.brandBorder,backgroundColor:n.surfaceCream},o],children:[e.length>0?jsxRuntime.jsx(m,{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:om,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:l.lg,borderRadius:s.pill,borderWidth:1.5,borderColor:n.brand},children:jsxRuntime.jsx(m,{style:{fontSize:c.size.body,color:n.brand},children:r})})]})}i(im,"RecordsGateOffState");function Be(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsxRuntime.jsx(im,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i(Be,"recordsGateExit");var sm="your pet";function He(e){let t=e?.trim()??"";return t.length>0?t:sm}i(He,"petNameOr");var dt=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${He(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")}),Mt=Object.freeze({title:"Marker Summary",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")}),wi=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")}),or=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",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")}),Ct=Object.freeze({title:"Where this reading came 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"}),Mr=Object.freeze({title:i(e=>`${He(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${He(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 ${He(e)}.`,"a11y"),openA11y:i((e,t)=>`Open ${He(e)}\u2019s records request. ${t}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),_r=Object.freeze({title:i(e=>`Add ${He(e)}\u2019s records`,"title"),body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicA11y:i(e=>`Request ${He(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${He(e)}\u2019s records`,"uploadDocumentA11y")});var to="rgba(0,0,0,0.4)";function be(){let e=L();return react.useMemo(()=>um(e),[e])}i(be,"useScreenStyles");function hr({disclaimer:e,style:t}){let r=be();return e.trim().length===0?null:jsxRuntime.jsxs(reactNative.View,{style:[r.band,t],accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e),testID:"records-disclaimer-band",children:[jsxRuntime.jsx(reactNative.View,{style:r.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(m,{style:r.infoGlyphText,children:"i"})}),jsxRuntime.jsx(m,{style:r.bandText,children:e})]})}i(hr,"DisclaimerBand");function re({label:e,onPress:t,kind:r="primary",disabled:o=false,busy:n=false,accessibilityLabel:l,testID:s,style:c}){let a=be(),d=L(),u=r==="primary"?a.pillPrimary:r==="outline"?a.pillOutline:r==="danger"?a.pillDanger:r==="ask"?a.pillAsk:a.pillLink,p=r==="primary"?a.pillPrimaryLabel:r==="danger"?a.pillDangerLabel:r==="ask"?a.pillAskLabel:r==="link"?a.pillLinkLabel:a.pillOutlineLabel;return jsxRuntime.jsxs(reactNative.Pressable,{onPress:t,disabled:o||n,accessibilityRole:"button",accessibilityLabel:l??e,accessibilityState:{disabled:o||n,busy:n},style:[a.pill,u,o?a.pillDisabled:null,c],testID:s,children:[n?jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:r==="primary"?d.color.onPrimary:d.color.brandInk}):null,jsxRuntime.jsx(m,{style:p,children:e})]})}i(re,"Pill");function Kt({label:e,tone:t="neutral",testID:r}){let o=be(),{bg:n,fg:l}=o.chipTones[t];return jsxRuntime.jsx(reactNative.View,{style:[o.chip,n],testID:r,children:jsxRuntime.jsx(m,{style:[o.chipText,l],children:e})})}i(Kt,"Chip");function Bt({title:e,count:t}){let r=be();return jsxRuntime.jsxs(reactNative.View,{style:r.sectionHeader,children:[jsxRuntime.jsx(m,{style:r.sectionTitle,accessibilityRole:"header",children:e}),t!==void 0?jsxRuntime.jsx(m,{style:r.sectionCount,children:t}):null]})}i(Bt,"SectionHeader");function Pr({direction:e="right"}){let t=be(),r=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsxRuntime.jsx(reactNative.View,{style:[t.chevron,{transform:[{rotate:r}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Pr,"Chevron");function um(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((v,y)=>Math.round(v*y),"lh"),d=reactNative.StyleSheet.hairlineWidth,u=r.xxl+r.md,p=i((v,y,g,b="regular")=>({..._(e,b),fontSize:v,lineHeight:a(v,y),color:g}),"text"),f=ot(l.recordCard),h=e.brightness==="dark"?t.errorRed:t.danger,R=i((v,y)=>({bg:{backgroundColor:v},fg:{color:y}}),"tone");return {chipTones:{neutral:R(t.badgeBgNeutral,t.text.secondary),info:R(t.brandSoft,t.brandInk),warning:R(t.badgeBgCaution,t.warningStrong),critical:R(t.badgeBgCritical,t.danger),positive:R(t.badgeBgPositive,t.success)},...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:{...p(s.body+1,c.snug,t.text.primary,"bold")},sectionCount:{...p(s.bodyTight,c.snug,t.text.muted,"medium")},card:{borderRadius:o.lg-r.xs,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.xs,...Je(l.recordCard,d)},creamCard:{borderRadius:o.lg-r.xs/2,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md,...Je(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:{...p(s.body,c.snug,t.text.primary,"medium"),...f},rowDetail:{...p(s.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...f},rowValue:{...p(s.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...f},rowMuted:{...p(s.caption,c.normal,t.text.muted),...f},chip:{borderRadius:o.pill,paddingHorizontal:r.sm,paddingVertical:r.xs-1,alignSelf:"flex-start"},chipText:{...p(s.tiny,c.snug,t.text.primary,"medium")},pill:{minHeight:u,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm},pillPrimary:{backgroundColor:t.brand,...Je(l.primaryButton)},pillPrimaryLabel:{...p(s.body,c.snug,t.onPrimary,"bold"),...ot(l.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...p(s.body,c.snug,t.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:t.danger,backgroundColor:t.surface},pillDangerLabel:{...p(s.bodyTight,c.snug,t.danger,"bold")},pillAsk:{borderWidth:d,borderColor:t.borderRingCream,backgroundColor:t.surface},pillAskLabel:{...p(s.body,c.snug,t.text.primary,"bold")},pillLink:{backgroundColor:"transparent",paddingHorizontal:r.sm},pillLinkLabel:{...p(s.body,c.snug,t.linkInk,"bold")},pillDisabled:{opacity:.5},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,...p(s.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,...p(s.bodyTight,c.normal,t.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2},statusText:p(s.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,...p(s.bodyTight,c.normal,h)},band:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft},bandText:{flex:1,...p(s.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:{...p(s.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,...p(s.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,..._(e,"regular"),fontSize:s.body},fieldLabel:{...p(s.bodyTight,c.normal,t.text.secondary,"medium")},muted:p(s.caption,c.normal,t.text.muted),bodyText:p(s.body,c.normal,t.text.primary)})}}i(um,"makeScreenStyles");function Br(e,t){return e===null?"":t?`${e} ${t}`:e}i(Br,"formatEntityValue");var vl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Q(e){if(!e)return "-";let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t!==null){let n=vl[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 `${vl[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(Q,"formatRecordsDate");var fe=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 Qt(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(Qt,"markerStatusLabel");function Hr(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(Hr,"trajectoryLabel");function ir(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(ir,"humanize");var xl=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 Ir(e){return Object.prototype.hasOwnProperty.call(xl,e)?xl[e]:ir(e)}i(Ir,"bodySystemLabel");var wl=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 Ur(e){return Object.prototype.hasOwnProperty.call(wl,e)?wl[e]:ir(e)}i(Ur,"soapSectionLabel");function Cl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(Cl,"formatWeightKg");function Et(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(Et,"formatMarkerReading");function Ei(e,t,r){let o=Hr(t,r);return e?`${fe.measured(Q(e))}${o?` \xB7 ${o}`:""}`:o}i(Ei,"labDetailLine");var de=Object.freeze({openA11y:"Share medical record",title:"Share medical record",helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",createLink:"Create link and share",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.",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.",copied:"Link copied.",copyFailed:"Could not copy the link.",turnedOff:"Link turned off."})});function pm(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(pm,"isShareExpired");function mm(e,t){let r=Q(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(mm,"formatShareExpiry");function El(e,t,r){let o=e.map(n=>{let l=pm(n.expiresAt,r),s=mm(n.expiresAt,l),c=Q(n.createdAt),a=l?"Expired":"Active",d=s.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:a,expiryLabel:s,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${a}. ${s}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(El,"buildShareRows");function ro(e,t){let r=e?.httpStatus;if(tr(e)){if(t==="create")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.";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.";default:return "Could not download the record PDF. Please try again."}}i(ro,"shareErrorMessage");function ve({width:e,height:t,radius:r,style:o}){let{color:n,radius:l}=L();return jsxRuntime.jsx(reactNative.View,{style:[{width:e,height:t,borderRadius:r??l.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(ve,"SkeletonBlock");var Si=180,kl=70,no=22,fm=300,Tl=44,oo=24,ki=34,gm=6,bm=5;function io({testID:e}){let t=mn(),r=i(o=>jsxRuntime.jsxs(reactNative.View,{style:t.actionRow,children:[jsxRuntime.jsxs(reactNative.View,{style:t.actionLeft,children:[jsxRuntime.jsx(ve,{width:18,height:18,radius:9}),jsxRuntime.jsx(ve,{width:"55%",height:14,radius:7})]}),jsxRuntime.jsx(ve,{width:18,height:18,radius:9})]},o),"action");return jsxRuntime.jsxs(reactNative.View,{style:t.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:e,children:[jsxRuntime.jsx(reactNative.View,{style:t.inset,children:jsxRuntime.jsxs(reactNative.View,{style:t.summaryCard,children:[jsxRuntime.jsx(ve,{width:Si,height:Si,radius:Si/2}),jsxRuntime.jsxs(reactNative.View,{style:t.badges,children:[jsxRuntime.jsx(ve,{width:kl,height:no,radius:no/2}),jsxRuntime.jsx(ve,{width:kl,height:no,radius:no/2})]})]})}),jsxRuntime.jsx(ve,{width:150,height:16,radius:8,style:t.inset}),jsxRuntime.jsx(reactNative.View,{style:t.carouselCard,children:jsxRuntime.jsx(ve,{width:"100%",height:fm,radius:14})}),jsxRuntime.jsxs(reactNative.View,{style:t.dots,children:[jsxRuntime.jsx(ve,{width:6,height:6,radius:3}),jsxRuntime.jsx(ve,{width:18,height:6,radius:3}),jsxRuntime.jsx(ve,{width:6,height:6,radius:3})]}),jsxRuntime.jsx(ve,{width:46,height:12,radius:6,style:t.centered}),jsxRuntime.jsx(reactNative.View,{style:t.inset,children:jsxRuntime.jsx(ve,{width:"100%",height:Tl,radius:12})}),jsxRuntime.jsxs(reactNative.View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(io,"DashboardSkeleton");function _l({testID:e}){let t=mn();return jsxRuntime.jsxs(reactNative.View,{style:t.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ge.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(ve,{width:oo,height:oo,radius:oo/2}),r<3?jsxRuntime.jsx(ve,{width:2,height:20,radius:1,style:t.connector}):null]}),jsxRuntime.jsxs(reactNative.View,{style:t.railBody,children:[jsxRuntime.jsx(ve,{width:"55%",height:14,radius:7}),jsxRuntime.jsx(ve,{width:"75%",height:11,radius:6})]})]},r))}),jsxRuntime.jsxs(reactNative.View,{style:t.statusCard,children:[jsxRuntime.jsx(ve,{width:"90%",height:13,radius:6}),jsxRuntime.jsx(ve,{width:"60%",height:13,radius:6})]}),jsxRuntime.jsx(ve,{width:"100%",height:50,radius:25})]})}i(_l,"RequestSkeleton");function Pl({testID:e}){let t=mn();return jsxRuntime.jsxs(reactNative.View,{style:t.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:fe.loadingTimeline,testID:e,children:[jsxRuntime.jsx(reactNative.View,{style:t.timelineDisclaimer,children:jsxRuntime.jsx(ve,{width:"100%",height:Tl,radius:12})}),Array.from({length:gm},(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(ve,{width:ki,height:ki,radius:ki/2}),jsxRuntime.jsxs(reactNative.View,{style:t.timelineBody,children:[jsxRuntime.jsxs(reactNative.View,{style:t.timelineTop,children:[jsxRuntime.jsx(ve,{width:44,height:10,radius:5}),jsxRuntime.jsx(ve,{width:56,height:12,radius:6})]}),jsxRuntime.jsx(ve,{width:"70%",height:14,radius:7}),o%2===0?jsxRuntime.jsx(ve,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Pl,"TimelineSkeleton");function Il({testID:e}){let t=mn();return jsxRuntime.jsx(reactNative.View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:xe.loading,testID:e,children:Array.from({length:bm},(r,o)=>jsxRuntime.jsxs(reactNative.View,{style:t.clinicRow,children:[jsxRuntime.jsx(ve,{width:"65%",height:14,radius:7}),jsxRuntime.jsx(ve,{width:"40%",height:11,radius:6})]},o))})}i(Il,"ClinicsSkeleton");function Dl({testID:e}){let t=mn();return jsxRuntime.jsx(reactNative.View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:de.loadingLinks,testID:e,children:[0,1].map(r=>jsxRuntime.jsxs(reactNative.View,{style:t.shareRow,children:[jsxRuntime.jsx(ve,{width:"55%",height:13}),jsxRuntime.jsx(ve,{width:"40%",height:11})]},r))})}i(Dl,"SharesSkeleton");var Ti=62;function mn(){let e=L();return react.useMemo(()=>hm(e),[e])}i(mn,"useStyles");function hm(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:oo},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:Ti},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(hm,"makeStyles");var Em=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function _i(e){let{userRef:t,scopeEpoch:r}=ke();return jsxRuntime.jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsxRuntime.jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsxRuntime.jsx(Sm,{...Fe(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i(_i,"EverfurClinicPicker");function Sm({petRef:e,controller:t,recordsController:r,location:o,onNavigate:n,onBack:l,style:s}){let c=be(),a=Tm(),d=L(),u=Nt(),p=Hs(t??u,o),f=yt(r?{petRef:e,controller:r}:{petRef:e}),h=react.useRef(rr()),[R,v]=react.useState(false),[y,g]=react.useState(null),[b,w]=react.useState(false),[x,E]=react.useState(""),[D,k]=react.useState(false),[S,I]=react.useState(""),[Y,z]=react.useState(false),$=react.useCallback(A=>{n?.({name:"consent",clinic:pi(A,null,"",h.current())});},[n]),G=i(()=>{R||(v(true),g(null),f.createRequest(`records-upload-${Date.now().toString(36)}`).then(A=>{if(v(false),!A.ok){g(ge.errors.start);return}n?.({name:"request",requestId:A.value.id});}));},"startUpload"),Z=D?x:p.query,oe=Em.test(S.trim()),Ee=Z.trim().length>0&&oe,H=i(A=>{let{layoutMeasurement:M,contentOffset:K,contentSize:ye}=A.nativeEvent;M.height+K.y>=ye.height-M.height*.6&&p.loadMore();},"onEndReached"),C=p.isSearchActive?p.clinics:p.recent,T=p.isSearchActive?p.error?wt(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle";return jsxRuntime.jsxs(reactNative.View,{style:[c.root,s],children:[jsxRuntime.jsx(et,{title:xe.title,onBack:l,testID:"records-clinic-header"}),jsxRuntime.jsxs(reactNative.View,{style:a.searchBar,children:[jsxRuntime.jsx(reactNative.View,{style:a.searchGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(qe,{value:p.query,onChangeText:p.setQuery,placeholder:xe.placeholder,placeholderTextColor:d.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:xe.searchA11y,style:a.searchInput,testID:"records-clinic-search-input"}),p.query.length>0?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>p.setQuery(""),accessibilityRole:"button",accessibilityLabel:xe.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:jsxRuntime.jsx(m,{style:a.clearGlyph,children:"\xD7"})}):null]}),n?jsxRuntime.jsxs(reactNative.View,{style:a.uploadWrap,children:[y?jsxRuntime.jsx(reactNative.View,{style:c.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(m,{style:c.errorText,children:y})}):null,jsxRuntime.jsx(re,{label:R?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",accessibilityLabel:xe.uploadOwnA11y,busy:R,onPress:G,testID:"records-clinic-upload-own"})]}):null,jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:a.list,keyboardShouldPersistTaps:"handled",onScroll:p.isSearchActive?H:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[p.isSearchActive?jsxRuntime.jsxs(reactNative.View,{style:a.fallbackCard,testID:"records-clinic-fallback-card",children:[jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>w(A=>!A),accessibilityRole:"button",accessibilityLabel:b?xe.fallback.collapseA11y:xe.fallback.expandA11y,style:a.fallbackHeader,testID:"records-clinic-fallback",children:[jsxRuntime.jsxs(reactNative.View,{style:a.fallbackCopy,children:[jsxRuntime.jsx(m,{style:a.fallbackTitle,numberOfLines:1,children:xe.fallback.title}),jsxRuntime.jsx(m,{style:a.fallbackSubtitle,numberOfLines:2,children:xe.fallback.subtitle})]}),jsxRuntime.jsx(Pr,{direction:b?"up":"down"})]}),b?jsxRuntime.jsxs(reactNative.View,{style:a.fallbackForm,children:[jsxRuntime.jsx(m,{style:c.fieldLabel,children:xe.fallback.nameLabel}),jsxRuntime.jsx(qe,{accessibilityLabel:xe.fallback.nameLabel,style:c.field,value:Z,onChangeText:A=>{E(A),k(true);},placeholder:xe.fallback.namePlaceholder,placeholderTextColor:d.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),jsxRuntime.jsx(m,{style:c.fieldLabel,children:xe.fallback.emailLabel}),jsxRuntime.jsx(qe,{accessibilityLabel:xe.fallback.emailLabel,style:c.field,value:S,onChangeText:A=>{I(A),z(false);},onBlur:()=>z(true),placeholder:xe.fallback.emailPlaceholder,placeholderTextColor:d.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),Y&&S.trim().length>0&&!oe?jsxRuntime.jsx(m,{style:c.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsxRuntime.jsx(m,{style:c.muted,children:xe.fallback.reviewNote}),jsxRuntime.jsx(re,{label:xe.fallback.submit,accessibilityLabel:xe.fallback.submitA11y,disabled:!Ee||!n,onPress:()=>n?.({name:"consent",clinic:pi(null,Z.trim(),S.trim().toLowerCase(),h.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsxRuntime.jsx(m,{style:a.sectionLabel,accessibilityRole:"header",testID:"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsxRuntime.jsx(Il,{testID:"records-clinic-page-loading"}):null,C.map(A=>jsxRuntime.jsx(km,{clinic:A,onSelect:$,styles:a},A.id)),T&&!p.initialLoading?jsxRuntime.jsx(Qe,{variant:T,message:p.isSearchActive&&T==="idle"?xe.noMatch(p.debouncedQuery):p.error?.displayMessage,onAction:p.error?.retryable===true?p.retry:void 0,testID:"records-clinic-empty"}):null,jsxRuntime.jsxs(reactNative.View,{style:a.footer,children:[p.loadingMore?jsxRuntime.jsxs(reactNative.View,{style:a.footerLoading,testID:"records-clinic-loading-more",children:[jsxRuntime.jsx(reactNative.ActivityIndicator,{color:d.color.brandInk,size:"small"}),jsxRuntime.jsx(m,{style:c.muted,children:xe.loadingMore})]}):null,p.pageError?jsxRuntime.jsx(reactNative.Pressable,{onPress:p.loadMore,accessibilityRole:"button",accessibilityLabel:xe.loadMoreRetryA11y,style:a.footerRetry,testID:"records-clinic-page-error-retry",children:jsxRuntime.jsx(m,{style:a.footerRetryLabel,children:xe.loadMoreFailed})}):null]})]}),jsxRuntime.jsx(Me,{})]})}i(Sm,"PickerBody");function km({clinic:e,onSelect:t,styles:r}){let o=As(e.emailStatus),n=Os(e.distanceKm),l=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?Ls(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(m,{style:r.itemName,numberOfLines:1,children:e.name}),n?jsxRuntime.jsx(m,{style:r.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:n}):null]}),e.address?jsxRuntime.jsx(m,{style:r.itemAddress,numberOfLines:2,children:e.address}):null,e.phone?jsxRuntime.jsx(m,{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(m,{style:[r.badgeLabel,o.tone==="positive"?r.badgePositiveText:o.tone==="caution"?r.badgeCautionText:r.badgeNeutralText],children:o.label})})]})}i(km,"ClinicRow");function Tm(){let e=L();return react.useMemo(()=>_m(e),[e])}i(Tm,"useLocalStyles");function _m(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return reactNative.StyleSheet.create({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,...s(n.size.body,n.lineHeight.snug,t.text.primary),paddingVertical:0},clearGlyph:s(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:{...s(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:{...s(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},fallbackSubtitle:s(n.size.caption,n.lineHeight.normal,t.text.muted),fallbackForm:{gap:r.sm},item:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,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,...s(n.size.body,n.lineHeight.snug,t.brandInk,"bold")},itemDistance:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},itemAddress:s(n.size.caption,n.lineHeight.normal,t.text.primary),itemPhone:s(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:{...s(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:{...s(n.size.bodyTight,n.lineHeight.snug,t.brandInk,"bold")}})}i(_m,"makeLocalStyles");var Oe=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Nr} 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")});function yn(e,t,r,o){let n={owner_name:t,pet_name:r,clinic_name:o},l=false,s=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,a)=>Object.prototype.hasOwnProperty.call(n,a)?n[a]??"":(l=true,""));return l||/[{}]/.test(s)?null:s}i(yn,"renderClinicScope");function fn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(fn,"clinicNeedsEmail");function Ol(e,t,r){let[o,n]=react.useState(e.ownerName),[l,s]=react.useState(""),[c,a]=react.useState(null),[d,u]=react.useState(""),[p,f]=react.useState([]),[h,R]=react.useState([]),[v,y]=react.useState(null),[g,b]=react.useState(null),[w,x]=react.useState(false),[E,D]=react.useState(false),[k,S]=react.useState(null),[I,Y]=react.useState(0),z=react.useRef(false),$=react.useRef(false),G=react.useRef(0),Z=react.useRef(rr()),oe=react.useRef(null),Ee=react.useRef(null),H=react.useRef(0);react.useEffect(()=>(z.current=true,$.current=false,x(false),()=>{z.current=false,H.current+=1,G.current+=1,oe.current=null,Ee.current?.abort();}),[t]),react.useEffect(()=>{let ie=true;return y(null),oe.current=null,t.getAuthorizationCopy().then(we=>{ie&&(we.ok?(y(we.value),b(null)):b(we.error));}).catch(()=>{ie&&b(q("internalError"));}),()=>{ie=false;}},[t,I]),react.useEffect(()=>{let ie=true;return R([]),t.recentClinics({limit:5}).then(we=>{ie&&we.ok&&R(we.value.clinics);}).catch(()=>{}),()=>{ie=false;}},[t]);let C=i(()=>{oe.current=null,b(null);},"invalidate"),T=c?.name??l.trim(),A=v?yn(v,o.trim(),e.petName,T):null,M=fn(c),K=!!(v&&A&&o.trim()&&e.petName.trim()&&T&&(!M||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),ye=i(async()=>{if($.current)return;let ie=++G.current;D(true);try{let we=await t.searchClinics({query:l.trim(),limit:100});if(!z.current||ie!==G.current)return;we.ok?(f(we.value.clinics),b(null)):b(we.error);}catch{z.current&&ie===G.current&&b(q("internalError"));}finally{z.current&&ie===G.current&&D(false);}},"search"),Ve=i(async()=>{if($.current||k||!K||!v||!A||!r)return;$.current=true;let ie=H.current,we=i(()=>z.current&&H.current===ie,"current");x(true),b(null);try{if(!oe.current){Ee.current=new AbortController;let Xe=await r({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:T,authorizationVersion:v.authorizationVersion,scopeText:A,signal:Ee.current.signal});if(!we()||Xe===null)return;let Vt=c&&(!M||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:T};oe.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:v.authorizationVersion,...Vt,...M?{clinicEmail:d.trim().toLowerCase()}:{},...Xe.signatureId!==void 0?{signatureId:Xe.signatureId}:{signaturePngBase64:Xe.signaturePngBase64},idempotencyKey:Z.current()};}if(!we())return;let vt=await t.createClinicRequest(oe.current);if(!we())return;if(!vt.ok){b(vt.error);return}if(vt.value.petRef!==e.petRef){b(q("internalError"));return}S(vt.value),oe.current=null,e.onCreated?.(vt.value);}catch{we()&&b(q("internalError"));}finally{$.current=false,we()&&x(false);}},"submit");return {ownerName:o,query:l,clinic:c,email:d,clinics:p,copy:v,scope:A,error:g,busy:w,searching:E,created:k,ready:K,needsEmail:M,recent:p.length===0&&c===null?h:[],setOwnerName(ie){$.current||(C(),n(ie));},setQuery(ie){$.current||(C(),G.current+=1,D(false),f([]),a(null),u(""),s(ie));},setEmail(ie){$.current||(C(),u(ie));},selectClinic(ie){$.current||(C(),G.current+=1,D(false),f([]),a(ie),s(ie.name),u(""));},invalidate:C,search:ye,submit:Ve,retryCopy(){b(null),Y(ie=>ie+1);}}}i(Ol,"useClinicRequestForm");var Pm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function bn(e){return e.clinic?.name??e.freeText??""}i(bn,"draftName");function gn(e){return fn(e.clinic)}i(gn,"draftNeedsEmail");function Ll(e,t,r,o,n){let[l,s]=react.useState(e.ownerName),[c,a]=react.useState(""),[d,u]=react.useState([]),[p,f]=react.useState([]),[h,R]=react.useState([]),[v,y]=react.useState(null),[g,b]=react.useState(null),[w,x]=react.useState(false),[E,D]=react.useState(false),[k,S]=react.useState(null),[I,Y]=react.useState(null),[z,$]=react.useState(0),G=react.useRef(false),Z=react.useRef(false),oe=react.useRef(0),Ee=react.useRef(0),H=react.useRef(rr()),C=react.useRef(null),T=react.useRef(null);react.useEffect(()=>(G.current=true,Z.current=false,x(false),()=>{G.current=false,Ee.current+=1,oe.current+=1,C.current=null,T.current?.abort();}),[t,r]),react.useEffect(()=>{let F=true;return y(null),C.current=null,t.getAuthorizationCopy().then(Re=>{F&&(Re.ok?(y(Re.value),b(null)):b(Re.error));}).catch(()=>{F&&b(q("internalError"));}),()=>{F=false;}},[t,z]),react.useEffect(()=>{let F=true;return f([]),t.recentClinics({limit:5}).then(Re=>{F&&Re.ok&&f(Re.value.clinics);}).catch(()=>{}),()=>{F=false;}},[t]);let A=i(()=>{C.current=null,b(null);},"invalidate"),M=h.map(bn),K=v?M.map(F=>yn(v,l.trim(),e.petName,F)):[],ye=K.every(F=>F!==null)?K.join(`
2
2
 
3
- var react = require('react');
4
- var zod = require('zod');
5
- require('react-native-safe-area-context');
6
- var reactNative = require('react-native');
7
- var jsxRuntime = require('react/jsx-runtime');
8
-
9
- // src/rn/records/useRecords.ts
10
- var CONTRACT_RETRYABILITY = Object.freeze([
11
- Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
12
- Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
13
- Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
14
- Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
15
- Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
16
- Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
17
- Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
18
- Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
19
- Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
20
- Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
21
- Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
22
- Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
23
- Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
24
- Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
25
- Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
26
- Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
27
- Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
28
- Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
29
- Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
30
- Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
31
- Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
32
- Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
33
- ]);
34
- Object.freeze(
35
- CONTRACT_RETRYABILITY.map((row) => row.wireCode)
36
- );
37
-
38
- // src/client/errors/contract.ts
39
- var NORMALIZED_FOLD = Object.freeze({
40
- // the default status-mapped envelope
41
- ValidationException: "validationFailed",
42
- AuthorizationException: "authRejected",
43
- PaymentRequiredException: "paymentRequired",
44
- AccessDeniedException: "accessDenied",
45
- ResourceNotFoundException: "resourceNotFound",
46
- ConflictException: "conflict",
47
- ThrottlingException: "rateLimited",
48
- InternalFailureException: "internalError",
49
- NotImplementedException: "notImplemented",
50
- ServiceUnavailableException: "serviceUnavailable",
51
- // dict-detail codes on the widget surface
52
- authExpired: "authExpired",
53
- unavailable: "serviceUnavailable",
54
- session_required: "sessionRequired",
55
- accessDenied: "accessDenied",
56
- invalidRequest: "sdkUpdateRequired",
57
- // typed codes
58
- IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
59
- IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
60
- DAILY_QUOTA_EXCEEDED: "quotaExceeded",
61
- TIER_UPGRADE_REQUIRED: "paymentRequired",
62
- // SSE error frames
63
- not_found: "conversationNotFound",
64
- timeout: "streamTimeout",
65
- internal_error: "internalError"
66
- });
67
- var CONTRACT_ERROR_ROWS = Object.freeze(
68
- CONTRACT_RETRYABILITY.map(
69
- (generated) => Object.freeze({
70
- wireCode: generated.wireCode,
71
- envelope: generated.envelope,
72
- retryable: generated.retryable,
73
- normalized: NORMALIZED_FOLD[generated.wireCode]
74
- })
75
- )
76
- );
77
- var BY_UPPER = new Map(
78
- CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
79
- );
80
- function contractErrorFor(wireCode) {
81
- if (typeof wireCode !== "string") return void 0;
82
- const key = wireCode.trim().toUpperCase();
83
- return key.length > 0 ? BY_UPPER.get(key) : void 0;
84
- }
85
- var CATEGORY_OF = Object.freeze({
86
- // the caller's sign-in state is wrong and a credential change is the remedy
87
- authExpired: "authentication",
88
- authRejected: "authentication",
89
- sessionRequired: "authentication",
90
- // signed in, correctly identified, and still not allowed
91
- accessDenied: "authorization",
92
- // a plan gate, not a permission failure: the remedy is commercial
93
- paymentRequired: "entitlement",
94
- // slow down / come back later
95
- quotaExceeded: "rateLimit",
96
- rateLimited: "rateLimit",
97
- // the request itself was wrong; retrying it unchanged can never succeed
98
- validationFailed: "invalidRequest",
99
- sdkUpdateRequired: "invalidRequest",
100
- // the target is gone, hidden, or was never visible to this caller
101
- conversationNotFound: "notFound",
102
- petNotFound: "notFound",
103
- resourceNotFound: "notFound",
104
- // something else already holds the thing
105
- conflict: "conflict",
106
- idempotencyConflict: "conflict",
107
- idempotencyInFlight: "conflict",
108
- // the pipe, not the request: timeouts, drops, a briefly unreachable dependency
109
- streamTimeout: "connection",
110
- streamIncomplete: "connection",
111
- upstreamLlmTimeout: "connection",
112
- serviceUnavailable: "connection",
113
- // the server admits fault
114
- internalError: "server",
115
- notImplemented: "server",
116
- mediaUploadFailed: "media",
117
- moderationBlocked: "policy",
118
- unknown: "unknown"
119
- });
120
- function categoryFor(code) {
121
- return CATEGORY_OF[code];
122
- }
123
- function fromWire(wire) {
124
- const contractRow = contractErrorFor(wire);
125
- if (contractRow) return contractRow.normalized;
126
- const upper = (wire ?? "").trim().toUpperCase();
127
- const canonical = upper.replace(/[^A-Z0-9]/g, "");
128
- if (canonical === "AUTHREJECTED") return "authRejected";
129
- if (upper.startsWith("AUTH")) return "authExpired";
130
- switch (canonical) {
131
- case "DAILYQUOTAEXCEEDED":
132
- case "QUOTAEXCEEDED":
133
- return "quotaExceeded";
134
- case "RATELIMITED":
135
- case "TOOMANYREQUESTS":
136
- return "rateLimited";
137
- case "IDEMPOTENCYKEYCONFLICT":
138
- case "IDEMPOTENCYCONFLICT":
139
- return "idempotencyConflict";
140
- case "ACCESSDENIED":
141
- case "FORBIDDEN":
142
- return "accessDenied";
143
- case "NOTFOUND":
144
- case "CONVERSATIONNOTFOUND":
145
- return "conversationNotFound";
146
- case "PETNOTFOUND":
147
- return "petNotFound";
148
- case "TIMEOUT":
149
- case "STREAMTIMEOUT":
150
- return "streamTimeout";
151
- // Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
152
- // fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
153
- // (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
154
- case "MEDIAUPLOADFAILED":
155
- case "UNRECOGNIZEDVIDEOFORMAT":
156
- case "FILETOOSMALL":
157
- return "mediaUploadFailed";
158
- case "MODERATIONBLOCKED":
159
- return "moderationBlocked";
160
- case "UPSTREAMLLMTIMEOUT":
161
- return "upstreamLlmTimeout";
162
- case "INTERNALERROR":
163
- case "INTERNALSERVERERROR":
164
- return "internalError";
165
- case "STREAMINCOMPLETE":
166
- case "CHATSTREAMINCOMPLETE":
167
- return "streamIncomplete";
168
- // Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
169
- // (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
170
- case "INVALIDANALYSISTYPE":
171
- case "INVALIDUPLOADPURPOSE":
172
- return "unknown";
173
- default:
174
- return "unknown";
175
- }
176
- }
177
- var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
178
- "streamTimeout",
179
- "rateLimited",
180
- "internalError",
181
- "upstreamLlmTimeout",
182
- "streamIncomplete"
183
- ]);
184
- function isAutoRetryable(code) {
185
- return AUTO_RETRYABLE_CODES.has(code);
186
- }
187
- var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
188
- "serviceUnavailable",
189
- "conflict",
190
- "idempotencyInFlight"
191
- ]);
192
- function isRetryableCode(code) {
193
- return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
194
- }
195
- var BACKOFF_BASE_MS = 500;
196
- var BACKOFF_CAP_MS = 8e3;
197
- var MAX_RETRY_ATTEMPTS = 4;
198
- function backoffDelayMs(attempt, rng = Math.random) {
199
- const bounded = Math.max(0, attempt);
200
- const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
201
- return Math.floor(rng() * ceiling);
202
- }
203
-
204
- // src/client/errors/EverfurError.ts
205
- var USER_FACING_COPY = Object.freeze({
206
- authExpired: "Please sign in again to continue.",
207
- authRejected: "Please sign in again to continue.",
208
- sessionRequired: "This app needs to be updated to keep using Everfur.",
209
- accessDenied: "This feature isn't available on your account right now.",
210
- paymentRequired: "This is part of a paid plan.",
211
- quotaExceeded: "You have used today's messages. This resets tomorrow.",
212
- rateLimited: "You are sending messages quickly. Try again in a few seconds.",
213
- validationFailed: "Something in that request was not right. Check the details and try again.",
214
- sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
215
- conflict: "That is already running. Wait for it to finish, then try again.",
216
- idempotencyConflict: "That message was already delivered.",
217
- idempotencyInFlight: "That is still processing. Give it a moment.",
218
- conversationNotFound: "This conversation is no longer available.",
219
- petNotFound: "We could not find that pet. Please pick a pet and try again.",
220
- resourceNotFound: "We could not find that.",
221
- streamTimeout: "The response timed out. Tap retry to try again.",
222
- mediaUploadFailed: "We could not upload that photo. Please attach it again.",
223
- moderationBlocked: "This request cannot be answered here.",
224
- upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
225
- internalError: "We hit a snag on our end. Please try again.",
226
- notImplemented: "That is not available yet.",
227
- serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
228
- streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
229
- unknown: "Something went wrong. Please try again."
230
- });
231
- function userFacingError(code) {
232
- return USER_FACING_COPY[code];
233
- }
234
- function defineHidden(target, key, value) {
235
- Object.defineProperty(target, key, {
236
- value,
237
- enumerable: false,
238
- writable: false,
239
- configurable: false
240
- });
241
- }
242
- function makeEverfurError(code, opts) {
243
- contractErrorFor(opts?.wireCode);
244
- const error = {
245
- code,
246
- category: categoryFor(code),
247
- retryable: opts?.retryable ?? isRetryableCode(code),
248
- displayMessage: userFacingError(code)
249
- };
250
- if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
251
- if (opts?.requestId) error.requestId = opts.requestId;
252
- if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
253
- if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
254
- return Object.freeze(error);
255
- }
256
-
257
- // src/client/errors/EverfurResult.ts
258
- function ok(value, warning) {
259
- return Object.freeze(
260
- { ok: true, value }
261
- );
262
- }
263
- function err(error) {
264
- return Object.freeze({ ok: false, error });
265
- }
266
- var EverfurConfigError = class _EverfurConfigError extends Error {
267
- constructor(kind, message) {
268
- super(message);
269
- this.name = "EverfurConfigError";
270
- this.kind = kind;
271
- Object.setPrototypeOf(this, _EverfurConfigError.prototype);
272
- }
273
- };
274
- function brandPetRef(raw) {
275
- return raw;
276
- }
277
- function brandRequestId(raw) {
278
- return raw;
279
- }
280
- function brandDocumentId(raw) {
281
- return raw;
282
- }
283
- var KNOWN_STATUSES = /* @__PURE__ */ new Set([
284
- "awaiting_upload",
285
- "received",
286
- "parsing",
287
- "in_review",
288
- "published",
289
- "failed",
290
- "revoked"
291
- ]);
292
- var STATUS_ALIASES = Object.freeze({
293
- records_received: "received",
294
- // the server's spelling; `received` is never sent verbatim
295
- parsing_failed: "failed",
296
- // TERMINAL. Folding to `parsing` polled forever on a dead request.
297
- clinic_declined: "failed"
298
- // TERMINAL. The clinic refused; nothing further will arrive.
299
- });
300
- function normalizeStatus(raw) {
301
- const aliased = Object.prototype.hasOwnProperty.call(STATUS_ALIASES, raw) ? STATUS_ALIASES[raw] : void 0;
302
- if (aliased !== void 0) return aliased;
303
- const value = raw;
304
- return KNOWN_STATUSES.has(value) ? value : "parsing";
305
- }
306
- function normalizeOrigin(raw) {
307
- return raw === "owner_reported" || raw === "clinic_document" ? raw : null;
308
- }
309
- var requestSchema = zod.z.object({
310
- request_id: zod.z.string().min(1),
311
- pet_ref: zod.z.string().min(1),
312
- status: zod.z.string(),
313
- status_label: zod.z.string().optional(),
314
- document_count: zod.z.number().optional(),
315
- held_item_count: zod.z.number().optional(),
316
- received_at: zod.z.string().nullish(),
317
- parsing_started_at: zod.z.string().nullish(),
318
- review_started_at: zod.z.string().nullish(),
319
- created_at: zod.z.string().optional(),
320
- updated_at: zod.z.string().optional()
321
- }).passthrough();
322
- function mapRequestView(wire) {
323
- const parsed = requestSchema.safeParse(wire);
324
- if (!parsed.success) return null;
325
- const w = parsed.data;
326
- return Object.freeze({
327
- id: brandRequestId(w.request_id),
328
- petRef: brandPetRef(w.pet_ref),
329
- status: normalizeStatus(w.status),
330
- statusLabel: w.status_label ?? "",
331
- documentCount: numberOr(w.document_count, 0),
332
- heldItemCount: numberOr(w.held_item_count, 0),
333
- receivedAt: w.received_at ?? null,
334
- parsingStartedAt: w.parsing_started_at ?? null,
335
- reviewStartedAt: w.review_started_at ?? null,
336
- createdAt: w.created_at ?? "",
337
- updatedAt: w.updated_at ?? ""
338
- });
339
- }
340
- function mapRequestList(wire) {
341
- const list = Array.isArray(wire) ? wire : [];
342
- const out = [];
343
- for (const entry of list) {
344
- const view = mapRequestView(entry);
345
- if (view !== null) out.push(view);
346
- }
347
- return Object.freeze(out);
348
- }
349
- var acceptedSchema = zod.z.object({
350
- source_doc_id: zod.z.string().min(1),
351
- request_id: zod.z.string().min(1)
352
- });
353
- function mapUploadedDocument(wire) {
354
- const parsed = acceptedSchema.safeParse(wire);
355
- if (!parsed.success) return null;
356
- return Object.freeze({
357
- documentId: brandDocumentId(parsed.data.source_doc_id),
358
- requestId: brandRequestId(parsed.data.request_id),
359
- status: "received"
360
- });
361
- }
362
- var identitySchema = zod.z.object({ label: zod.z.string(), value: zod.z.string() });
363
- var entitySchema = zod.z.object({
364
- key: zod.z.string(),
365
- category: zod.z.string().optional(),
366
- label: zod.z.string().optional(),
367
- value: zod.z.string().nullish(),
368
- unit: zod.z.string().nullish(),
369
- observed_at: zod.z.string().nullish(),
370
- status: zod.z.string().nullish(),
371
- origin: zod.z.string().nullish()
372
- });
373
- var seriesPointSchema = zod.z.object({
374
- at: zod.z.string(),
375
- value: zod.z.number().nullish(),
376
- display: zod.z.string().nullish(),
377
- origin: zod.z.string().nullish()
378
- });
379
- var seriesSchema = zod.z.object({
380
- key: zod.z.string(),
381
- label: zod.z.string().optional(),
382
- points: zod.z.array(seriesPointSchema).optional()
383
- });
384
- var forwardSchema = zod.z.object({
385
- title: zod.z.string(),
386
- detail: zod.z.string().nullish(),
387
- due_at: zod.z.string().nullish()
388
- });
389
- var documentSchema = zod.z.object({
390
- doc_id: zod.z.string(),
391
- title: zod.z.string().nullish(),
392
- page_count: zod.z.number().nullish(),
393
- received_at: zod.z.string().nullish()
394
- });
395
- var contentSchema = zod.z.object({
396
- identity: zod.z.array(identitySchema).optional(),
397
- entities: zod.z.array(entitySchema).optional(),
398
- entity_series: zod.z.array(seriesSchema).optional(),
399
- forward_looking: zod.z.array(forwardSchema).optional(),
400
- documents: zod.z.array(documentSchema).optional()
401
- });
402
- function mapRecordView(petRef, wire) {
403
- const w = isObject(wire) ? wire : {};
404
- const schemaVersion = strOr(w["schema_version"], "epdf/1.0");
405
- const disclaimer = strOr(w["disclaimer"], "");
406
- const pet = brandPetRef(typeof w["pet_ref"] === "string" && w["pet_ref"].length > 0 ? w["pet_ref"] : petRef);
407
- if (w["withheld"] === true) {
408
- return withheldView(pet, schemaVersion, disclaimer);
409
- }
410
- const content = contentSchema.safeParse(w);
411
- if (!content.success) {
412
- return withheldView(pet, schemaVersion, disclaimer);
413
- }
414
- const c = content.data;
415
- const identity = (c.identity ?? []).map(
416
- (i) => Object.freeze({ label: i.label, value: i.value })
417
- );
418
- const entities = (c.entities ?? []).map(
419
- (e) => Object.freeze({
420
- key: e.key,
421
- category: e.category ?? "",
422
- label: e.label ?? e.key,
423
- value: e.value ?? null,
424
- unit: e.unit ?? null,
425
- observedAt: e.observed_at ?? null,
426
- status: e.status ?? null,
427
- origin: normalizeOrigin(e.origin)
428
- })
429
- );
430
- const entitySeries = (c.entity_series ?? []).map(
431
- (s) => Object.freeze({
432
- key: s.key,
433
- label: s.label ?? s.key,
434
- points: Object.freeze(
435
- (s.points ?? []).map(
436
- (p) => Object.freeze({
437
- at: p.at,
438
- value: p.value ?? null,
439
- display: p.display ?? null,
440
- origin: normalizeOrigin(p.origin)
441
- })
442
- )
443
- )
444
- })
445
- );
446
- const forwardLooking = (c.forward_looking ?? []).map(
447
- (f) => Object.freeze({ title: f.title, detail: f.detail ?? null, dueAt: f.due_at ?? null })
448
- );
449
- const documents = {};
450
- for (const d of c.documents ?? []) {
451
- documents[d.doc_id] = Object.freeze({
452
- docId: d.doc_id,
453
- title: d.title ?? null,
454
- pageCount: d.page_count ?? null,
455
- receivedAt: d.received_at ?? null
456
- });
457
- }
458
- const isEmpty = w["is_empty"] === true || identity.length === 0 && entities.length === 0 && entitySeries.length === 0 && forwardLooking.length === 0 && Object.keys(documents).length === 0;
459
- return Object.freeze({
460
- petRef: pet,
461
- schemaVersion,
462
- isEmpty,
463
- withheld: false,
464
- generatedAt: strOrNull(w["generated_at"]),
465
- identity: Object.freeze(identity),
466
- entities: Object.freeze(entities),
467
- entitySeries: Object.freeze(entitySeries),
468
- forwardLooking: Object.freeze(forwardLooking),
469
- documents: Object.freeze(documents),
470
- disclaimer
471
- });
472
- }
473
- function withheldView(petRef, schemaVersion, disclaimer) {
474
- return Object.freeze({
475
- petRef,
476
- schemaVersion,
477
- isEmpty: false,
478
- withheld: true,
479
- generatedAt: null,
480
- identity: Object.freeze([]),
481
- entities: Object.freeze([]),
482
- entitySeries: Object.freeze([]),
483
- forwardLooking: Object.freeze([]),
484
- documents: Object.freeze({}),
485
- disclaimer
486
- });
487
- }
488
- var consentSchema = zod.z.object({
489
- pet_ref: zod.z.string().optional(),
490
- granted: zod.z.boolean().optional(),
491
- version: zod.z.string().nullish(),
492
- granted_at: zod.z.string().nullish()
493
- });
494
- function mapConsent(petRef, wire) {
495
- const parsed = consentSchema.safeParse(wire);
496
- const data = parsed.success ? parsed.data : {};
497
- return Object.freeze({
498
- petRef: brandPetRef(typeof data.pet_ref === "string" && data.pet_ref.length > 0 ? data.pet_ref : petRef),
499
- granted: data.granted === true,
500
- version: data.version ?? null,
501
- grantedAt: data.granted_at ?? null
502
- });
503
- }
504
- function isObject(v) {
505
- return typeof v === "object" && v !== null && !Array.isArray(v);
506
- }
507
- function numberOr(v, fallback) {
508
- return typeof v === "number" && Number.isFinite(v) ? v : fallback;
509
- }
510
- function strOr(v, fallback) {
511
- return typeof v === "string" && v.length > 0 ? v : fallback;
512
- }
513
- function strOrNull(v) {
514
- return typeof v === "string" && v.length > 0 ? v : null;
515
- }
516
-
517
- // src/core/records/models.ts
518
- var RECORDS_TERMINAL = Object.freeze([
519
- "published",
520
- "failed",
521
- "revoked"
522
- ]);
523
- function isTerminalStatus(status) {
524
- return RECORDS_TERMINAL.includes(status);
525
- }
526
- function recordsDenialReasonOf(error) {
527
- if (error === null) return null;
528
- const reason = error.recordsReason;
529
- return reason === "consent_required" || reason === "session_required" || reason === "entitlement" ? reason : null;
530
- }
531
-
532
- // src/core/records/ports.ts
533
- var noopRecordsTelemetry = Object.freeze({
534
- record() {
535
- }
536
- });
537
- var MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
538
- var CONSENT_VERSION_MAX = 64;
539
- var IDEMPOTENCY_KEY_MAX = 128;
540
- var PET_REF_MAX = 128;
541
- var RECORDS_UPLOAD_CONTENT_TYPE = "application/pdf";
542
- var UPLOAD_DEADLINE_MS = 9e4;
543
-
544
- // src/core/records/RecordsController.ts
545
- function createRecordsController(deps) {
546
- return new RecordsControllerImpl(deps);
547
- }
548
- var RecordsControllerImpl = class {
549
- constructor(deps) {
550
- /** In-memory record cache (per pet). NEVER persisted to disk. Cleared on revoke. */
551
- this.recordCache = /* @__PURE__ */ new Map();
552
- /** Parse-gap dedup: a request's gap metric fires at most once per id. */
553
- this.reportedGaps = /* @__PURE__ */ new Set();
554
- this.repository = deps.repository;
555
- this.uploads = deps.uploads;
556
- this.telemetry = deps.telemetry ?? noopRecordsTelemetry;
557
- this.newIdempotencyKey = deps.newIdempotencyKey ?? defaultIdempotencyFactory();
558
- this.timers = deps.timers ?? defaultTimers;
559
- this.uploadDeadlineMs = deps.uploadDeadlineMs ?? UPLOAD_DEADLINE_MS;
560
- }
561
- // ---- request lifecycle ------------------------------------------------
562
- async createUploadRequest(input) {
563
- const res = await this.repository.createRequest({
564
- pet_ref: input.petRef,
565
- idempotency_key: input.idempotencyKey
566
- });
567
- if (!res.ok) return this.onRequestError(res.error);
568
- const view = mapRequestView(res.value);
569
- if (view === null) return err(internal());
570
- this.observeRequest(view);
571
- return ok(view);
572
- }
573
- async getRequest(id) {
574
- const res = await this.repository.getRequest(id);
575
- if (!res.ok) return this.onRequestError(res.error);
576
- const view = mapRequestView(res.value);
577
- if (view === null) return err(internal());
578
- this.observeRequest(view);
579
- return ok(view);
580
- }
581
- async listRequests() {
582
- const res = await this.repository.listRequests();
583
- if (!res.ok) return this.onRequestError(res.error);
584
- const views = mapRequestList(res.value);
585
- for (const view of views) this.observeRequest(view);
586
- return ok(views);
587
- }
588
- // ---- two-phase upload (§3.2) ------------------------------------------
589
- async uploadDocument(input) {
590
- const { requestId, file } = input;
591
- const rejection = validateFile(file);
592
- if (rejection !== null) {
593
- this.telemetry.record("records.upload.rejected", { reason: rejection });
594
- return err(uploadFailed(`upload rejected: ${rejection}`));
595
- }
596
- const initiated = await this.repository.initiateUpload(requestId, {
597
- content_type: RECORDS_UPLOAD_CONTENT_TYPE,
598
- file_size: file.sizeBytes
599
- });
600
- if (!initiated.ok) {
601
- return this.onRequestError(initiated.error);
602
- }
603
- const s3 = await this.postToS3(initiated.value, file, input);
604
- if (!s3.ok) {
605
- this.telemetry.record("records.upload.failed", { reason: s3.reason });
606
- return err(uploadFailed(s3.reason));
607
- }
608
- const completed = await this.repository.completeUpload(requestId, {
609
- upload_id: initiated.value.upload_id
610
- });
611
- if (!completed.ok) {
612
- if (completed.error.code === "mediaUploadFailed") {
613
- this.telemetry.record("records.upload.rejected", {
614
- reason: reasonFromWire(completed.error) ?? "corrupt"
615
- });
616
- }
617
- return this.onRequestError(completed.error);
618
- }
619
- const doc = mapUploadedDocument(completed.value);
620
- if (doc === null) return err(internal());
621
- return ok(doc);
622
- }
623
- async postToS3(policy, file, input) {
624
- const deadline = new AbortController();
625
- const signal = mergeSignals(deadline.signal, input.signal);
626
- const handle = this.timers.setTimeout(() => deadline.abort(), this.uploadDeadlineMs);
627
- try {
628
- const opts = { signal };
629
- if (input.onProgress) opts.onProgress = input.onProgress;
630
- await this.uploads.postMultipart(policy, file, opts);
631
- return { ok: true };
632
- } catch {
633
- const reason = deadline.signal.aborted && input.signal?.aborted !== true ? "timeout" : "upload_error";
634
- return { ok: false, reason };
635
- } finally {
636
- this.timers.clearTimeout(handle);
637
- }
638
- }
639
- // ---- record read (consent-gated, redaction-fail-closed) ---------------
640
- async getRecord(pet) {
641
- const res = await this.repository.getRecord(pet);
642
- if (!res.ok) {
643
- const reason = recordsDenialReasonOf(res.error);
644
- if (reason === "consent_required") {
645
- this.telemetry.record("records.consent.denied", { pet_ref: pet });
646
- } else if (reason === "entitlement") {
647
- this.telemetry.record("records.capability.denied", { pet_ref: pet });
648
- }
649
- return err(res.error);
650
- }
651
- const view = mapRecordView(pet, res.value);
652
- if (view.withheld) {
653
- this.telemetry.record("records.redaction.withheld", { pet_ref: pet });
654
- this.recordCache.delete(pet);
655
- return ok(view);
656
- }
657
- this.recordCache.set(pet, view);
658
- return ok(view);
659
- }
660
- peekCachedRecord(pet) {
661
- return this.recordCache.get(pet) ?? null;
662
- }
663
- // ---- consent ----------------------------------------------------------
664
- async getConsent(pet) {
665
- const res = await this.repository.getConsent(pet);
666
- if (!res.ok) {
667
- return err(res.error);
668
- }
669
- return ok(mapConsent(pet, res.value));
670
- }
671
- async grantConsent(input) {
672
- const res = await this.repository.putConsent(
673
- input.petRef,
674
- { consent_version: input.consentVersion, idempotency_key: input.idempotencyKey }
675
- );
676
- if (!res.ok) {
677
- const reason = recordsDenialReasonOf(res.error);
678
- if (reason === "entitlement") this.telemetry.record("records.capability.denied", { pet_ref: input.petRef });
679
- return err(res.error);
680
- }
681
- return ok(mapConsent(input.petRef, res.value));
682
- }
683
- async revokeConsent(pet) {
684
- const res = await this.repository.deleteConsent(pet);
685
- if (!res.ok) return err(res.error);
686
- this.recordCache.delete(pet);
687
- return ok(mapConsent(pet, res.value));
688
- }
689
- // ---- telemetry ---------------------------------------------------------
690
- reportCapabilityDenied(pet) {
691
- this.telemetry.record("records.capability.denied", pet ? { pet_ref: pet } : {});
692
- }
693
- // ---- internals ---------------------------------------------------------
694
- /** Emit `records.parse.gap` at most once when a request first shows a manual-review gap (R6). */
695
- observeRequest(view) {
696
- if (view.reviewStartedAt !== null && !this.reportedGaps.has(view.id)) {
697
- this.reportedGaps.add(view.id);
698
- this.telemetry.record("records.parse.gap", { request_id: view.id });
699
- }
700
- }
701
- /** Shared error path for the request lane: emit capability-denied on an entitlement 403, then surface. */
702
- onRequestError(error) {
703
- const reason = recordsDenialReasonOf(error);
704
- if (reason === "entitlement") this.telemetry.record("records.capability.denied", {});
705
- return err(error);
706
- }
707
- };
708
- function validateFile(file) {
709
- if (file.mimeType !== RECORDS_UPLOAD_CONTENT_TYPE) return "unsupported_format";
710
- const size = file.sizeBytes;
711
- if (typeof size !== "number" || !Number.isFinite(size) || size <= 0 || size > MAX_UPLOAD_BYTES) {
712
- return "oversize";
713
- }
714
- return null;
715
- }
716
- function reasonFromWire(error) {
717
- const raw = error.wireMessage;
718
- if (raw === "unsupported_format" || raw === "oversize" || raw === "corrupt") return raw;
719
- return null;
720
- }
721
- function uploadFailed(wireMessage) {
722
- return makeEverfurError("mediaUploadFailed", { retryable: false, wireMessage });
723
- }
724
- function internal() {
725
- return makeEverfurError("internalError", { retryable: true });
726
- }
727
- var defaultTimers = {
728
- setTimeout: (handler, ms) => setTimeout(handler, ms),
729
- clearTimeout: (handle) => clearTimeout(handle)
730
- };
731
- function mergeSignals(a, b) {
732
- if (!b) return a;
733
- const ctrl = new AbortController();
734
- if (a.aborted || b.aborted) {
735
- ctrl.abort();
736
- return ctrl.signal;
737
- }
738
- const onAbort = () => ctrl.abort();
739
- a.addEventListener("abort", onAbort, { once: true });
740
- b.addEventListener("abort", onAbort, { once: true });
741
- return ctrl.signal;
742
- }
743
- function defaultIdempotencyFactory() {
744
- let counter = 0;
745
- return () => `records-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
746
- }
747
-
748
- // src/client/protocol/frames.ts
749
- function assertNever(x) {
750
- throw new Error(
751
- `assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
752
- );
753
- }
754
- function errorFrame(fields) {
755
- return Object.freeze({
756
- kind: "error",
757
- terminal: true,
758
- code: fields.code,
759
- retryable: fields.retryable,
760
- wireMessage: fields.wireMessage,
761
- synthesized: fields.synthesized,
762
- lastEventId: fields.lastEventId,
763
- serverRequestId: null
764
- });
765
- }
766
-
767
- // src/client/identity.ts
768
- function authHeaders(auth) {
769
- const headers = {};
770
- if (auth.mode === "personalized") {
771
- headers.authorization = `Bearer ${auth.token}`;
772
- } else {
773
- headers["x-everfur-partner-key"] = auth.publishableKey;
774
- }
775
- if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
776
- if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
777
- return headers;
778
- }
779
- function withAuthHeaders(req, auth) {
780
- return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
781
- }
782
- function stripAuthHeaders(headers) {
783
- if (!headers) return {};
784
- const out = {};
785
- for (const [key, value] of Object.entries(headers)) {
786
- const lower = key.toLowerCase();
787
- if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
788
- out[key] = value;
789
- }
790
- return out;
791
- }
792
- async function authedSend(req, ctx) {
793
- if (ctx.mode === "anonymous") {
794
- return ctx.transport.request(
795
- withAuthHeaders(req, {
796
- mode: "anonymous",
797
- publishableKey: ctx.publishableKey,
798
- userRef: ctx.userRef,
799
- ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
800
- })
801
- );
802
- }
803
- let token;
804
- try {
805
- token = await ctx.identity.currentToken();
806
- } catch {
807
- return err(authRejectedError());
808
- }
809
- const first = await ctx.transport.request(
810
- withAuthHeaders(req, {
811
- mode: "personalized",
812
- token,
813
- userRef: ctx.userRef,
814
- ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
815
- })
816
- );
817
- if (first.ok || first.error.httpStatus !== 401) return first;
818
- let refreshed;
819
- try {
820
- refreshed = await ctx.identity.currentToken({ forceRefresh: true });
821
- } catch {
822
- return err(authRejectedError());
823
- }
824
- const retry = await ctx.transport.request(
825
- withAuthHeaders(req, {
826
- mode: "personalized",
827
- token: refreshed,
828
- userRef: ctx.userRef,
829
- ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
830
- })
831
- );
832
- if (!retry.ok && retry.error.httpStatus === 401) {
833
- return err(authRejectedError(retry.error.httpStatus));
834
- }
835
- return retry;
836
- }
837
- function authRejectedError(httpStatus) {
838
- return makeEverfurError("authRejected", {
839
- retryable: false,
840
- ...httpStatus !== void 0 ? { httpStatus } : {}
841
- });
842
- }
843
-
844
- // src/client/transport.ts
845
- function networkError(cause) {
846
- return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
847
- }
848
- function describeCause(cause) {
849
- if (cause instanceof Error) return cause.message;
850
- return typeof cause === "string" ? cause : "network request failed";
851
- }
852
-
853
- // src/client/funnel/requestFunnel.ts
854
- var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
855
- var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
856
- var IDEMPOTENCY_HEADER = "idempotency-key";
857
- var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
858
- var NOOP_OBSERVER = Object.freeze({
859
- onEvent() {
860
- }
861
- });
862
- var defaultFunnelTimers = Object.freeze({
863
- setTimeout: (handler, ms) => setTimeout(handler, ms),
864
- clearTimeout: (handle) => clearTimeout(handle),
865
- now: () => Date.now()
866
- });
867
- function createRequestFunnel(deps) {
868
- const observer = deps.observer ?? NOOP_OBSERVER;
869
- const timers = deps.timers ?? defaultFunnelTimers;
870
- const rng = deps.rng ?? Math.random;
871
- const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
872
- const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
873
- const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
874
- const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
875
- const emit = (event) => {
876
- try {
877
- observer.onEvent(event);
878
- } catch {
879
- }
880
- };
881
- async function send(call, req, opts) {
882
- const perCallMaxAttempts = opts?.maxAttempts;
883
- const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
884
- const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
885
- const idempotencyKey = idempotent ? mintKey() : null;
886
- const base = assembleHeaders(req, idempotencyKey);
887
- let attempt = 0;
888
- for (; ; ) {
889
- const stamp = (extra) => Object.freeze({
890
- call,
891
- method: req.method,
892
- path: req.path,
893
- attempt,
894
- ...idempotencyKey ? { idempotencyKey } : {},
895
- ...extra
896
- });
897
- emit(stamp({ phase: "attempt" }));
898
- const deadline = boundedSignal(timeoutMs, timers);
899
- const merged = mergeSignals2(deadline.signal, req.signal);
900
- let settled;
901
- try {
902
- settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
903
- } catch (cause) {
904
- settled = err(networkError(cause));
905
- } finally {
906
- merged.dispose();
907
- deadline.cancel();
908
- }
909
- if (settled.ok) {
910
- emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
911
- return settled;
912
- }
913
- const error = settled.error;
914
- const decision = decideRetry(error, attempt, {
915
- maxAttempts,
916
- rng,
917
- now: timers.now(),
918
- aborted: req.signal?.aborted === true,
919
- ...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
920
- ...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
921
- });
922
- const settledEvent = {
923
- ok: false,
924
- code: error.code,
925
- reason: decision.reason,
926
- ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
927
- ...error.requestId !== void 0 ? { requestId: error.requestId } : {}
928
- };
929
- if (!decision.retry) {
930
- emit(stamp({ phase: "settled", ...settledEvent }));
931
- return err(error);
932
- }
933
- emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
934
- await sleep(decision.delayMs, req.signal);
935
- if (req.signal?.aborted === true) {
936
- emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
937
- return err(error);
938
- }
939
- attempt += 1;
940
- }
941
- }
942
- async function authorize(req) {
943
- return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
944
- }
945
- async function* stream(call, req, signal) {
946
- emit(
947
- Object.freeze({
948
- call,
949
- phase: "stream.open",
950
- method: req.method,
951
- path: req.path,
952
- attempt: 0
953
- })
954
- );
955
- try {
956
- yield* deps.auth.transport.stream(req, signal);
957
- } catch {
958
- yield errorFrame({
959
- // The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
960
- // like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
961
- // host exception's `.message` is not that.
962
- code: "internal_error",
963
- retryable: true,
964
- wireMessage: null,
965
- synthesized: true,
966
- lastEventId: null});
967
- }
968
- }
969
- return Object.freeze({ send, authorize, stream });
970
- }
971
- function assembleHeaders(req, idempotencyKey) {
972
- const headers = {};
973
- for (const [key, value] of Object.entries(req.headers ?? {})) {
974
- if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
975
- headers[key] = value;
976
- }
977
- if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
978
- return { ...req, headers };
979
- }
980
- function defaultIdempotencyKeyFactory() {
981
- let counter = 0;
982
- return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
983
- }
984
- var POLICY_MAX_ATTEMPTS_CAP = 10;
985
- function decideRetry(error, attempt, ctx) {
986
- if (ctx.aborted) return { retry: false, reason: "aborted" };
987
- const throttle = throttleKind(error);
988
- if (throttle === "quota") {
989
- return { retry: false, reason: "daily-quota-exhausted" };
990
- }
991
- if (throttle !== "burst" && !isAutoRetryable(error.code)) {
992
- return { retry: false, reason: "terminal-code" };
993
- }
994
- const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
995
- const policyVetoedRetry = () => {
996
- if (ctx.policy === void 0) return false;
997
- try {
998
- return !ctx.policy.shouldRetry(error.code, attempt);
999
- } catch {
1000
- return false;
1001
- }
1002
- };
1003
- if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
1004
- const policyCeiling = () => {
1005
- if (ctx.policy === void 0) return null;
1006
- let raw;
1007
- try {
1008
- raw = ctx.policy.maxAttempts(error.code);
1009
- } catch {
1010
- return null;
1011
- }
1012
- if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
1013
- return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
1014
- };
1015
- const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
1016
- if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
1017
- const override = retryOverrideMs(error, ctx.now);
1018
- if (override !== null) {
1019
- if (override > RETRY_OVERRIDE_MAX_MS) {
1020
- return { retry: false, reason: "server-reset-beyond-budget" };
1021
- }
1022
- return { retry: true, reason, delayMs: override };
1023
- }
1024
- return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
1025
- }
1026
- function throttleKind(error) {
1027
- const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
1028
- if (code === "quotaExceeded") return "quota";
1029
- if (code === "rateLimited") return "burst";
1030
- if (error.httpStatus === 429) {
1031
- return "burst";
1032
- }
1033
- return null;
1034
- }
1035
- function retryOverrideMs(error, now) {
1036
- const at = findResetsAt(error.raw);
1037
- if (at === null) return null;
1038
- const delta = at - now;
1039
- return delta > 0 ? delta : 0;
1040
- }
1041
- function findResetsAt(raw) {
1042
- for (const scope of candidateScopes(raw)) {
1043
- const value = scope["resets_at"];
1044
- const parsed = parseInstantMs(value);
1045
- if (parsed !== null) return parsed;
1046
- }
1047
- return null;
1048
- }
1049
- function candidateScopes(raw) {
1050
- if (!isRecord(raw)) return [];
1051
- const out = [raw];
1052
- for (const nested of ["error", "detail"]) {
1053
- const value = raw[nested];
1054
- if (isRecord(value)) out.push(value);
1055
- }
1056
- return out;
1057
- }
1058
- function parseInstantMs(value) {
1059
- if (typeof value === "number" && Number.isFinite(value)) {
1060
- return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
1061
- }
1062
- if (typeof value === "string" && value.trim().length > 0) {
1063
- const parsed = Date.parse(value);
1064
- return Number.isFinite(parsed) ? parsed : null;
1065
- }
1066
- return null;
1067
- }
1068
- function rawWireCode(raw) {
1069
- for (const scope of candidateScopes(raw)) {
1070
- const code = scope["code"];
1071
- if (typeof code === "string" && code.length > 0) return code;
1072
- }
1073
- return null;
1074
- }
1075
- function isRecord(value) {
1076
- return typeof value === "object" && value !== null;
1077
- }
1078
- async function resolveDeviceAuth(auth) {
1079
- if (auth.mode === "anonymous") {
1080
- return {
1081
- mode: "anonymous",
1082
- publishableKey: auth.publishableKey,
1083
- userRef: auth.userRef,
1084
- ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1085
- };
1086
- }
1087
- return {
1088
- mode: "personalized",
1089
- token: await auth.identity.currentToken(),
1090
- userRef: auth.userRef,
1091
- ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1092
- };
1093
- }
1094
- function boundedSignal(ms, timers) {
1095
- const ctrl = new AbortController();
1096
- const handle = timers.setTimeout(() => ctrl.abort(), ms);
1097
- return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
1098
- }
1099
- function mergeSignals2(deadline, caller) {
1100
- const noop = () => void 0;
1101
- if (!caller) return { signal: deadline, dispose: noop };
1102
- const ctrl = new AbortController();
1103
- if (deadline.aborted || caller.aborted) {
1104
- ctrl.abort();
1105
- return { signal: ctrl.signal, dispose: noop };
1106
- }
1107
- const onAbort = () => ctrl.abort();
1108
- deadline.addEventListener("abort", onAbort, { once: true });
1109
- caller.addEventListener("abort", onAbort, { once: true });
1110
- return {
1111
- signal: ctrl.signal,
1112
- dispose: () => {
1113
- deadline.removeEventListener("abort", onAbort);
1114
- caller.removeEventListener("abort", onAbort);
1115
- }
1116
- };
1117
- }
1118
- function delayAbortable(ms, timers, signal) {
1119
- if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
1120
- return new Promise((resolve) => {
1121
- const handle = timers.setTimeout(() => {
1122
- signal?.removeEventListener("abort", onAbort);
1123
- resolve();
1124
- }, ms);
1125
- const onAbort = () => {
1126
- timers.clearTimeout(handle);
1127
- resolve();
1128
- };
1129
- signal?.addEventListener("abort", onAbort, { once: true });
1130
- });
1131
- }
1132
-
1133
- // src/client/text.ts
1134
- function hasLoneSurrogate(value) {
1135
- for (let i = 0; i < value.length; i += 1) {
1136
- const code = value.charCodeAt(i);
1137
- if (code >= 55296 && code <= 56319) {
1138
- const low = value.charCodeAt(i + 1);
1139
- if (!(low >= 56320 && low <= 57343)) return true;
1140
- i += 1;
1141
- } else if (code >= 56320 && code <= 57343) {
1142
- return true;
1143
- }
1144
- }
1145
- return false;
1146
- }
1147
-
1148
- // src/core/records/repository.ts
1149
- var BASE = "/widget/v1/records";
1150
- function createHttpRecordsRepository(deps) {
1151
- const { auth } = deps;
1152
- const mode = auth.mode;
1153
- const funnel = deps.funnel ?? createRequestFunnel({ auth, ...deps.errorPolicy ? { errorPolicy: deps.errorPolicy } : {} });
1154
- const send = async (call, req, kind) => {
1155
- const res = await funnel.send(call, req);
1156
- if (res.ok) return res;
1157
- return err(tagReason(res.error, mode, kind));
1158
- };
1159
- const segmentError = (field, value) => {
1160
- if (typeof value !== "string" || value.length === 0) {
1161
- return makeEverfurError("validationFailed", {
1162
- retryable: false,
1163
- wireMessage: `${field} is required and must be a non-empty string`
1164
- });
1165
- }
1166
- if (hasLoneSurrogate(value)) {
1167
- return makeEverfurError("validationFailed", {
1168
- retryable: false,
1169
- wireMessage: `${field} contains an unpaired surrogate and cannot be encoded`
1170
- });
1171
- }
1172
- return null;
1173
- };
1174
- const boundsError = (field, value, max) => {
1175
- const unusable = segmentError(field, value);
1176
- if (unusable !== null) return unusable;
1177
- const value_ = value;
1178
- const length = [...value_].length;
1179
- if (length > max) {
1180
- return makeEverfurError("validationFailed", {
1181
- retryable: false,
1182
- wireMessage: `${field} is ${length} characters; the server accepts at most ${max}`
1183
- });
1184
- }
1185
- return null;
1186
- };
1187
- const firstError = (...checks) => checks.find((c) => c !== null) ?? null;
1188
- return {
1189
- createRequest: (body) => {
1190
- const invalid = firstError(
1191
- boundsError("idempotency_key", body.idempotency_key, IDEMPOTENCY_KEY_MAX),
1192
- boundsError("pet_ref", body.pet_ref, PET_REF_MAX)
1193
- );
1194
- if (invalid) return Promise.resolve(err(invalid));
1195
- return send("records.createRequest", post(`${BASE}/requests`, body), "request");
1196
- },
1197
- initiateUpload: (requestId, body) => {
1198
- const invalid = segmentError("request_id", requestId);
1199
- if (invalid) return Promise.resolve(err(invalid));
1200
- return send(
1201
- "records.initiateUpload",
1202
- post(`${BASE}/requests/${encodeURIComponent(requestId)}/uploads/initiate`, body),
1203
- "request"
1204
- );
1205
- },
1206
- completeUpload: (requestId, body) => {
1207
- const invalid = segmentError("request_id", requestId);
1208
- if (invalid) return Promise.resolve(err(invalid));
1209
- return send(
1210
- "records.completeUpload",
1211
- post(`${BASE}/requests/${encodeURIComponent(requestId)}/uploads/complete`, body),
1212
- "request"
1213
- );
1214
- },
1215
- getRequest: (requestId) => {
1216
- const invalid = segmentError("request_id", requestId);
1217
- if (invalid) return Promise.resolve(err(invalid));
1218
- return send(
1219
- "records.getRequest",
1220
- get(`${BASE}/requests/${encodeURIComponent(requestId)}`),
1221
- "request"
1222
- );
1223
- },
1224
- listRequests: async () => {
1225
- const res = await send(
1226
- "records.listRequests",
1227
- get(`${BASE}/requests`),
1228
- "request"
1229
- );
1230
- if (!res.ok) return res;
1231
- const value = res.value;
1232
- const items = Array.isArray(value) ? value : value.items ?? [];
1233
- return { ok: true, value: items };
1234
- },
1235
- getRecord: (petRef) => {
1236
- const invalid = boundsError("pet_ref", petRef, PET_REF_MAX);
1237
- if (invalid) return Promise.resolve(err(invalid));
1238
- return send(
1239
- "records.getRecord",
1240
- get(`${BASE}/pets/${encodeURIComponent(petRef)}/record`),
1241
- "content"
1242
- );
1243
- },
1244
- getConsent: (petRef) => {
1245
- const invalid = boundsError("pet_ref", petRef, PET_REF_MAX);
1246
- if (invalid) return Promise.resolve(err(invalid));
1247
- return send(
1248
- "records.getConsent",
1249
- get(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),
1250
- "consent"
1251
- );
1252
- },
1253
- putConsent: (petRef, body) => {
1254
- const invalid = firstError(
1255
- boundsError("consent_version", body.consent_version, CONSENT_VERSION_MAX),
1256
- boundsError("idempotency_key", body.idempotency_key, IDEMPOTENCY_KEY_MAX),
1257
- boundsError("pet_ref", petRef, PET_REF_MAX)
1258
- );
1259
- if (invalid) return Promise.resolve(err(invalid));
1260
- return send(
1261
- "records.putConsent",
1262
- put(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`, body),
1263
- "consent"
1264
- );
1265
- },
1266
- deleteConsent: (petRef) => {
1267
- const invalid = boundsError("pet_ref", petRef, PET_REF_MAX);
1268
- if (invalid) return Promise.resolve(err(invalid));
1269
- return send(
1270
- "records.deleteConsent",
1271
- del(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),
1272
- "consent"
1273
- );
1274
- }
1275
- };
1276
- }
1277
- function withReason(error, reason) {
1278
- const tagged = { ...error, recordsReason: reason };
1279
- for (const key of ["wireMessage", "raw"]) {
1280
- const descriptor = Object.getOwnPropertyDescriptor(error, key);
1281
- if (descriptor !== void 0) Object.defineProperty(tagged, key, descriptor);
1282
- }
1283
- return Object.freeze(tagged);
1284
- }
1285
- function tagReason(error, mode, kind) {
1286
- if (error.httpStatus === 404) return withReason(error, "entitlement");
1287
- if (error.code !== "accessDenied") return error;
1288
- const reason = mode === "anonymous" ? "session_required" : kind === "content" ? "consent_required" : "entitlement";
1289
- return withReason(error, reason);
1290
- }
1291
- function get(path) {
1292
- return { method: "GET", path };
1293
- }
1294
- function post(path, body) {
1295
- return { method: "POST", path, body };
1296
- }
1297
- function put(path, body) {
1298
- return { method: "PUT", path, body };
1299
- }
1300
- function del(path) {
1301
- return { method: "DELETE", path };
1302
- }
1303
-
1304
- // src/client/entitlements/resolve.ts
1305
- var REQUIRES = Object.freeze({
1306
- chat: Object.freeze(["chat.message.create"]),
1307
- records: Object.freeze(["records.upload.create", "records.record.read"]),
1308
- video: Object.freeze(["video.gait.execute"]),
1309
- photo: Object.freeze(["photo.checkup.execute"]),
1310
- animations: Object.freeze(["animations.state.read"])
1311
- });
1312
- function requires(name) {
1313
- return REQUIRES[name];
1314
- }
1315
- function decideCapability(name, decisions, opts) {
1316
- if (opts?.isPending === true) {
1317
- return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
1318
- }
1319
- const keys = requires(name);
1320
- const byResource = /* @__PURE__ */ new Map();
1321
- for (const decision of decisions) byResource.set(decision.resource, decision);
1322
- const limits = mergeLimits(keys, byResource);
1323
- const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
1324
- if (missing.length === 0) {
1325
- return freezeDecision({ name, enabled: true, isPending: false, limits });
1326
- }
1327
- return freezeDecision({
1328
- name,
1329
- enabled: false,
1330
- isPending: false,
1331
- limits,
1332
- disabled: disabledFor(keys, byResource)
1333
- });
1334
- }
1335
- function mergeLimits(keys, byResource) {
1336
- const out = {};
1337
- for (const key of keys) {
1338
- const decisionLimits = byResource.get(key)?.limits;
1339
- if (!decisionLimits) continue;
1340
- for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
1341
- const existing = out[limitKey];
1342
- out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
1343
- }
1344
- }
1345
- return out;
1346
- }
1347
- function disabledFor(keys, byResource) {
1348
- for (const key of keys) {
1349
- const explicit = byResource.get(key)?.disabled;
1350
- if (explicit) {
1351
- return Object.freeze({
1352
- reason: explicit.reason,
1353
- level: explicit.level,
1354
- recoverable: explicit.recoverable
1355
- });
1356
- }
1357
- }
1358
- return Object.freeze({
1359
- reason: userFacingError("accessDenied"),
1360
- level: "user_entitlement",
1361
- recoverable: false
1362
- });
1363
- }
1364
- function freezeDecision(d) {
1365
- const base = {
1366
- name: d.name,
1367
- enabled: d.enabled,
1368
- isPending: d.isPending,
1369
- limits: Object.freeze({ ...d.limits })
1370
- };
1371
- if (d.disabled !== void 0) base.disabled = d.disabled;
1372
- return Object.freeze(base);
1373
- }
1374
-
1375
- // src/client/theme/tokens.ts
1376
- function deepFreeze(value) {
1377
- if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
1378
- Object.freeze(value);
1379
- for (const key of Object.keys(value)) {
1380
- deepFreeze(value[key]);
1381
- }
1382
- }
1383
- return value;
1384
- }
1385
- var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
1386
- var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
1387
- var TYPE_SIZE = {
1388
- nano: 8,
1389
- small: 9,
1390
- micro: 10,
1391
- tiny: 11,
1392
- caption: 12,
1393
- bodyTight: 13,
1394
- body: 14,
1395
- subtitle: 16,
1396
- heading: 18,
1397
- verdict: 24
1398
- };
1399
- var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
1400
- var WEIGHT = { regular: "400", medium: "500", bold: "700" };
1401
- var LETTER_SPACING = {
1402
- eyebrow: 1,
1403
- monoWide: 0.9,
1404
- headerBrand: -0.42,
1405
- tight: -0.35
1406
- };
1407
- function baseType() {
1408
- return {
1409
- family: "System",
1410
- mono: "monospace",
1411
- fontUrl: null,
1412
- size: TYPE_SIZE,
1413
- lineHeight: LINE_HEIGHT,
1414
- weight: WEIGHT,
1415
- letterSpacing: LETTER_SPACING
1416
- };
1417
- }
1418
- var MOTION = {
1419
- duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
1420
- spring: { gentle: { damping: 18, stiffness: 200 } },
1421
- easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
1422
- reducedMotion: false
1423
- };
1424
- var LIGHT_COLOR = {
1425
- brand: "#10462E",
1426
- brandSoft: "rgba(16,70,46,0.10)",
1427
- brandSofter: "rgba(16,70,46,0.15)",
1428
- brandBorder: "rgba(16,70,46,0.18)",
1429
- borderHairlineGreen: "rgba(16,70,46,0.25)",
1430
- surface: "#FFFFFF",
1431
- surfaceCream: "#FDFBF8",
1432
- surfaceSubtle: "#EFE9E3",
1433
- background: "#FFFFFF",
1434
- borderRingCream: "#D8D2C8",
1435
- text: {
1436
- primary: "#111111",
1437
- secondary: "#0E462E",
1438
- muted: "#6E6660",
1439
- placeholder: "rgba(0,0,0,0.30)",
1440
- onBrand: "#FFFFFF",
1441
- metaCool: "#3D3D3D"
1442
- },
1443
- primary: "#10462E",
1444
- onPrimary: "#FFFFFF",
1445
- accent: "#10462E",
1446
- onAccent: "#FFFFFF",
1447
- accentEdge: "#07C168",
1448
- success: "#07C168",
1449
- danger: "#B91C1C",
1450
- errorRed: "#FF1B00",
1451
- warningStrong: "#A45610",
1452
- cautionAccent: "#D9821D",
1453
- riskConcern: "#EFA700",
1454
- badgeBgPositive: "rgba(7,193,104,0.12)",
1455
- badgeBgCaution: "rgba(217,130,29,0.14)",
1456
- badgeBgCritical: "rgba(185,28,28,0.12)",
1457
- badgeBgNeutral: "rgba(110,102,96,0.12)",
1458
- bubbleUser: "#10462E",
1459
- bubbleAssistant: "#FFFFFF",
1460
- skeleton: "#EFE9E3",
1461
- scanButtonPink: "#FFC3BC",
1462
- checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
1463
- checkupCardConcernBg: "rgba(239,167,0,0.10)"
1464
- };
1465
- var EVERFUR_LIGHT = deepFreeze({
1466
- brightness: "light",
1467
- meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1468
- color: LIGHT_COLOR,
1469
- space: SPACE,
1470
- radius: RADIUS,
1471
- type: baseType(),
1472
- motion: MOTION
1473
- });
1474
- var DARK_COLOR = {
1475
- brand: "#6BD39A",
1476
- brandSoft: "rgba(107,211,154,0.12)",
1477
- brandSofter: "rgba(107,211,154,0.18)",
1478
- brandBorder: "rgba(107,211,154,0.22)",
1479
- borderHairlineGreen: "rgba(107,211,154,0.28)",
1480
- surface: "#1C1F23",
1481
- surfaceCream: "#23272C",
1482
- surfaceSubtle: "#23272C",
1483
- background: "#15171A",
1484
- borderRingCream: "#3A3F45",
1485
- text: {
1486
- primary: "#F5F3F0",
1487
- secondary: "#A9E4C4",
1488
- muted: "#9A938C",
1489
- placeholder: "rgba(255,255,255,0.35)",
1490
- onBrand: "#0E1F17",
1491
- metaCool: "#C9C9C9"
1492
- },
1493
- primary: "#6BD39A",
1494
- onPrimary: "#0E1F17",
1495
- accent: "#6BD39A",
1496
- onAccent: "#0E1F17",
1497
- accentEdge: "#34D888",
1498
- success: "#07C168",
1499
- danger: "#B91C1C",
1500
- errorRed: "#FF1B00",
1501
- warningStrong: "#A45610",
1502
- cautionAccent: "#D9821D",
1503
- riskConcern: "#EFA700",
1504
- badgeBgPositive: "rgba(7,193,104,0.18)",
1505
- badgeBgCaution: "rgba(217,130,29,0.20)",
1506
- badgeBgCritical: "rgba(185,28,28,0.22)",
1507
- badgeBgNeutral: "rgba(255,255,255,0.10)",
1508
- bubbleUser: "#6BD39A",
1509
- bubbleAssistant: "#1C1F23",
1510
- skeleton: "#23272C",
1511
- scanButtonPink: "#FFC3BC",
1512
- checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
1513
- checkupCardConcernBg: "rgba(239,167,0,0.16)"
1514
- };
1515
- deepFreeze({
1516
- brightness: "dark",
1517
- meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1518
- color: DARK_COLOR,
1519
- space: SPACE,
1520
- radius: RADIUS,
1521
- type: baseType(),
1522
- motion: MOTION
1523
- });
1524
- var EVERFUR_THEME_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurThemeContext@v1");
1525
- var globalThemeHost = globalThis;
1526
- var EverfurThemeContext = globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] ?? (globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] = react.createContext(EVERFUR_LIGHT));
1527
- EverfurThemeContext.displayName ??= "EverfurThemeContext";
1528
- function useEverfurTheme() {
1529
- return react.useContext(EverfurThemeContext);
1530
- }
1531
-
1532
- // src/rn/facade.ts
1533
- var EVERFUR_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurContext@v1");
1534
- var globalContextHost = globalThis;
1535
- var EverfurContext = globalContextHost[EVERFUR_CONTEXT_SYMBOL] ?? (globalContextHost[EVERFUR_CONTEXT_SYMBOL] = react.createContext(null));
1536
- EverfurContext.displayName ??= "EverfurContext";
1537
- function useEverfurContext() {
1538
- const ctx = react.useContext(EverfurContext);
1539
- if (ctx === null) {
1540
- throw new EverfurConfigError(
1541
- "not-initialized",
1542
- "Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high."
1543
- );
1544
- }
1545
- return ctx;
1546
- }
1547
-
1548
- // src/rn/records/useRecords.ts
1549
- var INITIAL = {
1550
- record: null,
1551
- requests: [],
1552
- consent: null,
1553
- error: null,
1554
- denialReason: null,
1555
- withheld: false,
1556
- loading: true,
1557
- isUploading: false,
1558
- uploadProgress: null
1559
- };
1560
- var POLL_INTERVAL_MS = 4e3;
1561
- var MAX_POLLS = 30;
1562
- function useEverfurRecords(opts) {
1563
- const { petRef } = opts;
1564
- const { runtime, userRef } = useEverfurContext();
1565
- const [controller, setController] = react.useState(opts.controller ?? null);
1566
- const [snap, setSnap] = react.useState(INITIAL);
1567
- const generation = react.useRef(0);
1568
- react.useEffect(() => {
1569
- if (opts.controller) {
1570
- setController(opts.controller);
1571
- return;
1572
- }
1573
- const { services } = runtime.registry;
1574
- const telemetry = {
1575
- record: (event, props) => services.telemetry.track(event, props)
1576
- };
1577
- const acquired = runtime.registry.acquire(
1578
- "records",
1579
- `${userRef ?? ""}|${petRef}`,
1580
- () => createRecordsController({
1581
- repository: createHttpRecordsRepository({
1582
- auth: services.authFor(userRef),
1583
- ...services.errorPolicy ? { errorPolicy: services.errorPolicy } : {}
1584
- }),
1585
- uploads: services.uploadTransport,
1586
- telemetry
1587
- }),
1588
- // The records controller holds only an in-memory cache and has no dispose; dropping the ref clears it.
1589
- () => {
1590
- }
1591
- );
1592
- setController(acquired);
1593
- return () => {
1594
- runtime.registry.release(acquired);
1595
- setController((current) => current === acquired ? null : current);
1596
- };
1597
- }, [runtime, userRef, petRef, opts.controller]);
1598
- const patch = react.useCallback((partial) => {
1599
- setSnap((current) => ({ ...current, ...partial }));
1600
- }, []);
1601
- const load = react.useCallback(async () => {
1602
- if (!controller) return;
1603
- const gen = generation.current += 1;
1604
- pollsRef.current = 0;
1605
- rearmPolls();
1606
- patch({ loading: true, error: null, denialReason: null, withheld: false });
1607
- const [consentRes, listRes] = await Promise.all([
1608
- controller.getConsent(petRef),
1609
- controller.listRequests()
1610
- ]);
1611
- if (gen !== generation.current) return;
1612
- const consent = consentRes.ok ? consentRes.value : null;
1613
- const requests = listRes.ok ? listRes.value : [];
1614
- const listError = listRes.ok ? null : listRes.error;
1615
- if (consent && consent.granted) {
1616
- const recordRes = await controller.getRecord(petRef);
1617
- if (gen !== generation.current) return;
1618
- if (recordRes.ok) {
1619
- patch({
1620
- consent,
1621
- requests,
1622
- record: recordRes.value,
1623
- withheld: recordRes.value.withheld,
1624
- error: recordRes.value.withheld ? withheldSentinel() : listError,
1625
- denialReason: null,
1626
- loading: false
1627
- });
1628
- return;
1629
- }
1630
- patch({
1631
- consent,
1632
- requests,
1633
- record: null,
1634
- error: recordRes.error,
1635
- denialReason: recordsDenialReasonOf(recordRes.error),
1636
- withheld: false,
1637
- loading: false
1638
- });
1639
- return;
1640
- }
1641
- patch({
1642
- consent,
1643
- requests,
1644
- record: null,
1645
- // When the CONSENT read itself failed, its error is the one that explains the state; `listError` is
1646
- // incidental. This branch is now reachable with a real error because a 404 no longer folds into a
1647
- // fake `granted:false`.
1648
- error: consentRes.ok ? listError : consentRes.error,
1649
- denialReason: consent ? "consent_required" : consentDenial(consentRes),
1650
- withheld: false,
1651
- loading: false
1652
- });
1653
- }, [controller, petRef, patch]);
1654
- react.useEffect(() => {
1655
- void load();
1656
- }, [load]);
1657
- const activeRequest = react.useMemo(() => newestRequest(snap.requests), [snap.requests]);
1658
- const activeId = activeRequest?.id ?? null;
1659
- const activeStatus = activeRequest?.status ?? null;
1660
- const pollsRef = react.useRef(0);
1661
- const polledIdRef = react.useRef(null);
1662
- const [pollEpoch, rearmPolls] = react.useReducer((n) => n + 1, 0);
1663
- react.useEffect(() => {
1664
- if (!controller || activeId === null || activeStatus === null) return;
1665
- if (isTerminalStatus(activeStatus) || activeStatus === "in_review") return;
1666
- if (polledIdRef.current !== String(activeId)) {
1667
- polledIdRef.current = String(activeId);
1668
- pollsRef.current = 0;
1669
- }
1670
- let cancelled = false;
1671
- const tick = async () => {
1672
- if (cancelled || pollsRef.current >= MAX_POLLS) return;
1673
- pollsRef.current += 1;
1674
- const res = await controller.getRequest(activeId);
1675
- if (cancelled) return;
1676
- if (res.ok) {
1677
- setSnap((current) => ({ ...current, requests: replaceRequest(current.requests, res.value) }));
1678
- if (isTerminalStatus(res.value.status)) {
1679
- if (res.value.status === "published") void load();
1680
- return;
1681
- }
1682
- if (res.value.status === "in_review") return;
1683
- }
1684
- handle = setTimeout(() => void tick(), POLL_INTERVAL_MS);
1685
- };
1686
- let handle = setTimeout(() => void tick(), POLL_INTERVAL_MS);
1687
- return () => {
1688
- cancelled = true;
1689
- clearTimeout(handle);
1690
- };
1691
- }, [controller, activeId, activeStatus, load, pollEpoch]);
1692
- const createRequest = react.useCallback(
1693
- async (idempotencyKey) => {
1694
- if (!controller) return notReady();
1695
- const res = await controller.createUploadRequest({ petRef, idempotencyKey });
1696
- if (res.ok) setSnap((c) => ({ ...c, requests: replaceRequest(c.requests, res.value) }));
1697
- return res;
1698
- },
1699
- [controller, petRef]
1700
- );
1701
- const uploadDocument = react.useCallback(
1702
- async (requestId, file) => {
1703
- if (!controller) return notReady();
1704
- patch({ isUploading: true, uploadProgress: 0 });
1705
- const res = await controller.uploadDocument({
1706
- requestId,
1707
- file,
1708
- onProgress: (fraction) => patch({ uploadProgress: fraction })
1709
- });
1710
- patch({ isUploading: false, uploadProgress: null });
1711
- if (res.ok) {
1712
- const refreshed = await controller.getRequest(requestId);
1713
- if (refreshed.ok) setSnap((c) => ({ ...c, requests: replaceRequest(c.requests, refreshed.value) }));
1714
- }
1715
- return res;
1716
- },
1717
- [controller, patch]
1718
- );
1719
- const grantConsent = react.useCallback(
1720
- async (consentVersion, idempotencyKey) => {
1721
- if (!controller) return notReady();
1722
- const res = await controller.grantConsent({ petRef, consentVersion, idempotencyKey });
1723
- if (res.ok) void load();
1724
- return res;
1725
- },
1726
- [controller, petRef, load]
1727
- );
1728
- const revokeConsent = react.useCallback(async () => {
1729
- if (!controller) return notReady();
1730
- const res = await controller.revokeConsent(petRef);
1731
- if (res.ok) {
1732
- patch({ record: null, withheld: false, denialReason: "consent_required", consent: res.value });
1733
- }
1734
- return res;
1735
- }, [controller, petRef, patch]);
1736
- const refresh = react.useCallback(() => {
1737
- void load();
1738
- }, [load]);
1739
- const status = selectStatus(snap, controller !== null);
1740
- return react.useMemo(
1741
- () => ({
1742
- status,
1743
- record: snap.record,
1744
- requests: snap.requests,
1745
- activeRequest,
1746
- consent: snap.consent,
1747
- error: snap.error,
1748
- denialReason: snap.denialReason,
1749
- withheld: snap.withheld,
1750
- isUploading: snap.isUploading,
1751
- uploadProgress: snap.uploadProgress,
1752
- createRequest,
1753
- uploadDocument,
1754
- grantConsent,
1755
- revokeConsent,
1756
- refresh
1757
- }),
1758
- [status, snap, activeRequest, createRequest, uploadDocument, grantConsent, revokeConsent, refresh]
1759
- );
1760
- }
1761
- function selectStatus(snap, hasController) {
1762
- if (snap.loading || !hasController) return "loading";
1763
- if (snap.withheld || snap.denialReason !== null || snap.error !== null) return "error";
1764
- if (snap.record !== null && !snap.record.isEmpty) return "populated";
1765
- if (snap.requests.length > 0) return "populated";
1766
- return "empty";
1767
- }
1768
- function newestRequest(requests) {
1769
- if (requests.length === 0) return null;
1770
- let newest = requests[0];
1771
- for (const r of requests) if (r.updatedAt > newest.updatedAt) newest = r;
1772
- return newest;
1773
- }
1774
- function replaceRequest(requests, next) {
1775
- const filtered = requests.filter((r) => r.id !== next.id);
1776
- return [next, ...filtered];
1777
- }
1778
- function consentDenial(res) {
1779
- return res.ok ? "consent_required" : recordsDenialReasonOf(res.error) ?? "consent_required";
1780
- }
1781
- function withheldSentinel() {
1782
- return makeEverfurError("internalError", { retryable: false });
1783
- }
1784
- function notReady() {
1785
- return { ok: false, error: makeEverfurError("internalError", { retryable: true }) };
1786
- }
1787
- function useCapability(name) {
1788
- const { runtime } = useEverfurContext();
1789
- const store = runtime.entitlements;
1790
- const snapshot = react.useSyncExternalStore(
1791
- store.subscribe,
1792
- store.getSnapshot,
1793
- store.getSnapshot
1794
- );
1795
- return react.useMemo(
1796
- () => decideCapability(name, snapshot.decisions, { isPending: snapshot.isPending }),
1797
- [name, snapshot]
1798
- );
1799
- }
1800
- var MIN_OFFSTATE_HEIGHT = 48;
1801
- function selectView(decision) {
1802
- if (decision.isPending) return "pending";
1803
- return decision.enabled ? "enabled" : "disabled";
1804
- }
1805
- function CapabilityGate(props) {
1806
- const { capability, children, renderDisabled, renderPending, style } = props;
1807
- const decision = useCapability(capability);
1808
- const view = react.useMemo(() => selectView(decision), [decision]);
1809
- switch (view) {
1810
- case "enabled":
1811
- return children;
1812
- case "pending":
1813
- return renderPending ? renderPending() : /* @__PURE__ */ jsxRuntime.jsx(PendingSkeleton, { capability, style });
1814
- case "disabled":
1815
- return renderDisabled ? renderDisabled(decision) : /* @__PURE__ */ jsxRuntime.jsx(OffState, { decision, style });
1816
- default:
1817
- return assertNever(view);
1818
- }
1819
- }
1820
- function PendingSkeleton({
1821
- capability,
1822
- style
1823
- }) {
1824
- const theme = useEverfurTheme();
1825
- const styles = react.useMemo(() => makeStyles(theme), [theme]);
1826
- return /* @__PURE__ */ jsxRuntime.jsx(
1827
- reactNative.View,
1828
- {
1829
- style: [styles.offstate, style],
1830
- accessible: true,
1831
- accessibilityState: { busy: true },
1832
- accessibilityLabel: `Loading ${capability}`,
1833
- children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.skeletonBar })
1834
- }
1835
- );
1836
- }
1837
- function OffState({
1838
- decision,
1839
- style
1840
- }) {
1841
- const theme = useEverfurTheme();
1842
- const styles = react.useMemo(() => makeStyles(theme), [theme]);
1843
- const message = decision.disabled?.reason ?? "";
1844
- return /* @__PURE__ */ jsxRuntime.jsx(
1845
- reactNative.View,
1846
- {
1847
- style: [styles.offstate, style],
1848
- accessible: true,
1849
- accessibilityRole: "text",
1850
- accessibilityLabel: message,
1851
- children: message.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.offstateText, children: message }) : null
1852
- }
1853
- );
1854
- }
1855
- function makeStyles(theme) {
1856
- const { color, space, radius, type } = theme;
1857
- return reactNative.StyleSheet.create({
1858
- // A deliberate cream card with a soft brand hairline, never a bare grey slab.
1859
- offstate: {
1860
- minHeight: MIN_OFFSTATE_HEIGHT,
1861
- justifyContent: "center",
1862
- paddingHorizontal: space.lg,
1863
- paddingVertical: space.md,
1864
- backgroundColor: color.surfaceCream,
1865
- borderRadius: radius.md,
1866
- borderWidth: reactNative.StyleSheet.hairlineWidth,
1867
- borderColor: color.brandBorder
1868
- },
1869
- offstateText: {
1870
- fontFamily: type.family,
1871
- fontSize: type.size.body,
1872
- lineHeight: Math.round(type.size.body * type.lineHeight.normal),
1873
- color: color.text.muted
1874
- },
1875
- // A soft green shimmer bar (brand wash) that stays legible on the cream card in both light and dark,
1876
- // where the neutral `skeleton` token would collide with the dark cream surface.
1877
- skeletonBar: {
1878
- height: space.md,
1879
- borderRadius: radius.xs,
1880
- backgroundColor: color.brandSofter
1881
- }
1882
- });
1883
- }
1884
- var CLINICAL_DISCLAIMER = Object.freeze({
1885
- title: "For educational use only",
1886
- body: "Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."
1887
- });
1888
- function ClinicalDisclaimer(props) {
1889
- const theme = useEverfurTheme();
1890
- const styles = react.useMemo(() => makeStyles2(theme), [theme]);
1891
- return /* @__PURE__ */ jsxRuntime.jsxs(
1892
- reactNative.View,
1893
- {
1894
- style: [styles.container, props.style],
1895
- accessible: true,
1896
- accessibilityRole: "text",
1897
- accessibilityLabel: `${CLINICAL_DISCLAIMER.title}. ${CLINICAL_DISCLAIMER.body}`,
1898
- children: [
1899
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.title, children: CLINICAL_DISCLAIMER.title }),
1900
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.body, children: CLINICAL_DISCLAIMER.body })
1901
- ]
1902
- }
1903
- );
1904
- }
1905
- function makeStyles2(theme) {
1906
- const { color, space, type } = theme;
1907
- return reactNative.StyleSheet.create({
1908
- container: {
1909
- paddingHorizontal: space.lg,
1910
- paddingVertical: space.md,
1911
- borderTopWidth: reactNative.StyleSheet.hairlineWidth,
1912
- borderTopColor: color.borderHairlineGreen,
1913
- backgroundColor: color.surfaceCream,
1914
- gap: space.xs
1915
- },
1916
- title: {
1917
- fontFamily: type.family,
1918
- fontSize: type.size.caption,
1919
- lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
1920
- color: color.text.secondary,
1921
- fontWeight: type.weight.bold,
1922
- letterSpacing: type.letterSpacing.eyebrow
1923
- },
1924
- body: {
1925
- fontFamily: type.family,
1926
- fontSize: type.size.caption,
1927
- lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
1928
- color: color.text.muted,
1929
- fontWeight: type.weight.regular
1930
- }
1931
- });
1932
- }
1933
-
1934
- // src/rn/records/format.ts
1935
- function formatEntityValue(value, unit) {
1936
- if (value === null) return "";
1937
- return unit ? `${value} ${unit}` : value;
1938
- }
1939
- function formatShortDate(at) {
1940
- if (at === null || at.length === 0) return "";
1941
- const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(at);
1942
- if (iso !== null) {
1943
- const year = iso[1] ?? "";
1944
- const month = iso[2] ?? "";
1945
- const day = iso[3] ?? "";
1946
- return `${Number(month)}/${Number(day)}/${year.slice(2)}`;
1947
- }
1948
- const ms = Date.parse(at);
1949
- if (Number.isNaN(ms)) return at;
1950
- const date = new Date(ms);
1951
- return `${date.getUTCMonth() + 1}/${date.getUTCDate()}/${String(date.getUTCFullYear()).slice(2)}`;
1952
- }
1953
- var TINT_KEYS = ["brandSoft", "badgeBgPositive", "badgeBgCaution", "badgeBgNeutral"];
1954
- function buildRows(entities, forwardLooking, documents) {
1955
- const rows = [];
1956
- const order = [];
1957
- const byCategory = /* @__PURE__ */ new Map();
1958
- for (const entity of entities) {
1959
- const category = entity.category.trim();
1960
- if (category.length === 0) continue;
1961
- const bucket = byCategory.get(category);
1962
- if (bucket === void 0) {
1963
- order.push(category);
1964
- byCategory.set(category, [entity]);
1965
- } else {
1966
- bucket.push(entity);
1967
- }
1968
- }
1969
- for (const category of order) {
1970
- const group = byCategory.get(category) ?? [];
1971
- rows.push({
1972
- id: `cat:${category}`,
1973
- title: category,
1974
- count: group.length,
1975
- dateLabel: null,
1976
- entities: group,
1977
- detail: null
1978
- });
1979
- }
1980
- forwardLooking.forEach((item, index) => {
1981
- const title = item.title.trim();
1982
- if (title.length === 0) return;
1983
- const detail = item.detail !== null && item.detail.length > 0 ? item.detail : null;
1984
- rows.push({
1985
- id: `fwd:${index}`,
1986
- title,
1987
- count: null,
1988
- dateLabel: formatShortDate(item.dueAt),
1989
- entities: null,
1990
- detail
1991
- });
1992
- });
1993
- for (const doc of Object.values(documents)) {
1994
- const title = doc.title !== null ? doc.title.trim() : "";
1995
- if (title.length === 0) continue;
1996
- rows.push({
1997
- id: `doc:${doc.docId}`,
1998
- title,
1999
- count: null,
2000
- dateLabel: formatShortDate(doc.receivedAt),
2001
- entities: null,
2002
- detail: null
2003
- });
2004
- }
2005
- return rows;
2006
- }
2007
- function RecordNavCards({
2008
- entities,
2009
- forwardLooking,
2010
- documents,
2011
- testID
2012
- }) {
2013
- const styles = useStyles();
2014
- const rows = react.useMemo(
2015
- () => buildRows(entities, forwardLooking, documents),
2016
- [entities, forwardLooking, documents]
2017
- );
2018
- const [expanded, setExpanded] = react.useState(() => /* @__PURE__ */ new Set());
2019
- if (rows.length === 0) return null;
2020
- const toggle = (id) => {
2021
- setExpanded((current) => {
2022
- const next = new Set(current);
2023
- if (next.has(id)) next.delete(id);
2024
- else next.add(id);
2025
- return next;
2026
- });
2027
- };
2028
- return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.stack, testID, children: rows.map((row, index) => {
2029
- const tintKey = TINT_KEYS[index % TINT_KEYS.length] ?? "brandSoft";
2030
- const tint = styles.tints[tintKey];
2031
- const body = row.entities ?? (row.detail !== null ? row.detail : null);
2032
- const expandable = row.entities !== null || row.detail !== null;
2033
- const isOpen = expanded.has(row.id);
2034
- const trailing = row.count !== null ? `${row.count}` : row.dateLabel !== null ? row.dateLabel : null;
2035
- const a11y = [row.title, trailing].filter((s) => s !== null && s.length > 0).join(", ");
2036
- return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { testID: testID ? `${testID}-row-${index}` : void 0, children: [
2037
- /* @__PURE__ */ jsxRuntime.jsx(
2038
- NavCard,
2039
- {
2040
- styles,
2041
- tint,
2042
- title: row.title,
2043
- trailing,
2044
- expandable,
2045
- isOpen,
2046
- a11y,
2047
- onPress: expandable ? () => toggle(row.id) : void 0
2048
- }
2049
- ),
2050
- expandable && isOpen ? /* @__PURE__ */ jsxRuntime.jsx(NavCardBody, { styles, body }) : null
2051
- ] }, row.id);
2052
- }) });
2053
- }
2054
- function NavCard({
2055
- styles,
2056
- tint,
2057
- title,
2058
- trailing,
2059
- expandable,
2060
- isOpen,
2061
- a11y,
2062
- onPress
2063
- }) {
2064
- return /* @__PURE__ */ jsxRuntime.jsxs(
2065
- reactNative.Pressable,
2066
- {
2067
- onPress,
2068
- disabled: onPress === void 0,
2069
- accessibilityRole: "button",
2070
- accessibilityLabel: a11y,
2071
- accessibilityState: { expanded: expandable ? isOpen : void 0, disabled: onPress === void 0 },
2072
- style: [styles.card, tint],
2073
- children: [
2074
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.iconChip }),
2075
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.title, numberOfLines: 2, children: title }),
2076
- /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.trailing, children: [
2077
- trailing !== null ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.pill, children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.pillLabel, numberOfLines: 1, children: trailing }) }) : null,
2078
- expandable ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: isOpen ? styles.chevronOpen : styles.chevron }) : null
2079
- ] })
2080
- ]
2081
- }
2082
- );
2083
- }
2084
- function NavCardBody({
2085
- styles,
2086
- body
2087
- }) {
2088
- if (body === null) return null;
2089
- if (typeof body === "string") {
2090
- return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.body, children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.detailText, children: body }) });
2091
- }
2092
- return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.body, children: body.map((entity) => /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.factRow, children: [
2093
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.factLabel, numberOfLines: 2, children: entity.label }),
2094
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.factValue, numberOfLines: 2, children: formatEntityValue(entity.value, entity.unit) })
2095
- ] }, entity.key)) });
2096
- }
2097
- function useStyles() {
2098
- const theme = useEverfurTheme();
2099
- return react.useMemo(() => makeStyles3(theme), [theme]);
2100
- }
2101
- function makeStyles3(theme) {
2102
- const { color, space, radius, type } = theme;
2103
- const { size, lineHeight, weight, letterSpacing, family } = type;
2104
- const lh = (fontSize, multiplier) => Math.round(fontSize * multiplier);
2105
- const hairline = reactNative.StyleSheet.hairlineWidth;
2106
- const boldWeight = weight.bold;
2107
- const mediumWeight = weight.medium;
2108
- const rowMinHeight = space.xxl + space.xl;
2109
- const chipSize = space.xl;
2110
- const chevronSize = space.sm;
2111
- const chevronStroke = space.xs / 2;
2112
- const softShadow = {
2113
- shadowColor: color.brand,
2114
- shadowOffset: { width: 0, height: space.xs },
2115
- shadowRadius: space.sm,
2116
- shadowOpacity: 0.06,
2117
- elevation: space.xs
2118
- };
2119
- const chevronBase = {
2120
- width: chevronSize,
2121
- height: chevronSize,
2122
- borderTopWidth: chevronStroke,
2123
- borderRightWidth: chevronStroke,
2124
- borderColor: color.brand
2125
- };
2126
- return {
2127
- tints: {
2128
- brandSoft: { backgroundColor: color.brandSoft },
2129
- badgeBgPositive: { backgroundColor: color.badgeBgPositive },
2130
- badgeBgCaution: { backgroundColor: color.badgeBgCaution },
2131
- badgeBgNeutral: { backgroundColor: color.badgeBgNeutral }
2132
- },
2133
- ...reactNative.StyleSheet.create({
2134
- stack: { gap: space.sm },
2135
- card: {
2136
- flexDirection: "row",
2137
- alignItems: "center",
2138
- gap: space.md,
2139
- minHeight: rowMinHeight,
2140
- paddingHorizontal: space.lg,
2141
- paddingVertical: space.md,
2142
- borderRadius: radius.md,
2143
- borderWidth: hairline,
2144
- borderColor: color.brandBorder,
2145
- ...softShadow
2146
- },
2147
- iconChip: {
2148
- width: chipSize,
2149
- height: chipSize,
2150
- borderRadius: radius.sm,
2151
- backgroundColor: color.brand
2152
- },
2153
- title: {
2154
- flex: 1,
2155
- fontFamily: family,
2156
- fontSize: size.subtitle,
2157
- lineHeight: lh(size.subtitle, lineHeight.snug),
2158
- color: color.text.secondary,
2159
- fontWeight: boldWeight,
2160
- letterSpacing: letterSpacing.tight
2161
- },
2162
- trailing: {
2163
- flexDirection: "row",
2164
- alignItems: "center",
2165
- gap: space.sm
2166
- },
2167
- pill: {
2168
- minWidth: space.xl,
2169
- alignItems: "center",
2170
- justifyContent: "center",
2171
- paddingHorizontal: space.sm,
2172
- paddingVertical: space.xs,
2173
- borderRadius: radius.pill,
2174
- backgroundColor: color.surfaceCream,
2175
- borderWidth: hairline,
2176
- borderColor: color.brandBorder
2177
- },
2178
- pillLabel: {
2179
- fontFamily: family,
2180
- fontSize: size.caption,
2181
- lineHeight: lh(size.caption, lineHeight.tight),
2182
- color: color.text.secondary,
2183
- fontWeight: boldWeight
2184
- },
2185
- chevron: { ...chevronBase, transform: [{ rotate: "45deg" }] },
2186
- chevronOpen: { ...chevronBase, transform: [{ rotate: "135deg" }] },
2187
- body: {
2188
- gap: space.xs,
2189
- marginTop: space.xs,
2190
- paddingHorizontal: space.lg,
2191
- paddingVertical: space.md,
2192
- borderRadius: radius.sm,
2193
- backgroundColor: color.surfaceCream,
2194
- borderWidth: hairline,
2195
- borderColor: color.brandBorder
2196
- },
2197
- factRow: {
2198
- flexDirection: "row",
2199
- justifyContent: "space-between",
2200
- gap: space.md,
2201
- paddingVertical: space.xs,
2202
- borderBottomWidth: hairline,
2203
- borderBottomColor: color.borderHairlineGreen
2204
- },
2205
- factLabel: {
2206
- fontFamily: family,
2207
- fontSize: size.body,
2208
- lineHeight: lh(size.body, lineHeight.normal),
2209
- color: color.text.muted,
2210
- flexShrink: 1
2211
- },
2212
- factValue: {
2213
- fontFamily: family,
2214
- fontSize: size.body,
2215
- lineHeight: lh(size.body, lineHeight.normal),
2216
- color: color.text.primary,
2217
- fontWeight: mediumWeight,
2218
- textAlign: "right",
2219
- flexShrink: 1
2220
- },
2221
- detailText: {
2222
- fontFamily: family,
2223
- fontSize: size.body,
2224
- lineHeight: lh(size.body, lineHeight.normal),
2225
- color: color.text.secondary
2226
- }
2227
- })
2228
- };
2229
- }
2230
- function pct(value) {
2231
- return `${value}%`;
2232
- }
2233
- function isFinitePoint(point) {
2234
- return point.value !== null && Number.isFinite(point.value);
2235
- }
2236
- function pointDisplay(point) {
2237
- if (point.display !== null && point.display.length > 0) return point.display;
2238
- return point.value !== null ? String(point.value) : "";
2239
- }
2240
- function buildTrendModel(series) {
2241
- const primary = series.find((s) => s.points.some(isFinitePoint));
2242
- if (primary === void 0) return null;
2243
- const numeric = primary.points.filter(isFinitePoint);
2244
- const first = numeric[0];
2245
- if (first === void 0) return null;
2246
- const values = numeric.map((p) => p.value);
2247
- let lo = Math.min(...values);
2248
- let hi = Math.max(...values);
2249
- if (lo === hi) {
2250
- lo -= 1;
2251
- hi += 1;
2252
- }
2253
- const pad = (hi - lo) * 0.18;
2254
- const yMin = lo - pad;
2255
- const yMax = hi + pad;
2256
- const span = yMax - yMin;
2257
- const xInset = 6;
2258
- const count = numeric.length;
2259
- const points = numeric.map((p, index) => ({
2260
- xPct: count <= 1 ? 50 : xInset + index / (count - 1) * (100 - 2 * xInset),
2261
- // y in percent DOWN from the top: the max of the domain sits at 0%, the min at 100%.
2262
- yPct: (yMax - p.value) / span * 100
2263
- }));
2264
- const bandTopPct = (yMax - hi) / span * 100;
2265
- const bandBottomPct = (yMax - lo) / span * 100;
2266
- const minPoint = numeric.reduce((acc, p) => p.value < acc.value ? p : acc, first);
2267
- const maxPoint = numeric.reduce((acc, p) => p.value > acc.value ? p : acc, first);
2268
- const lastNumeric = numeric[numeric.length - 1] ?? first;
2269
- const latest = primary.points[primary.points.length - 1] ?? lastNumeric;
2270
- const latestDisplay = pointDisplay(latest);
2271
- const heroDisplay = latestDisplay.length > 0 ? latestDisplay : pointDisplay(lastNumeric);
2272
- return {
2273
- label: primary.label,
2274
- heroDisplay,
2275
- minDisplay: pointDisplay(minPoint),
2276
- maxDisplay: pointDisplay(maxPoint),
2277
- firstDate: formatShortDate(primary.points[0]?.at ?? null),
2278
- lastDate: formatShortDate(latest.at),
2279
- points,
2280
- bandTopPct,
2281
- bandBottomPct
2282
- };
2283
- }
2284
- function TrendRangeCard({ series, testID }) {
2285
- const styles = useStyles2();
2286
- const model = react.useMemo(() => buildTrendModel(series), [series]);
2287
- if (model === null) return null;
2288
- const summary = model.heroDisplay.length > 0 ? `${model.label}, ${model.heroDisplay}` : model.label;
2289
- const bandHeightPct = Math.max(0, model.bandBottomPct - model.bandTopPct);
2290
- return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.card, testID, children: [
2291
- /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { accessible: true, accessibilityRole: "text", accessibilityLabel: summary, children: [
2292
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.eyebrow, numberOfLines: 1, children: model.label }),
2293
- model.heroDisplay.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.hero, numberOfLines: 1, children: model.heroDisplay }) : null
2294
- ] }),
2295
- /* @__PURE__ */ jsxRuntime.jsxs(
2296
- reactNative.View,
2297
- {
2298
- style: styles.plot,
2299
- accessibilityElementsHidden: true,
2300
- importantForAccessibility: "no-hide-descendants",
2301
- children: [
2302
- model.points.map((p, index) => /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: [styles.guide, { left: pct(p.xPct) }] }, `g-${index}`)),
2303
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: [styles.band, { top: pct(model.bandTopPct), height: pct(bandHeightPct) }] }),
2304
- model.points.map((p, index) => {
2305
- const latest = index === model.points.length - 1;
2306
- return /* @__PURE__ */ jsxRuntime.jsx(
2307
- reactNative.View,
2308
- {
2309
- style: [styles.point, latest ? styles.pointLatest : null, { left: pct(p.xPct), top: pct(p.yPct) }]
2310
- },
2311
- `pt-${index}`
2312
- );
2313
- }),
2314
- model.maxDisplay.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: [styles.edgeLabel, { top: pct(model.bandTopPct) }], numberOfLines: 1, children: model.maxDisplay }) : null,
2315
- model.minDisplay.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: [styles.edgeLabel, { top: pct(model.bandBottomPct) }], numberOfLines: 1, children: model.minDisplay }) : null
2316
- ]
2317
- }
2318
- ),
2319
- model.firstDate.length > 0 || model.lastDate.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.dates, children: [
2320
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.dateLabel, children: model.firstDate }),
2321
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.dateLabel, children: model.lastDate })
2322
- ] }) : null
2323
- ] });
2324
- }
2325
- function useStyles2() {
2326
- const theme = useEverfurTheme();
2327
- return react.useMemo(() => makeStyles4(theme), [theme]);
2328
- }
2329
- function makeStyles4(theme) {
2330
- const { color, space, radius, type } = theme;
2331
- const { size, lineHeight, weight, letterSpacing, family } = type;
2332
- const lh = (fontSize, multiplier) => Math.round(fontSize * multiplier);
2333
- const hairline = reactNative.StyleSheet.hairlineWidth;
2334
- const boldWeight = weight.bold;
2335
- const mediumWeight = weight.medium;
2336
- const plotHeight = space.xxl * 3;
2337
- const dotSize = space.sm;
2338
- const dotOffset = -(dotSize / 2);
2339
- const bandInset = space.xs;
2340
- const softShadow = {
2341
- shadowColor: color.brand,
2342
- shadowOffset: { width: 0, height: space.xs },
2343
- shadowRadius: space.sm,
2344
- shadowOpacity: 0.08,
2345
- elevation: space.xs
2346
- };
2347
- return reactNative.StyleSheet.create({
2348
- card: {
2349
- gap: space.sm,
2350
- padding: space.lg,
2351
- borderRadius: radius.md,
2352
- backgroundColor: color.surfaceCream,
2353
- borderWidth: hairline,
2354
- borderColor: color.brandBorder,
2355
- ...softShadow
2356
- },
2357
- eyebrow: {
2358
- fontFamily: family,
2359
- fontSize: size.caption,
2360
- lineHeight: lh(size.caption, lineHeight.normal),
2361
- color: color.text.muted,
2362
- letterSpacing: letterSpacing.eyebrow,
2363
- textTransform: "uppercase"
2364
- },
2365
- hero: {
2366
- fontFamily: family,
2367
- fontSize: size.verdict,
2368
- lineHeight: lh(size.verdict, lineHeight.tight),
2369
- color: color.text.primary,
2370
- fontWeight: boldWeight,
2371
- letterSpacing: letterSpacing.tight
2372
- },
2373
- plot: {
2374
- position: "relative",
2375
- height: plotHeight,
2376
- marginTop: space.xs
2377
- },
2378
- guide: {
2379
- position: "absolute",
2380
- top: 0,
2381
- bottom: 0,
2382
- width: hairline,
2383
- backgroundColor: color.borderHairlineGreen
2384
- },
2385
- band: {
2386
- position: "absolute",
2387
- left: bandInset,
2388
- right: space.xs,
2389
- borderRadius: radius.sm,
2390
- backgroundColor: color.brandSoft
2391
- },
2392
- point: {
2393
- position: "absolute",
2394
- width: dotSize,
2395
- height: dotSize,
2396
- marginLeft: dotOffset,
2397
- marginTop: dotOffset,
2398
- borderRadius: radius.pill,
2399
- backgroundColor: color.brand,
2400
- borderWidth: hairline,
2401
- borderColor: color.surfaceCream
2402
- },
2403
- pointLatest: {
2404
- backgroundColor: color.accent,
2405
- borderColor: color.onAccent
2406
- },
2407
- edgeLabel: {
2408
- position: "absolute",
2409
- right: 0,
2410
- marginTop: -space.sm,
2411
- fontFamily: family,
2412
- fontSize: size.tiny,
2413
- lineHeight: lh(size.tiny, lineHeight.tight),
2414
- color: color.text.muted,
2415
- fontWeight: mediumWeight
2416
- },
2417
- dates: {
2418
- flexDirection: "row",
2419
- justifyContent: "space-between"
2420
- },
2421
- dateLabel: {
2422
- fontFamily: family,
2423
- fontSize: size.tiny,
2424
- lineHeight: lh(size.tiny, lineHeight.normal),
2425
- color: color.text.muted
2426
- }
2427
- });
2428
- }
2429
- var SPINNER_DELAY_MS = 300;
2430
- function EverfurRecords(props) {
2431
- const { petRef, controller, onPickDocument, consentVersion, style } = props;
2432
- return /* @__PURE__ */ jsxRuntime.jsx(CapabilityGate, { capability: "records", style, children: /* @__PURE__ */ jsxRuntime.jsx(
2433
- RecordsBody,
2434
- {
2435
- petRef,
2436
- controller,
2437
- onPickDocument,
2438
- consentVersion,
2439
- style
2440
- }
2441
- ) });
2442
- }
2443
- function RecordsBody({
2444
- petRef,
2445
- controller,
2446
- onPickDocument,
2447
- consentVersion,
2448
- style
2449
- }) {
2450
- const styles = useStyles3();
2451
- const recordsOpts = react.useMemo(
2452
- () => controller ? { petRef, controller } : { petRef },
2453
- [petRef, controller]
2454
- );
2455
- const records = useEverfurRecords(recordsOpts);
2456
- const view = records.status;
2457
- const canUpload = onPickDocument !== void 0;
2458
- const onUpload = react.useMemo(
2459
- () => makeUploadHandler(records, onPickDocument),
2460
- [records, onPickDocument]
2461
- );
2462
- const onGrant = react.useMemo(
2463
- () => makeGrantHandler(records, consentVersion),
2464
- [records, consentVersion]
2465
- );
2466
- const canGrant = react.useMemo(
2467
- () => (consentVersion ?? records.consent?.version ?? "").length > 0,
2468
- [consentVersion, records.consent]
2469
- );
2470
- return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: [styles.container, style], children: [
2471
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.body, children: renderView(view, records, onUpload, onGrant, canUpload, canGrant) }),
2472
- /* @__PURE__ */ jsxRuntime.jsx(ClinicalDisclaimer, {})
2473
- ] });
2474
- }
2475
- function renderView(view, records, onUpload, onGrant, canUpload, canGrant) {
2476
- switch (view) {
2477
- case "loading":
2478
- return /* @__PURE__ */ jsxRuntime.jsx(LoadingState, {});
2479
- case "empty":
2480
- return /* @__PURE__ */ jsxRuntime.jsx(EmptyState, { onUpload, canUpload });
2481
- case "error":
2482
- return renderErrorFamily(records, onGrant, canGrant);
2483
- case "populated":
2484
- return /* @__PURE__ */ jsxRuntime.jsx(PopulatedState, { record: records.record, activeRequest: records.activeRequest });
2485
- default:
2486
- return assertNever(view);
2487
- }
2488
- }
2489
- function renderErrorFamily(records, onGrant, canGrant) {
2490
- if (records.denialReason === "consent_required") {
2491
- return canGrant ? /* @__PURE__ */ jsxRuntime.jsx(ConsentRequiredState, { onGrant }) : /* @__PURE__ */ jsxRuntime.jsx(ConsentUnavailableState, {});
2492
- }
2493
- if (records.denialReason === "entitlement") {
2494
- return /* @__PURE__ */ jsxRuntime.jsx(ErrorState, { error: makeEverfurError("accessDenied"), onRetry: records.refresh });
2495
- }
2496
- if (records.denialReason === "session_required") {
2497
- return /* @__PURE__ */ jsxRuntime.jsx(SessionRequiredState, {});
2498
- }
2499
- if (records.withheld) {
2500
- return /* @__PURE__ */ jsxRuntime.jsx(WithheldState, {});
2501
- }
2502
- const error = records.error;
2503
- if (error === null) return /* @__PURE__ */ jsxRuntime.jsx(WithheldState, {});
2504
- return /* @__PURE__ */ jsxRuntime.jsx(ErrorState, { error, onRetry: records.refresh });
2505
- }
2506
- function makeUploadHandler(records, onPickDocument) {
2507
- return () => {
2508
- if (!onPickDocument) return;
2509
- void (async () => {
2510
- const file = await onPickDocument();
2511
- if (!file) return;
2512
- const key = `records-upload-${Date.now().toString(36)}`;
2513
- const created = await records.createRequest(key);
2514
- if (!created.ok) return;
2515
- await records.uploadDocument(created.value.id, file);
2516
- })();
2517
- };
2518
- }
2519
- function makeGrantHandler(records, consentVersion) {
2520
- return () => {
2521
- const version = consentVersion ?? records.consent?.version ?? "";
2522
- if (version.length === 0) return;
2523
- const key = `records-consent-${Date.now().toString(36)}`;
2524
- void records.grantConsent(version, key);
2525
- };
2526
- }
2527
- function LoadingState() {
2528
- const styles = useStyles3();
2529
- const [visible, setVisible] = react.useState(false);
2530
- react.useEffect(() => {
2531
- const id = setTimeout(() => setVisible(true), SPINNER_DELAY_MS);
2532
- return () => clearTimeout(id);
2533
- }, []);
2534
- return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.centered, accessible: true, accessibilityState: { busy: true }, accessibilityLabel: "Loading", children: visible ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.ActivityIndicator, {}) : null });
2535
- }
2536
- function EmptyState({ onUpload, canUpload }) {
2537
- const styles = useStyles3();
2538
- return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.centered, accessible: true, accessibilityRole: "summary", accessibilityLabel: "No records yet", children: [
2539
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.emptyGlyph }),
2540
- /* @__PURE__ */ jsxRuntime.jsx(
2541
- reactNative.Pressable,
2542
- {
2543
- onPress: canUpload ? onUpload : void 0,
2544
- disabled: !canUpload,
2545
- accessibilityRole: "button",
2546
- accessibilityLabel: "Upload records",
2547
- accessibilityState: { disabled: !canUpload },
2548
- style: canUpload ? styles.primaryButton : styles.disabledButton,
2549
- children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: canUpload ? styles.primaryLabel : styles.disabledLabel, children: "Upload records" })
2550
- }
2551
- )
2552
- ] });
2553
- }
2554
- function ConsentRequiredState({ onGrant }) {
2555
- const styles = useStyles3();
2556
- return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.centered, accessible: true, accessibilityRole: "alert", accessibilityLabel: "Consent required", children: /* @__PURE__ */ jsxRuntime.jsx(
2557
- reactNative.Pressable,
2558
- {
2559
- onPress: onGrant,
2560
- accessibilityRole: "button",
2561
- accessibilityLabel: "Allow",
2562
- style: styles.primaryButton,
2563
- children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.primaryLabel, children: "Allow" })
2564
- }
2565
- ) });
2566
- }
2567
- function AlertState({ label, glyph }) {
2568
- const styles = useStyles3();
2569
- react.useEffect(() => {
2570
- reactNative.AccessibilityInfo.announceForAccessibility?.(label);
2571
- }, [label]);
2572
- return /* @__PURE__ */ jsxRuntime.jsxs(
2573
- reactNative.View,
2574
- {
2575
- style: styles.centered,
2576
- accessible: true,
2577
- accessibilityRole: "alert",
2578
- accessibilityLiveRegion: "assertive",
2579
- accessibilityLabel: label,
2580
- children: [
2581
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: glyph === "withheld" ? styles.withheldGlyph : styles.emptyGlyph }),
2582
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.errorText, children: label })
2583
- ]
2584
- }
2585
- );
2586
- }
2587
- function ConsentUnavailableState() {
2588
- return /* @__PURE__ */ jsxRuntime.jsx(AlertState, { label: "Consent required", glyph: "empty" });
2589
- }
2590
- function SessionRequiredState() {
2591
- return /* @__PURE__ */ jsxRuntime.jsx(AlertState, { label: "Sign in required", glyph: "empty" });
2592
- }
2593
- function WithheldState() {
2594
- return /* @__PURE__ */ jsxRuntime.jsx(AlertState, { label: "Record unavailable", glyph: "withheld" });
2595
- }
2596
- function ErrorState({ error, onRetry }) {
2597
- const styles = useStyles3();
2598
- react.useEffect(() => {
2599
- reactNative.AccessibilityInfo.announceForAccessibility?.(error.displayMessage);
2600
- }, [error.displayMessage]);
2601
- return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.centered, accessible: true, accessibilityRole: "alert", accessibilityLiveRegion: "assertive", children: [
2602
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.errorText, children: error.displayMessage }),
2603
- error.retryable ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Pressable, { onPress: onRetry, accessibilityRole: "button", accessibilityLabel: "Try again", style: styles.primaryButton, children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.primaryLabel, children: "Try again" }) }) : null
2604
- ] });
2605
- }
2606
- function PopulatedState({
2607
- record,
2608
- activeRequest
2609
- }) {
2610
- const styles = useStyles3();
2611
- const hasTimeline = activeRequest !== null && (activeRequest.statusLabel.length > 0 || activeRequest.heldItemCount > 0);
2612
- const hasRecord = record !== null && !record.isEmpty;
2613
- if (!hasTimeline && !hasRecord) return /* @__PURE__ */ jsxRuntime.jsx(LoadingState, {});
2614
- return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.ScrollView, { style: styles.list, contentContainerStyle: styles.listContent, accessibilityLabel: "Records", children: [
2615
- hasTimeline && activeRequest ? /* @__PURE__ */ jsxRuntime.jsx(RequestTimeline, { request: activeRequest }) : null,
2616
- record && !record.isEmpty ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2617
- /* @__PURE__ */ jsxRuntime.jsx(TrendRangeCard, { series: record.entitySeries, testID: "records-trend-card" }),
2618
- /* @__PURE__ */ jsxRuntime.jsx(
2619
- RecordNavCards,
2620
- {
2621
- entities: record.entities,
2622
- forwardLooking: record.forwardLooking,
2623
- documents: record.documents,
2624
- testID: "records-nav-cards"
2625
- }
2626
- ),
2627
- /* @__PURE__ */ jsxRuntime.jsx(RecordDetails, { record })
2628
- ] }) : null
2629
- ] });
2630
- }
2631
- function RequestTimeline({ request }) {
2632
- const styles = useStyles3();
2633
- const hasLabel = request.statusLabel.length > 0;
2634
- const hasHeld = request.heldItemCount > 0;
2635
- if (!hasLabel && !hasHeld) return null;
2636
- return /* @__PURE__ */ jsxRuntime.jsxs(
2637
- reactNative.View,
2638
- {
2639
- style: styles.timeline,
2640
- accessible: true,
2641
- accessibilityRole: "text",
2642
- ...hasLabel ? { accessibilityLabel: request.statusLabel } : {},
2643
- children: [
2644
- hasLabel ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.timelineLabel, children: request.statusLabel }) : null,
2645
- hasHeld ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.timelineMeta, children: `${request.heldItemCount} being reviewed` }) : null
2646
- ]
2647
- }
2648
- );
2649
- }
2650
- function RecordDetails({ record }) {
2651
- const styles = useStyles3();
2652
- const uncategorized = record.entities.filter((entity) => entity.category.trim().length === 0);
2653
- const hasDetails = record.identity.length > 0 || uncategorized.length > 0;
2654
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2655
- hasDetails ? /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.recordBlock, children: [
2656
- record.identity.map((field) => /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.row, children: [
2657
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.rowLabel, children: field.label }),
2658
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.rowValue, children: field.value })
2659
- ] }, field.label)),
2660
- uncategorized.map((entity) => /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.row, children: [
2661
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.rowLabel, children: entity.label }),
2662
- /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.rowValue, children: formatEntityValue(entity.value, entity.unit) })
2663
- ] }, entity.key))
2664
- ] }) : null,
2665
- record.disclaimer.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.disclaimer, children: record.disclaimer }) : null
2666
- ] });
2667
- }
2668
- function useStyles3() {
2669
- const theme = useEverfurTheme();
2670
- return react.useMemo(() => makeStyles5(theme), [theme]);
2671
- }
2672
- function makeStyles5(theme) {
2673
- const { color, space, radius, type } = theme;
2674
- const { size, lineHeight, weight, letterSpacing, family } = type;
2675
- const lh = (fontSize, multiplier) => Math.round(fontSize * multiplier);
2676
- const hairline = reactNative.StyleSheet.hairlineWidth;
2677
- const boldWeight = weight.bold;
2678
- const mediumWeight = weight.medium;
2679
- const minSurface = space.xxl * 3 + space.xl;
2680
- const touchTarget = space.xxl + space.md;
2681
- const glyphSize = space.xxl + space.sm;
2682
- const errorColor = theme.brightness === "dark" ? color.errorRed : color.danger;
2683
- const softShadow = {
2684
- shadowColor: color.brand,
2685
- shadowOffset: { width: 0, height: space.xs },
2686
- shadowRadius: space.sm,
2687
- shadowOpacity: 0.08,
2688
- elevation: space.xs
2689
- };
2690
- return reactNative.StyleSheet.create({
2691
- container: { flex: 1, minHeight: minSurface, backgroundColor: color.background },
2692
- body: { flex: 1 },
2693
- centered: {
2694
- minHeight: minSurface,
2695
- flexGrow: 1,
2696
- alignItems: "center",
2697
- justifyContent: "center",
2698
- padding: space.xl,
2699
- gap: space.lg
2700
- },
2701
- // Branded empty placeholder: a soft-brand disc ringed in the hairline brand border.
2702
- emptyGlyph: {
2703
- width: glyphSize,
2704
- height: glyphSize,
2705
- borderRadius: radius.lg,
2706
- backgroundColor: color.brandSoft,
2707
- borderWidth: hairline,
2708
- borderColor: color.brandBorder
2709
- },
2710
- // Withheld / fail-closed glyph: a caution wash ringed in the caution accent.
2711
- withheldGlyph: {
2712
- width: glyphSize,
2713
- height: glyphSize,
2714
- borderRadius: radius.sm,
2715
- backgroundColor: color.badgeBgCaution,
2716
- borderWidth: hairline,
2717
- borderColor: color.cautionAccent
2718
- },
2719
- errorText: {
2720
- fontFamily: family,
2721
- fontSize: size.subtitle,
2722
- lineHeight: lh(size.subtitle, lineHeight.snug),
2723
- color: errorColor,
2724
- textAlign: "center",
2725
- marginBottom: space.md
2726
- },
2727
- // Primary CTA: brand fill, WCAG onPrimary foreground, pill radius, soft brand shadow.
2728
- primaryButton: {
2729
- minHeight: touchTarget,
2730
- minWidth: touchTarget,
2731
- alignItems: "center",
2732
- justifyContent: "center",
2733
- paddingHorizontal: space.xl,
2734
- paddingVertical: space.md,
2735
- borderRadius: radius.pill,
2736
- backgroundColor: color.primary,
2737
- ...softShadow
2738
- },
2739
- primaryLabel: {
2740
- fontFamily: family,
2741
- color: color.onPrimary,
2742
- fontSize: size.body,
2743
- fontWeight: boldWeight,
2744
- letterSpacing: letterSpacing.tight
2745
- },
2746
- disabledButton: {
2747
- minHeight: touchTarget,
2748
- minWidth: touchTarget,
2749
- alignItems: "center",
2750
- justifyContent: "center",
2751
- paddingHorizontal: space.xl,
2752
- paddingVertical: space.md,
2753
- borderRadius: radius.pill,
2754
- backgroundColor: color.surfaceSubtle,
2755
- borderWidth: hairline,
2756
- borderColor: color.brandBorder
2757
- },
2758
- disabledLabel: {
2759
- fontFamily: family,
2760
- color: color.text.muted,
2761
- fontSize: size.body,
2762
- fontWeight: boldWeight,
2763
- letterSpacing: letterSpacing.tight
2764
- },
2765
- list: { flex: 1 },
2766
- listContent: { padding: space.lg, gap: space.md },
2767
- // Request timeline: a cream card with the brand hairline border + soft depth.
2768
- timeline: {
2769
- paddingVertical: space.md,
2770
- paddingHorizontal: space.lg,
2771
- borderRadius: radius.md,
2772
- backgroundColor: color.surfaceCream,
2773
- borderWidth: hairline,
2774
- borderColor: color.brandBorder,
2775
- gap: space.xs,
2776
- ...softShadow
2777
- },
2778
- timelineLabel: {
2779
- fontFamily: family,
2780
- fontSize: size.subtitle,
2781
- lineHeight: lh(size.subtitle, lineHeight.snug),
2782
- color: color.text.secondary,
2783
- fontWeight: boldWeight,
2784
- letterSpacing: letterSpacing.tight
2785
- },
2786
- timelineMeta: {
2787
- fontFamily: family,
2788
- fontSize: size.bodyTight,
2789
- lineHeight: lh(size.bodyTight, lineHeight.normal),
2790
- color: color.text.muted
2791
- },
2792
- // Parsed record: a cream card of hairline-divided label/value rows.
2793
- recordBlock: {
2794
- gap: space.sm,
2795
- padding: space.md,
2796
- borderRadius: radius.md,
2797
- backgroundColor: color.surfaceCream,
2798
- borderWidth: hairline,
2799
- borderColor: color.brandBorder,
2800
- ...softShadow
2801
- },
2802
- row: {
2803
- flexDirection: "row",
2804
- justifyContent: "space-between",
2805
- gap: space.md,
2806
- paddingVertical: space.xs,
2807
- borderBottomWidth: hairline,
2808
- borderBottomColor: color.borderHairlineGreen
2809
- },
2810
- rowLabel: {
2811
- fontFamily: family,
2812
- fontSize: size.body,
2813
- lineHeight: lh(size.body, lineHeight.normal),
2814
- color: color.text.muted,
2815
- flexShrink: 1
2816
- },
2817
- rowValue: {
2818
- fontFamily: family,
2819
- fontSize: size.body,
2820
- lineHeight: lh(size.body, lineHeight.normal),
2821
- color: color.text.primary,
2822
- fontWeight: mediumWeight,
2823
- textAlign: "right",
2824
- flexShrink: 1
2825
- },
2826
- disclaimer: {
2827
- fontFamily: family,
2828
- fontSize: size.caption,
2829
- lineHeight: lh(size.caption, lineHeight.normal),
2830
- color: color.text.muted,
2831
- marginTop: space.md
2832
- }
2833
- });
2834
- }
2835
-
2836
- exports.EverfurRecords = EverfurRecords;
2837
- exports.RECORDS_TERMINAL = RECORDS_TERMINAL;
2838
- exports.isTerminalStatus = isTerminalStatus;
2839
- exports.recordsDenialReasonOf = recordsDenialReasonOf;
2840
- exports.useEverfurRecords = useEverfurRecords;
3
+ `):null,Ve=h.length>0&&h.every(F=>!gn(F)||Pm.test(F.email.trim())),ie=h.length>=Nr,we=!!(v&&ye&&l.trim()&&e.petName.trim()&&Ve&&o)&&k===null,vt=i(async()=>{if(Z.current)return;let F=++oe.current;D(true);try{let Re=await t.searchClinics({query:c.trim(),limit:100});if(!G.current||F!==oe.current)return;Re.ok?(u(Re.value.clinics),b(null)):b(Re.error);}catch{G.current&&F===oe.current&&b(q("internalError"));}finally{G.current&&F===oe.current&&D(false);}},"search"),Xe=i(F=>{Z.current||ie||k!==null||F.clinic!==null&&h.some(Re=>Re.clinic?.id===F.clinic?.id)||(A(),R(Re=>[...Re,{...F,key:H.current(),idempotencyKey:H.current()}]),u([]),a(""));},"add"),Vt=i(async()=>{if(Z.current||k!==null||!we||!v||!ye||!o)return;Z.current=true;let F=Ee.current,Re=i(()=>G.current&&Ee.current===F,"current");x(true),b(null);try{if(C.current===null){T.current=new AbortController;let xt=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:M.join(", "),authorizationVersion:v.authorizationVersion,scopeText:ye,signal:T.current.signal});if(!Re()||xt===null)return;if(C.current=xt,xt.signaturePngBase64!==void 0&&n!==void 0){let Vd=await n(xt.signaturePngBase64,T.current.signal);if(!Re())return;C.current={signatureId:Vd.signatureId};}}let Ft=C.current,Jr=h.map(xt=>({...xt.clinic!==null&&(!gn(xt)||xt.clinic.emailStatus==="none")?{clinicId:xt.clinic.id}:{clinicFreeText:bn(xt)},...gn(xt)?{clinicEmail:xt.email.trim().toLowerCase()}:{},...Ft.signatureId!==void 0?{signatureId:Ft.signatureId}:{signaturePngBase64:Ft.signaturePngBase64},idempotencyKey:xt.idempotencyKey})),Zr=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:v.authorizationVersion,clinics:Jr});if(!Re())return;if(!Zr.ok){b(Zr.error);return}S(Zr.value),e.onCreated?.(Zr.value),qt(Zr.value.requestGroupId,F);}catch{Re()&&b(q("internalError"));}finally{Z.current=false,Re()&&x(false);}},"submit"),qt=i(async(F,Re)=>{try{let Ft=await t.getRequestGroup(F);if(!G.current||Ee.current!==Re)return;Ft.ok&&Ft.value.petRef===e.petRef&&Y(Ft.value);}catch{}},"loadGroup"),Se=i(async()=>{k===null||Z.current||await qt(k.requestGroupId,Ee.current);},"refreshGroup");return {ownerName:l,query:c,clinics:d,copy:v,scopeText:ye,error:g,busy:w,searching:E,drafts:h,outcome:k,group:I,ready:we,atCap:ie,recent:d.length===0?p.filter(F=>!h.some(Re=>Re.clinic?.id===F.id)):[],setOwnerName(F){Z.current||(A(),s(F));},setQuery(F){Z.current||(oe.current+=1,D(false),u([]),a(F));},search:vt,addClinic(F){Xe({clinic:F,freeText:null,email:""});},addFreeText(){let F=c.trim();F.length!==0&&Xe({clinic:null,freeText:F,email:""});},setDraftEmail(F,Re){Z.current||(A(),R(Ft=>Ft.map(Jr=>Jr.key===F?{...Jr,email:Re}:Jr)));},removeDraft(F){Z.current||k!==null||(A(),R(Re=>Re.filter(Ft=>Ft.key!==F)));},submit:Vt,refreshGroup:Se,retryCopy(){b(null),$(F=>F+1);}}}i(Ll,"useClinicBatchForm");function Vl(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(Vl,"trustedSignatureUploadUrl");var Im="Signature upload failed",Dm=3e4;function Am(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(Am,"base64ByteLength");async function Di(e,t,r,o){let n=i(()=>new Error(Im),"fail"),l=Am(e);if(l<=0||r.aborted)throw n();let s=await t.initiateSignatureUpload(l);if(!s.ok||r.aborted||!Vl(s.value.uploadUrl))throw n();let c=new FormData;for(let[f,h]of Object.entries(s.value.uploadFields))c.append(f,h);c.append("file",{uri:`data:image/png;base64,${e}`,name:"signature.png",type:"image/png"});let a=new AbortController,d=i(()=>a.abort(),"onAbort");r.addEventListener("abort",d,{once:true});let u=setTimeout(d,Dm);try{if(!(await(o??fetch)(s.value.uploadUrl,{method:"POST",body:c,credentials:"omit",signal:a.signal})).ok||r.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),r.removeEventListener("abort",d);}let p=await t.completeSignatureUpload(s.value.uploadId);if(!p.ok||r.aborted)throw n();return {signatureId:p.value}}i(Di,"registerRnSignature");var jr=Object.freeze({width:360,height:120});function Nl(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(Nl,"blank");function Ml(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 s=t+l,c=r+n;s<0||c<0||s>=e.width||c>=e.height||(e.pixels[c*e.width+s]=1);}}i(Ml,"stamp");var Om=16384;function Lm(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(Lm,"padPoint");function Vm(e,t,r,o,n){let[l,s]=t,[c,a]=r,d=Math.abs(c-l),u=-Math.abs(a-s),p=l<c?1:-1,f=s<a?1:-1,h=d+u,R=0;for(;R<n&&(Ml(e,l,s,o),R+=1,!(l===c&&s===a));){let v=2*h;v>=u&&(h+=u,l+=p),v<=d&&(h+=d,s+=f);}return R}i(Vm,"line");function Bl(e,t=1){let r=Nl(jr.width,jr.height);for(let o of e){let n=[];for(let s of o){let c=Lm(s,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[s,c]=n[0];Ml(r,s,c,t);continue}let l=Om;for(let s=1;s<n.length&&l>0;s+=1)l-=Vm(r,n[s-1],n[s],t,l);}return r}i(Bl,"rasterizeStrokes");var qm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",Fm="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",zm="0123456789abcdefghijklmnopqrstuv",Fi=5,zi=7,Ai=Fi+1;function Nm(e,t){let r=qm.indexOf(e);return r<0?0:zm.indexOf(Fm.charAt(r*zi+t))}i(Nm,"glyphRow");function Hl(e){let t=Nl(jr.width,jr.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*Ai-1)*n>t.width-8;)n-=1;let l=(o.length*Ai-1)*n,s=Math.max(0,Math.floor((t.width-l)/2)),c=Math.floor((t.height-zi*n)/2);return o.forEach((a,d)=>{let u=s+d*Ai*n;for(let p=0;p<zi;p+=1){let f=Nm(a,p);for(let h=0;h<Fi;h+=1)if((f>>Fi-1-h&1)!==0)for(let R=0;R<n;R+=1)for(let v=0;v<n;v+=1){let y=u+h*n+v,g=c+p*n+R;y<t.width&&g<t.height&&(t.pixels[g*t.width+y]=1);}}}),t}i(Hl,"rasterizeTypedName");var Hi=class Hi{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(Hi,"BitWriter");var Ni=Hi;function Mi(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(Mi,"writeLiteral");var Oi=[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],ql=[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],Li=[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],Fl=[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 Mm(e,t,r){let o=Oi.length-1;for(;Oi[o]>t;)o-=1;Mi(e,257+o),ql[o]>0&&e.writeBits(t-Oi[o],ql[o]);let n=Li.length-1;for(;Li[n]>r;)n-=1;e.writeCode(n,5),Fl[n]>0&&e.writeBits(r-Li[n],Fl[n]);}i(Mm,"writeMatch");var Bm=32768,Vi=3,Hm=258,zl=15,Um=64;function jm(e){let t=new Ni;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<zl).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<zl)-1,"hashAt"),l=i(c=>{if(c+Vi>e.length)return;let a=n(c);o[c]=r[a],r[a]=c;},"insert"),s=0;for(;s<e.length;){let c=0,a=0;if(s+Vi<=e.length){let d=r[n(s)],u=0,p=Math.min(Hm,e.length-s);for(;d>=0&&u<Um&&s-d<=Bm;){let f=0;for(;f<p&&e[d+f]===e[s+f];)f+=1;if(f>c&&(c=f,a=s-d,f===p))break;d=o[d],u+=1;}}if(c>=Vi){Mm(t,c,a);for(let d=0;d<c;d+=1)l(s+d);s+=c;}else Mi(t,e[s]),l(s),s+=1;}return Mi(t,256),t.finish()}i(jm,"deflate");function $m(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($m,"adler32");var so=null;function Wm(e){if(so===null){so=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;so[r]=o>>>0;}}let t=4294967295;for(let r of e)t=so[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(Wm,"crc32");function hn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(hn,"u32");function qi(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),[...hn(t.length),...o,...hn(Wm(o))]}i(qi,"chunk");var lo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Gm(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,s=o<<16|n<<8|l;t+=lo.charAt(s>>18&63)+lo.charAt(s>>12&63),t+=r+1<e.length?lo.charAt(s>>6&63):"=",t+=r+2<e.length?lo.charAt(s&63):"=";}return t}i(Gm,"toBase64");function Bi(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 p=u*n;l[p]=0,l.fill(255,p+1,p+n);for(let f=0;f<t;f+=1)if(o[u*t+f]===1){let h=p+1+(f>>3);l[h]=l[h]&~(128>>(f&7));}}let s=jm(l),c=new Uint8Array(2+s.length+4);c[0]=120,c[1]=1,c.set(s,2),c.set(hn($m(l)),2+s.length);let a=Uint8Array.from([...hn(t),...hn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...qi("IHDR",a),...qi("IDAT",c),...qi("IEND",new Uint8Array(0))]);return Gm(d)}i(Bi,"encodeSignaturePng");var Xm=8,$l=2,Rn=3;function Lr({onChange:e,disabled:t=false}){let r=Jm(),[o,n]=react.useState("draw"),[l,s]=react.useState(""),[c,a]=react.useState([]),[d,u]=react.useState(0),p=react.useRef([]),f=react.useRef(null),h=d>0?jr.width/d:1,R=react.useRef(h);R.current=h;let v=react.useRef(t);v.current=t,react.useEffect(()=>{if(o==="type"){jn(e,l.trim().length>0?Bi(Hl(l)):null);return}let E=c.reduce((D,k)=>D+k.length,0);jn(e,E>=Xm?Bi(Bl(c)):null);},[o,l,c,e]);let y=i(E=>{let{locationX:D,locationY:k}=E.nativeEvent;return [D*R.current,k*R.current]},"point"),g=react.useMemo(()=>reactNative.PanResponder.create({onStartShouldSetPanResponder:i(()=>!v.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!v.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(E=>{p.current=[y(E)];},"onPanResponderGrant"),onPanResponderMove:i(E=>{let D=y(E),k=p.current[p.current.length-1];k!==void 0&&Math.abs(k[0]-D[0])<$l&&Math.abs(k[1]-D[1])<$l||(p.current=[...p.current,D],a(S=>[...S.filter(I=>I!==f.current),f.current=p.current]));},"onPanResponderMove"),onPanResponderRelease:i(()=>{let E=p.current;p.current=[],a(D=>[...D.filter(k=>k!==f.current),E]),f.current=null;},"onPanResponderRelease"),onPanResponderTerminate:i(()=>{let E=p.current;p.current=[],a(D=>[...D.filter(k=>k!==f.current),E]),f.current=null;},"onPanResponderTerminate")}),[]),b=react.useCallback(()=>{v.current||(p.current=[],f.current=null,a([]),s(""));},[]),w=react.useCallback(()=>{b(),n(E=>E==="draw"?"type":"draw");},[b]),x=i(E=>u(E.nativeEvent.layout.width),"onLayout");return jsxRuntime.jsxs(reactNative.View,{style:r.container,testID:"records-signature-pad",children:[jsxRuntime.jsx(m,{style:r.label,children:o==="draw"?U.draw:U.type}),o==="type"?jsxRuntime.jsx(qe,{accessibilityLabel:U.type,style:r.input,value:l,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:E=>{v.current||s(E);}}):null,jsxRuntime.jsx(reactNative.View,{onLayout:x,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:U.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?g.panHandlers:{},children:o==="type"?jsxRuntime.jsx(m,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:l.trim()}):c.map((E,D)=>E.map(([k,S],I)=>jsxRuntime.jsx(reactNative.View,{pointerEvents:"none",style:[r.dot,{left:k/h-Rn/2,top:S/h-Rn/2}]},`${D}-${I}`)))}),jsxRuntime.jsxs(reactNative.View,{style:r.actions,children:[jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:U.clear,accessibilityState:{disabled:t},disabled:t,onPress:b,style:r.button,children:jsxRuntime.jsx(m,{style:r.buttonLabel,children:U.clear})}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?U.toType:U.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:w,style:r.button,children:jsxRuntime.jsx(m,{style:r.buttonLabel,children:o==="draw"?U.toType:U.toDraw})})]})]})}i(Lr,"SignaturePad");function Jm(){let e=L();return react.useMemo(()=>Zm(e),[e])}i(Jm,"useStyles");function Zm(e){let{color:t,space:r,radius:o,type:n}=e;return reactNative.StyleSheet.create({container:{gap:r.sm},label:{..._(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,..._(e,"regular"),fontSize:n.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,overflow:"hidden",justifyContent:"center"},dot:{position:"absolute",width:Rn,height:Rn,borderRadius:Rn/2,backgroundColor:"#111111"},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:"#111111",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:{..._(e,"regular"),fontSize:n.size.body,color:t.text.primary}})}i(Zm,"makeStyles");function ji(e){let{userRef:t,scopeEpoch:r}=ke();return jsxRuntime.jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,U.cancel),children:t===null?jsxRuntime.jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsxRuntime.jsx(ry,{...Fe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(ji,"EverfurClinicRequestBatch");function ry(e){let t=Nt(),r=mi(),o=e.controller??t,[n,l]=react.useState(null),s=react.useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=react.useCallback((y,g)=>Di(y,o,g),[o]),a=Ll(e,o,e.batchClient??r,e.onCaptureSignature??s,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=L(),p={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},f={color:u.color.text.primary,fontSize:u.type.size.body},h={color:u.color.text.muted,fontSize:u.type.size.bodyTight},R=i((y,g,b=false,w=y)=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:w,accessibilityState:{disabled:b},disabled:b,onPress:g,style:[p,{justifyContent:"center",opacity:b?.5:1}],children:jsxRuntime.jsx(m,{style:f,children:y})}),"button"),v=a.busy?Oe.sending:a.drafts.length===0?Oe.addToContinue:a.error?Oe.tryAgain:Oe.send(a.drafts.length);return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:a.outcome?Oe.resultTitle:Oe.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(m,{accessibilityRole:"header",style:[f,{..._(u,"bold"),fontSize:u.type.size.heading}],children:a.outcome?Oe.resultTitle:Oe.title}),jsxRuntime.jsx(m,{style:f,children:e.petName}),a.outcome?jsxRuntime.jsxs(reactNative.View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsxRuntime.jsx(m,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:f,children:a.outcome.createdCount===0?Oe.allFailed:a.outcome.failedCount>0?Oe.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):Oe.allSent(a.outcome.createdCount)}),jsxRuntime.jsx(m,{accessibilityRole:"header",style:f,children:Oe.perClinic}),a.outcome.results.map((y,g)=>{let b=y.request?.clinicName??a.drafts[g]?.clinic?.name??y.clinicFreeText??"",w=y.created?Oe.sent:Oe.notSent;return jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${b}. ${w}.`,y.created?y.request?.statusLabel:y.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${y.created?"created":"failed"}`,children:[jsxRuntime.jsx(m,{style:f,children:b}),jsxRuntime.jsx(m,{style:h,children:w}),y.created&&y.request?.statusLabel?jsxRuntime.jsx(m,{style:h,children:y.request.statusLabel}):null,!y.created&&y.failureReason?jsxRuntime.jsx(m,{style:h,children:y.failureReason}):null]},y.idempotencyKey)}),a.group?jsxRuntime.jsx(m,{accessibilityLiveRegion:"polite",style:f,children:Oe.responded(a.group.responded,a.group.total)}):null,a.group?.members.map(y=>y.statusLabel?jsxRuntime.jsx(m,{style:h,children:[y.clinicName,y.statusLabel].filter(Boolean).join(": ")},y.id):null)]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(m,{style:f,children:U.ownerName}),jsxRuntime.jsx(qe,{accessibilityLabel:U.ownerName,style:p,value:a.ownerName,maxLength:200,editable:!a.busy,autoComplete:"name",onChangeText:a.setOwnerName}),a.drafts.map(y=>jsxRuntime.jsxs(reactNative.View,{style:{gap:u.space.xs},testID:`records-batch-draft-${y.key}`,children:[jsxRuntime.jsx(m,{style:f,children:bn(y)}),gn(y)?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(m,{style:h,children:y.email.trim()?y.email:Oe.emailToAdd}),jsxRuntime.jsx(qe,{accessibilityLabel:U.email,style:p,value:y.email,placeholder:U.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!a.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:g=>a.setDraftEmail(y.key,g)})]}):null,R(Oe.remove(bn(y)),()=>a.removeDraft(y.key),a.busy)]},y.key)),jsxRuntime.jsx(m,{style:f,children:a.atCap?Oe.atCap:Oe.addClinic}),!a.atCap&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(qe,{accessibilityLabel:U.clinic,style:p,value:a.query,placeholder:U.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!a.busy,onChangeText:a.setQuery}),R(U.search,()=>{a.search();},a.busy||a.searching||a.query.trim().length<2),a.query.trim().length>0&&a.clinics.length===0&&!a.searching&&R(Oe.addClinic,a.addFreeText,a.busy),a.searching&&jsxRuntime.jsx(m,{accessibilityLiveRegion:"polite",style:f,children:ce.loading}),a.recent.length>0&&jsxRuntime.jsx(m,{accessibilityRole:"header",style:f,children:U.recentlyUsed}),a.recent.map(y=>jsxRuntime.jsx(reactNative.View,{children:R([y.name,y.address,y.phone].filter(Boolean).join(", "),()=>a.addClinic(y),a.busy)},`recent-${y.id}`)),a.clinics.map(y=>jsxRuntime.jsx(reactNative.View,{children:R([y.name,y.address,y.phone].filter(Boolean).join(", "),()=>a.addClinic(y),a.busy)},y.id))]}),jsxRuntime.jsx(m,{accessibilityRole:"header",style:f,children:U.scopeHeading}),a.copy?jsxRuntime.jsx(m,{style:f,children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??q("internalError").displayMessage:ce.consentRequired}):!a.error&&jsxRuntime.jsx(m,{accessibilityLiveRegion:"polite",style:f,children:ce.loading}),!e.onCaptureSignature&&jsxRuntime.jsx(Lr,{onChange:l,disabled:a.busy}),!d&&jsxRuntime.jsx(m,{accessibilityRole:"alert",style:f,children:U.missingSignature}),a.error&&jsxRuntime.jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:f,children:a.error.displayMessage}),!a.copy&&a.error&&R(ce.retry,a.retryCopy),R(v,()=>{a.submit();},a.busy||!a.ready||!d,Oe.sendA11y(a.drafts.length))]}),e.onClose&&R(U.cancel,e.onClose,a.busy),jsxRuntime.jsx(Me,{})]})}i(ry,"BatchBody");var se=Object.freeze({scopeHeading:"What you\u2019re authorizing",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,t)=>`I authorize ${t} to release ${He(e)}\u2019s records to Everfur.`,"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:"Confirm your request",titleDirectory:"Authorize records release",noEmailNote:i((e,t)=>`We don\u2019t have an email on file for ${t}. Add it so we can request ${He(e)}\u2019s records.`,"noEmailNote"),emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",emailRequired:"Enter the clinic email before sending the request.",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:"Authorize & send request",submitting:"Submitting\u2026",submitA11y:"Submit authorization"});var ny="value_text",Kl=64,Ql=512;function Xl(e){return e!==null&&e.httpStatus===409&&!tr(e)}i(Xl,"isFactReviewerLocked");var vn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:ny}),Jl=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Zl=/^\d{4}-\d{2}-\d{2}$/;function ec(e){if(e==null)return "text";let t=e.trim();return Jl.test(t)?"num":Zl.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(ec,"inferFactValueKind");function $i(e,t){let r=t.trim(),o=ec(e);if(o==="num"&&Jl.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[vn.num]:n})}return o==="date"&&Zl.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[vn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[vn.bool]:r==="true"}:{[vn.text]:r})}i($i,"factCorrectionFor");var Ie=zod.z.string().nullish(),mo=zod.z.number().nullish(),oy=zod.z.object({collected_at:Ie,at:Ie,value:mo,unit:Ie,qualitative_result:Ie,ref_low:mo,ref_high:mo,status:Ie,source_clinic:Ie,source_doc_id:Ie,doc_id:Ie,reviewed:zod.z.boolean().nullish()}),iy=zod.z.object({collected_at:Ie,at:Ie,value:mo,unit:Ie,qualitative_result:Ie,status:Ie}),ay=zod.z.object({marker_id:zod.z.string().min(1),canonical_name:Ie,name:Ie,loinc_code:Ie,canonical_unit:Ie,unit:Ie,panel_name:Ie,panel:Ie,meaning_text:Ie,meaning:Ie,latest:iy.nullish(),trajectory:Ie,points:zod.z.array(oy).optional()}),sy=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()}),ly=zod.z.object({markers:zod.z.array(ay).optional(),summary:sy.nullish(),disclaimer:zod.z.string().optional(),featured_marker_id:Ie});function cy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(cy,"isObject");function tc(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(tc,"withheldMarkers");function rc(e,t){let r=cy(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return tc(o);let n=ly.safeParse(r);if(!n.success)return tc(o);let l=n.data,s=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),c=(l.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(s))}));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(rc,"mapRecordMarkers");var dy=zod.z.string().min(1).refine(e=>e.startsWith("https://")),xn=zod.z.string().nullish(),uy=zod.z.object({share_id:zod.z.string().min(1),share_url:zod.z.string().min(1),expires_at:xn}),py=zod.z.object({shares:zod.z.array(zod.z.object({share_id:zod.z.string().min(1),expires_at:xn,created_at:xn,view_count:zod.z.number().int().nonnegative().nullish(),last_viewed_at:xn})).optional()}),my=zod.z.object({download_url:dy,expires_at:xn});function yy(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(yy,"resolveShareUrl");function nc(e,t){let r=uy.safeParse(e);if(!r.success)return null;let o=yy(r.data.share_url,t);return o===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:o,expiresAt:r.data.expires_at??null})}i(nc,"mapRecordShareLink");function oc(e){let t=py.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(oc,"mapRecordShareList");function ic(e){let t=my.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(ic,"mapRecordPdfLink");var fy=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 ac(e){let t=fy.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(ac,"mapSignatureSuggestions");var N=zod.z.string().nullish(),wn=zod.z.number().nullish(),gy=zod.z.object({at:N,value:wn,unit:N,qualitative_result:N,ref_low:wn,ref_high:wn,status:N,doc_id:N}),by=zod.z.object({marker_id:zod.z.string(),name:zod.z.string(),loinc_code:N,unit:N,panel:N,meaning:N,latest:zod.z.object({at:N,value:wn,unit:N,qualitative_result:N,status:N}).nullish(),trajectory:N,points:zod.z.array(gy).optional()}),hy=zod.z.object({encounter_id:zod.z.string(),date:N,type:N,clinic_name:N,veterinarian:N,doc_id:N}),Ry=zod.z.object({note_id:zod.z.string(),encounter_id:N,observed_on:N,sections:zod.z.array(zod.z.object({section:zod.z.string(),text:zod.z.string()})).optional()}),vy=zod.z.object({exam_id:zod.z.string(),encounter_id:N,observed_on:N,doc_id:N,systems:zod.z.record(zod.z.object({finding_status:N,finding:N})).optional()}),xy=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:N,latest_record_at:N,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()}),wy=zod.z.object({conflict_id:zod.z.string(),entity_type:zod.z.string(),field:N,severity:N,candidates:zod.z.array(zod.z.object({value:zod.z.string(),source_doc_id:N,doc_id:N,collected_at:N})).optional()}),Cy=zod.z.object({lab_results:zod.z.array(by).optional(),encounters:zod.z.array(hy).optional(),clinician_notes:zod.z.array(Ry).optional(),physical_exams:zod.z.array(vy).optional(),completeness:xy.nullish(),conflicts:zod.z.array(wy).optional()}),Ey=zod.z.object({visits:zod.z.array(zod.z.object({visit_id:zod.z.string(),visit_date:N,veterinarian:N,summary:N,doc_id:N})),vaccines:zod.z.array(zod.z.object({vaccine_id:zod.z.string(),product:N,lot:N,administered_on:N,expires_on:N,doc_id:N})),weights:zod.z.array(zod.z.object({weight_id:zod.z.string(),observed_on:N,weight_kg:wn,doc_id:N})),medications:zod.z.array(zod.z.object({medication_id:zod.z.string(),drug_name:N,dose:N,route:N,frequency:N,sig:N,rx_number:N,started_on:N,stopped_on:N,doc_id:N})),disclaimer:zod.z.string().optional()}),Sy=zod.z.object({document:Mo,contributions:zod.z.array(No),contribution_count:zod.z.number().int().nonnegative().optional()});function Gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Gi,"isObject");function Yi(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Yi,"petOf");function Wi(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(Wi,"emptyDepth");function ky(e,t){let r=Gi(t)?t:{},o=Yi(r,e);if(r.withheld===true)return Wi(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Wi(o,false);let l=Cy.safeParse(r);if(!l.success)return Wi(o,true);let s=l.data,c=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:o,available:true,withheld:false,labResults:Object.freeze((s.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(c))}))),encounters:Object.freeze((s.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((s.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((s.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,u])=>Object.freeze({system:d,findingStatus:u.finding_status??null,finding:u.finding??null})))}))),completeness:s.completeness?Object.freeze({hasLabHistory:s.completeness.has_lab_history===true,hasVaccinationHistory:s.completeness.has_vaccination_history===true,hasWeightHistory:s.completeness.has_weight_history===true,hasVitalsHistory:s.completeness.has_vitals_history===true,hasPhysicalExamHistory:s.completeness.has_physical_exam_history===true,hasProcedureHistory:s.completeness.has_procedure_history===true,hasGeneticHistory:s.completeness.has_genetic_history===true,hasReproductiveHistory:s.completeness.has_reproductive_history===true,hasParasitePreventionHistory:s.completeness.has_parasite_prevention_history===true,earliestRecordAt:s.completeness.earliest_record_at??null,latestRecordAt:s.completeness.latest_record_at??null,documentsIngested:s.completeness.documents_ingested??0,documentsInReview:s.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...s.completeness.entities_pending_review??{}}),heldTotal:s.completeness.held_total??0}):null,conflicts:Object.freeze((s.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(ky,"mapRecordDepth");function sc(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(sc,"withheldTimeline");function Ty(e,t){let r=Gi(t)?t:{},o=Yi(r,e);if(r.withheld===true)return sc(o);let n=Ey.safeParse(r);if(!n.success)return sc(o);let l=n.data,s=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})),a=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:s.length===0&&c.length===0&&a.length===0&&d.length===0,visits:Object.freeze(s),vaccines:Object.freeze(c),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:l.disclaimer??""})}i(Ty,"mapRecordsTimeline");function _y(e,t){let r=Gi(t)?t:{},o=Yi(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=Sy.safeParse(r);if(!l.success)return n();let s=Object.freeze(l.data.contributions.map(Bo));return Object.freeze({petRef:o,withheld:false,document:Ho(l.data.document),contributions:s,contributionCount:l.data.contribution_count??s.length})}i(_y,"mapDocumentContributions");var Py="/widget/v1/records/pets";function lc(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!yr(a)&&[...a].length<=d,"segment"),o=i(async(a,d,u,p)=>{if(!r(d,mt))return Rr();let f=await t.send(a,{method:"GET",path:u});if(!f.ok)return f;let h=p(f.value);return h.petRef===d?_e(h):B(q("internalError",{retryable:false}))},"read"),n=i(a=>`${Py}/${encodeURIComponent(a)}`,"pet"),l=i(a=>`${n(a)}/everfur_record`,"record"),s=i(async(a,d,u)=>{let p=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let f=u(p.value);return f===null?B(q("internalError",{retryable:false})):_e(f)},"parsed"),c=i((a,d)=>!r(a.entityType,Kl)||!r(a.canonicalKey,Ql)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,tn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>o("records.depth.record",a,`${n(a)}/record`,d=>ky(a,d)),"getRecordDepth"),getTimeline:i(a=>o("records.depth.timeline",a,`${n(a)}/timeline`,d=>Ty(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?o("records.depth.contributions",a,`${n(a)}/documents/${encodeURIComponent(d)}/contributions`,u=>_y(a,u)):Rr()},getMarkers:i(a=>o("records.depth.markers",a,`${n(a)}/markers`,d=>rc(a,d)),"getMarkers"),createShare(a){return r(a,mt)?s("records.share.create",{method:"POST",path:`${l(a)}/share`},d=>nc(d,e.apiBaseUrl)):Rr()},listShares(a){return r(a,mt)?s("records.share.list",{method:"GET",path:`${l(a)}/shares`},oc):Rr()},async revokeShare(a,d){if(!r(a,mt)||!r(d,64))return Rr();let u=await t.send("records.share.revoke",{method:"DELETE",path:`${l(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?_e(void 0):u},getPdfLink(a){return r(a,mt)?s("records.pdf.link",{method:"GET",path:`${l(a)}/pdf-link`},ic):Rr()},async editFact(a,d){let u=r(a,mt)?c(d,d.correctedFields):null;if(u===null)return Rr();let p=await t.send("records.fact.edit",{method:"POST",path:`${l(a)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},async removeFact(a,d){let u=r(a,mt)?c(d):null;if(u===null)return Rr();let p=await t.send("records.fact.remove",{method:"POST",path:`${l(a)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},listAuthorizationSignatures:i(()=>s("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},ac),"listAuthorizationSignatures")}}i(lc,"createRecordsDepthClient");function Rr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(Rr,"invalid");function sr(){let{runtime:e,userRef:t,scopeEpoch:r}=ke();return react.useMemo(()=>{let{services:o}=e.registry;return lc({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(sr,"useEverfurRecordsDepthClient");function Ut(e,t,r,o=""){let n=sr(),{userRef:l}=ke(),s=Mn(e),c=react.useMemo(()=>({}),[n,e,o,s]),[a,d]=react.useState({scope:c,value:null,error:null,loading:true}),u=react.useRef(0),p=react.useCallback(async()=>{let g=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);g===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(()=>(p(),()=>{u.current+=1;}),[p]);let f=a.scope===c?a:{value:null,error:null,loading:true},h=react.useCallback(()=>{p();},[p]),R=f.error===null||f.error.httpStatus!==404,v=R?f.error:null,y=f.loading?"loading":v!==null?"error":f.value===null?"empty":f.value.withheld?"populated":r(f.value)?"empty":"populated";return react.useMemo(()=>({status:y,value:f.value,error:v,available:R,refresh:h}),[y,f.value,v,R,h])}i(Ut,"useRecordsDepthRead");function vr(e){return e!==null&&e.httpStatus===404}i(vr,"isDarkRouteError");var Ly=i((e,t)=>e.getMarkers(t),"readMarkers"),Vy=i(e=>e.markers.length===0,"markersEmpty");function Qi(e){let t=Ut(e,Ly,Vy);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(Qi,"useRecordsMarkers");var qy=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function uc(e){let{clinic:t,controller:r,depthClient:o,capture:n,onCreated:l}=e,s=t.clinic?.name??t.freeText??"",c=t.clinic===null,[a,d]=react.useState(false),[u,p]=react.useState(e.ownerName),[f,h]=react.useState(t.email),[R,v]=react.useState(false),[y,g]=react.useState(null),[b,w]=react.useState(null),[x,E]=react.useState(0),[D,k]=react.useState(null),[S,I]=react.useState(false),[Y,z]=react.useState(null),[$,G]=react.useState([]),[Z,oe]=react.useState(null),[Ee,H]=react.useState(false),C=react.useRef(false),T=react.useRef(true),A=react.useRef(rr()),M=react.useRef(null);react.useEffect(()=>(T.current=true,()=>{T.current=false,M.current=null;}),[r]),react.useEffect(()=>{let Se=true;return g(null),M.current=null,r.getAuthorizationCopy().then(F=>{Se&&(F.ok?(g(F.value),w(null)):w(F.error));}).catch(()=>{Se&&w(q("internalError"));}),()=>{Se=false;}},[r,x]),react.useEffect(()=>{if(o===void 0)return;let Se=true;return o.listAuthorizationSignatures().then(F=>{Se&&(F.ok?G(F.value):vr(F.error)||G([]));}).catch(()=>{}),()=>{Se=false;}},[o]);let K=fn(t.clinic),ye=f.trim().toLowerCase(),Ve=qy.test(ye),ie=K&&(R||ye.length>0)&&!Ve?se.emailRequired:null,we=y?yn(y,u.trim(),He(e.petName),s):null,vt=e.hostCapture===true||Ee||Z!==null,Xe=!!(a&&y&&we&&u.trim()&&s&&vt&&(!K||Ve)),Vt=react.useCallback(async()=>{if(!(C.current||Y!==null||!y||!we)){if(!s){k(se.missingDraftError);return}if(K&&!Ve){v(true),k(se.emailRequired);return}if(!(!a||!u.trim())){C.current=true,I(true),k(null);try{if(M.current===null){let F=Z!==null?{signatureId:Z}:await n();if(!T.current)return;if(F===null){k(se.missingSignatureError);return}let Re=t.clinic&&(!K||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:s};M.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:y.authorizationVersion,...Re,...K?{clinicEmail:ye}:{},...F.signatureId!==void 0?{signatureId:F.signatureId}:{signaturePngBase64:F.signaturePngBase64},idempotencyKey:A.current()};}let Se=await r.createClinicRequest(M.current);if(!T.current)return;if(!Se.ok){k(Se.error.displayMessage);return}if(Se.value.petRef!==e.petRef){k(q("internalError").displayMessage);return}z(Se.value),M.current=null,l?.(Se.value);}catch{T.current&&k(q("internalError").displayMessage);}finally{C.current=false,T.current&&I(false);}}}},[a,n,t.clinic,s,r,y,Y,e.petRef,K,ye,l,u,Z,we,Ve]),qt=react.useCallback(()=>{M.current=null,k(null);},[]);return {title:c?se.titleFreeText:se.titleDirectory,clinicName:s,isFreeText:c,authorized:a,ownerName:u,email:f,emailError:ie,needsEmail:K,directoryClinicNoEmail:K&&t.clinic!==null,copy:y,copyError:b,scope:we,error:D,busy:S,created:Y,ready:Xe,signatures:$,reuseSignatureId:Z,hasSignature:vt,setAuthorized(Se){C.current||(qt(),d(Se));},setOwnerName(Se){C.current||(qt(),p(Se));},setEmail(Se){C.current||(qt(),v(false),h(Se));},setSigned(Se){C.current||(qt(),H(Se),Se&&oe(null));},pickReuseSignature(Se){C.current||(qt(),oe(Se));},retryCopy(){w(null),E(Se=>Se+1);},submit:Vt}}i(uc,"useRecordsConsentForm");function Zi(e){let{userRef:t,scopeEpoch:r}=ke();return jsxRuntime.jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsxRuntime.jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsxRuntime.jsx(By,{...Fe(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(Zi,"EverfurRecordsConsent");function By({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:l,controller:s,onNavigate:c,onBack:a,style:d}){let u=be(),p=Hy(),f=L(),h=Nt(),R=sr(),[v,y]=react.useState(null),[g,b]=react.useState("draw"),w=react.useCallback(async()=>v===null?null:{signaturePngBase64:v},[v]),x=uc({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:s??h,depthClient:R,capture:n?()=>n({petRef:e,petName:He(t),ownerName:x.ownerName,clinicName:x.clinicName,authorizationVersion:x.copy?.authorizationVersion??"",scopeText:x.scope??"",signal:new AbortController().signal}):w,hostCapture:n!==void 0,onCreated:i(S=>{l?.(S),c?.({name:"dashboard"});},"onCreated")}),E=react.useRef(x);E.current=x;let D=react.useCallback(S=>{y(S),E.current.setSigned(S!==null);},[]),k=x.busy;return jsxRuntime.jsxs(reactNative.View,{style:[u.root,d],children:[jsxRuntime.jsx(et,{title:x.title,onBack:a,testID:"records-consent-header"}),jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:"padding",style:u.body,children:[jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:p.content,keyboardShouldPersistTaps:"handled",testID:"records-consent",children:[jsxRuntime.jsxs(reactNative.View,{style:p.scopeCard,accessibilityRole:"summary",children:[jsxRuntime.jsx(m,{style:p.scopeHeading,accessibilityRole:"header",children:se.scopeHeading}),jsxRuntime.jsx(m,{style:p.scopeBody,children:se.scopeBody}),jsxRuntime.jsx(reactNative.View,{style:p.bullets,children:se.whatWeDo.map(S=>jsxRuntime.jsxs(reactNative.View,{style:p.bulletRow,children:[jsxRuntime.jsx(m,{style:p.check,children:"\u2713"}),jsxRuntime.jsx(m,{style:p.bulletText,children:S})]},S))}),jsxRuntime.jsx(reactNative.View,{style:p.retentionRow,children:jsxRuntime.jsx(m,{style:p.retentionText,children:se.retentionNote})}),x.copy&&x.scope?jsxRuntime.jsx(m,{style:p.serverScope,testID:"records-consent-scope",children:x.scope}):x.copyError?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(m,{style:u.errorText,accessibilityRole:"alert",children:x.copyError.displayMessage}),jsxRuntime.jsx(re,{label:ce.retry,kind:"outline",onPress:x.retryCopy,testID:"records-consent-copy-retry"})]}):jsxRuntime.jsx(m,{style:u.muted,accessibilityLiveRegion:"polite",children:ce.loading})]}),jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>x.setAuthorized(!x.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:x.authorized},accessibilityLabel:se.authorizeLabel(t,x.clinicName),hitSlop:6,style:[p.toggle,x.authorized?p.toggleChecked:null],testID:"records-authorize-toggle",children:[jsxRuntime.jsx(reactNative.View,{style:[p.box,x.authorized?p.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:x.authorized?jsxRuntime.jsx(m,{style:p.boxCheck,children:"\u2713"}):null}),jsxRuntime.jsx(m,{style:p.toggleLabel,children:se.authorizeLabel(t,x.clinicName)})]}),jsxRuntime.jsxs(reactNative.View,{style:p.block,children:[jsxRuntime.jsx(m,{style:u.fieldLabel,children:se.fullName}),jsxRuntime.jsx(qe,{accessibilityLabel:se.fullName,style:u.field,value:x.ownerName,placeholder:se.fullNamePlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:200,editable:!k,autoComplete:"name",autoCapitalize:"words",onChangeText:x.setOwnerName,testID:"records-consent-owner-name"})]}),x.needsEmail?jsxRuntime.jsxs(reactNative.View,{style:p.block,testID:"records-consent-email-block",children:[x.directoryClinicNoEmail?jsxRuntime.jsx(reactNative.View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsxRuntime.jsx(m,{style:u.cautionNoteText,children:se.noEmailNote(t,x.clinicName)})}):null,jsxRuntime.jsx(m,{style:u.fieldLabel,children:se.emailLabel}),jsxRuntime.jsx(qe,{accessibilityLabel:se.emailLabel,style:u.field,value:x.email,placeholder:se.emailPlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:320,editable:!k,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:x.setEmail,testID:"records-consent-clinic-email"}),x.emailError?jsxRuntime.jsx(m,{style:u.errorText,accessibilityRole:"alert",children:x.emailError}):null,jsxRuntime.jsx(m,{style:u.muted,testID:"records-consent-review-note",children:se.newClinicDirectSendNote})]}):null,n?null:jsxRuntime.jsxs(reactNative.View,{style:p.signatureBlock,children:[x.signatures.length>0?jsxRuntime.jsxs(reactNative.View,{style:p.block,children:[jsxRuntime.jsx(m,{style:u.fieldLabel,children:se.reuseSignature}),jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:p.gallery,children:x.signatures.map(S=>{let I=x.reuseSignatureId===S.signatureId;return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>x.pickReuseSignature(I?null:S.signatureId),accessibilityRole:"button",accessibilityLabel:I?se.reuseTileSelectedA11y:se.reuseTileA11y,style:[p.tile,I?p.tileSelected:null],testID:`records-consent-reuse-${S.signatureId}`,children:jsxRuntime.jsx(reactNative.Image,{source:{uri:S.previewUrl},style:p.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},S.signatureId)})}),jsxRuntime.jsx(m,{style:u.muted,children:se.reuseHint})]}):null,jsxRuntime.jsx(reactNative.View,{style:p.signatureHeader,children:jsxRuntime.jsx(m,{style:u.fieldLabel,children:g==="type"?se.signType:se.signDraw})}),jsxRuntime.jsx(Lr,{onChange:D,disabled:k}),jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>b(S=>S==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:g==="draw"?se.toTypeA11y:se.toDraw,style:p.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsxRuntime.jsx(m,{style:p.modeToggleText,children:g==="draw"?se.toType:se.toDraw})}),jsxRuntime.jsx(m,{style:u.muted,children:se.signatureHint(x.clinicName)})]}),x.error?jsxRuntime.jsx(reactNative.View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsxRuntime.jsx(m,{style:u.errorText,children:x.error})}):null,x.created?jsxRuntime.jsx(m,{accessibilityLiveRegion:"polite",style:u.bodyText,children:x.created.statusLabel||ce.records}):null]}),jsxRuntime.jsx(reactNative.View,{style:p.footer,children:jsxRuntime.jsx(re,{label:k?se.submitting:se.submit,accessibilityLabel:se.submitA11y,disabled:!x.ready,busy:k,onPress:()=>{x.submit();},style:p.submit,testID:"records-consent-submit"})})]}),jsxRuntime.jsx(Me,{})]})}i(By,"ConsentBody");function Hy(){let e=L();return react.useMemo(()=>Uy(e),[e])}i(Hy,"useLocalStyles");function Uy(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return reactNative.StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xl+r.xs,gap:r.lg+r.xs/2},scopeCard:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md},scopeHeading:{...s(n.size.body+1,n.lineHeight.snug,t.brandInk,"bold")},scopeBody:s(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),bullets:{gap:r.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:r.sm},check:{...s(n.size.body,n.lineHeight.normal,t.brandInk,"bold")},bulletText:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary)},retentionRow:{paddingTop:r.xs,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},retentionText:s(n.size.tiny,n.lineHeight.normal,t.text.muted),serverScope:{...s(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:{...s(n.size.body,n.lineHeight.tight,t.surface,"bold")},toggleLabel:{flex:1,...s(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:{...s(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(Uy,"makeLocalStyles");function fo(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(fo,"markerStatusTone");function $y(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($y,"markerStatusSpoken");function Wy(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(Wy,"rangePhrase");function go(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(go,"formatReferenceRange");function gc(e,t){let r=t.reviewed?", reviewed by our team":"",o=t.sourceClinic?`, from ${t.sourceClinic}`:"";return `${Q(t.at)}: ${Et(t.value,e.unit,t.qualitativeResult)}, ${$y(t.status)}${Wy(t)}${o}${r}`}i(gc,"markerPointSpoken");function Ge(e){return e?.trim()||"my pet"}i(Ge,"lead");function bc(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(bc,"clause");function hc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Ge(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(bc(t.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:t.markerId,payload:{marker:r,...t.statusText?.trim()?{status:t.statusText.trim()}:{}}}}}i(hc,"buildMarkerAskPrompt");function Rc(e,t,r){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:s}=t;if(o===0)return {prompt:`I'm looking at ${Ge(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Ge(e)}?`,entityRef:{type:"marker_summary",id:r,payload:{total:0}}};let c=s>0?`, ${s} without a reference range`:"";return {prompt:`I'm looking at ${Ge(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:s}}}}i(Rc,"buildMarkerSummaryAskPrompt");function vc(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 ${Ge(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:t.entityId,payload:n}}}i(vc,"buildMarkerReadingAskPrompt");function xc(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 ${Ge(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(xc,"buildRecordsRequestAskPrompt");var Gy=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function wc(e,t,r,o){let n=t.entityTypeLabel.trim()||"record",l=t.title.trim()||n,s=t.detail?.trim();return {prompt:`I'm looking at ${Ge(e)}'s ${n.toLowerCase()}: ${l}${s?`, ${s}`:""}. What does this mean, and what should I keep on top of for ${Ge(e)}?`,entityRef:{type:Gy[r]??r,id:o,payload:{kind:n,title:l,...s?{detail:s}:{}}}}}i(wc,"buildEntityRowAskPrompt");function Cc(e,t,r){let o=t.filter(s=>s.label.trim()),n={type:"upcoming_care",id:r};if(o.length===0)return {prompt:`I'm looking at ${Ge(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Ge(e)} be on?`,entityRef:n};let l=[...o].sort((s,c)=>(s.tone==="overdue"?0:1)-(c.tone==="overdue"?0:1)).slice(0,4).map(s=>s.relativeText.trim()?`${s.label.trim()} (${s.relativeText.trim().toLowerCase()})`:s.label.trim());return {prompt:`I'm looking at ${Ge(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Ge(e)}, and how do I stay on top of these?`,entityRef:n}}i(Cc,"buildUpcomingCareAskPrompt");function Ec(e,t,r){let o=[`I'm looking at ${Ge(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 ${Ge(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Ge(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:r}}}i(Ec,"buildPhysicalExamAskPrompt");function Sc(e,t,r){let o=[`I'm looking at ${Ge(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"}: ${bc(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:r}}}i(Sc,"buildVisitNoteAskPrompt");function kc(e,t,r){let o=t.scopeLabel.trim()||"a detail",n=t.candidates.filter(s=>s.value.trim()),l=n.slice(0,3).map(s=>`"${s.value.trim()}"${s.clinicName?.trim()?` (${s.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${Ge(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(s=>s.value.trim()).join(" | ")}}}}i(kc,"buildConflictAskPrompt");function Cn(e){return e!==void 0}i(Cn,"canUploadRecords");function ea(e,t){return e??t?.version??""}i(ea,"resolveConsentVersion");function qr(e,t){return ea(e,t).length>0}i(qr,"canGrantConsent");function xr(e,t){return e.denialReason==="consent_required"?t?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:q("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:q("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(xr,"selectErrorView");function bo(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?Tc.ownerUpload:Tc.clinicRequest}i(bo,"selectRequestTitle");var Tc=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function Yy(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(Yy,"selectRequestList");function En(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(En,"selectPrimaryLabel");function ho(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(ho,"selectClinicCall");var gt=200,Pc=16;function Qy(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 s of o){if(!(s.count>0))continue;let c=s.count/r*360;if(!Number.isFinite(c))return null;l.push({key:s.key,color:s.color,startDeg:n,sweepDeg:c}),n+=c;}return l}i(Qy,"buildRingSegments");function Dc({summary:e,onAsk:t,testID:r}){let o=Jy(),n=L(),{totalMarkers:l,inRangeCount:s,outOfRangeCount:c,unknownCount:a}=e,d=react.useMemo(()=>Qy(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(m,{style:o.title,children:Mt.title}),jsxRuntime.jsx(reactNative.View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:Mt.a11y(l,s,c,a),children:jsxRuntime.jsxs(reactNative.View,{style:o.ringWrap,children:[jsxRuntime.jsx(reactNative.View,{style:o.track}),d===null?null:d.map(p=>jsxRuntime.jsx(Xy,{segment:p,styles:o},p.key)),jsxRuntime.jsxs(reactNative.View,{style:o.center,pointerEvents:"none",children:[jsxRuntime.jsx(m,{style:o.centerCount,children:l}),jsxRuntime.jsx(m,{style:o.centerLabel,children:l===1?Mt.marker:Mt.markers})]})]})}),u||d===null?jsxRuntime.jsxs(reactNative.View,{style:o.badges,children:[jsxRuntime.jsx(ta,{count:c,label:Mt.outOfRange,color:n.color.danger,styles:o}),jsxRuntime.jsx(ta,{count:s,label:Mt.inRange,color:n.color.success,styles:o}),a>0?jsxRuntime.jsx(ta,{count:a,label:Mt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsxRuntime.jsx(m,{style:o.subtitle,children:Mt.subtitle}),t?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Mt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsxRuntime.jsx(m,{style:o.askLabel,children:Mt.ask})}):null]})}i(Dc,"MarkerSummaryCard");function Xy({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(Xy,"Arc");function ta({count:e,label:t,color:r,styles:o}){return jsxRuntime.jsx(reactNative.View,{style:[o.badge,{borderColor:r}],children:jsxRuntime.jsx(m,{style:[o.badgeText,{color:r}],children:`${e} ${t}`})})}i(ta,"Badge");function Jy(){let e=L();return react.useMemo(()=>Zy(e),[e])}i(Jy,"useStyles");function Zy(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=reactNative.StyleSheet.hairlineWidth,c=ot(l.recordCard);return reactNative.StyleSheet.create({card:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder,padding:r.lg-1,gap:r.sm+r.xs/2,...Je(l.recordCard,s)},title:{..._(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.letterSpacing.headerBrand,...c},ringRow:{alignItems:"center"},ringWrap:{width:gt,height:gt,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:gt,height:gt,borderRadius:gt/2,borderWidth:Pc,borderColor:t.surfaceSubtle},piece:{position:"absolute",width:gt,height:gt},window:{position:"absolute",left:gt/2,top:0,width:gt/2,height:gt,overflow:"hidden"},halfRing:{position:"absolute",left:-gt/2,top:0,width:gt,height:gt,borderRadius:gt/2,borderWidth:Pc,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{..._(e,"medium"),fontSize:n.size.verdict*2,lineHeight:n.size.verdict*2+r.xs,color:t.text.primary,textAlign:"center",...c},centerLabel:{..._(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:{..._(e,"mono"),fontSize:n.size.nano,lineHeight:n.size.tiny,letterSpacing:n.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{..._(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:s,borderColor:t.borderRingCream,backgroundColor:t.surface},askLabel:{..._(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.primary,letterSpacing:n.letterSpacing.tight}})}i(Zy,"makeStyles");function ef(e){return e.value!==null&&Number.isFinite(e.value)}i(ef,"numeric");function Ac(e){let t=e.points.filter(ef);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(g=>g.value),s=Math.min(...l,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...l,...o!==null?[o]:[],...n!==null?[n]:[]);s===c&&(s-=1,c+=1);let a=(c-s)*.18,d=s-a,u=c+a,p=u-d,f=i(g=>(u-g)/p*100,"y"),h=6,R=t.length,v=t.map((g,b)=>({index:b,xPct:R<=1?50:h+b/(R-1)*(100-2*h),yPct:f(g.value),status:g.status,point:g})),y=o!==null||n!==null?{topPct:n!==null?f(n):0,bottomPct:o!==null?f(o):100}:null;return {points:v,band:y,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Ac,"buildMarkerChart");var nf=416,of=140;function vo(e){return `${e}%`}i(vo,"pct");function af({marker:e,width:t,onPointPress:r,onAsk:o}){let n=ra(),l=be(),s=Qt(e.latest?.status??null),c=fo(e.latest?.status??null),a=Hr(e.trajectory,e.points.length),d=react.useMemo(()=>Ac(e),[e]),u=e.latest?Et(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(m,{style:n.markerName,numberOfLines:2,children:e.name}),e.unit?jsxRuntime.jsx(m,{style:n.unit,children:e.unit}):null]}),jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:or.status(s.label),children:jsxRuntime.jsx(Kt,{label:s.label,tone:c})})]}),e.latest&&u!==null?jsxRuntime.jsxs(reactNative.View,{style:n.latestRow,children:[jsxRuntime.jsx(m,{style:[n.latestValue,s.outOfRange?n.latestValueDanger:null],accessibilityLabel:or.latestA11y(u,s.label,Q(e.latest.at)),children:u}),jsxRuntime.jsx(m,{style:n.latestDate,children:Q(e.latest.at)})]}):null,a?jsxRuntime.jsx(m,{style:n.trajectory,accessibilityRole:"text",children:a}):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:vo(d.band.topPct),height:vo(Math.max(0,d.band.bottomPct-d.band.topPct))}]}):null,d.points.map(p=>jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>r(e,p.point),hitSlop:12,style:[n.point,p.status==="above"||p.status==="below"?n.pointDanger:null,{left:vo(p.xPct),top:vo(p.yPct)}],testID:`marker-point-${e.markerId}-${p.index}`},p.index))]}),jsxRuntime.jsx(reactNative.View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:or.readingsA11y(e.name),children:e.points.map((p,f)=>jsxRuntime.jsx(reactNative.View,{accessibilityRole:"text",accessibilityLabel:gc(e,p)},f))}),jsxRuntime.jsx(m,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?or.singleHint:or.tapHint})]}):jsxRuntime.jsx(reactNative.View,{style:n.emptyBody,accessibilityRole:"text",children:jsxRuntime.jsx(m,{style:n.emptyText,children:or.empty})}),o?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:or.askA11y(e.name),style:[l.pill,l.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsxRuntime.jsx(m,{style:l.pillAskLabel,children:or.ask})}):null]})})}i(af,"MarkerTrendCard");function qc({markers:e,onPointPress:t,onAsk:r}){let o=ra(),[n,l]=react.useState(0),[s,c]=react.useState(0),a=i(p=>l(p.nativeEvent.layout.width),"onLayout"),d=i(p=>{if(n<=0)return;let f=Math.round(p.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(f,e.length-1)));},"onMomentumEnd"),u=e[s]??null;return jsxRuntime.jsxs(reactNative.View,{style:o.carousel,onLayout:a,testID:"marker-carousel",children:[jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:d,snapToAlignment:"start",children:e.map(p=>jsxRuntime.jsx(af,{marker:p,width:n>0?n:void 0,onPointPress:t,onAsk:r},p.markerId))}),jsxRuntime.jsxs(reactNative.View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:wi.a11y(u?.name??null,s,e.length),children:[jsxRuntime.jsx(reactNative.View,{style:o.dots,children:e.map((p,f)=>jsxRuntime.jsx(reactNative.View,{style:[o.dot,f===s?o.dotActive:null]},p.markerId))}),jsxRuntime.jsx(m,{style:o.counter,children:wi.counter(s,e.length)})]})]})}i(qc,"MarkerTrendCarousel");function Fc({marker:e,point:t,onClose:r,onAsk:o}){let n=ra(),l=be();if(e===null||t===null)return null;let s=i((c,a)=>jsxRuntime.jsxs(reactNative.View,{style:n.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${c}: ${a}`,children:[jsxRuntime.jsx(m,{style:n.detailLabel,children:c}),jsxRuntime.jsx(m,{style:n.detailValue,children:a})]},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:Ct.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(m,{style:n.sheetTitle,accessibilityRole:"header",children:Ct.title}),jsxRuntime.jsx(reactNative.Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Ct.close,hitSlop:10,style:n.closeButton,testID:"marker-provenance-close",children:jsxRuntime.jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsxRuntime.jsxs(reactNative.View,{style:n.sheetBody,children:[jsxRuntime.jsxs(reactNative.View,{style:n.valueRow,children:[jsxRuntime.jsx(m,{style:n.sheetName,children:e.name}),jsxRuntime.jsx(m,{style:n.sheetValue,children:Et(t.value,e.unit,t.qualitativeResult)})]}),t.reviewed?jsxRuntime.jsx(reactNative.View,{style:n.reviewed,accessibilityRole:"text",children:jsxRuntime.jsx(m,{style:n.reviewedText,children:Ct.reviewed})}):null,s(Ct.collected,Q(t.at)),t.sourceClinic?s(Ct.clinic,t.sourceClinic):null,s(Ct.referenceRange,t.refLow!==null||t.refHigh!==null?go(t,e.unit):Ct.noRange),t.docId?s(Ct.sourceDocument,t.docId):null,t.reviewed?null:jsxRuntime.jsx(m,{style:n.unverified,accessibilityRole:"text",children:Ct.unverified}),o?jsxRuntime.jsx(reactNative.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Ct.askA11y,style:[l.pill,l.pillAsk],testID:"marker-provenance-ask",children:jsxRuntime.jsx(m,{style:l.pillAskLabel,children:Ct.ask})}):null]})]})]})}i(Fc,"MarkerProvenanceSheet");function ra(){let e=L();return react.useMemo(()=>sf(e),[e])}i(ra,"useStyles");function sf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=reactNative.StyleSheet.hairlineWidth,c=r.md,a=i((f,h,R,v="regular")=>({..._(e,v),fontSize:f,lineHeight:Math.round(f*h),color:R}),"text"),d=ot(l.recordCard),u=a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),p=a(n.size.verdict+r.xs,n.lineHeight.tight,t.text.primary,"bold");return reactNative.StyleSheet.create({page:{paddingHorizontal:r.sm},card:{borderRadius:o.lg-r.xs/2,borderWidth:s,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg,gap:r.md,...Je(l.recordCard,s)},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:{..._(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:{...p,...d},sheetValue:p,latestValueDanger:{color:t.danger},latestDate:{...a(n.size.caption,n.lineHeight.normal,t.text.muted),...d},trajectory:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),...d},chartWrap:{gap:r.sm},plot:{height:of,borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,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:{...a(n.size.tiny,n.lineHeight.normal,t.text.placeholder),textAlign:"center",...d},singleHint:{...a(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:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},carousel:{height:nf},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:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,letterSpacing:n.letterSpacing.eyebrow/3,color:t.text.muted},backdrop:{flex:1,backgroundColor:to},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,...a(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:{...a(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:{...a(n.size.tiny,n.lineHeight.normal,t.success,"medium")},detailRow:{gap:r.xs/2},detailLabel:{...a(n.size.caption,n.lineHeight.normal,t.text.muted,"medium")},detailValue:a(n.size.body,n.lineHeight.normal,t.text.primary),unverified:a(n.size.caption,n.lineHeight.normal,t.text.muted)})}i(sf,"makeStyles");var W=Object.freeze({title:"Full medical record",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 your 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)=>`${Q(e)} to ${Q(t)}`,"dateRange"),documents:"Documents",uploadedDocument:fe.uploadedDocument,documentRowA11y:i(e=>`View what ${e} contributed to this record`,"documentRowA11y"),identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",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:fe.labResults,visits:fe.visits,physicalExams:fe.physicalExams,visitNotes:fe.visitNotes,document:Object.freeze({title:"Health Record",download:"Download record PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:i(e=>`Generated ${Q(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"})}),zc=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 kn(e){return Object.prototype.hasOwnProperty.call(zc,e)?zc[e]:ir(e)}i(kn,"entityTypeLabel");var Nc=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function Mc(e){let t=Nc.filter(o=>e.includes(o)),r=e.filter(o=>!Nc.includes(o));return [...t,...r]}i(Mc,"orderEntityTypes");function xo(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(xo,"conflictSeverityMeta");function Tn(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?W.overdue:W.due(Q(e)),overdue:o}}i(Tn,"dueBadge");function Bc(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(Bc,"formatReferenceBand");var at=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 Hc(e,t){return tr(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.":Xl(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(Hc,"factEditErrorMessage");var lf=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function na(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(na,"applyFactOverlay");function oa(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(oa,"isFactEditable");function cf(){return `records-fact-${Date.now().toString(36)}`}i(cf,"defaultFactKey");function ia(e,t={}){let r=sr(),{userRef:o}=ke(),[n,l]=react.useState(lf),[s,c]=react.useState(false),[a,d]=react.useState(null),u=react.useMemo(()=>({}),[r,e,o]),[p,f]=react.useState(null),h=react.useCallback(()=>f(u),[u]),R=o!==null&&p!==u,v=react.useRef(false),y=react.useRef(t.newIdempotencyKey);y.current=t.newIdempotencyKey;let g=react.useCallback(()=>(y.current??cf)(),[]),b=react.useCallback((D,k,S)=>{if(c(false),!D.ok){if(k(),vr(D.error)){h();return}d(Hc(D.error,S));}},[h]),w=react.useCallback(async(D,k)=>{let S=D.canonicalKey??"",I=k.trim();if(v.current||S.length===0||I.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let Y=n;l($=>({...$,edits:{...$.edits,[S]:I}}));let z=await r.editFact(e,{entityType:D.category,canonicalKey:S,correctedFields:$i(D.value,I),idempotencyKey:g()});return v.current=false,b(z,()=>l(Y),"edit"),z},[r,e,n,b,g]),x=react.useCallback(async D=>{let k=D.canonicalKey??"";if(v.current||k.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let S=n;l(Y=>({...Y,removed:[...Y.removed,k]}));let I=await r.removeFact(e,{entityType:D.category,canonicalKey:k,idempotencyKey:g()});return v.current=false,b(I,()=>l(S),"remove"),I},[r,e,n,b,g]),E=react.useCallback(()=>d(null),[]);return react.useMemo(()=>({overlay:n,busy:s,error:a,available:R,edit:w,remove:x,clearError:E}),[n,s,a,R,w,x,E])}i(ia,"useRecordFactEdit");function Wc({entity:e,factEdit:t,children:r}){let o=Gc(),[n,l]=react.useState(false),s=e.label.trim()||at.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:at.editA11y(s),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(yf,{entity:e,title:s,factEdit:t,onClose:()=>l(false)}):null]})}i(Wc,"FactEditAffordance");function yf({entity:e,title:t,factEdit:r,onClose:o}){let n=Gc(),l=be(),s=L(),[c,a]=react.useState(e.value??""),[d,u]=react.useState(null),[p,f]=react.useState(false);react.useEffect(()=>{r.clearError();},[r]);let h=c.trim().length>0&&c.trim()!==(e.value??"").trim(),R=d??r.error,v=r.busy,y=i(()=>{if(!h){u(at.noChange);return}u(null),r.edit(e,c).then(b=>{b.ok&&o();});},"submitEdit"),g=i(()=>{u(null),r.remove(e).then(b=>{b.ok?o():f(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:reactNative.StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:at.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(m,{style:n.title,accessibilityRole:"header",children:at.title(t)}),jsxRuntime.jsx(m,{style:[n.helper,R?n.helperError:null],accessibilityLiveRegion:"polite",children:R??at.helper})]}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:at.close,onPress:o,hitSlop:12,style:n.closeButton,testID:"fact-edit-close",children:jsxRuntime.jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsxRuntime.jsx(m,{style:l.fieldLabel,children:e.label}),jsxRuntime.jsx(qe,{accessibilityLabel:e.label,style:l.field,value:c,onChangeText:b=>{a(b),u(null);},editable:!v,maxLength:512,placeholderTextColor:s.color.text.placeholder,testID:"fact-edit-field"}),p?jsxRuntime.jsxs(reactNative.View,{style:n.confirmBlock,testID:"fact-edit-confirm-remove",children:[jsxRuntime.jsx(m,{style:n.confirmText,children:at.confirmRemove}),jsxRuntime.jsxs(reactNative.View,{style:n.confirmRow,children:[jsxRuntime.jsx(re,{label:v?at.removing:at.removeConfirm,kind:"danger",busy:v,onPress:g,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsxRuntime.jsx(re,{label:at.keep,kind:"outline",disabled:v,onPress:()=>f(false),style:n.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):jsxRuntime.jsxs(reactNative.View,{style:n.actions,children:[jsxRuntime.jsx(re,{label:v?at.saving:at.save,busy:v,disabled:!h,onPress:y,testID:"fact-edit-save"}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:at.removeA11y(t),disabled:v,onPress:()=>{u(null),f(true);},style:[n.removeButton,v?n.removeDisabled:null],testID:"fact-edit-remove",children:jsxRuntime.jsx(m,{style:n.removeText,children:at.remove})})]})]})]})})}i(yf,"FactEditSheet");function Gc(){let e=L();return react.useMemo(()=>ff(e),[e])}i(Gc,"useStyles");function ff(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=e.brightness==="dark"?t.errorRed:t.danger,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*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:to},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:s},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(ff,"makeStyles");function So({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:s,nowMs:c}){let a=be(),d=gf(),u=c??Date.now(),p=react.useMemo(()=>s?na(e.entities,s.overlay):e.entities,[e.entities,s]),f=react.useMemo(()=>{let y=[],g=new Map;for(let b of p){let w=b.category.trim();if(w.length===0)continue;let x=g.get(w);x===void 0?(y.push(w),g.set(w,[b])):x.push(b);}return {order:Mc(y),groups:g}},[p]),h=Object.values(e.documents),R=i((y,g,b)=>l?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{let w=y();l(w.prompt,w.entityRef);},accessibilityRole:"button",accessibilityLabel:g,style:[a.pill,a.pillAsk,d.ask],testID:b,children:jsxRuntime.jsx(m,{style:a.pillAskLabel,children:g})}):null,"ask"),v=s!==void 0&&s.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:a.section,testID:"record-section-conflicts",children:[jsxRuntime.jsx(Bt,{title:W.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((y,g)=>xo(y.severity).rank-xo(g.severity).rank).map(y=>{let g=xo(y.severity),b=ir(y.field??y.entityType);return jsxRuntime.jsxs(reactNative.View,{style:[d.conflictCard,{borderColor:a.chipTones[g.tone].fg.color}],accessibilityRole:"summary",children:[jsxRuntime.jsxs(reactNative.View,{style:d.conflictHead,children:[jsxRuntime.jsx(m,{style:d.conflictTitle,children:g.label}),jsxRuntime.jsx(Kt,{label:b,tone:g.tone})]}),jsxRuntime.jsx(m,{style:a.rowDetail,children:W.conflictSub}),y.candidates.map((w,x)=>jsxRuntime.jsxs(reactNative.View,{style:d.candidate,children:[jsxRuntime.jsx(m,{style:a.rowTitle,children:w.value}),jsxRuntime.jsx(m,{style:a.rowMuted,children:[w.docId?e.documents[w.docId]?.title??W.uploadedDocument:W.uploadedDocument,w.collectedAt?Q(w.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},x)),R(()=>kc(r,{scopeLabel:b,severity:y.severity,candidates:y.candidates.map(w=>({value:w.value,clinicName:w.docId?e.documents[w.docId]?.title??null:null}))},y.conflictId),W.askConflict,`records-ask-conflict-${y.conflictId}`)]},y.conflictId)})]}):null,t?.completeness?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-completeness",children:[jsxRuntime.jsx(Bt,{title:W.whatsOnFile}),jsxRuntime.jsxs(reactNative.View,{style:a.card,children:[jsxRuntime.jsx(reactNative.View,{style:d.coverageRow,children:[[W.coverage.labs,t.completeness.hasLabHistory],[W.coverage.vaccines,t.completeness.hasVaccinationHistory],[W.coverage.weight,t.completeness.hasWeightHistory],[W.coverage.vitals,t.completeness.hasVitalsHistory],[W.coverage.exams,t.completeness.hasPhysicalExamHistory],[W.coverage.procedures,t.completeness.hasProcedureHistory],[W.coverage.genetics,t.completeness.hasGeneticHistory],[W.coverage.parasite,t.completeness.hasParasitePreventionHistory],[W.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([y,g])=>jsxRuntime.jsx(reactNative.View,{style:[d.coveragePill,g?a.chipTones.positive.bg:a.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${g?W.onFile:W.noneOnFile}`,children:jsxRuntime.jsx(m,{style:[d.coverageText,g?a.chipTones.positive.fg:{color:a.rowMuted.color}],children:y})},y))}),jsxRuntime.jsxs(reactNative.View,{style:d.metaRow,children:[jsxRuntime.jsx(m,{style:d.metaText,children:W.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsxRuntime.jsx(Kt,{label:W.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:W.beingVerifiedA11y(aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsxRuntime.jsx(Kt,{label:W.beingVerified(aa(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(m,{style:d.metaText,children:W.dateRange(t.completeness.earliestRecordAt,t.completeness.latestRecordAt)})}):null,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).length>0?jsxRuntime.jsxs(m,{style:d.pendingText,children:[W.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).map(([y,g])=>`${kn(y)} (${g})`).join(", ")]}):null]})]}):null,h.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-documents",children:[jsxRuntime.jsx(Bt,{title:W.documents,count:h.length}),jsxRuntime.jsx(reactNative.View,{style:a.card,children:h.map((y,g)=>{let b=y.title?.trim()||W.uploadedDocument,w=y.receivedAt?Q(y.receivedAt):null,x=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(reactNative.View,{style:a.rowMain,children:[jsxRuntime.jsx(m,{style:a.rowTitle,children:b}),w?jsxRuntime.jsx(m,{style:a.rowDetail,children:w}):null]}),n?jsxRuntime.jsx(Pr,{}):null]});return n?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>n({name:"contributions",docId:y.docId}),accessibilityRole:"button",accessibilityLabel:W.documentRowA11y(b),style:[a.row,g>0?a.rowDivider:null],testID:`records-document-row-${y.docId}`,children:x},y.docId):jsxRuntime.jsx(reactNative.View,{style:[a.row,g>0?a.rowDivider:null],children:x},y.docId)})})]}):null,e.identity.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-identity",children:[jsxRuntime.jsx(Bt,{title:W.identity}),jsxRuntime.jsx(reactNative.View,{style:a.card,children:e.identity.map((y,g)=>jsxRuntime.jsxs(reactNative.View,{style:[a.row,g>0?a.rowDivider:null],children:[jsxRuntime.jsx(m,{style:d.identityLabel,children:y.label}),jsxRuntime.jsx(m,{style:d.identityValue,children:y.value})]},`${g}:${y.label}`))})]}):null,e.forwardLooking.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-upcoming",children:[jsxRuntime.jsx(Bt,{title:W.upcomingCare,count:e.forwardLooking.length}),jsxRuntime.jsx(reactNative.View,{style:a.card,children:e.forwardLooking.map((y,g)=>{let b=Tn(y.dueAt,u);return jsxRuntime.jsxs(reactNative.View,{style:[a.row,g>0?a.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:a.rowMain,children:[jsxRuntime.jsx(m,{style:a.rowTitle,children:y.title}),y.detail?jsxRuntime.jsx(m,{style:a.rowDetail,children:y.detail}):null]}),b?jsxRuntime.jsx(Kt,{label:b.label,tone:b.overdue?"critical":"info"}):null]},`${y.title}-${g}`)})}),R(()=>Cc(r,e.forwardLooking.map(y=>{let g=Tn(y.dueAt,u);return {label:y.title,relativeText:g?.label??"",tone:g?.overdue?"overdue":"upcoming"}}),e.petRef),W.askUpcomingCare,"records-ask-upcoming-care")]}):null,f.order.map(y=>{let g=f.groups.get(y)??[];if(g.length===0)return null;let b=kn(y);return jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:`record-section-${y}`,children:[jsxRuntime.jsx(Bt,{title:b,count:g.length}),jsxRuntime.jsx(reactNative.View,{style:a.card,children:g.map((w,x)=>{let D=[Br(w.value,w.unit),w.observedAt?Q(w.observedAt):null].filter(S=>S&&S.length>0).join(" \xB7 "),k=jsxRuntime.jsxs(reactNative.View,{style:[a.row,x>0?a.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:a.rowMain,children:[jsxRuntime.jsx(m,{style:a.rowTitle,children:w.label}),D?jsxRuntime.jsx(m,{style:a.rowDetail,children:D}):null,R(()=>wc(r,{entityTypeLabel:b,title:w.label,detail:D||null},y,w.key),W.askEverfur,`records-ask-entity-${w.key}`)]}),w.status?jsxRuntime.jsx(Kt,{label:ir(w.status)}):null]});return v&&oa(w)&&s?jsxRuntime.jsx(Wc,{entity:w,factEdit:s,children:k},w.key):jsxRuntime.jsx(reactNative.View,{children:k},w.key)})})]},y)}),t&&t.physicalExams.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-exams",children:[jsxRuntime.jsx(Bt,{title:W.physicalExams,count:t.physicalExams.length}),t.physicalExams.map(y=>jsxRuntime.jsxs(reactNative.View,{style:a.card,children:[jsxRuntime.jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.exam}),y.systems.map((g,b)=>{let w=g.findingStatus==="abnormal",x=w?fe.abnormal:g.findingStatus==="not_examined"?fe.notExamined:fe.normal;return jsxRuntime.jsxs(reactNative.View,{style:[a.row,b>0?a.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[Ir(g.system),x,w?g.finding:null].filter(Boolean).join(", "),children:[jsxRuntime.jsxs(reactNative.View,{style:a.rowMain,children:[jsxRuntime.jsx(m,{style:a.rowTitle,children:Ir(g.system)}),w&&g.finding?jsxRuntime.jsx(m,{style:a.rowDetail,children:g.finding}):null]}),jsxRuntime.jsx(Kt,{label:x,tone:w?"warning":g.findingStatus==="not_examined"?"neutral":"positive"})]},g.system)}),R(()=>Ec(r,{observedOn:y.observedOn?Q(y.observedOn):null,abnormal:y.systems.filter(g=>g.findingStatus==="abnormal").map(g=>({system:Ir(g.system),finding:g.finding??""}))},y.examId),W.askExam,`records-ask-exam-${y.examId}`)]},y.examId))]}):null,t&&t.clinicianNotes.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-notes",children:[jsxRuntime.jsx(Bt,{title:W.visitNotes,count:t.clinicianNotes.length}),t.clinicianNotes.map(y=>jsxRuntime.jsxs(reactNative.View,{style:a.card,children:[jsxRuntime.jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.visitNote}),y.sections.map((g,b)=>jsxRuntime.jsxs(reactNative.View,{style:[d.noteSection,b>0?a.rowDivider:null],children:[jsxRuntime.jsx(m,{style:d.noteLabel,children:Ur(g.section)}),jsxRuntime.jsx(m,{style:g.text?d.noteBody:d.noteBodyMuted,children:g.text||fe.notRecorded})]},`${g.section}:${b}`)),R(()=>Sc(r,{observedOn:y.observedOn?Q(y.observedOn):null,sections:y.sections.map(g=>({label:Ur(g.section),text:g.text}))},y.noteId),W.askVisit,`records-ask-note-${y.noteId}`)]},y.noteId))]}):null,o&&t&&t.labResults.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-labs",children:[jsxRuntime.jsx(Bt,{title:W.labResults,count:t.labResults.length}),jsxRuntime.jsx(reactNative.View,{style:a.card,children:t.labResults.map((y,g)=>{let b=Qt(y.latest.status),w=Ei(y.latest.at,y.trajectory,y.points.length);return jsxRuntime.jsxs(reactNative.View,{style:[a.row,g>0?a.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:a.rowMain,children:[jsxRuntime.jsx(m,{style:a.rowTitle,children:y.name}),jsxRuntime.jsx(m,{style:a.rowValue,children:Et(y.latest.value,y.latest.unit,y.latest.qualitativeResult)}),w?jsxRuntime.jsx(m,{style:a.rowDetail,children:w}):null]}),jsxRuntime.jsx(Kt,{label:b.label,tone:fo(y.latest.status)})]},y.markerId)})})]}):null,t&&t.encounters.length>0?jsxRuntime.jsxs(reactNative.View,{style:a.section,testID:"record-section-visits",children:[jsxRuntime.jsx(Bt,{title:W.visits,count:t.encounters.length}),jsxRuntime.jsx(reactNative.View,{style:a.card,children:t.encounters.map((y,g)=>{let b=[y.date?Q(y.date):null,y.clinicName,y.veterinarian].filter(w=>w&&w!=="-").join(" \xB7 ");return jsxRuntime.jsx(reactNative.View,{style:[a.row,g>0?a.rowDivider:null],children:jsxRuntime.jsxs(reactNative.View,{style:a.rowMain,children:[jsxRuntime.jsx(m,{style:a.rowTitle,children:y.type?ir(y.type):fe.visit}),b?jsxRuntime.jsx(m,{style:a.rowDetail,children:b}):null]})},y.encounterId)})})]}):null]}),jsxRuntime.jsx(hr,{disclaimer:e.disclaimer})]})}i(So,"RecordSections");function aa(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(aa,"heldCount");function gf(){let e=L();return react.useMemo(()=>bf(e),[e])}i(gf,"useLocalStyles");function bf(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},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,..._(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:{..._(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,..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},pendingText:{..._(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted,paddingBottom:r.md},identityLabel:{..._(e,"medium"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},identityValue:{flexShrink:1,textAlign:"right",..._(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:{..._(e,"bold"),fontSize:n.size.bodyTight,color:t.text.secondary,textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},noteBody:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.primary},noteBodyMuted:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.muted,fontStyle:"italic"}})}i(bf,"makeLocalStyles");var _n=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 hf=Math.round(ur/(1024*1024)),rt=Object.freeze({title:i(e=>`Upload ${He(e)}\u2019s records`,"title"),subtitle:i(e=>`Already have lab results, a vet summary, or test reports? Add them here and we\u2019ll read them and pull out ${He(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 ${hf} MB each. You can pick several at once. We\u2019ll read them and add the results to your records.`,chooseFiles:"Choose files",chooseFilesA11y:"Choose records to upload",uploading:i((e,t)=>`Uploading ${e+1} 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"),addMore:"Add more files",addMoreA11y:"Add more records",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."})});var Xc=Math.round(ur/(1024*1024)),Fr=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,t)=>`Uploading ${e+1} of ${t} records`,"uploading"),uploaded:i((e,t)=>`${e} of ${t} records uploaded`,"uploaded")});function Jc(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return Fr.done;case "failed":return Fr.failed;case "uploading":return e.progress>=1?Fr.verifying:`${t}%`;case "queued":return Fr.queued;default:return null}}i(Jc,"uploadItemStatusLabel");function Zc(e){if(e.length===0)return null;let t=i(l=>{let s=l.map(c=>c.name??"");return s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`},"nameList"),r=e.filter(l=>l.reason==="too_large"),o=e.filter(l=>l.reason==="unsupported"),n=[];return o.length>0&&n.push(`${t(o)} ${o.length>1?"are not PDFs":"is not a PDF"}`),r.length>0&&n.push(`${t(r)} ${r.length>1?"are":"is"} over ${Xc} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${Xc} MB right now.`}i(Zc,"skippedFilesMessage");function ed(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(ed,"skippedOf");var Ot=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 request",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 td({request:e,onRecovered:t,canUpload:r=false},o){let[n,l]=react.useState(""),[s,c]=react.useState(false),[a,d]=react.useState(null),[u,p]=react.useState(false),[f,h]=react.useState(null),R=react.useRef(false),v=react.useRef(false),y=react.useRef(0);react.useEffect(()=>(v.current=true,()=>{v.current=false,y.current+=1;}),[o]);let g=f!==null&&f.before===e.updatedAt?{...f.value,canRetrySend:e.canRetrySend===true&&f.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&f.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&f.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&f.value.canConvertToUpload===true}:e,b=n.trim(),w=b.length<=320&&!Array.from(b).some(I=>I.charCodeAt(0)<=32||I.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(b),x=g.canUpdateClinicEmail===true&&b.length>0,E=g.canRetrySend===true&&!s&&!x,D=g.canUpdateClinicEmail===true&&!s&&w,k=g.canConvertToUpload===true&&r,S=i(async I=>{let Y={retry:E,email:D,revoke:g.canRevoke===true&&u,convert:k};if(R.current||!v.current||!Y[I])return;R.current=true,c(true),d(null);let z=y.current,$=i(()=>v.current&&z===y.current,"live");try{let G=I==="retry"?await o.retryRequest(e.id):I==="email"?await o.updateClinicEmail(e.id,b):I==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!$())return;if(!G.ok){d(G.error);return}if(G.value.id!==e.id||G.value.petRef!==e.petRef){d(q("internalError"));return}h({before:e.updatedAt,value:G.value}),l(""),p(!1),t();}catch{$()&&d(q("internalError"));}finally{R.current=false,$()&&c(false);}},"run");return {request:g,email:n,busy:s,error:a,canRetry:E,canUpdateEmail:D,canConvert:k,hasEmailEdit:x,confirmingRevoke:u&&g.canRevoke===true,emailInvalid:b.length>0&&!w,setEmail(I){R.current||(l(I),d(null));},retry:i(()=>S("retry"),"retry"),updateEmail:i(()=>S("email"),"updateEmail"),revoke:i(()=>S("revoke"),"revoke"),convert:i(()=>S("convert"),"convert"),askRevoke(){!R.current&&g.canRevoke===true&&p(true);},keepRequest(){R.current||p(false);}}}i(td,"useRecordsRecovery");var vf=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],xf=["requested","awaiting_upload","records_received","processing","ready"],wf=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],In=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"}),kt=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"}),Cf=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"}),Ef=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 Sf(e){return e.wireStatus??Ef[e.status]??"sent"}i(Sf,"wireStatusOf");function kf(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(kf,"reminderProgressLabel");function Tf(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(Tf,"reachedRailIndex");function _f(e){switch(e.dispatchStatus){case "sent":return kt.delivered;case "preparing":case "queued":case "sending":return kt.emailing;case "failed":return kt.bounced;default:return null}}i(_f,"deliveryDetail");function Pf(e,t){return kf(t,e.reminderCount??0)??kt.waiting}i(Pf,"awaitingDetail");function If(e,t,r){let o=t.source==="owner_provided"||!!t.convertedToUploadAt;switch(e){case "sent_to_clinic":return _f(t);case "awaiting_clinic":return Pf(t,r);case "awaiting_upload":return kt.upload;case "records_received":return o?kt.ownerAdded:kt.clinicSent;case "processing":return kt.preparing;case "ready":return kt.ready;default:return null}}i(If,"railDetail");function Df(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(Df,"tookReviewBranch");function Af(e,t,r){if(e.key!=="processing"||!Df(t,r))return [e];let o=r==="parsing_failed",n=r==="published",l=n?"done":o?"current":"done",s=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:In.parsing_failed,detail:kt.parsingFailed,at:null,state:l},{key:"manual_review",title:In.manual_review,detail:kt.manualReview,at:t.reviewStartedAt??null,state:s}]}i(Af,"expandProcessingPhase");function Of(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(Of,"convertedReachedIndex");function rd(e){return {key:"awaiting_clinic",title:kt.switchedTitle,detail:kt.switched,at:e.convertedToUploadAt??null,state:"done"}}i(rd,"convertedClinicSwitchEvent");function Lf(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(Lf,"ownerReachedIndex");function Vf(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(Vf,"railTimestamp");function nd(e,t,r,o){return {key:e,title:In[e],detail:If(e,t,r),at:Vf(e,t,r),state:o}}i(nd,"railEvent");function lr(e,t){return {key:e,title:In[e],detail:Cf[e]??null,at:t.updatedAt||null,state:"failed"}}i(lr,"terminalEvent");function ca(e,t,r,o,n){return e.map((l,s)=>{let c=n?.(l)??null;if(c!==null)return c;let a=o==="published"||s<t?"done":s===t?"current":"upcoming";return nd(l,r,o,a)}).flatMap(l=>Af(l,r,o))}i(ca,"walkRail");function da(e){let t=Sf(e),r=i(n=>nd(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),lr("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),rd(e),r("awaiting_upload"),r("records_received"),lr("processing_failed",e)]:ca(wf,Of(t),e,t,n=>n==="awaiting_clinic"?rd(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),lr("processing_failed",e)];let n=Lf(t);return ca(xf,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("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"),lr("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),lr("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),lr("processing_failed",e)]:[r("requested"),lr("delivery_failed",e)]}let o=Tf(t);return ca(vf,o<0?1:o,e,t)}i(da,"buildRequestTimeline");var zf=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),ko=24,ua=10;function _o({request:e}){let t=Bf(),r=da(e);return jsxRuntime.jsx(reactNative.View,{style:t.container,accessibilityRole:"summary",children:r.map((o,n)=>jsxRuntime.jsx(Nf,{event:o,isLast:n===r.length-1,styles:t},o.key))})}i(_o,"RequestTimeline");function Nf({event:e,isLast:t,styles:r}){let o=e.at?Q(e.at):null,n=[e.title,e.detail,o,zf[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(Mf,{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(m,{style:[r.title,e.state==="current"&&r.titleCurrent,e.state==="failed"&&r.titleFailed,e.state==="upcoming"&&r.titleUpcoming],children:e.title}),o?jsxRuntime.jsx(m,{style:r.date,children:o}):null]}),e.detail?jsxRuntime.jsx(m,{style:[r.detail,e.state==="upcoming"&&r.detailUpcoming],children:e.detail}):null]})]})}i(Nf,"TimelineRow");function Mf({state:e,styles:t}){return e==="done"?jsxRuntime.jsx(reactNative.View,{style:[t.dot,t.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsxRuntime.jsx(m,{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(m,{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(Mf,"TimelineDot");function Bf(){let e=L();return react.useMemo(()=>Hf(e),[e])}i(Bf,"useStyles");function Hf(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:ko},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},dot:{width:ko,height:ko,borderRadius:ko/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brand,backgroundColor:t.surface},dotCurrentCore:{width:ua,height:ua,borderRadius:ua/2,backgroundColor:t.brand},dotUpcoming:{borderWidth:2,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},glyph:{..._(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:{flex:1,..._(e,"bold"),fontSize:o.body,lineHeight:o.body+4,color:t.text.primary},titleCurrent:{color:t.brandInk},titleFailed:{color:t.danger},titleUpcoming:{color:t.text.muted,..._(e,"regular")},date:{..._(e,"regular"),fontSize:o.caption,lineHeight:o.caption+4,color:t.text.muted},detail:{..._(e,"regular"),fontSize:o.bodyTight,lineHeight:o.bodyTight+4,color:t.text.muted},detailUpcoming:{color:t.text.muted,opacity:.7}})}i(Hf,"makeStyles");function Yr(e,t,r){let o=xr(e,r);switch(o.kind){case "consent_required":return jsxRuntime.jsx($f,{onGrant:t});case "consent_unavailable":return jsxRuntime.jsx(Wf,{});case "session_required":return jsxRuntime.jsx(Gf,{});case "withheld":return jsxRuntime.jsx(Yf,{});case "pet_not_found":case "error":return jsxRuntime.jsx(Kf,{error:o.error,onRetry:e.refresh});default:return pr(o)}}i(Yr,"renderErrorFamily");function Kr(e,t){return ()=>{let r=ea(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(Kr,"makeGrantHandler");function ad({records:e}){let t=An(),r=e.uploadQueue;if(r.length===0)return null;let o=r.filter(s=>s.status!=="skipped"),n=o.filter(s=>s.status==="done").length,l=Zc(ed(r));return jsxRuntime.jsxs(reactNative.View,{style:t.timeline,testID:"records-upload-queue",children:[l!==null?jsxRuntime.jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:t.errorText,children:l}):null,o.length>0?jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",accessibilityLabel:e.isUploading?Fr.uploading(n,o.length):Fr.uploaded(n,o.length),children:o.map(s=>{let c=Math.round(s.progress*100);return jsxRuntime.jsxs(reactNative.View,{style:t.row,testID:`records-upload-file-${s.status}`,children:[jsxRuntime.jsx(m,{style:t.rowLabel,children:s.name??""}),jsxRuntime.jsx(m,{style:t.rowValue,children:Jc(s)}),s.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,s.status==="failed"&&s.error?jsxRuntime.jsx(m,{style:t.timelineMeta,children:s.error.displayMessage}):null]},s.key)})}):null]})}i(ad,"UploadQueue");function $f({onGrant:e}){let t=An();return jsxRuntime.jsx(reactNative.View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:ce.consentRequired,children:jsxRuntime.jsx(reactNative.Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:ce.allow,style:t.primaryButton,children:jsxRuntime.jsx(m,{style:t.primaryLabel,children:ce.allow})})})}i($f,"ConsentRequiredState");function ya({label:e,glyph:t}){let r=An();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(m,{style:r.errorText,children:e})]})}i(ya,"AlertState");function Wf(){return jsxRuntime.jsx(ya,{label:ce.consentRequired,glyph:"empty"})}i(Wf,"ConsentUnavailableState");function Gf(){return jsxRuntime.jsx(ya,{label:ce.sessionRequired,glyph:"empty"})}i(Gf,"SessionRequiredState");function Yf(){return jsxRuntime.jsx(ya,{label:ce.recordUnavailable,glyph:"withheld"})}i(Yf,"WithheldState");function Kf({error:e,onRetry:t}){let r=An();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(m,{style:r.errorText,children:e.displayMessage}),e.retryable?jsxRuntime.jsx(reactNative.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:ce.retry,style:r.primaryButton,children:jsxRuntime.jsx(m,{style:r.primaryLabel,children:ce.retry})}):null]})}i(Kf,"ErrorState");function sd({call:e,prompt:t}){let r=An(),o=t.trim().length>0?t:_n.fallbackPrompt;return jsxRuntime.jsxs(reactNative.View,{style:r.callCard,accessibilityRole:"summary",children:[jsxRuntime.jsx(m,{style:r.timelineLabel,children:_n.heading}),jsxRuntime.jsx(m,{style:r.timelineMeta,children:o}),jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{reactNative.Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:_n.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsxRuntime.jsx(m,{style:r.linkLabel,children:_n.call})})]})}i(sd,"ClinicCallCard");function An(){let e=L();return react.useMemo(()=>Qf(e),[e])}i(An,"useStyles");function Qf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c,letterSpacing:a}=n,d=Je(l.recordCard,reactNative.StyleSheet.hairlineWidth),u=ot(l.recordCard),p=i((b,w)=>Math.round(b*w),"lh"),f=reactNative.StyleSheet.hairlineWidth,h=r.xxl*3+r.xl,R=r.xxl+r.md,v=r.xxl+r.sm,y=e.brightness==="dark"?t.errorRed:t.danger,g={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:h,backgroundColor:t.background},body:{flex:1},centered:{minHeight:h,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:v,height:v,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:f,borderColor:t.brandBorder},withheldGlyph:{width:v,height:v,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:f,borderColor:t.cautionAccent},errorText:{..._(e,"regular"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:y,textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},linkButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...Je(l.primaryButton)},linkLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},disabledButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.surfaceSubtle,borderWidth:f,borderColor:t.brandBorder},disabledLabel:{..._(e,"bold"),color:t.text.muted,fontSize:s.body,letterSpacing:a.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:f,borderColor:t.brandBorder,gap:r.xs,...g,...d},timelineTitle:{..._(e,"bold"),fontSize:s.heading,lineHeight:p(s.heading,c.snug),color:t.text.primary,letterSpacing:a.tight,...u},timelineLabel:{..._(e,"bold"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:t.text.secondary,letterSpacing:a.tight,...u},callCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...d},timelineMeta:{..._(e,"regular"),fontSize:s.bodyTight,lineHeight:p(s.bodyTight,c.normal),color:t.text.muted,...u},recordBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...g,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:f,borderBottomColor:t.borderHairlineGreen},rowLabel:{..._(e,"regular"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.muted,flexShrink:1,...u},rowValue:{..._(e,"medium"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.primary,textAlign:"right",flexShrink:1,...u},disclaimer:{..._(e,"regular"),fontSize:s.caption,lineHeight:p(s.caption,c.normal),color:t.text.muted,marginTop:r.md},progressTrack:{height:r.xs,borderRadius:o.pill,backgroundColor:t.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:t.brand}})}i(Qf,"makeStyles");var Zf=i((e,t)=>e.getRecordDepth(t),"readDepth"),eg=i(e=>!e.available,"depthEmpty");function ha(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack","onAsk"]);return jsxRuntime.jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsxRuntime.jsx(tg,{...o,style:t})})}i(ha,"EverfurRecordsDashboard");function tg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,style:c}){let a=be(),d=Ra(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=Qi(e),f=Ut(e,Zf,eg),[h,R]=react.useState(null),v=react.useCallback((C,T)=>R({marker:C,point:T}),[]),y=react.useMemo(()=>qr(o,u.consent),[o,u.consent]),g=react.useMemo(()=>Kr(u,o),[u,o]),b=p.markers?.markers??[],w=b.length>0,x=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,E=Qn(u.requests,e),D=si({hasMarkers:w,requests:u.requests,petRef:e}),k=li({recordLoading:u.status==="loading",hasFullRecord:x,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:w,requestsLoading:u.status==="loading",dashboardState:D,drivingRequest:E}),S=p.markers?.disclaimer??u.record?.disclaimer??"",I=i(()=>{u.refresh(),p.refresh(),f.refresh();},"retryAll"),Y=f.value!==null&&!f.value.withheld&&f.value.available?f.value:null,z=He(t),$=s&&p.markers?.summary?()=>{let C=Rc(t,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);s(C.prompt,C.entityRef);}:void 0,G=s?C=>{let T=hc(t,{canonicalName:C.name,markerId:C.markerId,latestValueText:C.latest?Et(C.latest.value,C.unit,C.latest.qualitativeResult):null,statusText:C.latest?Qt(C.latest.status).label:null,trajectoryText:Hr(C.trajectory,C.points.length),meaningText:C.meaning});s(T.prompt,T.entityRef);}:void 0,Z=s&&h?()=>{let{marker:C,point:T}=h,A=vc(t,{canonicalName:C.name,valueText:Et(T.value,C.unit,T.qualitativeResult),collectedAt:Q(T.at),sourceClinic:T.sourceClinic,referenceText:T.refLow!==null||T.refHigh!==null?go(T,C.unit):null,flagged:T.status==="above"?"above":T.status==="below"?"below":null,reviewed:T.reviewed,entityId:T.docId??C.markerId});R(null),s(A.prompt,A.entityRef);}:void 0,oe=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[p.markers?.summary?jsxRuntime.jsx(reactNative.View,{style:a.inset,children:jsxRuntime.jsx(Dc,{summary:p.markers.summary,onAsk:$,testID:"dashboard-marker-summary"})}):null,jsxRuntime.jsx(m,{style:a.lead,children:dt.lead(t)}),jsxRuntime.jsx(qc,{markers:b,onPointPress:v,onAsk:G})]}),Ee=i(C=>n?jsxRuntime.jsxs(reactNative.View,{style:[a.inset,d.actions],children:[C?jsxRuntime.jsx(fa,{label:dt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsxRuntime.jsx(fa,{label:dt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"})]}):null,"actions"),H;if(u.status==="error"){let C=xr(u,y);H=C.kind==="error"||C.kind==="pet_not_found"?jsxRuntime.jsx(Qe,{variant:wt(C.error),message:C.error.displayMessage,onAction:C.error.retryable?I:void 0,testID:"dashboard-error"}):Yr(u,g,y);}else switch(k){case "loading":H=jsxRuntime.jsx(io,{testID:"dashboard-loading"});break;case "record":H=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-record",children:[w?oe:p.status==="error"?jsxRuntime.jsx(reactNative.View,{style:[a.inset,d.actions],children:jsxRuntime.jsx(fa,{label:dt.retryMarkers,onPress:I,testID:"dashboard-markers-retry"})}):null,jsxRuntime.jsx(reactNative.View,{style:a.inset,children:u.record?jsxRuntime.jsx(So,{record:u.record,depth:Y,petName:t,showLabs:!w,onNavigate:n,onAsk:s}):null}),Ee(true)]});break;case "error":H=jsxRuntime.jsx(Qe,{variant:wt(p.error??u.error),message:(p.error??u.error)?.displayMessage,onAction:(p.error??u.error)?.retryable?I:void 0,testID:"dashboard-error"});break;case "in_progress":H=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:a.content,testID:"dashboard-in-progress",children:[E?jsxRuntime.jsx(rg,{request:E,petName:z,onOpen:n?()=>n({name:"request",requestId:E.id}):void 0,onAsk:s?()=>{let C=xc(t,{clinicName:E.clinicName??null,statusLabel:En(E),status:E.status,heldItemCount:E.heldItemCount},E.id);s(C.prompt,C.entityRef);}:void 0}):null,jsxRuntime.jsx(hr,{disclaimer:S})]});break;case "none":H=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:a.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(m,{style:d.promptTitle,children:_r.title(t)})]}),jsxRuntime.jsx(m,{style:d.promptBody,children:_r.body}),n?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(re,{label:_r.requestFromClinic,accessibilityLabel:_r.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsxRuntime.jsx(re,{label:_r.uploadDocument,kind:"outline",accessibilityLabel:_r.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsxRuntime.jsx(hr,{disclaimer:S})]});break;case "labs_only":H=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-labs-only",children:[oe,jsxRuntime.jsx(reactNative.View,{style:a.inset,children:jsxRuntime.jsx(hr,{disclaimer:S})}),Ee(false)]});break;default:H=pr(k);}return jsxRuntime.jsxs(reactNative.View,{style:[a.root,c],children:[jsxRuntime.jsx(et,{title:dt.title,onBack:l,testID:"dashboard-header",right:n?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>n({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:dt.openTimeline,hitSlop:12,style:d.headerButton,testID:"dashboard-timeline-link",children:jsxRuntime.jsx(fl,{})}):void 0}),jsxRuntime.jsx(reactNative.View,{style:a.body,children:H}),jsxRuntime.jsx(Fc,{marker:h?.marker??null,point:h?.point??null,onClose:()=>R(null),onAsk:Z}),jsxRuntime.jsx(Me,{})]})}i(tg,"DashboardBody");function fa({label:e,onPress:t,testID:r}){let o=Ra();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(m,{style:o.actionLabel,children:e})]}),jsxRuntime.jsx(Pr,{})]})}i(fa,"ActionRow");function rg({request:e,petName:t,onOpen:r,onAsk:o}){let n=be(),l=Ra(),s=e.clinicName?.trim()||Mr.title(t),c=En(e),a=jsxRuntime.jsxs(reactNative.View,{style:l.inProgressInner,children:[jsxRuntime.jsxs(reactNative.View,{style:l.inProgressHead,children:[jsxRuntime.jsx(m,{style:l.inProgressTitle,children:s}),r?jsxRuntime.jsx(Pr,{}):null]}),jsxRuntime.jsx(_o,{request:e}),c.length>0?jsxRuntime.jsx(reactNative.View,{style:n.statusCard,children:jsxRuntime.jsx(m,{style:n.statusText,children:c})}):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:Mr.a11y(t),children:[r?jsxRuntime.jsx(reactNative.Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Mr.openA11y(t,c),testID:"dashboard-in-progress-open",children:a}):a,o?jsxRuntime.jsx(re,{label:Mr.ask,kind:"ask",accessibilityLabel:Mr.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(rg,"InProgressCard");function Ra(){let e=L();return react.useMemo(()=>ng(e),[e])}i(Ra,"useLocalStyles");function ng(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,s=r.xxl+r.md;return reactNative.StyleSheet.create({headerButton:{width:s,height:s,alignItems:"center",justifyContent:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:l,borderColor:t.brandBorder,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,..._(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},inProgressCard:{borderRadius:o.lg-r.xs/2,backgroundColor:t.surface,borderWidth:l,borderColor:t.brandBorder,padding:r.lg+r.xs/2,gap:r.lg},inProgressInner:{gap:r.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},inProgressTitle:{flex:1,..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),color:t.text.primary},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,..._(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,..._(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}})}i(ng,"makeLocalStyles");var Io=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function dd(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(dd,"toMillis");function ud(e){let t=[...e.visits.map((r,o)=>({key:`visit-${o}-${r.visitId}`,kind:"visit",kindLabel:fe.kind.visit,at:r.visitDate,date:Q(r.visitDate),title:r.summary??fe.clinicVisit,detail:r.veterinarian?fe.doctor(r.veterinarian):null,docId:r.docId})),...e.vaccines.map((r,o)=>{let n=[];return r.lot&&n.push(fe.lot(r.lot)),r.expiresOn&&n.push(fe.expires(Q(r.expiresOn))),{key:`vaccine-${o}-${r.vaccineId}`,kind:"vaccine",kindLabel:fe.kind.vaccine,at:r.administeredOn,date:Q(r.administeredOn),title:r.product||fe.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:fe.kind.weight,at:r.observedOn,date:Q(r.observedOn),title:Cl(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:fe.kind.medication,at:r.startedOn,date:Q(r.startedOn),title:r.drugName||fe.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}})];return Object.freeze(t.sort((r,o)=>{let n=dd(r.at),l=dd(o.at);return n===null&&l===null?Io[r.kind]-Io[o.kind]:n===null?1:l===null?-1:l!==n?l-n:Io[r.kind]-Io[o.kind]}))}i(ud,"buildTimelineRows");var cg=300,dg=i((e,t)=>e.getTimeline(t),"readTimeline"),ug=i(e=>e.isEmpty,"timelineEmpty");var pg=i(e=>e.contributions.length===0,"contributionsEmpty");function yd({petRef:e,style:t,onBack:r}){let o=Ut(e,dg,ug);return jsxRuntime.jsx(gd,{state:o,style:t,onBack:r,header:jsxRuntime.jsx(et,{title:fe.timeline,onBack:an(r),testID:"timeline-header"}),loading:jsxRuntime.jsx(Pl,{testID:"timeline-loading"}),empty:jsxRuntime.jsx(Qe,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsxRuntime.jsx(fg,{timeline:n})})}i(yd,"EverfurRecordsTimeline");function fd({petRef:e,docId:t,style:r,onBack:o}){let n=react.useCallback((c,a)=>c.getDocumentContributions(a,t),[t]),l=Ut(e,n,pg,t),s=l.value?.document?.title?.trim()||fe.uploadedDocument;return jsxRuntime.jsx(gd,{state:l,style:r,onBack:o,header:jsxRuntime.jsx(et,{title:s,onBack:an(o),testID:"contributions-header"}),empty:jsxRuntime.jsx(Qe,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsxRuntime.jsx(gg,{view:c})})}i(fd,"EverfurDocumentContributions");function gd({state:e,style:t,header:r,loading:o,empty:n,render:l,onBack:s}){let c=va();return jsxRuntime.jsx(Ne,{capability:"records",style:t,...Be(an(s),Ze),children:jsxRuntime.jsxs(reactNative.View,{style:[c.container,t],children:[r??null,jsxRuntime.jsx(reactNative.View,{style:c.body,children:mg(e,l,c,o,n)}),jsxRuntime.jsx(Me,{})]})})}i(gd,"DepthSurface");function mg(e,t,r,o,n){switch(e.status){case "loading":return o??jsxRuntime.jsx(yg,{styles:r});case "empty":return n??jsxRuntime.jsx(reactNative.View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:ce.empty,children:jsxRuntime.jsx(reactNative.View,{style:r.emptyGlyph})});case "error":return e.error?jsxRuntime.jsx(Qe,{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(mg,"renderState");function yg({styles:e}){let[t,r]=react.useState(false);return react.useEffect(()=>{let o=setTimeout(()=>r(true),cg);return ()=>clearTimeout(o)},[]),jsxRuntime.jsx(reactNative.View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:ce.loading,children:t?jsxRuntime.jsx(reactNative.ActivityIndicator,{}):null})}i(yg,"LoadingState");function fg({timeline:e}){let t=va(),r=ud(e);return jsxRuntime.jsxs(reactNative.ScrollView,{style:t.list,contentContainerStyle:t.timelineContent,accessibilityLabel:fe.timeline,children:[e.disclaimer.length>0?jsxRuntime.jsx(reactNative.View,{style:t.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e.disclaimer),children:jsxRuntime.jsx(m,{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(m,{style:t.timelineKind,children:o.kindLabel}),jsxRuntime.jsx(m,{style:t.date,children:o.date})]}),jsxRuntime.jsx(m,{style:t.timelineTitle,children:o.title}),o.detail?jsxRuntime.jsx(m,{style:t.rowDetail,children:o.detail}):null]})]})]},o.key))]})}i(fg,"TimelineBody");function gg({view:e}){let t=va();return jsxRuntime.jsxs(reactNative.ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:ce.records,children:[e.document?.receivedAt?jsxRuntime.jsx(m,{style:t.rowDetail,children:Q(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(m,{style:t.rowTitle,children:r.label}),jsxRuntime.jsx(m,{style:t.rowValue,children:Br(r.value,r.unit)}),r.observedAt?jsxRuntime.jsx(m,{style:t.rowDetail,children:Q(r.observedAt)}):null]},r.key))})]})}i(gg,"ContributionsBody");function va(){let e=L();return react.useMemo(()=>bg(e),[e])}i(va,"useStyles");function bg(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((y,g)=>Math.round(y*g),"lh"),d=reactNative.StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,p=r.xxl+r.md,f=e.brightness==="dark"?t.errorRed:t.danger,h=ot(l.recordCard),R=i((y,g,b,w="regular")=>({..._(e,w),fontSize:y,lineHeight:a(y,g),color:b}),"text"),v=i((y,g,b,w="regular")=>({...R(y,g,b,w),...h}),"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:{...R(s.subtitle,c.snug,f),textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:p,minWidth:p,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,...ot(l.primaryButton)},list:{flex:1},listContent:{padding:r.lg,gap:r.md},section:{gap:r.sm},heading:{...R(s.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,...Je(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:{...v(s.caption,c.normal,t.text.muted,"medium")},date:v(s.caption,c.normal,t.text.muted),rowTitle:{...v(s.body,c.normal,t.text.primary,"bold")},rowValue:{...v(s.body,c.normal,t.text.primary,"medium")},rowDetail:v(s.bodyTight,c.normal,t.text.muted),rowMuted:{...v(s.bodyTight,c.normal,t.text.muted),opacity:.7},chip:{...R(s.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:{...R(s.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,...R(s.caption,c.normal,t.text.secondary)},timelineSeparator:{height:d,backgroundColor:t.brandBorder,marginLeft:Ti},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:{..._(e,"mono"),fontSize:s.micro,lineHeight:s.bodyTight,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:t.text.secondary},timelineTitle:{...R(s.body,c.normal,t.text.primary,"medium")}})}i(bg,"makeStyles");function xa(e,t={}){let r=sr(),{userRef:o}=ke(),n=t.now??Date.now,[l,s]=react.useState(null),[c,a]=react.useState(true),[d,u]=react.useState(null),[p,f]=react.useState(null),h=p===true,[R,v]=react.useState({}),[y,g]=react.useState(false),[b,w]=react.useState(null),[x,E]=react.useState(false),[D,k]=react.useState(false),S=Mn(e),I=react.useRef(0),Y=react.useRef(true),z=react.useCallback(async()=>{let T=I.current+=1;if(a(true),u(null),o===null){s(null),a(false);return}let A=await r.listShares(e);T!==I.current||!Y.current||(A.ok?(s(A.value),f(true)):vr(A.error)?(s(null),f(false)):(s(null),u(A.error),bd(A)&&f(true)),a(false));},[r,e,o]);react.useEffect(()=>(Y.current=true,z(),()=>{Y.current=false,I.current+=1;}),[z]);let $=react.useRef(S);react.useEffect(()=>{$.current!==S&&($.current=S,v({}),k(true),z());},[S,z]);let G=react.useCallback(async()=>{g(true);let T=await r.createShare(e);return Y.current&&(g(false),T.ok?(v(A=>({...A,[T.value.shareId]:T.value.shareUrl})),z()):vr(T.error)?f(false):tr(T.error)&&k(true)),T},[r,e,z]),Z=react.useCallback(async T=>{w(T);let A=await r.revokeShare(e,T);return Y.current&&(w(null),z()),A},[r,e,z]),oe=react.useCallback(async()=>{E(true);let T=await r.getPdfLink(e);return Y.current&&(E(false),!T.ok&&tr(T.error)&&k(true)),T},[r,e]),Ee=react.useCallback(()=>{k(false),z();},[z]),H=react.useMemo(()=>El(l??[],R,n()),[l,R,n]),C=c?"loading":d!==null?"error":H.length===0?"empty":"populated";return react.useMemo(()=>({status:C,rows:H,available:h,consentRequired:D,error:d,creating:y,revokingId:b,preparingPdf:x,createLink:G,revoke:Z,pdfLink:oe,refresh:Ee}),[C,H,h,D,d,y,b,x,G,Z,oe,Ee])}i(xa,"useRecordShares");function bd(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(bd,"answeredBehindGate");function hd(e){return e.available||e.status!=="empty"}i(hd,"sharesListShown");function wa(e){let t=sr(),{userRef:r}=ke(),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(a=>{c&&(!a.ok&&vr(a.error)?l({scope:o,lit:false}):bd(a)&&l({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[t,e,r,o]);let s=n.scope===o?n.lit:null;return react.useMemo(()=>({lit:s}),[s])}i(wa,"useRecordsDepthProbe");function Ca(e){let t=sr(),o=wa(e).lit===true,[n,l]=react.useState(false),[s,c]=react.useState(null),a=react.useRef(true);react.useEffect(()=>(a.current=true,()=>{a.current=false;}),[]);let d=react.useCallback(async()=>{l(true),c(null);let u=await t.getPdfLink(e);return a.current&&(l(false),u.ok||c(u.error)),u},[t,e]);return react.useMemo(()=>({preparing:n,available:o,error:s,pdfLink:d}),[n,o,s,d])}i(Ca,"useRecordPdfLink");var Tt=W.document,xd=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),xg=i((e,t)=>e.getRecordDepth(t),"readDepth"),wg=i(e=>!e.available,"depthEmpty");function Ea(e){let{style:t,renderPending:r,...o}=Fe(e,["onBack"]);return jsxRuntime.jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsxRuntime.jsx(Eg,{...o,style:t})})}i(Ea,"EverfurRecordDocument");function Cg(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(Cg,"documentIsEmpty");function Eg({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:l,style:s}){let c=be(),a=wd(),d=L(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=Ut(e,xg,wg),f=Ca(e),h=react.useMemo(()=>qr(o,u.consent),[o,u.consent]),R=react.useMemo(()=>Kr(u,o),[u,o]),v=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,y=u.record,g=i(()=>{f.pdfLink().then(x=>{if(!x.ok)return;kr(l??(D=>reactNative.Linking.openURL(D)),x.value.downloadUrl,"record_pdf");});},"download"),b,w=false;if(u.status==="loading"||p.status==="loading"&&y!==null)b=jsxRuntime.jsx(reactNative.View,{style:a.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:"record-document-loading",children:jsxRuntime.jsx(reactNative.ActivityIndicator,{color:d.color.brandInk})});else if(u.status==="error"){let x=xr(u,h);b=x.kind==="error"||x.kind==="pet_not_found"?jsxRuntime.jsx(Qe,{variant:wt(x.error),message:x.error.displayMessage,onAction:x.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):Yr(u,R,h);}else y===null||Cg(y,v)?b=jsxRuntime.jsx(reactNative.View,{style:a.centered,testID:"record-document-empty",children:jsxRuntime.jsx(m,{style:a.emptyText,children:Tt.empty})}):(w=true,b=jsxRuntime.jsx(Sg,{record:y,depth:v,petName:t,wordmark:d.meta.displayName}));return jsxRuntime.jsxs(reactNative.View,{style:[c.root,a.root,s],children:[jsxRuntime.jsx(et,{title:Tt.title,variant:"document",onBack:n,testID:"record-document-header",right:f.available&&w?jsxRuntime.jsx(reactNative.Pressable,{onPress:g,disabled:f.preparing,accessibilityRole:"button",accessibilityLabel:Tt.download,accessibilityState:{disabled:f.preparing,busy:f.preparing},hitSlop:8,style:a.download,testID:"record-document-download",children:f.preparing?jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:d.color.brandInk}):jsxRuntime.jsx(hl,{})}):void 0}),f.error?jsxRuntime.jsx(m,{style:[c.errorText,a.inset],accessibilityRole:"alert",children:f.error.displayMessage}):null,jsxRuntime.jsx(reactNative.View,{style:c.body,children:b}),jsxRuntime.jsx(Me,{})]})}i(Eg,"DocumentBody");function Sg({record:e,depth:t,petName:r,wordmark:o}){let n=wd(),l=react.useMemo(()=>{let a=[],d=new Map;for(let f of e.entities){let h=f.category.trim();if(h.length===0)continue;let R=d.get(h);R===void 0?(a.push(h),d.set(h,[f])):R.push(f);}let u=xd.filter(f=>a.includes(f)),p=a.filter(f=>!xd.includes(f));return [...u,...p].map(f=>({type:f,rows:d.get(f)??[]}))},[e.entities]),s=Date.now(),c=i((a,d,u)=>jsxRuntime.jsxs(reactNative.View,{style:n.section,testID:u,children:[jsxRuntime.jsxs(reactNative.View,{style:n.sectionHeader,children:[jsxRuntime.jsx(m,{style:n.sectionTitle,accessibilityRole:"header",children:a}),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(m,{style:n.wordmark,children:o}),jsxRuntime.jsx(m,{style:n.docTitle,children:Tt.docTitle}),jsxRuntime.jsx(m,{style:n.petName,children:r?.trim()||Tt.namelessPet}),jsxRuntime.jsx(m,{style:n.generated,children:Tt.generated(e.generatedAt)})]}),e.identity.length>0?c(Tt.identity,e.identity.map((a,d)=>jsxRuntime.jsxs(reactNative.View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxRuntime.jsx(m,{style:n.rowLabel,children:a.label}),jsxRuntime.jsx(m,{style:n.rowValue,children:a.value})]},`${d}:${a.label}`)),"record-document-identity"):null,t&&t.labResults.length>0?c(Tt.labs,t.labResults.map((a,d)=>{let u=Qt(a.latest.status),p=Bc(a.points[a.points.length-1]??null),f=Et(a.latest.value,a.latest.unit??a.unit,a.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(m,{style:n.rowLabel,children:a.name}),jsxRuntime.jsxs(m,{style:n.rowMeta,children:[p?Tt.ref(p):Tt.noRange,a.latest.at?` \xB7 ${Q(a.latest.at)}`:""]})]}),jsxRuntime.jsxs(reactNative.View,{style:n.rowRight,children:[f!=="-"?jsxRuntime.jsx(m,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:f}):null,jsxRuntime.jsx(m,{style:[n.markerStatus,u.outOfRange?n.rowValueAlert:null],children:u.label})]})]},a.markerId)}),"record-document-labs"):null,l.map(({type:a,rows:d})=>c(kn(a),d.map((u,p)=>{let f=[Br(u.value,u.unit),u.observedAt?Q(u.observedAt):null].filter(h=>h&&h.length>0).join(" \xB7 ");return jsxRuntime.jsx(reactNative.View,{style:[n.row,p>0?n.rowDivider:null],children:jsxRuntime.jsxs(reactNative.View,{style:n.rowMain,children:[jsxRuntime.jsx(m,{style:n.rowLabel,children:u.label}),f?jsxRuntime.jsx(m,{style:n.rowMeta,children:f}):null]})},u.key)}),`record-document-${a}`)),e.forwardLooking.length>0?c(Tt.upcomingCare,e.forwardLooking.map((a,d)=>{let u=Tn(a.dueAt,s);return jsxRuntime.jsxs(reactNative.View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxRuntime.jsxs(reactNative.View,{style:n.rowMain,children:[jsxRuntime.jsx(m,{style:n.rowLabel,children:a.title}),a.detail?jsxRuntime.jsx(m,{style:n.rowMeta,children:a.detail}):null]}),u?jsxRuntime.jsx(m,{style:[n.rowValue,u.overdue?n.rowValueAlert:null],children:u.label}):null]},`${a.title}-${d}`)}),"record-document-upcoming"):null,t&&t.physicalExams.length>0?c(Tt.physicalExams,t.physicalExams.map((a,d)=>jsxRuntime.jsxs(reactNative.View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsxRuntime.jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.systems.filter(u=>u.finding).map(u=>jsxRuntime.jsxs(reactNative.View,{style:n.fieldRow,children:[jsxRuntime.jsx(m,{style:n.fieldLabel,children:Ir(u.system)}),jsxRuntime.jsx(m,{style:n.fieldValue,children:u.finding})]},u.system))]},a.examId)),"record-document-exams"):null,t&&t.clinicianNotes.length>0?c(Tt.clinicianNotes,t.clinicianNotes.map((a,d)=>jsxRuntime.jsxs(reactNative.View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsxRuntime.jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.sections.filter(u=>u.text).map((u,p)=>jsxRuntime.jsxs(reactNative.View,{style:n.noteSection,children:[jsxRuntime.jsx(m,{style:n.noteLabel,children:Ur(u.section)}),jsxRuntime.jsx(m,{style:n.noteBody,children:u.text})]},`${u.section}-${p}`))]},a.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsxRuntime.jsx(reactNative.View,{style:n.disclaimer,children:jsxRuntime.jsx(m,{style:n.disclaimerText,children:e.disclaimer})}):null]})}i(Sg,"RecordDocument");function wd(){let e=L();return react.useMemo(()=>kg(e),[e])}i(wd,"useLocalStyles");function kg(e){let{color:t,space:r,radius:o,type:n}=e,l=reactNative.StyleSheet.hairlineWidth,s=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text"),c=i((a,d)=>({..._(e,"mono"),fontSize:a,lineHeight:a+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:{...s(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.brand,gap:r.xs+r.xs/2,marginBottom:r.sm},wordmark:{...s(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:s(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,...s(n.size.body,n.lineHeight.normal,t.text.primary,"medium")},rowValue:{...s(n.size.body,n.lineHeight.normal,t.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:t.danger},rowMeta:{marginTop:r.xs/2,..._(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,...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted,"medium")},fieldValue:{flex:1,...s(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:s(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:s(n.size.tiny,n.lineHeight.relaxed,t.text.muted)})}i(kg,"makeLocalStyles");function Sd({petRef:e,onClose:t,onNavigate:r,onOpenUrl:o,onCopy:n}){let l=Dg(),s=be(),c=xa(e),[a,d]=react.useState(null),[u,p]=react.useState(null),f=c.available&&!c.consentRequired,h=i((b,w)=>{kr(o??(E=>reactNative.Linking.openURL(E)),b,w).then(E=>{E.ok||d(de.toasts.shareSheet);});},"open"),R=i(()=>{d(null),c.createLink().then(b=>{b.ok?h(b.value.shareUrl,"share_link"):d(ro(b.error,"create"));});},"onCreateLink"),v=i(()=>{d(null),c.pdfLink().then(b=>{b.ok?h(b.value.downloadUrl,"record_pdf"):d(ro(b.error,"download"));});},"onDownload"),y=i(b=>{!n||b.shareUrl===null||kr(n,b.shareUrl).then(w=>d(w.ok?de.toasts.copied:de.toasts.copyFailed));},"onCopyRow"),g=i(b=>{c.revoke(b).then(w=>{p(null),d(w.ok?de.toasts.turnedOff:ro(w.error,"revoke"));});},"onConfirmRevoke");return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:t,children:jsxRuntime.jsxs(reactNative.View,{style:l.backdrop,children:[jsxRuntime.jsx(reactNative.Pressable,{style:reactNative.StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:de.closeSheetA11y,onPress:t}),jsxRuntime.jsxs(reactNative.View,{style:l.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[jsxRuntime.jsx(reactNative.View,{style:l.handle}),jsxRuntime.jsxs(reactNative.View,{style:l.header,children:[jsxRuntime.jsxs(reactNative.View,{style:l.headerText,children:[jsxRuntime.jsx(m,{style:l.title,accessibilityRole:"header",children:de.title}),jsxRuntime.jsx(m,{style:l.helper,children:de.helper})]}),jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:de.close,onPress:t,hitSlop:12,style:l.closeButton,testID:"share-record-close",children:jsxRuntime.jsx(m,{style:l.closeGlyph,children:"\xD7"})})]}),jsxRuntime.jsxs(reactNative.ScrollView,{style:l.scroll,contentContainerStyle:l.body,showsVerticalScrollIndicator:false,children:[jsxRuntime.jsxs(reactNative.View,{style:l.actions,children:[r?jsxRuntime.jsx(re,{label:de.viewDocument,onPress:()=>{t(),r({name:"document"});},testID:"share-view-document"}):null,f?jsxRuntime.jsx(re,{label:c.creating?de.creatingLink:de.createLink,kind:"outline",busy:c.creating,onPress:R,testID:"share-create-link"}):null,f?jsxRuntime.jsx(re,{label:c.preparingPdf?de.preparingPdf:de.downloadPdf,kind:"outline",busy:c.preparingPdf,onPress:v,testID:"share-download-pdf"}):null]}),c.consentRequired?jsxRuntime.jsxs(reactNative.View,{style:l.stateCard,testID:"share-consent-off",children:[jsxRuntime.jsx(m,{style:l.stateTitle,accessibilityRole:"header",children:de.consentOffTitle}),jsxRuntime.jsx(m,{style:l.stateBody,children:de.consentOffBody}),jsxRuntime.jsx(re,{label:de.retry,kind:"outline",onPress:c.refresh,testID:"share-consent-retry"})]}):null,a?jsxRuntime.jsx(m,{style:l.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:a}):null,hd(c)?jsxRuntime.jsxs(reactNative.View,{style:l.section,children:[jsxRuntime.jsx(m,{style:l.sectionLabel,accessibilityRole:"header",children:de.activeLinks}),c.status==="loading"?jsxRuntime.jsx(Dl,{testID:"share-record-loading"}):c.status==="error"?jsxRuntime.jsxs(reactNative.View,{style:l.stateCard,testID:"share-record-error",children:[jsxRuntime.jsx(m,{style:l.stateTitle,children:de.errorTitle}),jsxRuntime.jsx(m,{style:l.stateBody,children:de.errorBody}),jsxRuntime.jsx(re,{label:de.retry,kind:"outline",onPress:c.refresh,testID:"share-record-retry"})]}):c.rows.length===0?jsxRuntime.jsxs(reactNative.View,{style:l.stateCard,testID:"share-record-empty",children:[jsxRuntime.jsx(m,{style:l.stateTitle,children:de.emptyTitle}),jsxRuntime.jsx(m,{style:l.stateBody,children:de.emptyBody})]}):jsxRuntime.jsx(reactNative.View,{style:l.list,children:c.rows.map(b=>jsxRuntime.jsxs(reactNative.View,{style:l.row,testID:`share-row-${b.shareId}`,children:[jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:b.a11yLabel,children:[jsxRuntime.jsxs(reactNative.View,{style:l.statusLine,children:[jsxRuntime.jsx(reactNative.View,{style:[l.statusDot,{backgroundColor:b.active?l.active.color:l.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(m,{style:l.status,children:b.statusLabel}),jsxRuntime.jsx(m,{style:l.expiry,children:b.expiryLabel})]}),b.createdLabel?jsxRuntime.jsx(m,{style:l.created,children:b.createdLabel}):null]}),b.shareUrl!==null&&!n?jsxRuntime.jsx(m,{selectable:true,style:l.url,testID:`share-url-${b.shareId}`,children:b.shareUrl}):null,u===b.shareId?jsxRuntime.jsxs(reactNative.View,{style:l.confirm,testID:`share-revoke-confirm-${b.shareId}`,children:[jsxRuntime.jsx(m,{style:l.confirmText,children:de.confirmTurnOff}),jsxRuntime.jsxs(reactNative.View,{style:l.rowActions,children:[jsxRuntime.jsx(re,{label:c.revokingId===b.shareId?de.turningOff:de.turnOff,kind:"danger",busy:c.revokingId===b.shareId,onPress:()=>g(b.shareId),testID:`share-revoke-do-${b.shareId}`}),jsxRuntime.jsx(re,{label:de.keep,kind:"outline",disabled:c.revokingId===b.shareId,onPress:()=>p(null),testID:`share-revoke-cancel-${b.shareId}`})]})]}):jsxRuntime.jsxs(reactNative.View,{style:l.rowActions,children:[n?jsxRuntime.jsx(re,{label:de.copyLink,kind:"outline",disabled:b.shareUrl===null,accessibilityLabel:de.copyLinkA11y(b.actionContext),onPress:()=>y(b),testID:`share-copy-${b.shareId}`}):null,jsxRuntime.jsx(re,{label:de.turnOff,kind:"danger",accessibilityLabel:de.turnOffA11y(b.actionContext),onPress:()=>p(b.shareId),testID:`share-ask-revoke-${b.shareId}`})]})]},b.shareId))})]}):null]}),jsxRuntime.jsx(reactNative.View,{style:s.inset})]})]})})}i(Sd,"ShareSheet");function Dg(){let e=L();return react.useMemo(()=>Ag(e),[e])}i(Dg,"useStyles");function Ag(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=reactNative.StyleSheet.hairlineWidth,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*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),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},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:s,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:s,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(Ag,"makeStyles");var Vg=i((e,t)=>e.getRecordDepth(t),"readDepth"),qg=i(e=>!e.available,"depthEmpty");function _a(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack","onAsk"]);return jsxRuntime.jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsxRuntime.jsx(Fg,{...o,style:t})})}i(_a,"EverfurRecordDetail");function Fg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,onOpenUrl:c,onCopy:a,style:d}){let u=be(),p=zg(),f=yt(r?{petRef:e,controller:r}:{petRef:e}),h=Ut(e,Vg,qg),R=ia(e),v=wa(e),[y,g]=react.useState(false),b=react.useMemo(()=>qr(o,f.consent),[o,f.consent]),w=react.useMemo(()=>Kr(f,o),[f,o]),x=h.value!==null&&!h.value.withheld&&h.value.available?h.value:null,E=f.record,D=i(()=>{f.refresh(),h.refresh();},"retry"),k=n!==void 0||v.lit===true,S;if(f.status==="loading"||h.status==="loading"&&E!==null&&!E.isEmpty)S=jsxRuntime.jsx(io,{testID:"everfur-record-loading"});else if(f.status==="error"){let I=xr(f,b);S=I.kind==="error"||I.kind==="pet_not_found"?jsxRuntime.jsx(Qe,{variant:wt(I.error),message:I.error.displayMessage,onAction:I.error.retryable?D:void 0,testID:"everfur-record-error"}):Yr(f,w,b);}else if(E===null||E.isEmpty){let I=x?.completeness?.documentsInReview??0;S=jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsxRuntime.jsx(Qe,{variant:"no_records",message:I>0?W.inReview(I):void 0}),jsxRuntime.jsx(hr,{disclaimer:E?.disclaimer??""})]});}else S=jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:p.content,testID:"everfur-record",children:jsxRuntime.jsx(So,{record:E,depth:x,petName:t,onNavigate:n,onAsk:s,factEdit:R})});return jsxRuntime.jsxs(reactNative.View,{style:[u.root,d],children:[jsxRuntime.jsx(et,{title:W.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:W.requestClinicsA11y,hitSlop:8,style:p.share,testID:"everfur-record-request-clinics",children:jsxRuntime.jsx(bl,{})}):null,k?jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>g(true),accessibilityRole:"button",accessibilityLabel:W.shareA11y,hitSlop:8,style:p.share,testID:"everfur-record-share",children:jsxRuntime.jsx(gl,{})}):null]}):void 0}),jsxRuntime.jsx(reactNative.View,{style:u.body,children:S}),y?jsxRuntime.jsx(Sd,{petRef:e,onClose:()=>g(false),onNavigate:n,...c?{onOpenUrl:c}:{},...a?{onCopy:a}:{}}):null,jsxRuntime.jsx(Me,{})]})}i(Fg,"RecordBody");function zg(){let e=L();return react.useMemo(()=>Ng(e),[e])}i(zg,"useLocalStyles");function Ng(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(Ng,"makeLocalStyles");function Ia(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack"]);return jsxRuntime.jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsxRuntime.jsx(Ug,{...o,style:t})})}i(Ia,"EverfurRecordsUpload");function Ug({petRef:e,petName:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c}){let a=be(),d=Ad(),{runtime:u}=ke(),p=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),f=Cn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport));return jsxRuntime.jsxs(reactNative.View,{style:[a.root,c],children:[jsxRuntime.jsx(et,{title:"",onBack:s,testID:"upload-header"}),jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:d.content,testID:"upload-screen",children:[jsxRuntime.jsxs(reactNative.View,{style:d.header,children:[jsxRuntime.jsx(reactNative.View,{style:d.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxRuntime.jsx(m,{style:d.title,accessibilityRole:"header",children:rt.title(t)}),jsxRuntime.jsx(m,{style:d.subtitle,children:rt.subtitle(t)})]}),jsxRuntime.jsx(Da,{records:p,requestId:null,onPickDocument:o,canUpload:f,onDone:l?h=>l({name:"request",requestId:h}):void 0})]}),jsxRuntime.jsx(Me,{})]})}i(Ug,"UploadBody");function Da({records:e,requestId:t,onPickDocument:r,canUpload:o,onDone:n}){let l=be(),s=Ad(),[c,a]=react.useState(null),[d,u]=react.useState(0),p=react.useRef(t),f=react.useRef([]),h=e.uploadQueue.filter(x=>x.status!=="skipped"),R=h.filter(x=>x.status==="done").length,v=h.filter(x=>x.status==="failed").length,y=!e.isUploading&&d>0,g=react.useCallback(async x=>{if(x.length===0)return;a(null);let E=p.current;if(E===null){let k=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!k.ok){a(rt.errors.start);return}E=k.value.id,p.current=E;}u(k=>k+1);let D=await e.uploadDocuments(E,x);f.current=D.flatMap((k,S)=>k.status==="failed"&&x[S]!==void 0?[x[S]]:[]);},[e]),b=react.useCallback(()=>{!r||!o||kr(r).then(x=>{if(!x.ok){a(rt.errors.startPlain);return}let E=x.value;E!==null&&g(Array.isArray(E)?E:[E]);});},[r,o,g]),w=react.useCallback(()=>{g(f.current);},[g]);return jsxRuntime.jsxs(reactNative.View,{style:s.card,testID:"records-upload-card",children:[jsxRuntime.jsx(m,{style:s.cardTitle,accessibilityRole:"header",children:rt.cardTitle}),jsxRuntime.jsx(m,{style:s.cardSubtitle,children:rt.cardSubtitle}),c?jsxRuntime.jsx(reactNative.View,{style:l.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(m,{style:l.errorText,children:c})}):null,jsxRuntime.jsx(ad,{records:e}),e.isUploading?jsxRuntime.jsx(reactNative.View,{style:s.uploadingRow,children:jsxRuntime.jsx(m,{style:s.progressText,children:rt.uploading(R,h.length)})}):y?jsxRuntime.jsxs(reactNative.View,{style:s.settled,children:[R>0?jsxRuntime.jsx(m,{style:s.success,accessibilityRole:"alert",children:rt.received(R)}):null,v>0?jsxRuntime.jsx(re,{label:rt.retryFailed(v),kind:"link",accessibilityLabel:rt.retryFailedA11y(v),onPress:w,testID:"records-upload-retry-failed"}):null,jsxRuntime.jsxs(reactNative.View,{style:s.settledActions,children:[jsxRuntime.jsx(re,{label:rt.addMore,kind:"link",accessibilityLabel:rt.addMoreA11y,disabled:!o,onPress:b,testID:"records-upload-another"}),n&&p.current!==null&&R>0?jsxRuntime.jsx(re,{label:rt.done,accessibilityLabel:rt.doneA11y,onPress:()=>n(p.current),testID:"records-upload-done"}):null]})]}):jsxRuntime.jsx(re,{label:rt.chooseFiles,accessibilityLabel:rt.chooseFilesA11y,disabled:!o,onPress:b,testID:"records-upload-choose"})]})}i(Da,"UploadRecordCard");function Ad(){let e=L();return react.useMemo(()=>jg(e),[e])}i(Ad,"useLocalStyles");function jg(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"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.md,backgroundColor:t.surface,borderWidth:1,borderColor:t.brandSoft,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}})}i(jg,"makeLocalStyles");function Oa(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack"]);return jsxRuntime.jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsxRuntime.jsx(Xg,{...o,style:t})})}i(Oa,"EverfurRecordsRequest");function Xg({petRef:e,requestId:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c,nowMs:a}){let d=be(),{runtime:u,userRef:p,scopeEpoch:f}=ke(),h=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),R=h.requests.find(b=>b.id===t)??null,v=Cn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport)),y=R?bo(R):"",g;return h.status==="loading"?g=jsxRuntime.jsx(_l,{testID:"records-request-loading"}):h.status==="error"&&h.error?g=jsxRuntime.jsx(Qe,{variant:wt(h.error),message:h.error.displayMessage,onAction:h.error.retryable?h.refresh:void 0,testID:"records-request-error"}):R===null?g=jsxRuntime.jsx(Qe,{variant:"no_requests",testID:"records-request-missing"}):p===null?g=jsxRuntime.jsx(Qe,{variant:"error",testID:"records-request-error"}):g=jsxRuntime.jsx(Jg,{request:R,records:h,canUpload:v,onPickDocument:o,onNavigate:l,nowMs:a},JSON.stringify([p,f,R.id])),jsxRuntime.jsxs(reactNative.View,{style:[d.root,c],children:[jsxRuntime.jsx(et,{title:y,onBack:s,testID:"records-request-header"}),jsxRuntime.jsx(reactNative.KeyboardAvoidingView,{behavior:"padding",style:d.body,children:g}),jsxRuntime.jsx(Me,{})]})}i(Xg,"RequestBody");function Jg({request:e,records:t,canUpload:r,onPickDocument:o,onNavigate:n,nowMs:l}){let s=be(),c=Zg(),a=L(),d=td({request:e,onRecovered:t.refresh,canUpload:r},Nt()),[u,p]=react.useState(null),[f,h]=react.useState(false),[R,v]=react.useState(null),y=react.useRef(true);react.useEffect(()=>(y.current=true,()=>{y.current=false;}),[]);let g=d.request,b=l??Date.now(),w=g.status==="published",x=g.status==="published"||g.status==="failed"||g.status==="revoked",E=di(g),D=g.wireStatus==="clinic_responded_no_records",k=zs(g,b),S=ci(g,b),I=x?null:g.waitingExpectation?.trim()||null,Y=ho(g),z=Ns(g),$=d.canConvert,G=x&&!w,Z=d.error!==null&&u!==null&&u!=="start"?u==="revoke"?ge.errors.cancel:ge.errors[u]:null,oe=i((H,C)=>{p(H),C();},"run"),Ee=i(()=>{f||(h(true),v(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(H=>{if(y.current){if(h(false),!H.ok){v(ge.errors.start);return}n?.({name:"request",requestId:H.value.id});}}));},"startFresh");return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:c.content,keyboardShouldPersistTaps:"handled",testID:`records-request-${g.id}`,children:[jsxRuntime.jsx(_o,{request:g}),g.status==="awaiting_upload"?jsxRuntime.jsx(Da,{records:t,requestId:g.id,onPickDocument:o,canUpload:r}):null,g.statusLabel.length>0?jsxRuntime.jsx(reactNative.View,{style:s.statusCard,accessibilityRole:"summary",children:jsxRuntime.jsx(m,{style:s.statusText,children:g.statusLabel})}):null,I&&!k?jsxRuntime.jsx(reactNative.View,{style:s.infoNote,accessibilityRole:"summary",children:jsxRuntime.jsx(m,{style:s.infoNoteText,children:I})}):g.wireStatus==="awaiting_response"&&!k?jsxRuntime.jsx(reactNative.View,{style:s.infoNote,accessibilityRole:"summary",children:jsxRuntime.jsx(m,{style:s.infoNoteText,children:ge.awaitingNote})}):null,k?jsxRuntime.jsx(reactNative.View,{style:s.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsxRuntime.jsx(m,{style:s.cautionNoteText,children:ge.waitingBanner(S)})}):null,w&&n?jsxRuntime.jsx(re,{label:ge.viewRecords,onPress:()=>n({name:"dashboard"}),style:c.readyCta,testID:"records-request-view-dashboard"}):null,z?jsxRuntime.jsxs(reactNative.View,{style:[c.failureCard,E?c.failureCritical:c.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsxRuntime.jsx(m,{style:[c.failureTitle,E?c.failureTitleCritical:c.failureTitleCaution],children:Fs(g)}),g.canUpdateClinicEmail!==true&&g.canRetrySend!==true?jsxRuntime.jsx(m,{style:s.rowDetail,children:ge.nextStep}):null,g.canUpdateClinicEmail===true?jsxRuntime.jsxs(reactNative.View,{style:c.emailBlock,children:[jsxRuntime.jsx(m,{style:s.fieldLabel,children:Ot.email}),jsxRuntime.jsx(qe,{style:s.field,accessibilityLabel:Ot.email,placeholder:Ot.emailPlaceholder,placeholderTextColor:a.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:d.email,editable:!d.busy,onChangeText:d.setEmail,testID:"records-failure-clinic-email"}),d.emailInvalid?jsxRuntime.jsx(m,{style:s.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsxRuntime.jsx(re,{label:Ot.updateEmail,accessibilityLabel:Ot.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&u==="email",onPress:()=>oe("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,g.canRetrySend===true?jsxRuntime.jsx(re,{label:Ot.retry,kind:"outline",accessibilityLabel:Ot.retryA11y,disabled:!d.canRetry,busy:d.busy&&u==="retry",onPress:()=>oe("retry",d.retry),testID:"records-failure-retry-send"}):null,g.canRetrySend===true&&d.hasEmailEdit?jsxRuntime.jsx(m,{style:s.rowDetail,children:Ot.retryHint}):null,Z&&(u==="email"||u==="retry")?jsxRuntime.jsx(reactNative.View,{style:s.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(m,{style:s.errorText,children:Z})}):null]}):null,(E||D)&&n?jsxRuntime.jsx(re,{label:ge.tryAnotherClinic,kind:"outline",accessibilityLabel:ge.tryAnotherClinicA11y,onPress:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,Y!==null?jsxRuntime.jsxs(reactNative.View,{style:c.callBlock,children:[jsxRuntime.jsx(sd,{call:Y,prompt:g.statusLabel}),g.canRetrySend===true?jsxRuntime.jsx(re,{label:d.busy&&u==="retry"?ge.resending:ge.resend,kind:"outline",accessibilityLabel:d.busy&&u==="retry"?ge.resendingA11y:ge.resendA11y,disabled:!d.canRetry,onPress:()=>oe("retry",d.retry),testID:"records-resend-authorization"}):null]}):null,$?jsxRuntime.jsxs(reactNative.View,{style:c.block,children:[jsxRuntime.jsx(re,{label:d.busy&&u==="convert"?ge.converting:ge.convert,busy:d.busy&&u==="convert",onPress:()=>oe("convert",d.convert),testID:"records-convert-upload"}),jsxRuntime.jsx(m,{style:s.muted,children:ge.convertHint}),Z&&u==="convert"?jsxRuntime.jsx(reactNative.View,{style:s.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(m,{style:s.errorText,children:Z})}):null]}):null,G?jsxRuntime.jsxs(reactNative.View,{style:c.block,children:[jsxRuntime.jsx(re,{label:f?ge.freshUploadStarting:ge.freshUpload,kind:E||D?"outline":"primary",busy:f,onPress:Ee,testID:"records-upload-own-fresh"}),R?jsxRuntime.jsx(reactNative.View,{style:s.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(m,{style:s.errorText,children:R})}):null]}):null,Z&&u==="revoke"?jsxRuntime.jsx(reactNative.View,{style:s.errorBanner,accessibilityRole:"alert",children:jsxRuntime.jsx(m,{style:s.errorText,children:Z})}):null,g.canRevoke===true?d.confirmingRevoke?jsxRuntime.jsxs(reactNative.View,{style:c.block,testID:"records-revoke-confirm",children:[jsxRuntime.jsx(m,{style:c.confirmTitle,accessibilityRole:"header",children:Ot.cancelQuestion}),jsxRuntime.jsx(m,{style:s.bodyText,children:Ot.cancelConsequence}),jsxRuntime.jsx(re,{label:d.busy&&u==="revoke"?ge.cancelling:ge.cancel,kind:"danger",accessibilityLabel:d.busy&&u==="revoke"?ge.cancellingA11y:ge.cancelA11y,busy:d.busy&&u==="revoke",onPress:()=>oe("revoke",d.revoke),testID:"records-revoke-do"}),jsxRuntime.jsx(re,{label:Ot.keepRequest,kind:"outline",disabled:d.busy,onPress:d.keepRequest,testID:"records-revoke-keep"})]}):jsxRuntime.jsx(re,{label:ge.cancel,kind:"danger",accessibilityLabel:ge.cancelA11y,disabled:d.busy,onPress:d.askRevoke,testID:"records-revoke"}):null]})}i(Jg,"RequestDetail");function Zg(){let e=L();return react.useMemo(()=>eb(e),[e])}i(Zg,"useLocalStyles");function eb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"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},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(eb,"makeLocalStyles");function Od(e){let{petRef:t,petName:r,controller:o,clinicController:n,onPickDocument:l,uploadTransport:s,consentVersion:c,ownerName:a,onCaptureSignature:d,initialScreen:u,onExit:p,style:f,renderPending:h,onOpenUrl:R,onCopy:v,onAsk:y,location:g}=Fe(e,["onExit"]),[b,w]=react.useReducer(ti,u,$n),x=Wn(b),E=b.stack.length;react.useEffect(()=>{let $=i(()=>E<=1?false:(w({type:"pop"}),true),"onBackPress"),G=reactNative.BackHandler.addEventListener("hardwareBackPress",$);return ()=>{G.remove();}},[E]);let D=react.useCallback($=>w({type:"navigate",screen:$}),[]),k=react.useMemo(()=>Gn(b).handled?()=>w({type:"pop"}):p,[b,p]),S={onNavigate:D,...k?{onBack:k}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...y?{onAsk:y}:{},...g?{location:g}:{}},I={...o?{controller:o}:{},...c!==void 0?{consentVersion:c}:{}},Y={...l?{onPickDocument:l}:{},...s?{uploadTransport:s}:{}},z=h?{renderPending:h}:{};switch(x.name){case "dashboard":return jsxRuntime.jsx(ha,{petRef:t,...S,...I,...z,style:f});case "request":return jsxRuntime.jsx(Oa,{petRef:t,requestId:x.requestId,...S,...I,...Y,...z,style:f});case "timeline":return jsxRuntime.jsx(yd,{petRef:t,...S,style:f});case "record":return jsxRuntime.jsx(_a,{petRef:t,...S,...I,...z,style:f});case "document":return jsxRuntime.jsx(Ea,{petRef:t,...S,...I,...z,style:f});case "contributions":return jsxRuntime.jsx(fd,{petRef:t,docId:x.docId,...S,style:f});case "clinicPicker":return jsxRuntime.jsx(_i,{petRef:t,...S,...n?{controller:n}:{},...o?{recordsController:o}:{},style:f});case "clinicBatch":return jsxRuntime.jsx(ji,{petRef:t,petName:r??"",ownerName:a??"",...k?{onClose:k}:{},onCreated:()=>w({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "consent":return jsxRuntime.jsx(Zi,{petRef:t,clinic:x.clinic,...S,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "upload":return jsxRuntime.jsx(Ia,{petRef:t,...S,...o?{controller:o}:{},...Y,...z,style:f});default:return pr(x)}}i(Od,"EverfurRecordsFlow");var ab=Od;function db(e){let{userRef:t,scopeEpoch:r}=ke();return jsxRuntime.jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,U.cancel),children:t===null?jsxRuntime.jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsxRuntime.jsx(ub,{...Fe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(db,"EverfurClinicRequest");function ub(e){let t=Nt(),[r,o]=react.useState(null),n=react.useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),l=Ol(e,e.controller??t,e.onCaptureSignature??n),s=e.onCaptureSignature!==void 0||r!==null,c=L(),a={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((p,f,h=false)=>jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:p,accessibilityState:{disabled:h},disabled:h,onPress:f,style:[a,{justifyContent:"center",opacity:h?.5:1}],children:jsxRuntime.jsx(m,{style:d,children:p})}),"button");return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:U.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(m,{accessibilityRole:"header",style:[d,{..._(c,"bold"),fontSize:c.type.size.heading}],children:U.title}),jsxRuntime.jsx(m,{style:d,children:e.petName}),l.created?jsxRuntime.jsx(m,{accessibilityLiveRegion:"polite",style:d,children:l.created.statusLabel||ce.records}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(m,{style:d,children:U.ownerName}),jsxRuntime.jsx(qe,{accessibilityLabel:U.ownerName,style:a,value:l.ownerName,maxLength:200,editable:!l.busy,autoComplete:"name",onChangeText:l.setOwnerName}),jsxRuntime.jsx(m,{style:d,children:U.clinic}),jsxRuntime.jsx(qe,{accessibilityLabel:U.clinic,style:a,value:l.query,placeholder:U.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!l.busy,onChangeText:l.setQuery}),u(U.search,()=>{l.search();},l.busy||l.searching||l.query.trim().length<2),l.searching&&jsxRuntime.jsx(m,{accessibilityLiveRegion:"polite",style:d,children:ce.loading}),l.recent.length>0&&jsxRuntime.jsx(m,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:U.recentlyUsed}),l.recent.map(p=>jsxRuntime.jsx(reactNative.View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},`recent-${p.id}`)),l.clinics.map(p=>jsxRuntime.jsx(reactNative.View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},p.id)),l.needsEmail&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(m,{style:d,children:U.email}),jsxRuntime.jsx(qe,{accessibilityLabel:U.email,style:a,value:l.email,placeholder:U.emailPlaceholder,placeholderTextColor:c.color.text.placeholder,maxLength:320,editable:!l.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:l.setEmail})]}),jsxRuntime.jsx(m,{accessibilityRole:"header",style:d,children:U.scopeHeading}),l.copy?jsxRuntime.jsx(m,{style:d,children:l.query.trim()&&l.ownerName.trim()?l.scope??q("internalError").displayMessage:ce.consentRequired}):!l.error&&jsxRuntime.jsx(m,{accessibilityLiveRegion:"polite",style:d,children:ce.loading}),!e.onCaptureSignature&&jsxRuntime.jsx(Lr,{onChange:o,disabled:l.busy}),!s&&jsxRuntime.jsx(m,{accessibilityRole:"alert",style:d,children:U.missingSignature}),l.error&&jsxRuntime.jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:l.error.displayMessage}),!l.copy&&l.error&&u(ce.retry,l.retryCopy),u(l.busy?U.sending:U.send,()=>{l.submit();},l.busy||!l.ready||!s)]}),e.onClose&&u(U.cancel,e.onClose,l.busy),jsxRuntime.jsx(Me,{})]})}i(ub,"ClinicRequestBody");
4
+ exports.EverfurClinicPicker=_i;exports.EverfurClinicRequest=db;exports.EverfurClinicRequestBatch=ji;exports.EverfurRecordDetail=_a;exports.EverfurRecordDocument=Ea;exports.EverfurRecords=ab;exports.EverfurRecordsConsent=Zi;exports.EverfurRecordsDashboard=ha;exports.EverfurRecordsFlow=Od;exports.EverfurRecordsRequest=Oa;exports.EverfurRecordsUpload=Ia;exports.RECORDS_CLINIC_BATCH_MAX=Nr;exports.RECORDS_TERMINAL=es;exports.REQUEST_TIMELINE_TITLES=In;exports.SignaturePad=Lr;exports.applyFactOverlay=na;exports.buildRequestTimeline=da;exports.currentRecordsScreen=Wn;exports.deriveRecordsDashboardState=si;exports.initialRecordsNav=$n;exports.isFactEditable=oa;exports.isTerminalStatus=zr;exports.pickPetRecordsRequest=Qn;exports.popRecordsNav=Gn;exports.pushRecordsNav=Jo;exports.recordsDenialReasonOf=dr;exports.recordsNavReducer=ti;exports.registerRnSignature=Di;exports.replaceRecordsNav=Zo;exports.resetRecordsNav=ei;exports.selectClinicCall=ho;exports.selectDashboardView=li;exports.selectPrimaryLabel=En;exports.selectRequestList=Yy;exports.selectRequestTitle=bo;exports.transitionRecordsNav=xs;exports.useEverfurRecords=yt;exports.useEverfurRecordsClinic=Nt;exports.useEverfurRecordsClinicBatch=mi;exports.useRecordFactEdit=ia;exports.useRecordPdfLink=Ca;exports.useRecordShares=xa;exports.useRecordsMarkers=Qi;