@everfur/sdk 0.9.0 → 0.9.2

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 (175) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +1 -1
  3. package/dist/{Chat-Cb3Y8VwS.d.cts → Chat-B7oN62ww.d.cts} +3 -3
  4. package/dist/{Chat-ClhB_8sp.d.ts → Chat-Cugs9Dsl.d.ts} +3 -3
  5. package/dist/{DepthViews-DDiPxyzg.d.cts → DepthViews-C6qFJ3fV.d.ts} +1 -1
  6. package/dist/{DepthViews-CSCS-tZg.d.ts → DepthViews-CUNmy99u.d.cts} +1 -1
  7. package/dist/{DepthViews-CW1z8pnl.d.cts → DepthViews-CiYBIBEZ.d.ts} +1 -1
  8. package/dist/{DepthViews-BSkuUGBB.d.ts → DepthViews-GxV7wSzT.d.cts} +1 -1
  9. package/dist/{ErrorPolicyPort-NFDPe-5w.d.cts → ErrorPolicyPort-10s3HJCt.d.cts} +1 -1
  10. package/dist/{ErrorPolicyPort-DwSnmGcX.d.ts → ErrorPolicyPort-C3nNSS_j.d.ts} +1 -1
  11. package/dist/{EverfurError-pEXDbUJ1.d.cts → EverfurError-DeBqRpQV.d.cts} +1 -1
  12. package/dist/{EverfurError-pEXDbUJ1.d.ts → EverfurError-DeBqRpQV.d.ts} +1 -1
  13. package/dist/{EverfurResult-dtl8ERAw.d.cts → EverfurResult-COlXj1wq.d.cts} +1 -1
  14. package/dist/{EverfurResult-sKkoXew0.d.ts → EverfurResult-ClPTS0P2.d.ts} +1 -1
  15. package/dist/{IntakeMedia-BFZfBLjB.d.cts → IntakeMedia-B-_vA9ZB.d.cts} +2 -1
  16. package/dist/{IntakeMedia-C8GlN_GK.d.ts → IntakeMedia-CIoTXAWs.d.ts} +2 -1
  17. package/dist/animations/index.cjs +1 -1
  18. package/dist/animations/index.d.cts +6 -6
  19. package/dist/animations/index.d.ts +6 -6
  20. package/dist/animations/index.js +1 -1
  21. package/dist/{attachments-DAUy3vPR.d.ts → attachments-20X7Vuip.d.ts} +3 -3
  22. package/dist/{attachments-BD70jZZL.d.cts → attachments-CkaPnIUw.d.cts} +3 -3
  23. package/dist/{attachments-CC7aHpwZ.d.ts → attachments-DN2cNGwe.d.ts} +7 -7
  24. package/dist/{attachments-DaOaIBNf.d.cts → attachments-HXFmzk-D.d.cts} +7 -7
  25. package/dist/{bookingCopy-CUW9Gdzc.d.ts → bookingCopy-B5igVNE0.d.ts} +7 -6
  26. package/dist/{bookingCopy-oEjqkiNA.d.cts → bookingCopy-pJpizqgz.d.cts} +7 -6
  27. package/dist/{branding-ctD0B2Th.d.cts → branding-BCfwLj0h.d.cts} +1 -1
  28. package/dist/{branding-aGleD_ki.d.ts → branding-DJf4h12Q.d.ts} +1 -1
  29. package/dist/{callCopy-DHjem0R-.d.cts → callCopy-Bw6oZT54.d.cts} +7 -2
  30. package/dist/{callCopy-DHjem0R-.d.ts → callCopy-Bw6oZT54.d.ts} +7 -2
  31. package/dist/{callRoom-B1qq_D-4.d.ts → callRoom-B92eH_ij.d.ts} +1 -1
  32. package/dist/{callRoom-DfZTWFXh.d.cts → callRoom-BhIdadyV.d.cts} +1 -1
  33. package/dist/{casesRepository-Bzs7aw4t.d.cts → casesRepository-DFoK5N1O.d.cts} +2 -2
  34. package/dist/{casesRepository-CywqL6mj.d.ts → casesRepository-qAkKKgji.d.ts} +2 -2
  35. package/dist/chat/index.cjs +9 -9
  36. package/dist/chat/index.d.cts +12 -12
  37. package/dist/chat/index.d.ts +12 -12
  38. package/dist/chat/index.js +9 -9
  39. package/dist/client/index.cjs +4 -4
  40. package/dist/client/index.d.cts +14 -14
  41. package/dist/client/index.d.ts +14 -14
  42. package/dist/client/index.js +4 -4
  43. package/dist/{config-BysLVhku.d.ts → config-BB7e52FP.d.ts} +3 -3
  44. package/dist/{config-EZzEyS-c.d.cts → config-u6rK4mKt.d.cts} +3 -3
  45. package/dist/consent/index.cjs +2 -2
  46. package/dist/consent/index.d.cts +9 -9
  47. package/dist/consent/index.d.ts +9 -9
  48. package/dist/consent/index.js +2 -2
  49. package/dist/{context-DUwYArkM.d.cts → context-BZ1k4qE3.d.cts} +9 -9
  50. package/dist/{context-DpfgbnOU.d.ts → context-CJYmubjx.d.ts} +9 -9
  51. package/dist/{copy-LxZGnFXJ.d.ts → copy-CtfctY-J.d.ts} +5 -5
  52. package/dist/{copy-DK4r9oGz.d.cts → copy-DCO_lUXd.d.cts} +5 -5
  53. package/dist/core/index.cjs +4 -4
  54. package/dist/core/index.d.cts +19 -19
  55. package/dist/core/index.d.ts +19 -19
  56. package/dist/core/index.js +4 -4
  57. package/dist/{depth-DAd77kRe.d.cts → depth-C_ym3qyi.d.cts} +6 -6
  58. package/dist/{depth-Mk7quUNa.d.ts → depth-_vMRMm4x.d.ts} +6 -6
  59. package/dist/{entitlementRepository-Dra_4FU_.d.cts → entitlementRepository-DA04yM54.d.cts} +4 -4
  60. package/dist/{entitlementRepository-CrD0O7VR.d.ts → entitlementRepository-tSY9WWad.d.ts} +4 -4
  61. package/dist/{identity-75whJXyP.d.cts → identity-CUynm8S2.d.cts} +2 -2
  62. package/dist/{identity-BiyMDMrR.d.ts → identity-D5uywCtp.d.ts} +2 -2
  63. package/dist/index.cjs +14 -14
  64. package/dist/index.d.cts +19 -19
  65. package/dist/index.d.ts +19 -19
  66. package/dist/index.js +14 -14
  67. package/dist/{models-DzvqEjMm.d.cts → models-A4A5S7AG.d.cts} +1 -1
  68. package/dist/{models-CrbUwbuS.d.ts → models-CnXY5LuO.d.ts} +1 -1
  69. package/dist/notifications/index.cjs +1 -1
  70. package/dist/notifications/index.d.cts +5 -5
  71. package/dist/notifications/index.d.ts +5 -5
  72. package/dist/notifications/index.js +1 -1
  73. package/dist/{pets-DoXxTw4x.d.cts → pets-BrdkpNJH.d.cts} +2 -2
  74. package/dist/{pets-W2BuLYko.d.ts → pets-mnbN0kZG.d.ts} +2 -2
  75. package/dist/{petsRepository-yyoo0k2I.d.cts → petsRepository-CQgzEFyz.d.cts} +2 -2
  76. package/dist/{petsRepository-ByMzq1Z9.d.ts → petsRepository-RGI_xPK1.d.ts} +2 -2
  77. package/dist/photo/index.cjs +1 -1
  78. package/dist/photo/index.d.cts +3 -3
  79. package/dist/photo/index.d.ts +3 -3
  80. package/dist/photo/index.js +1 -1
  81. package/dist/{ports-zYl8S_lI.d.ts → ports-Cu_Wc5Aw.d.ts} +7 -7
  82. package/dist/{ports-BeVJYP0_.d.cts → ports-DibY-h60.d.cts} +7 -7
  83. package/dist/records/depth/index.cjs +7 -5
  84. package/dist/records/depth/index.d.cts +11 -11
  85. package/dist/records/depth/index.d.ts +11 -11
  86. package/dist/records/depth/index.js +7 -5
  87. package/dist/records/index.cjs +23 -21
  88. package/dist/records/index.d.cts +14 -14
  89. package/dist/records/index.d.ts +14 -14
  90. package/dist/records/index.js +23 -21
  91. package/dist/{requestFunnel-BPeBZdKp.d.ts → requestFunnel-BkSFsLKh.d.ts} +5 -5
  92. package/dist/{requestFunnel-DHeSzCT6.d.cts → requestFunnel-nmhlEdbM.d.cts} +5 -5
  93. package/dist/{runtimeTypes-Cc207nbn.d.ts → runtimeTypes-CU2xVmiQ.d.ts} +7 -7
  94. package/dist/{runtimeTypes-DgMizQKz.d.cts → runtimeTypes-CWG1Cm4N.d.cts} +7 -7
  95. package/dist/server/events/index.cjs +2 -2
  96. package/dist/server/events/index.d.cts +4 -4
  97. package/dist/server/events/index.d.ts +4 -4
  98. package/dist/server/events/index.js +2 -2
  99. package/dist/server/index.cjs +2 -2
  100. package/dist/server/index.d.cts +5 -5
  101. package/dist/server/index.d.ts +5 -5
  102. package/dist/server/index.js +2 -2
  103. package/dist/televet/booking/index.cjs +9 -8
  104. package/dist/televet/booking/index.d.cts +12 -12
  105. package/dist/televet/booking/index.d.ts +12 -12
  106. package/dist/televet/booking/index.js +9 -8
  107. package/dist/televet/call/index.cjs +3 -5
  108. package/dist/televet/call/index.d.cts +3 -3
  109. package/dist/televet/call/index.d.ts +3 -3
  110. package/dist/televet/call/index.js +3 -5
  111. package/dist/televet/index.cjs +2 -2
  112. package/dist/televet/index.d.cts +7 -7
  113. package/dist/televet/index.d.ts +7 -7
  114. package/dist/televet/index.js +2 -2
  115. package/dist/testing/index.cjs +2 -2
  116. package/dist/testing/index.d.cts +3 -3
  117. package/dist/testing/index.d.ts +3 -3
  118. package/dist/testing/index.js +2 -2
  119. package/dist/testing/rn/index.cjs +2 -2
  120. package/dist/testing/rn/index.d.cts +13 -13
  121. package/dist/testing/rn/index.d.ts +13 -13
  122. package/dist/testing/rn/index.js +2 -2
  123. package/dist/testing/web/index.cjs +1 -1
  124. package/dist/testing/web/index.d.cts +14 -14
  125. package/dist/testing/web/index.d.ts +14 -14
  126. package/dist/testing/web/index.js +1 -1
  127. package/dist/{timelineRows-DUQIWSjc.d.cts → timelineRows-CYF_I5Aq.d.cts} +1 -1
  128. package/dist/{timelineRows-D22vGN9t.d.ts → timelineRows-PWRoTntZ.d.ts} +1 -1
  129. package/dist/{tokens-RAKZj7M8.d.cts → tokens-DLj8OnLH.d.cts} +4 -2
  130. package/dist/{tokens-RAKZj7M8.d.ts → tokens-DLj8OnLH.d.ts} +4 -2
  131. package/dist/{typeStyle-DVj8iCC1.d.ts → typeStyle-BxVyF71R.d.ts} +2 -2
  132. package/dist/{typeStyle-Nt7w0rhE.d.cts → typeStyle-DJedEu14.d.cts} +2 -2
  133. package/dist/{useRecordsDepth-Mbysp548.d.cts → useRecordsDepth-Cg4cc4bQ.d.cts} +4 -4
  134. package/dist/{useRecordsDepth-C0Qfoghi.d.ts → useRecordsDepth-eS9BJv_a.d.ts} +4 -4
  135. package/dist/{useVetVisit-RPBOabl8.d.ts → useVetVisit-DmWa7lt1.d.ts} +2 -2
  136. package/dist/{useVetVisit-BQX_aTJs.d.cts → useVetVisit-PtBjNwZr.d.cts} +2 -2
  137. package/dist/video/index.cjs +1 -1
  138. package/dist/video/index.d.cts +3 -3
  139. package/dist/video/index.d.ts +3 -3
  140. package/dist/video/index.js +1 -1
  141. package/dist/{view-CskIgOFV.d.cts → view-D4UOm-yo.d.cts} +11 -5
  142. package/dist/{view-DqKXtxEZ.d.ts → view-n_oSGiiT.d.ts} +11 -5
  143. package/dist/web/consent/index.cjs +2 -2
  144. package/dist/web/consent/index.d.cts +9 -9
  145. package/dist/web/consent/index.d.ts +9 -9
  146. package/dist/web/consent/index.js +2 -2
  147. package/dist/web/index.cjs +10 -10
  148. package/dist/web/index.d.cts +22 -22
  149. package/dist/web/index.d.ts +22 -22
  150. package/dist/web/index.js +10 -10
  151. package/dist/web/notifications/index.cjs +1 -1
  152. package/dist/web/notifications/index.d.cts +7 -7
  153. package/dist/web/notifications/index.d.ts +7 -7
  154. package/dist/web/notifications/index.js +1 -1
  155. package/dist/web/records/depth/index.cjs +6 -5
  156. package/dist/web/records/depth/index.d.cts +11 -11
  157. package/dist/web/records/depth/index.d.ts +11 -11
  158. package/dist/web/records/depth/index.js +7 -6
  159. package/dist/web/records/index.cjs +13 -11
  160. package/dist/web/records/index.d.cts +15 -15
  161. package/dist/web/records/index.d.ts +15 -15
  162. package/dist/web/records/index.js +13 -11
  163. package/dist/web/televet/booking/index.cjs +6 -6
  164. package/dist/web/televet/booking/index.d.cts +14 -11
  165. package/dist/web/televet/booking/index.d.ts +14 -11
  166. package/dist/web/televet/booking/index.js +6 -6
  167. package/dist/web/televet/call/index.cjs +3 -5
  168. package/dist/web/televet/call/index.d.cts +3 -3
  169. package/dist/web/televet/call/index.d.ts +3 -3
  170. package/dist/web/televet/call/index.js +3 -5
  171. package/dist/web/televet/index.cjs +1 -1
  172. package/dist/web/televet/index.d.cts +5 -5
  173. package/dist/web/televet/index.d.ts +5 -5
  174. package/dist/web/televet/index.js +1 -1
  175. package/package.json +1 -1
@@ -85,7 +85,7 @@
85
85
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
86
86
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
87
87
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
88
- /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
88
+ /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
89
89
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
90
90
  return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var RECORD_SHARE_AUDIENCES=/* @__PURE__ */Object.freeze(["vet","groomer","boarding"]),https=/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),str=/* @__PURE__ */zod.z.string().nullish(),audienceField=/* @__PURE__ */zod.z.unknown().optional(),linkSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),share_url:/* @__PURE__ */zod.z.string().min(1),expires_at:str,audience:audienceField}),listSchema=/* @__PURE__ */zod.z.object({shares:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str,created_at:str,view_count:/* @__PURE__ */zod.z.number().int().nonnegative().nullish(),last_viewed_at:str,audience:audienceField})).optional()}),pdfSchema=/* @__PURE__ */zod.z.object({download_url:https,expires_at:str}),emailSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str,audience:audienceField}),scopeSchema=/* @__PURE__ */zod.z.object({audience:/* @__PURE__ */zod.z.string().min(1),sections:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()),entity_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullable()}),SHARE_RECIPIENT_EMAIL_MAX=254;function isShareRecipientEmail(value){let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=SHARE_RECIPIENT_EMAIL_MAX&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)}var isAudience=value=>typeof value=="string"&&RECORD_SHARE_AUDIENCES.includes(value);function audienceOf(value){return isAudience(value)?value:null}function mapShareAudiences(wire){let parsed=zod.z.array(scopeSchema).safeParse(wire);if(!parsed.success)/* @__PURE__ */return Object.freeze([]);let seen=/* @__PURE__ */new Set,scopes=[];for(let scope of parsed.data)!isAudience(scope.audience)||seen.has(scope.audience)||(seen.add(scope.audience),scopes.push(/* @__PURE__ */Object.freeze({audience:scope.audience,sections:/* @__PURE__ */Object.freeze([...scope.sections]),entityTypes:scope.entity_types===null?null:/* @__PURE__ */Object.freeze([...scope.entity_types])}))/* @__PURE__ */);return Object.freeze(scopes)}function resolveShareUrl(shareUrl,apiBaseUrl){let trimmed=shareUrl.trim();if(trimmed.length===0)return null;try{let absolute=/^[a-z][a-z0-9+.-]*:/i.test(trimmed)?new URL(trimmed):apiBaseUrl!==void 0?new URL(trimmed,apiBaseUrl):null;return absolute===null||absolute.protocol!=="https:"?null:absolute.toString()}catch{return null}}function mapRecordShareLink(wire,apiBaseUrl){let parsed=linkSchema.safeParse(wire);if(!parsed.success)return null;let shareUrl=resolveShareUrl(parsed.data.share_url,apiBaseUrl);return shareUrl===null?null:/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,shareUrl:shareUrl,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)})}function mapRecordShareList(wire){let parsed=listSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.shares??[]).map(share=>/* @__PURE__ */Object.freeze({shareId:share.share_id,expiresAt:share.expires_at??null,createdAt:share.created_at??null,viewCount:share.view_count??0,lastViewedAt:share.last_viewed_at??null,audience:audienceOf(share.audience)}))):null}function mapRecordShareEmailReceipt(wire){let parsed=emailSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)}):null}function mapRecordPdfLink(wire){let parsed=pdfSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({downloadUrl:parsed.data.download_url,expiresAt:parsed.data.expires_at??null}):null}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var RECORDS_FEATURES_PDF_ONLY=/* @__PURE__ */Object.freeze({features:/* @__PURE__ */Object.freeze({}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE]),shareAudiences:/* @__PURE__ */Object.freeze([])}),featuresSchema=/* @__PURE__ */zod.z.object({features:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.boolean()),upload_content_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullish(),share_audiences:/* @__PURE__ */zod.z.unknown().optional()});function mapRecordsFeatures(wire){let parsed=featuresSchema.safeParse(wire);if(!parsed.success)return RECORDS_FEATURES_PDF_ONLY;let listed=parsed.data.upload_content_types??[],photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>listed.includes(type));/* @__PURE__ */
91
91
  return Object.freeze({features:/* @__PURE__ */Object.freeze({...parsed.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE,...photos]),shareAudiences:mapShareAudiences(parsed.data.share_audiences)})}function acceptsPhotos(types){return types!==void 0&&types.some(isPhotoType)}var KNOWN_STATUSES=/* @__PURE__ */new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),STATUS_ALIASES=/* @__PURE__ */Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function normalizeStatus(raw){let aliased=Object.prototype.hasOwnProperty.call(STATUS_ALIASES,raw)?STATUS_ALIASES[raw]:void 0;if(aliased!==void 0)return aliased;let value=raw;return KNOWN_STATUSES.has(value)?value:"parsing"}function normalizeOrigin(raw){return raw==="owner_reported"||raw==="clinic_document"?raw:null}var requestSchema=/* @__PURE__ */zod.z.object({request_id:/* @__PURE__ */zod.z.string().min(1),pet_ref:/* @__PURE__ */zod.z.string().min(1),status:/* @__PURE__ */zod.z.string(),simple_status:/* @__PURE__ */zod.z.string().nullish(),simple_status_detail:/* @__PURE__ */zod.z.string().nullish(),status_label:/* @__PURE__ */zod.z.string().optional(),dispatch_status:/* @__PURE__ */zod.z.string().nullish(),can_retry_send:/* @__PURE__ */zod.z.boolean().optional(),can_revoke:/* @__PURE__ */zod.z.boolean().optional(),can_convert_to_upload:/* @__PURE__ */zod.z.boolean().optional(),can_update_clinic_email:/* @__PURE__ */zod.z.boolean().optional(),reminder_count:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),last_reminder_at:/* @__PURE__ */zod.z.string().nullish(),waiting_expectation:/* @__PURE__ */zod.z.string().nullish(),document_count:/* @__PURE__ */zod.z.number().optional(),held_item_count:/* @__PURE__ */zod.z.number().optional(),received_at:/* @__PURE__ */zod.z.string().nullish(),parsing_started_at:/* @__PURE__ */zod.z.string().nullish(),review_started_at:/* @__PURE__ */zod.z.string().nullish(),created_at:/* @__PURE__ */zod.z.string().optional(),updated_at:/* @__PURE__ */zod.z.string().optional(),source:/* @__PURE__ */zod.z.string().nullish().catch(null),action_needed_label:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_reason:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_code:/* @__PURE__ */zod.z.string().nullish().catch(null),recovery_stage:/* @__PURE__ */zod.z.string().nullish().catch(null),show_clinic_phone:/* @__PURE__ */zod.z.boolean().optional().catch(void 0),clinic_name:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_email:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_phone:/* @__PURE__ */zod.z.string().nullish().catch(null),converted_to_upload_at:/* @__PURE__ */zod.z.string().nullish().catch(null),request_group_id:/* @__PURE__ */zod.z.string().nullish().catch(null)}).passthrough();function mapRequestView(wire){let parsed=requestSchema.safeParse(wire);if(!parsed.success)return null;let w=parsed.data,simpleStatus=normalizeSimpleStatus(w.simple_status),status=simpleStatus==="requested"&&(w.status==="awaiting_upload"||w.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":simpleStatus==="parsing"&&(w.simple_status_detail==="in_review"||w.simple_status_detail==="review_email_failed")?"in_review":simpleStatus??normalizeStatus(w.status);/* @__PURE__ */
@@ -102,7 +102,7 @@ return Object.freeze({send:send,authorize:authorize,stream:stream})}function ass
102
102
  return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";function recordsErrorReasonFor(error){return error.httpStatus!==404?null:error.reasonCode===PET_NOT_REGISTERED?"pet_not_found":"entitlement"}function tagReason(error,mode,kind){let notFound=recordsErrorReasonFor(error);return notFound!==null?withReason(error,notFound):error.code!=="accessDenied"?error:withReason(error,mode==="anonymous"?"session_required":kind==="content"?"consent_required":"entitlement")}function get(path){return{method:"GET",path:path}}function post(path,body){return{method:"POST",path:path,body:body}}function put(path,body){return{method:"PUT",path:path,body:body}}function del(path){return{method:"DELETE",path:path}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var epochs=/* @__PURE__ */new Map,listeners=/* @__PURE__ */new Set;function notifyRecordsConsentWithdrawn(petRef){epochs.set(petRef,(epochs.get(petRef)??0)+1);for(let listener of[...listeners])listener()}function recordsConsentEpochOf(petRef){return epochs.get(petRef)??0}function subscribe(onStoreChange){return listeners.add(onStoreChange),()=>{listeners.delete(onStoreChange)}}function useRecordsConsentEpoch(petRef){let snapshot=react.useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return react.useSyncExternalStore(subscribe,snapshot,snapshot)}var INITIAL={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:RECORDS_FEATURES_PDF_ONLY.uploadContentTypes},POLL_INTERVAL_MS=4e3,MAX_POLLS=30;function useEverfurRecords(opts){let{petRef:petRef}=opts,ownTransport=react.useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=react.useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=react.useRef(scope),[binding,setBinding]=react.useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=react.useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=react.useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=react.useRef(0);react.useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),react.useEffect(()=>{if(opts.controller)return;let{services:services}=runtime.registry,telemetry={record:(event,props)=>services.telemetry.track(event,props)},acquired=runtime.registry.acquire("records",`${userRef??""}|${petRef}${hasOwnTransport?"|own-upload":""}`,()=>createRecordsController({repository:createHttpRecordsRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),uploads:hasOwnTransport?{postMultipart:(policy,file,o)=>(ownTransport.current??services.uploadTransport).postMultipart(policy,file,o)}:services.uploadTransport,telemetry:telemetry}),()=>{});return setBinding({scope:scope,controller:acquired}),()=>{runtime.registry.release(acquired)}},[runtime,userRef,petRef,opts.controller,scopeEpoch,scope,hasOwnTransport]);let patch=react.useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return;let gen=generation.current+=1;pollsRef.current=0,rearmPolls(),patch({loading:true,error:null,denialReason:null,withheld:false});let[consentRes,listRes]=await Promise.all([controller.getConsent(petRef),controller.listRequests()]);if(gen!==generation.current)return;let consent=consentRes.ok?consentRes.value:null,requests=listRes.ok?listRes.value.filter(request=>request.petRef===petRef):[],listError=listRes.ok?null:listRes.error;if(consent&&consent.granted){let recordRes=await controller.getRecord(petRef);if(gen!==generation.current)return;if(recordRes.ok){patch({consent:consent,requests:requests,record:recordRes.value,withheld:recordRes.value.withheld,error:recordRes.value.withheld?withheldSentinel():listError,denialReason:null,loading:false});return}patch({consent:consent,requests:requests,record:null,error:recordRes.error,denialReason:recordsDenialReasonOf(recordRes.error),withheld:false,loading:false});return}patch({consent:consent,requests:requests,record:null,error:consentRes.ok?listError:consentRes.error,denialReason:consent?"consent_required":consentDenial(consentRes),withheld:false,loading:false})},[controller,petRef,patch,scope]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;react.useEffect(()=>{if(!readUploadFeatures||!controller?.readFeatures)return;let live=true;return controller.readFeatures().then(features=>{live&&activeScope.current===scope&&patch({uploadContentTypes:features.uploadContentTypes})}),()=>{live=false}},[controller,readUploadFeatures,patch,scope]);let activeRequest=react.useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=react.useRef(0),polledIdRef=react.useRef(null),[pollEpoch,rearmPolls]=react.useReducer(n=>n+1,0);react.useEffect(()=>{if(!controller||activeId===null||activeStatus===null||isTerminalStatus(activeStatus)||activeStatus==="in_review")return;polledIdRef.current!==String(activeId)&&(polledIdRef.current=String(activeId),pollsRef.current=0);let cancelled=false,tick=async()=>{if(cancelled||pollsRef.current>=MAX_POLLS)return;pollsRef.current+=1;let res=await controller.getRequest(activeId);if(!cancelled){if(res.ok&&res.value.petRef===petRef){if(setSnap(current=>({...current,requests:replaceRequest(current.requests,res.value)})),isTerminalStatus(res.value.status)){res.value.status==="published"&&load();return}if(res.value.status==="in_review")return}handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS)}},handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS);return()=>{cancelled=true,clearTimeout(handle)}},[controller,activeId,activeStatus,load,pollEpoch,petRef,setSnap]);let createRequest=react.useCallback(async idempotencyKey=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.createUploadRequest({petRef:petRef,idempotencyKey:idempotencyKey});return activeScope.current===scope&&res.ok&&res.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,res.value)})),res},[controller,petRef,scope,setSnap]),patchItem=react.useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=react.useCallback(async(requestId2,files)=>{let batch=Date.now().toString(36),queue=files.map((file,index)=>{let skipReason=skipReasonFor(file,snap.uploadContentTypes);return{key:`${batch}-${index}`,name:file.name??null,status:skipReason===null?"queued":"skipped",progress:0,skipReason:skipReason,error:null}}),settled=[...queue];if(!controller||activeScope.current!==scope)/* @__PURE__ */return Object.freeze(settled);setSnap(c=>({...c,uploadQueue:queue,isUploading:true,uploadProgress:0}));for(let[index,file]of files.entries()){let item=queue[index];if(item.status==="skipped")continue;if(activeScope.current!==scope)break;patchItem(item.key,current=>({...current,status:"uploading",progress:0})),patch({uploadProgress:0});let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{if(activeScope.current!==scope)return;let bounded=Math.min(1,Math.max(0,fraction));patchItem(item.key,current=>({...current,progress:Math.max(current.progress,bounded)})),patch({uploadProgress:bounded})}});if(activeScope.current!==scope)break;let next=res.ok?{...item,status:"done",progress:1}:{...item,status:"failed",error:res.error};if(settled[index]=next,patchItem(item.key,()=>next),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}}return activeScope.current===scope&&patch({isUploading:false,uploadProgress:null}),/* @__PURE__ */Object.freeze(settled)},[controller,patch,patchItem,petRef,scope,setSnap,snap.uploadContentTypes]),uploadDocument=react.useCallback(async(requestId2,file)=>{if(!controller||activeScope.current!==scope)return notReady();let key=`${Date.now().toString(36)}-0`;setSnap(c=>({...c,isUploading:true,uploadProgress:0,uploadQueue:[{key:key,name:file.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{activeScope.current===scope&&(patch({uploadProgress:fraction}),patchItem(key,current=>({...current,progress:Math.max(current.progress,Math.min(1,fraction))})))}});if(activeScope.current!==scope)return res;if(patch({isUploading:false,uploadProgress:null}),patchItem(key,current=>res.ok?{...current,status:"done",progress:1}:{...current,status:"failed",error:res.error}),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}return res},[controller,patch,patchItem,petRef,scope,setSnap]),grantConsent=react.useCallback(async(consentVersion,idempotencyKey)=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.grantConsent({petRef:petRef,consentVersion:consentVersion,idempotencyKey:idempotencyKey});return res.ok&&activeScope.current===scope&&load(),res},[controller,petRef,load,scope]),revokeConsent=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.revokeConsent(petRef);return res.ok&&notifyRecordsConsentWithdrawn(petRef),res.ok&&activeScope.current===scope&&(generation.current+=1,patch({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:res.value})),res},[controller,petRef,patch,scope]),refresh=react.useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return react.useMemo(()=>({status:status,record:snap.record,requests:snap.requests,activeRequest:activeRequest,consent:snap.consent,error:snap.error,denialReason:snap.denialReason,withheld:snap.withheld,isUploading:snap.isUploading,uploadProgress:snap.uploadProgress,uploadQueue:snap.uploadQueue,uploadContentTypes:snap.uploadContentTypes,createRequest:createRequest,uploadDocument:uploadDocument,uploadDocuments:uploadDocuments,grantConsent:grantConsent,revokeConsent:revokeConsent,refresh:refresh}),[status,snap,activeRequest,createRequest,uploadDocument,uploadDocuments,grantConsent,revokeConsent,refresh])}function skipReasonFor(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"too_large":null}function classifyPick(files,types){let uploadable=[],skipped=[];for(let file of files){let reason=skipReasonFor(file,types);reason===null?uploadable.push(file):skipped.push({name:file.name??null,reason:reason})}return{uploadable:uploadable,skipped:skipped}}function selectStatus(snap,hasController){return snap.loading||!hasController?"loading":snap.withheld||snap.denialReason!==null||snap.error!==null?"error":snap.record!==null&&!snap.record.isEmpty||snap.requests.length>0?"populated":"empty"}function newestRequest(requests){if(requests.length===0)return null;let newest=requests[0];for(let r of requests)r.updatedAt>newest.updatedAt&&(newest=r);return newest}function replaceRequest(requests,next){let filtered=requests.filter(r=>r.id!==next.id);return[next,...filtered]}function consentDenial(res){return res.ok?"consent_required":recordsDenialReasonOf(res.error)??"consent_required"}function withheldSentinel(){return makeEverfurError("internalError",{retryable:false})}function notReady(){return{ok:false,error:makeEverfurError("internalError",{retryable:true})}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
103
103
  return Object.freeze({stack:/* @__PURE__ */Object.freeze([initial])})}function currentRecordsScreen(state){return state.stack[state.stack.length-1]??RECORDS_DASHBOARD}function pushRecordsNav(state,screen){/* @__PURE__ */
104
104
  return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
105
- return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCountDraft:count=>`DRAFT COPY [[${String(count)} clinics found: the spoken count of search results]]`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){case"verified":return{label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case"unverified":return{label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return{label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date)=>`Latest reading ${reading}, ${status}, collected ${date}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=react.useState(""),[debouncedQuery,setDebounced]=react.useState(""),[clinics,setClinics]=react.useState([]),[cursor,setCursor]=react.useState(null),[recent,setRecent]=react.useState([]),[recentLoading,setRecentLoading]=react.useState(true),[initialLoading,setInitialLoading]=react.useState(false),[loadingMore,setLoadingMore]=react.useState(false),[error,setError]=react.useState(null),[pageError,setPageError]=react.useState(null),[attempt,setAttempt]=react.useState(0),generation=react.useRef(0),live=react.useRef(true),lat=location?.latitude,lng=location?.longitude,bias=react.useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);react.useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),react.useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),react.useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;react.useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=react.useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=react.useCallback(value=>setQueryValue(value),[]),retry=react.useCallback(()=>setAttempt(n=>n+1),[]);return react.useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
105
+ return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCount:count=>count===1?"Showing 1 clinic":`Showing ${String(count)} clinics`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){case"verified":return{label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case"unverified":return{label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return{label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date)=>`Latest reading ${reading}, ${status}, collected ${date}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=react.useState(""),[debouncedQuery,setDebounced]=react.useState(""),[clinics,setClinics]=react.useState([]),[cursor,setCursor]=react.useState(null),[recent,setRecent]=react.useState([]),[recentLoading,setRecentLoading]=react.useState(true),[initialLoading,setInitialLoading]=react.useState(false),[loadingMore,setLoadingMore]=react.useState(false),[error,setError]=react.useState(null),[pageError,setPageError]=react.useState(null),[attempt,setAttempt]=react.useState(0),generation=react.useRef(0),live=react.useRef(true),lat=location?.latitude,lng=location?.longitude,bias=react.useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);react.useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),react.useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),react.useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;react.useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=react.useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=react.useCallback(value=>setQueryValue(value),[]),retry=react.useCallback(()=>setAttempt(n=>n+1),[]);return react.useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
106
106
  return Object.freeze({key:clinic?.id??`free:${freeText??""}`,clinic:clinic,freeText:freeText,email:email2,idempotencyKey:idempotencyKey})}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),clinicSchema=/* @__PURE__ */zod.z.object({clinicId:/* @__PURE__ */uuid.optional(),clinicFreeText:text(200).refine(value=>value.trim().length>0).optional(),clinicEmail:text(320,3).refine(value=>!hasControl(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())).optional(),signatureId:/* @__PURE__ */uuid.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0)),inputSchema=/* @__PURE__ */zod.z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */zod.z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */zod.z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */zod.z.string(),created_count:/* @__PURE__ */zod.z.number().int().nonnegative(),failed_count:/* @__PURE__ */zod.z.number().int().nonnegative(),results:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({idempotency_key:/* @__PURE__ */zod.z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */zod.z.string().nullable().optional(),created:/* @__PURE__ */zod.z.boolean(),request:/* @__PURE__ */zod.z.unknown().optional(),failure_code:/* @__PURE__ */zod.z.string().nullable().optional(),failure_reason:/* @__PURE__ */zod.z.string().nullable().optional()}))});function createRecordsClinicBatchClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async createClinicRequestBatch(input){if(!inputSchema.safeParse(input).success)return err(makeEverfurError("validationFailed",{retryable:false}));let result=await funnel.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,clinics:input.clinics.map(clinic=>({...clinic.clinicId!==void 0?{clinic_id:clinic.clinicId}:{clinic_free_text:clinic.clinicFreeText},...clinic.clinicEmail!==void 0?{clinic_email:clinic.clinicEmail}:{},...clinic.signatureId!==void 0?{signature_id:clinic.signatureId}:{signature_png_base64:clinic.signaturePngBase64},idempotency_key:clinic.idempotencyKey}))}});if(!result.ok)return result;let parsed=responseSchema.safeParse(result.value);if(!parsed.success||parsed.data.pet_ref!==input.petRef)return malformed();let results=[];for(let row of parsed.data.results){let request=row.request===void 0||row.request===null?null:mapRequestView(row.request);if(row.created!==(request!==null))return malformed();results.push(/* @__PURE__ */Object.freeze({idempotencyKey:row.idempotency_key,clinicId:row.clinic_id??null,clinicFreeText:row.clinic_free_text??null,created:row.created,request:request,failureCode:row.failure_code??null,failureReason:row.failure_reason??null}))}return ok(/* @__PURE__ */Object.freeze({requestGroupId:parsed.data.request_group_id,petRef:parsed.data.pet_ref,results:/* @__PURE__ */Object.freeze(results),createdCount:parsed.data.created_count,failedCount:parsed.data.failed_count}))}}}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}var uuid2=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),clinicPageSchema=/* @__PURE__ */zod.z.object({clinics:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({clinic_id:uuid2,name:/* @__PURE__ */zod.z.string().min(1),address:/* @__PURE__ */zod.z.string().nullable(),phone:/* @__PURE__ */zod.z.string().nullable(),email_status:/* @__PURE__ */zod.z.string(),distance_km:/* @__PURE__ */zod.z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */zod.z.string().nullable().optional()}),copySchema=/* @__PURE__ */zod.z.object({authorization_version:/* @__PURE__ */zod.z.string().min(1),scope_template:/* @__PURE__ */zod.z.string().min(1),authorization_template:/* @__PURE__ */zod.z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */zod.z.object({upload_id:/* @__PURE__ */zod.z.string().min(1),upload_url:/* @__PURE__ */zod.z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string())});function createRecordsClinicController(deps){let{repository:repository}=deps,request=async pending=>{let result=await pending;if(!result.ok)return result;let mapped=mapRequestView(result.value);return mapped===null?malformed2():ok(mapped)},page=async pending=>{let result=await pending;if(!result.ok)return result;let parsed=clinicPageSchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({clinics:/* @__PURE__ */Object.freeze(parsed.data.clinics.map(clinic=>/* @__PURE__ */Object.freeze({id:clinic.clinic_id,name:clinic.name,address:clinic.address,phone:clinic.phone,emailStatus:clinic.email_status,distanceKm:clinic.distance_km}))),nextCursor:parsed.data.next_cursor??null})):malformed2()};return{searchClinics:(input={})=>page(repository.searchClinics(input)),recentClinics:(input={})=>page(repository.recentClinics(input)),async getRequestGroup(requestGroupId){let result=await repository.getRequestGroup(requestGroupId);if(!result.ok)return result;let group=mapRequestGroup(result.value);return group===null?malformed2():ok(group)},async getAuthorizationCopy(){let result=await repository.getAuthorizationCopy();if(!result.ok)return result;let parsed=copySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({authorizationVersion:parsed.data.authorization_version,scopeTemplate:parsed.data.scope_template,authorizationTemplate:parsed.data.authorization_template})):malformed2()},async createClinicRequest(input){let result=await request(repository.createClinicRequest(input));return result.ok&&result.value.petRef!==input.petRef?malformed2():result},retryRequest:id=>request(repository.retryRequest(id)),revokeRequest:id=>request(repository.revokeRequest(id)),updateClinicEmail:(id,clinicEmail)=>request(repository.updateClinicEmail(id,clinicEmail)),convertToUpload:id=>request(repository.convertToUpload(id)),async initiateSignatureUpload(fileSize){let result=await repository.initiateSignatureUpload(fileSize);if(!result.ok)return result;let parsed=signaturePolicySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({uploadId:parsed.data.upload_id,uploadUrl:parsed.data.upload_url,uploadFields:/* @__PURE__ */Object.freeze(parsed.data.upload_fields)})):malformed2()},async completeSignatureUpload(uploadId){let result=await repository.completeSignatureUpload(uploadId);if(!result.ok)return result;let parsed=zod.z.object({signature_id:uuid2}).safeParse(result.value);return parsed.success?ok(parsed.data.signature_id):malformed2()}}}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}var BASE2="/widget/v1/records",uuid3=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text2=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl2=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),email=text2(320,3).refine(value=>!hasControl2(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())),requestId=text2(64),recentSchema=/* @__PURE__ */zod.z.object({limit:/* @__PURE__ */zod.z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */zod.z.object({query:text2(200,0).optional(),location:/* @__PURE__ */zod.z.object({latitude:/* @__PURE__ */zod.z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */zod.z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */zod.z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */zod.z.object({petRef:text2(128),ownerName:text2(200).refine(value=>value.trim().length>0&&!hasControl2(value)),authorizationVersion:text2(64),clinicId:/* @__PURE__ */uuid3.optional(),clinicFreeText:text2(200).refine(value=>value.trim().length>0).optional(),clinicEmail:email.optional(),signatureId:/* @__PURE__ */uuid3.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0));function createHttpRecordsClinicRepository(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=(call,request,deduplicated=false)=>funnel.send(`records.clinic.${call}`,request,request.method==="GET"||deduplicated?void 0:{idempotent:false,maxAttempts:1}),recover=(id,action,body)=>requestId.safeParse(id).success?send(action,{method:"POST",path:`${BASE2}/requests/${encodeURIComponent(id)}/${action}`,...body?{body:body}:{}}):invalid();return{searchClinics(input){return searchSchema.safeParse(input).success?send("search",{method:"GET",path:`${BASE2}/clinics/search`,query:{q:input.query??"",lat:input.location?.latitude,lng:input.location?.longitude,limit:input.limit,cursor:input.cursor}}):invalid()},recentClinics(input){return recentSchema.safeParse(input).success?send("recent",{method:"GET",path:`${BASE2}/clinics/recent`,query:{limit:input.limit}}):invalid()},getRequestGroup(requestGroupId){return requestId.safeParse(requestGroupId).success?send("requestGroup",{method:"GET",path:`${BASE2}/request-groups/${encodeURIComponent(requestGroupId)}`}):invalid()},getAuthorizationCopy:()=>send("authorizationCopy",{method:"GET",path:`${BASE2}/authorization-copy`}),createClinicRequest(input){return createSchema.safeParse(input).success?send("create",{method:"POST",path:`${BASE2}/clinic-requests`,body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,idempotency_key:input.idempotencyKey,...input.clinicId!==void 0?{clinic_id:input.clinicId}:{clinic_free_text:input.clinicFreeText},...input.clinicEmail!==void 0?{clinic_email:input.clinicEmail}:{},...input.signatureId!==void 0?{signature_id:input.signatureId}:{signature_png_base64:input.signaturePngBase64}}},true):invalid()},retryRequest:id=>recover(id,"retry"),revokeRequest:id=>recover(id,"revoke"),convertToUpload:id=>recover(id,"convert-to-upload"),updateClinicEmail(id,clinicEmail){return email.safeParse(clinicEmail).success?recover(id,"clinic-email",{clinic_email:clinicEmail}):invalid()},initiateSignatureUpload(fileSize){return!Number.isInteger(fileSize)||fileSize<=0||fileSize>2*1024*1024?invalid():send("signatureInitiate",{method:"POST",path:`${BASE2}/signatures/initiate`,body:{content_type:"image/png",file_size:fileSize}})},completeSignatureUpload(uploadId){return/^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uploadId)?send("signatureComplete",{method:"POST",path:`${BASE2}/signatures/complete`,body:{upload_id:uploadId}}):invalid()}}}function invalid(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsClinic(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),controller=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=react.useRef(controller);return react.useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),react.useMemo(()=>{let run=async operation=>{if(userRef===null||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation();return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{searchClinics:input=>run(()=>controller.searchClinics(input)),recentClinics:input=>run(()=>controller.recentClinics(input)),getRequestGroup:id=>run(()=>controller.getRequestGroup(id)),getAuthorizationCopy:()=>run(()=>controller.getAuthorizationCopy()),createClinicRequest:input=>run(()=>controller.createClinicRequest(input)),retryRequest:id=>run(()=>controller.retryRequest(id)),revokeRequest:id=>run(()=>controller.revokeRequest(id)),updateClinicEmail:(id,email2)=>run(()=>controller.updateClinicEmail(id,email2)),convertToUpload:id=>run(()=>controller.convertToUpload(id)),initiateSignatureUpload:size=>run(()=>controller.initiateSignatureUpload(size)),completeSignatureUpload:id=>run(()=>controller.completeSignatureUpload(id))}},[controller,userRef])}function useEverfurRecordsClinicBatch(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=react.useRef(client);return react.useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),react.useMemo(()=>({async createClinicRequestBatch(input){if(userRef===null||active.current!==client)return err(makeEverfurError("accessDenied"));let result=await client.createClinicRequestBatch(input);return active.current===client?result:err(makeEverfurError("accessDenied"))}}),[client,userRef])}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
107
107
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
108
108
  return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
@@ -162,9 +162,19 @@ return jsxRuntime.jsx(WifiOffGlyph,{size:size,color:color});default:return null}
162
162
  return jsxRuntime.jsxs(reactNative.View,{style:styles.container,accessibilityRole:"summary",testID:testID,children:[
163
163
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"records-empty-glyph",children:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyGlyph,{variant:variant,size:GLYPH_SIZE,color:theme.color.brandInk})}),
164
164
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,children:copy.title}),
165
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,BACK_LABEL="Back";function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let styles=useStyles2(),theme=useEverfurTheme(),logoUrl=theme.meta.logoUrl,row=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:logoUrl===null?styles.row:styles.rowUnderLogo,testID:testID,children:[onBack?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,hitSlop:12,style:styles.back,testID:testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back}),title.trim().length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:variant==="document"?styles.documentTitle:styles.title,accessibilityRole:"header",numberOfLines:1,children:title}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:testID?`${testID}-spacer`:void 0}),
166
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.right,children:right??/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back})})]});return logoUrl===null?row:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.bar,children:[
167
- /* @__PURE__ */jsxRuntime.jsx(BrandLogo,{logoUrl:logoUrl,name:theme.meta.displayName,barStyle:styles.logoBar,logoStyle:styles.logo,testID:testID?`${testID}-logo`:void 0}),row]})}function ListGlyph2(){let styles=useStyles2();/* @__PURE__ */
165
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}var RECORDS_SANDBOX_COPY=/* @__PURE__ */Object.freeze({note:"Test account: clinics are never contacted. Use records test mode to move a request forward.",clinicNotContacted:"Clinic not contacted",notEmailed:email2=>`This is a test account, so no email went to ${email2}.`,newClinicDirectSendNote:"This is a test account, so this clinic will not be emailed."});var NO_SUBSCRIPTION=()=>()=>{};function isSandboxSnapshot(snapshot){return snapshot?.livemode===false}function useEntitlementSource(){try{return useEverfurContext().runtime.entitlements??null}catch{return null}}function useRecordsSandboxTenant(){let source=useEntitlementSource(),subscribe2=react.useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=react.useCallback(()=>source===null?false:isSandboxSnapshot(source.getSnapshot()),[source]);return react.useSyncExternalStore(subscribe2,read,read)}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text3=>text3.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text3=normalize(disclaimer);return text3.length===0||text3===FOOTNOTE}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var WHITE="#FFFFFF",BLACK="#000000";function poleForGrounds(grounds){let worst=ink=>grounds.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}var PUSH_STEP=.05;function pushToContrast(color,grounds,pole,target){let first=grounds[0];if(first===void 0)return pole;let reads=candidate=>grounds.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix(from.r,to.r),mix(from.g,to.g),mix(from.b,to.b));if(reads(candidate))return candidate}return pole}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b);return{success:!same(c.success,compiled.success),warning:!same(c.warningStrong,compiled.warningStrong)||!same(c.cautionAccent,compiled.cautionAccent),info:!(same(c.info,c.brandInk)&&same(c.badgeBgInfo,c.brandSoft)&&same(c.infoEdge,c.structureEdge))}}var SLOT_MIN_CONTRAST=4.5;function brandedSuccessInk(theme){if(!brandedStatus(theme).success)return null;let grounds=[theme.color.surface];return pushToContrast(theme.color.success,grounds,poleForGrounds(grounds),SLOT_MIN_CONTRAST)}var BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
166
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoGlyphText,children:"i"})}),
167
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,busy:busy=false,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID,style:style}){let styles=useScreenStyles(),theme=useEverfurTheme(),still=theme.motion.reducedMotion,box3=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink,text3=kind==="primary"?styles.pillPrimaryLabel:kind==="danger"?styles.pillDangerLabel:kind==="ask"?styles.pillAskLabel:kind==="link"?styles.pillLinkLabel:styles.pillOutlineLabel;/* @__PURE__ */
168
+ return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,accessibilityHint:accessibilityHint,accessibilityState:{disabled:disabled||busy,busy:busy},style:({pressed:pressed})=>[styles.pill,box3,disabled?styles.pillDisabled:null,pressed&&!still?styles.pressed:null,style],testID:testID,children:[busy?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:kind==="primary"?theme.color.onPrimary:theme.color.brandInk}):null,
169
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:label})]})}function Chip({label:label,tone:tone="neutral",testID:testID}){let styles=useScreenStyles(),{bg:bg,fg:fg}=styles.chipTones[tone],sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
170
+ return jsxRuntime.jsx(reactNative.View,{style:[styles.chip,sentence?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.chipText,sentence?styles.chipSentenceText:null,fg],children:label})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
171
+ return jsxRuntime.jsxs(reactNative.View,{style:styles.sectionHeader,children:[
172
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:title}),count!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionCount,children:count}):null]})}function Chevron({direction:direction="right"}){let styles=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
173
+ return jsxRuntime.jsx(reactNative.View,{style:[styles.chevron,{transform:[{rotate:rotate}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),bannerText=slotText(slots.banner),bannerInk=slots.banner?.textColor,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({bg:{backgroundColor:bg,borderColor:"transparent"},fg:{color:fg}}),edge=(line2,fg)=>({bg:{backgroundColor:color.surface,borderColor:line2},fg:{color:fg}});return{chipTones:{neutral:edge(color.brandBorderStrong,color.text.primary),info:tone(color.brandSoft,color.brandInk),warning:edge(color.cautionAccent,color.text.primary),critical:edge(color.danger,color.danger),positive:edge(color.success,brandedSuccessInk(theme)??color.brandInk)},...reactNative.StyleSheet.create({root:{flex:1,backgroundColor:color.background},body:{flex:1},content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg},contentTight:{paddingHorizontal:space.sm,paddingBottom:space.xxl,gap:space.lg},inset:{paddingHorizontal:space.sm},section:{gap:space.sm+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.xs},sectionTitle:{...text3(size.subtitle,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4},sectionCount:{...text3(size.bodyTight,lineHeight.snug,color.text.muted,"medium")},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.xs,...slotBox(recordCard,hairline)},creamCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(recordCard,hairline)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.md,paddingVertical:space.md},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text3(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(size.caption,lineHeight.normal,color.text.muted),...cardText},chip:{minHeight:24,justifyContent:"center",borderRadius:radius.pill,borderWidth:1.5,paddingHorizontal:space.sm+space.xs/2,alignSelf:"flex-start"},chipText:{...text3(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text3(size.caption,lineHeight.normal,color.text.primary,"medium"),letterSpacing:0,textTransform:"none"},pill:{minHeight:BUTTON_HEIGHT,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm},pillPrimary:{backgroundColor:color.brand,...slotBox(slots.primaryButton)},pillPrimaryLabel:{...text3(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text3(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text3(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text3(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text3(size.body,lineHeight.snug,color.linkInk,"bold")},pillDisabled:{opacity:.5},pressed:{transform:[{scale:RECORDS_MOTION.pressScale}]},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2,...slotBox(slots.banner)},infoNoteText:{flex:1,...text3(size.bodyTight,lineHeight.normal,color.text.primary),...bannerText},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},cautionNoteText:{flex:1,...text3(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text3(size.bodyTight,lineHeight.relaxed,color.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md},errorText:{flex:1,...text3(size.bodyTight,lineHeight.normal,errorColor)},band:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,...slotBox(slots.banner)},bandText:{flex:1,...text3(size.caption,lineHeight.normal,color.text.secondary),...bannerText},infoGlyph:{width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,borderWidth:1,borderColor:bannerInk??color.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...text3(size.small,lineHeight.tight,color.text.secondary,"bold"),...bannerText},chevron:{width:space.sm,height:space.sm,borderTopWidth:space.xs/2,borderRightWidth:space.xs/2,borderColor:color.text.muted},lead:{paddingHorizontal:space.sm,...text3(size.body+1,lineHeight.snug,color.text.primary,"bold")},field:{minHeight:touch,paddingHorizontal:space.md,paddingVertical:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:size.body,...slotBox(slots.input,1),...slotText(slots.input)},fieldLabel:{...text3(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text3(size.caption,lineHeight.normal,color.text.muted),bodyText:text3(size.body,lineHeight.normal,color.text.primary)})}}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,BACK_LABEL="Back";function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let styles=useStyles2(),theme=useEverfurTheme(),logoUrl=theme.meta.logoUrl,row=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:logoUrl===null?styles.row:styles.rowUnderLogo,testID:testID,children:[onBack?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,hitSlop:12,style:styles.back,testID:testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back}),title.trim().length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:variant==="document"?styles.documentTitle:styles.title,accessibilityRole:"header",numberOfLines:1,children:title}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:testID?`${testID}-spacer`:void 0}),
174
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.right,children:right??/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back})})]}),header=logoUrl===null?row:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.bar,children:[
175
+ /* @__PURE__ */jsxRuntime.jsx(BrandLogo,{logoUrl:logoUrl,name:theme.meta.displayName,barStyle:styles.logoBar,logoStyle:styles.logo,testID:testID?`${testID}-logo`:void 0}),row]});/* @__PURE__ */
176
+ return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[header,
177
+ /* @__PURE__ */jsxRuntime.jsx(SandboxNote,{})]})}function SandboxNote(){let sandbox=useRecordsSandboxTenant(),screen=useScreenStyles(),styles=useStyles2();return sandbox?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[screen.band,styles.sandboxNote],accessible:true,accessibilityRole:"text",testID:"records-sandbox-note",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.bandText,children:RECORDS_SANDBOX_COPY.note})}):null}function ListGlyph2(){let styles=useStyles2();/* @__PURE__ */
168
178
  return jsxRuntime.jsxs(reactNative.View,{style:styles.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
169
179
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.listBar}),
170
180
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.listBar}),
@@ -181,17 +191,9 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles.sendGlyph,accessibilityEle
181
191
  return jsxRuntime.jsxs(reactNative.View,{style:styles.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
182
192
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadStem}),
183
193
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadHead}),
184
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,header=theme.slots.header,ink=header?.textColor??color.brandInk,rowBase={flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,gap:space.sm},touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return reactNative.StyleSheet.create({row:{...rowBase,...slotBox(header)},rowUnderLogo:rowBase,bar:{...slotBox(header)},logoBar:{alignItems:"center",paddingTop:space.sm,paddingHorizontal:space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},back:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},chevron:{width:chevron,height:chevron,borderLeftWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginLeft:space.xs},title:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.tight)+1,color:ink},spacer:{flex:1},documentTitle:{flex:1,textAlign:"center",...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.text.primary,...slotText(header)},right:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2},listGlyph:{width:glyph,height:glyph,justifyContent:"space-evenly"},listBar:{height:stroke3,borderRadius:stroke3,backgroundColor:ink},shareGlyph:{width:glyph-space.xs,height:glyph-space.xs},shareDot:{position:"absolute",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs,borderWidth:stroke3,borderColor:ink},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:space.xs+space.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:space.xs,top:space.sm,width:space.sm+space.xs/2,height:stroke3,backgroundColor:ink},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:glyph-space.xs,height:glyph-space.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],borderRadius:stroke3},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:stroke3,backgroundColor:ink},downloadGlyph:{width:glyph-space.xs,height:glyph-space.xs,alignItems:"center"},downloadStem:{width:stroke3,height:space.sm+space.xs/2,backgroundColor:ink},downloadHead:{width:space.sm,height:space.sm,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginTop:-space.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:space.xs+space.xs/2,borderLeftWidth:stroke3,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink}})}var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
194
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,header=theme.slots.header,ink=header?.textColor??color.brandInk,rowBase={flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,gap:space.sm},touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return reactNative.StyleSheet.create({row:{...rowBase,...slotBox(header)},rowUnderLogo:rowBase,bar:{...slotBox(header)},logoBar:{alignItems:"center",paddingTop:space.sm,paddingHorizontal:space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},back:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},chevron:{width:chevron,height:chevron,borderLeftWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginLeft:space.xs},title:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.tight)+1,color:ink},spacer:{flex:1},sandboxNote:{marginHorizontal:space.lg,marginBottom:space.md},documentTitle:{flex:1,textAlign:"center",...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.text.primary,...slotText(header)},right:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2},listGlyph:{width:glyph,height:glyph,justifyContent:"space-evenly"},listBar:{height:stroke3,borderRadius:stroke3,backgroundColor:ink},shareGlyph:{width:glyph-space.xs,height:glyph-space.xs},shareDot:{position:"absolute",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs,borderWidth:stroke3,borderColor:ink},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:space.xs+space.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:space.xs,top:space.sm,width:space.sm+space.xs/2,height:stroke3,backgroundColor:ink},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:glyph-space.xs,height:glyph-space.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],borderRadius:stroke3},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:stroke3,backgroundColor:ink},downloadGlyph:{width:glyph-space.xs,height:glyph-space.xs,alignItems:"center"},downloadStem:{width:stroke3,height:space.sm+space.xs/2,backgroundColor:ink},downloadHead:{width:space.sm,height:space.sm,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginTop:-space.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:space.xs+space.xs/2,borderLeftWidth:stroke3,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink}})}var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
185
195
  return jsxRuntime.jsxs(reactNative.View,{testID:"records-gate-off",style:[{minHeight:MIN_HEIGHT,justifyContent:"center",gap:space.md,padding:space.lg,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surfaceCream},style],children:[reason.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
186
- /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text3=>text3.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text3=normalize(disclaimer);return text3.length===0||text3===FOOTNOTE}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var WHITE="#FFFFFF",BLACK="#000000";function poleForGrounds(grounds){let worst=ink=>grounds.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}var PUSH_STEP=.05;function pushToContrast(color,grounds,pole,target){let first=grounds[0];if(first===void 0)return pole;let reads=candidate=>grounds.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix(from.r,to.r),mix(from.g,to.g),mix(from.b,to.b));if(reads(candidate))return candidate}return pole}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b);return{success:!same(c.success,compiled.success),warning:!same(c.warningStrong,compiled.warningStrong)||!same(c.cautionAccent,compiled.cautionAccent),info:!(same(c.info,c.brandInk)&&same(c.badgeBgInfo,c.brandSoft)&&same(c.infoEdge,c.structureEdge))}}var SLOT_MIN_CONTRAST=4.5;function brandedSuccessInk(theme){if(!brandedStatus(theme).success)return null;let grounds=[theme.color.surface];return pushToContrast(theme.color.success,grounds,poleForGrounds(grounds),SLOT_MIN_CONTRAST)}var BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
187
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoGlyphText,children:"i"})}),
188
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,busy:busy=false,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID,style:style}){let styles=useScreenStyles(),theme=useEverfurTheme(),still=theme.motion.reducedMotion,box3=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink,text3=kind==="primary"?styles.pillPrimaryLabel:kind==="danger"?styles.pillDangerLabel:kind==="ask"?styles.pillAskLabel:kind==="link"?styles.pillLinkLabel:styles.pillOutlineLabel;/* @__PURE__ */
189
- return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,accessibilityHint:accessibilityHint,accessibilityState:{disabled:disabled||busy,busy:busy},style:({pressed:pressed})=>[styles.pill,box3,disabled?styles.pillDisabled:null,pressed&&!still?styles.pressed:null,style],testID:testID,children:[busy?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:kind==="primary"?theme.color.onPrimary:theme.color.brandInk}):null,
190
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:text3,children:label})]})}function Chip({label:label,tone:tone="neutral",testID:testID}){let styles=useScreenStyles(),{bg:bg,fg:fg}=styles.chipTones[tone],sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
191
- return jsxRuntime.jsx(reactNative.View,{style:[styles.chip,sentence?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.chipText,sentence?styles.chipSentenceText:null,fg],children:label})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
192
- return jsxRuntime.jsxs(reactNative.View,{style:styles.sectionHeader,children:[
193
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:title}),count!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionCount,children:count}):null]})}function Chevron({direction:direction="right"}){let styles=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
194
- return jsxRuntime.jsx(reactNative.View,{style:[styles.chevron,{transform:[{rotate:rotate}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),bannerText=slotText(slots.banner),bannerInk=slots.banner?.textColor,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({bg:{backgroundColor:bg,borderColor:"transparent"},fg:{color:fg}}),edge=(line2,fg)=>({bg:{backgroundColor:color.surface,borderColor:line2},fg:{color:fg}});return{chipTones:{neutral:edge(color.brandBorderStrong,color.text.primary),info:tone(color.brandSoft,color.brandInk),warning:edge(color.cautionAccent,color.text.primary),critical:edge(color.danger,color.danger),positive:edge(color.success,brandedSuccessInk(theme)??color.brandInk)},...reactNative.StyleSheet.create({root:{flex:1,backgroundColor:color.background},body:{flex:1},content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg},contentTight:{paddingHorizontal:space.sm,paddingBottom:space.xxl,gap:space.lg},inset:{paddingHorizontal:space.sm},section:{gap:space.sm+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.xs},sectionTitle:{...text3(size.subtitle,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4},sectionCount:{...text3(size.bodyTight,lineHeight.snug,color.text.muted,"medium")},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.xs,...slotBox(recordCard,hairline)},creamCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(recordCard,hairline)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.md,paddingVertical:space.md},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text3(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(size.caption,lineHeight.normal,color.text.muted),...cardText},chip:{minHeight:24,justifyContent:"center",borderRadius:radius.pill,borderWidth:1.5,paddingHorizontal:space.sm+space.xs/2,alignSelf:"flex-start"},chipText:{...text3(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text3(size.caption,lineHeight.normal,color.text.primary,"medium"),letterSpacing:0,textTransform:"none"},pill:{minHeight:BUTTON_HEIGHT,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm},pillPrimary:{backgroundColor:color.brand,...slotBox(slots.primaryButton)},pillPrimaryLabel:{...text3(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text3(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text3(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text3(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text3(size.body,lineHeight.snug,color.linkInk,"bold")},pillDisabled:{opacity:.5},pressed:{transform:[{scale:RECORDS_MOTION.pressScale}]},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2,...slotBox(slots.banner)},infoNoteText:{flex:1,...text3(size.bodyTight,lineHeight.normal,color.text.primary),...bannerText},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},cautionNoteText:{flex:1,...text3(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text3(size.bodyTight,lineHeight.relaxed,color.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md},errorText:{flex:1,...text3(size.bodyTight,lineHeight.normal,errorColor)},band:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,...slotBox(slots.banner)},bandText:{flex:1,...text3(size.caption,lineHeight.normal,color.text.secondary),...bannerText},infoGlyph:{width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,borderWidth:1,borderColor:bannerInk??color.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...text3(size.small,lineHeight.tight,color.text.secondary,"bold"),...bannerText},chevron:{width:space.sm,height:space.sm,borderTopWidth:space.xs/2,borderRightWidth:space.xs/2,borderColor:color.text.muted},lead:{paddingHorizontal:space.sm,...text3(size.body+1,lineHeight.snug,color.text.primary,"bold")},field:{minHeight:touch,paddingHorizontal:space.md,paddingVertical:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:size.body,...slotBox(slots.input,1),...slotText(slots.input)},fieldLabel:{...text3(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text3(size.caption,lineHeight.normal,color.text.muted),bodyText:text3(size.body,lineHeight.normal,color.text.primary)})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){let month=MONTHS[Number(iso[2])-1];return month===void 0?"-":`${month} ${Number(iso[3])}, ${iso[1]}`}let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date=new Date(ms);return`${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}`}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}var DEPTH_COPY=/* @__PURE__ */Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:date=>`Measured ${date}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date=>`Expires ${date}`});function markerStatusLabel(status){switch(status){case"above":return{label:"Above range",outOfRange:true};case"below":return{label:"Below range",outOfRange:true};case"in_range":return{label:"In range",outOfRange:false};default:return{label:"No range on file",outOfRange:false}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num3=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num3} ${unit}`:num3}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:/* @__PURE__ */Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date=>`Last done ${date}`,overdue:"Overdue",due:date=>`Due ${date}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date=>`Generated ${formatRecordsDate(date)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){case"identity_risk":return{label:"Identity mismatch",rank:0,tone:"critical"};case"benign":return{label:"Minor difference",rank:2,tone:"neutral"};default:return{label:"Needs review",rank:1,tone:"warning"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:/* @__PURE__ */Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date=formatRecordsDate(expiresAt);return date==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date}`:`Expires ${date}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
196
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){let month=MONTHS[Number(iso[2])-1];return month===void 0?"-":`${month} ${Number(iso[3])}, ${iso[1]}`}let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date=new Date(ms);return`${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}`}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}var DEPTH_COPY=/* @__PURE__ */Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:date=>`Measured ${date}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date=>`Expires ${date}`});function markerStatusLabel(status){switch(status){case"above":return{label:"Above range",outOfRange:true};case"below":return{label:"Below range",outOfRange:true};case"in_range":return{label:"In range",outOfRange:false};default:return{label:"No range on file",outOfRange:false}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num3=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num3} ${unit}`:num3}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:/* @__PURE__ */Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date=>`Last done ${date}`,overdue:"Overdue",due:date=>`Due ${date}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date=>`Generated ${formatRecordsDate(date)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){case"identity_risk":return{label:"Identity mismatch",rank:0,tone:"critical"};case"benign":return{label:"Minor difference",rank:2,tone:"neutral"};default:return{label:"Needs review",rank:1,tone:"warning"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:/* @__PURE__ */Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date=formatRecordsDate(expiresAt);return date==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date}`:`Expires ${date}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
195
197
  return Object.freeze([...rows.filter(r=>r.active),...rows.filter(r=>!r.active)])}function shareErrorMessage(error,action){let status=error?.httpStatus;if(isRecordsConsentRequired(error)){if(action==="create"||action==="email")return"Records access for this pet is off, so a new link cannot be created.";if(action==="download")return"Records access for this pet is off, so the PDF cannot be downloaded."}if(status===429)return"You are creating links a little too fast. Wait a moment, then try again.";if(action==="revoke"&&(status===404||status===409||status===410))return"That link was already turned off.";if(status===401||status===403)return"You need to be signed in as this pet's owner to do that.";if(action==="email"&&(status===400||status===422||error?.code==="validationFailed"))return SHARE_COPY.emailInvalid;switch(action){case"create":return"Could not create a share link. Please try again.";case"revoke":return"Could not turn off that link. Please try again.";case"email":return SHARE_COPY.emailFailed;default:return"Could not download the record PDF. Please try again."}}function SkeletonBlock({width:width,height:height,radius:radius,style:style}){let{color:color,radius:radii}=useEverfurTheme();/* @__PURE__ */
196
198
  return jsxRuntime.jsx(reactNative.View,{style:[{width:width,height:height,borderRadius:radius??radii.xs,backgroundColor:color.skeleton},style],accessibilityElementsHidden:true,importantForAccessibility:"no"})}var DONUT=180,BADGE_W=70,BADGE_H=22,CAROUSEL_H=300,DISCLAIMER_H=44,RAIL_DOT=24,TIMELINE_BUBBLE=34,TIMELINE_ROWS=6,CLINIC_ROWS=5;function DashboardSkeleton({testID:testID}){let styles=useStyles3(),action=key=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionRow,children:[
197
199
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionLeft,children:[
@@ -317,7 +319,7 @@ return Object.freeze({petRef:pet,available:true,withheld:false,labResults:/* @__
317
319
  return Object.freeze({petRef:pet,withheld:true,isEmpty:false,visits:/* @__PURE__ */Object.freeze([]),vaccines:/* @__PURE__ */Object.freeze([]),weights:/* @__PURE__ */Object.freeze([]),medications:/* @__PURE__ */Object.freeze([]),disclaimer:""})}function mapRecordsTimeline(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return withheldTimeline(pet);let parsed=timelineSchema.safeParse(w);if(!parsed.success)return withheldTimeline(pet);let t=parsed.data,visits=t.visits.map(v=>/* @__PURE__ */Object.freeze({visitId:v.visit_id,visitDate:v.visit_date??null,veterinarian:v.veterinarian??null,summary:v.summary??null,docId:v.doc_id??null})),vaccines=t.vaccines.map(v=>/* @__PURE__ */Object.freeze({vaccineId:v.vaccine_id,product:v.product??null,lot:v.lot??null,administeredOn:v.administered_on??null,expiresOn:v.expires_on??null,docId:v.doc_id??null})),weights=t.weights.map(v=>/* @__PURE__ */Object.freeze({weightId:v.weight_id,observedOn:v.observed_on??null,weightKg:v.weight_kg??null,docId:v.doc_id??null})),medications=t.medications.map(m=>/* @__PURE__ */Object.freeze({medicationId:m.medication_id,drugName:m.drug_name??null,dose:m.dose??null,route:m.route??null,frequency:m.frequency??null,sig:m.sig??null,rxNumber:m.rx_number??null,startedOn:m.started_on??null,stoppedOn:m.stopped_on??null,docId:m.doc_id??null}));/* @__PURE__ */
318
320
  return Object.freeze({petRef:pet,withheld:false,isEmpty:visits.length===0&&vaccines.length===0&&weights.length===0&&medications.length===0,visits:/* @__PURE__ */Object.freeze(visits),vaccines:/* @__PURE__ */Object.freeze(vaccines),weights:/* @__PURE__ */Object.freeze(weights),medications:/* @__PURE__ */Object.freeze(medications),disclaimer:t.disclaimer??""})}function mapDocumentContributions(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef),withheld=()=>/* @__PURE__ */Object.freeze({petRef:pet,withheld:true,document:null,contributions:/* @__PURE__ */Object.freeze([]),contributionCount:0});if(w.withheld===true)return withheld();let parsed=contributionsSchema.safeParse(w);if(!parsed.success)return withheld();let contributions=/* @__PURE__ */Object.freeze(parsed.data.contributions.map(mapEntityRow));/* @__PURE__ */
319
321
  return Object.freeze({petRef:pet,withheld:false,document:mapDocumentRow(parsed.data.document),contributions:contributions,contributionCount:parsed.data.contribution_count??contributions.length})}var BASE3="/widget/v1/records/pets";function createRecordsDepthClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),segment=(value,max)=>typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)&&[...value].length<=max,read=async(call,petRef,path,map)=>{if(!segment(petRef,PET_REF_MAX))return invalid2();let result=await funnel.send(call,{method:"GET",path:path});if(!result.ok)return result;let view=map(result.value);return view.petRef===petRef?ok(view):err(makeEverfurError("internalError",{retryable:false}))},pet=petRef=>`${BASE3}/${encodeURIComponent(petRef)}`,record=petRef=>`${pet(petRef)}/everfur_record`,parsed=async(call,req,map)=>{let result=await funnel.send(call,req,req.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!result.ok)return result;let value=map(result.value);return value===null?err(makeEverfurError("internalError",{retryable:false})):ok(value)},factBody=(input,corrected)=>!segment(input.entityType,FACT_ENTITY_TYPE_MAX)||!segment(input.canonicalKey,FACT_CANONICAL_KEY_MAX)||input.idempotencyKey!==void 0&&!segment(input.idempotencyKey,IDEMPOTENCY_KEY_MAX)||corrected!==void 0&&Object.keys(corrected).length===0?null:{entity_type:input.entityType,canonical_key:input.canonicalKey,...corrected!==void 0?{corrected_fields:corrected}:{},...input.idempotencyKey!==void 0?{idempotency_key:input.idempotencyKey}:{}};return{getRecordDepth:petRef=>read("records.depth.record",petRef,`${pet(petRef)}/record`,wire=>mapRecordDepth(petRef,wire)),getTimeline:petRef=>read("records.depth.timeline",petRef,`${pet(petRef)}/timeline`,wire=>mapRecordsTimeline(petRef,wire)),getDocumentContributions(petRef,docId){return segment(docId,64)?read("records.depth.contributions",petRef,`${pet(petRef)}/documents/${encodeURIComponent(docId)}/contributions`,wire=>mapDocumentContributions(petRef,wire)):invalid2()},getMarkers:petRef=>read("records.depth.markers",petRef,`${pet(petRef)}/markers`,wire=>mapRecordMarkers(petRef,wire)),createShare(petRef,opts){if(!segment(petRef,PET_REF_MAX))return invalid2();let audience=opts?.audience;return audience!==void 0&&!RECORD_SHARE_AUDIENCES.includes(audience)?invalid2():parsed("records.share.create",{method:"POST",path:`${record(petRef)}/share`,...audience!==void 0?{body:{audience:audience}}:{}},wire=>mapRecordShareLink(wire,deps.apiBaseUrl))},emailShare(petRef,input){let kind=input.recipientKind,email2=typeof input.recipientEmail=="string"?input.recipientEmail.trim():"",kindOk=kind==="other"||RECORD_SHARE_AUDIENCES.includes(kind);return!segment(petRef,PET_REF_MAX)||!kindOk||!isShareRecipientEmail(email2)||hasLoneSurrogate(email2)?invalid2():parsed("records.share.email",{method:"POST",path:`${record(petRef)}/share/email`,body:{recipient_email:email2,recipient_kind:kind}},mapRecordShareEmailReceipt)},async readFeatures(){try{let result=await funnel.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return result.ok?mapRecordsFeatures(result.value):RECORDS_FEATURES_PDF_ONLY}catch{return RECORDS_FEATURES_PDF_ONLY}},listShares(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.share.list",{method:"GET",path:`${record(petRef)}/shares`},mapRecordShareList):invalid2()},async revokeShare(petRef,shareId){if(!segment(petRef,PET_REF_MAX)||!segment(shareId,64))return invalid2();let result=await funnel.send("records.share.revoke",{method:"DELETE",path:`${record(petRef)}/shares/${encodeURIComponent(shareId)}`},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},getPdfLink(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.pdf.link",{method:"GET",path:`${record(petRef)}/pdf-link`},mapRecordPdfLink):invalid2()},async editFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input,input.correctedFields):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.edit",{method:"POST",path:`${record(petRef)}/facts/edit`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},async removeFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.remove",{method:"POST",path:`${record(petRef)}/facts/remove`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},listRequestDocuments(requestId2){return segment(requestId2,64)?parsed("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(requestId2)}/documents`},mapRequestDocuments):invalid2()},listAuthorizationSignatures:()=>parsed("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mapSignatureSuggestions)}}function invalid2(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsDepthClient(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsDepthClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{},...typeof services.apiBaseUrl=="string"?{apiBaseUrl:services.apiBaseUrl}:{}})},[runtime,userRef,scopeEpoch])}function useRecordsDepthRead(petRef,read,isEmpty,extraKey=""){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),consentEpoch=useRecordsConsentEpoch(petRef),scope=react.useMemo(()=>({}),[client,petRef,extraKey,consentEpoch]),[state,setState]=react.useState({scope:scope,value:null,error:null,loading:true}),generation=react.useRef(0),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setState({scope:scope,value:null,error:null,loading:true}),userRef===null){setState({scope:scope,value:null,error:null,loading:false});return}let result=await read(client,petRef);gen===generation.current&&(result.ok?setState({scope:scope,value:result.value,error:null,loading:false}):setState({scope:scope,value:null,error:result.error,loading:false}))},[client,petRef,read,scope,userRef]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let current=state.scope===scope?state:{value:null,error:null,loading:true},refresh=react.useCallback(()=>{load()},[load]),available=current.error===null||current.error.httpStatus!==404,error=available?current.error:null,status=current.loading?"loading":error!==null?"error":current.value===null?"empty":current.value.withheld?"populated":isEmpty(current.value)?"empty":"populated";return react.useMemo(()=>({status:status,value:current.value,error:error,available:available,refresh:refresh}),[status,current.value,error,available,refresh])}function isDarkRouteError(error){return error!==null&&error.httpStatus===404}var readMarkers=(client,petRef)=>client.getMarkers(petRef),markersEmpty=value=>value.markers.length===0;function useRecordsMarkers(petRef){let state=useRecordsDepthRead(petRef,readMarkers,markersEmpty);return react.useMemo(()=>{let markers=state.available&&state.value!==null&&!state.value.withheld?state.value:null;return{status:state.status,markers:markers,available:state.available,error:state.error,refresh:state.refresh}},[state])}var EMAIL3=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function useRecordsConsentForm(input){let{clinic:clinic,controller:controller,depthClient:depthClient,capture:capture,onCreated:onCreated}=input,clinicName=clinic.clinic?.name??clinic.freeText??"",isFreeText=clinic.clinic===null,[authorized,setAuthorized]=react.useState(false),[ownerName,setOwnerName]=react.useState(input.ownerName),[email2,setEmail]=react.useState(clinic.email),[emailTouched,setEmailTouched]=react.useState(false),[copy,setCopy]=react.useState(null),[copyError,setCopyError]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[created,setCreated]=react.useState(null),[signatures,setSignatures]=react.useState([]),[reuseSignatureId,setReuseSignatureId]=react.useState(null),[signed,setSigned]=react.useState(false),locked=react.useRef(false),live=react.useRef(true),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null);react.useEffect(()=>(live.current=true,()=>{live.current=false,attempt.current=null}),[controller]),react.useEffect(()=>{let alive=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{alive&&(result.ok?(setCopy(result.value),setCopyError(null)):setCopyError(result.error))}).catch(()=>{alive&&setCopyError(makeEverfurError("internalError"))}),()=>{alive=false}},[controller,copyAttempt]),react.useEffect(()=>{if(depthClient===void 0)return;let alive=true;return depthClient.listAuthorizationSignatures().then(result=>{alive&&(result.ok?setSignatures(result.value):isDarkRouteError(result.error)||setSignatures([]))}).catch(()=>{}),()=>{alive=false}},[depthClient]);let needsEmail=clinicNeedsEmail(clinic.clinic),normalizedEmail=email2.trim().toLowerCase(),validEmail=EMAIL3.test(normalizedEmail),emailError=needsEmail&&(emailTouched||normalizedEmail.length>0)&&!validEmail?normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired:null,named=ownerName.trim().length>0,scope=copy&&named?renderClinicScope(copy,ownerName.trim(),petNameOr(input.petName),clinicName):null,hasSignature=input.hostCapture===true||signed||reuseSignatureId!==null,readyButSigned=!!(authorized&&copy&&scope&&named&&clinicName&&(!needsEmail||validEmail)),ready=readyButSigned&&hasSignature,submit=react.useCallback(async()=>{if(!(locked.current||created!==null||!copy||!scope)){if(!clinicName){setError(RECORDS_CONSENT_COPY.missingDraftError);return}if(needsEmail&&!validEmail){setEmailTouched(true),setError(normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired);return}if(!(!authorized||!ownerName.trim())){locked.current=true,setBusy(true),setError(null);try{if(attempt.current===null){let signature=reuseSignatureId!==null?{signatureId:reuseSignatureId}:await capture();if(!live.current)return;if(signature===null){setError(RECORDS_CONSENT_COPY.missingSignatureError);return}let target=clinic.clinic&&(!needsEmail||clinic.clinic.emailStatus==="none")?{clinicId:clinic.clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:input.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:normalizedEmail}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}let result=await controller.createClinicRequest(attempt.current);if(!live.current)return;if(!result.ok){setError(result.error.displayMessage);return}if(result.value.petRef!==input.petRef){setError(makeEverfurError("internalError").displayMessage);return}setCreated(result.value),attempt.current=null,onCreated?.(result.value)}catch{live.current&&setError(makeEverfurError("internalError").displayMessage)}finally{locked.current=false,live.current&&setBusy(false)}}}},[authorized,capture,clinic.clinic,clinicName,controller,copy,created,input.petRef,needsEmail,normalizedEmail,onCreated,ownerName,reuseSignatureId,scope,validEmail]),invalidate=react.useCallback(()=>{attempt.current=null,setError(null)},[]);return{title:isFreeText?RECORDS_CONSENT_COPY.titleFreeText:RECORDS_CONSENT_COPY.titleDirectory,clinicName:clinicName,isFreeText:isFreeText,authorized:authorized,ownerName:ownerName,email:email2,emailError:emailError,needsEmail:needsEmail,directoryClinicNoEmail:needsEmail&&clinic.clinic!==null,copy:copy,copyError:copyError,scope:scope,error:error,busy:busy,created:created,ready:ready,signatures:signatures,reuseSignatureId:reuseSignatureId,hasSignature:hasSignature,scopeAwaitingName:copy!==null&&!named,signatureLastMissing:readyButSigned&&!hasSignature,setAuthorized(value){locked.current||(invalidate(),setAuthorized(value))},setOwnerName(value){locked.current||(invalidate(),setOwnerName(value))},setEmail(value){locked.current||(invalidate(),setEmailTouched(false),setEmail(value))},setSigned(value){locked.current||(invalidate(),setSigned(value),value&&setReuseSignatureId(null))},pickReuseSignature(signatureId){locked.current||(invalidate(),setReuseSignatureId(signatureId))},retryCopy(){setCopyError(null),setCopyAttempt(n=>n+1)},submit:submit}}function EverfurRecordsConsent(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
320
- return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}var IOS2=reactNative.Platform.OS==="ios";function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles3(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),depthClient=useEverfurRecordsDepthClient(),[png,setPng]=react.useState(null),[mode,setMode]=react.useState("draw"),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:controller??runtimeController,depthClient:depthClient,capture:onCaptureSignature?()=>onCaptureSignature({petRef:petRef,petName:petNameOr(petName),ownerName:form.ownerName,clinicName:form.clinicName,authorizationVersion:form.copy?.authorizationVersion??"",scopeText:form.scope??"",signal:(new AbortController).signal}):padCapture,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),formRef=react.useRef(form);formRef.current=form;let onPadChange=react.useCallback(next=>{setPng(next),formRef.current.setSigned(next!==null)},[]),busy=form.busy,keyboard=useChatKeyboardOffset(void 0,IOS2);/* @__PURE__ */
322
+ return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}var IOS2=reactNative.Platform.OS==="ios";function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles3(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),directSendNote=useRecordsSandboxTenant()?RECORDS_SANDBOX_COPY.newClinicDirectSendNote:RECORDS_CONSENT_COPY.newClinicDirectSendNote,depthClient=useEverfurRecordsDepthClient(),[png,setPng]=react.useState(null),[mode,setMode]=react.useState("draw"),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:controller??runtimeController,depthClient:depthClient,capture:onCaptureSignature?()=>onCaptureSignature({petRef:petRef,petName:petNameOr(petName),ownerName:form.ownerName,clinicName:form.clinicName,authorizationVersion:form.copy?.authorizationVersion??"",scopeText:form.scope??"",signal:(new AbortController).signal}):padCapture,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),formRef=react.useRef(form);formRef.current=form;let onPadChange=react.useCallback(next=>{setPng(next),formRef.current.setSigned(next!==null)},[]),busy=form.busy,keyboard=useChatKeyboardOffset(void 0,IOS2);/* @__PURE__ */
321
323
  return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
322
324
  /* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:form.title,onBack:onBack,testID:"records-consent-header"}),
323
325
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:IOS2?"padding":void 0,style:styles.body,...keyboard.avoidingProps,children:[
@@ -341,7 +343,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
341
343
  /* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:RECORDS_CONSENT_COPY.fullName,style:styles.field,value:form.ownerName,placeholder:RECORDS_CONSENT_COPY.fullNamePlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!busy,autoComplete:"name",autoCapitalize:"words",onChangeText:form.setOwnerName,testID:"records-consent-owner-name"})]}),form.needsEmail?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,testID:"records-consent-email-block",children:[form.directoryClinicNoEmail?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.cautionNote,testID:"records-consent-no-email-note",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.cautionNoteText,children:RECORDS_CONSENT_COPY.noEmailNote(petName,form.clinicName)})}):null,
342
344
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.emailLabel}),
343
345
  /* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:RECORDS_CONSENT_COPY.emailLabel,style:styles.field,value:form.email,placeholder:RECORDS_CONSENT_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:320,editable:!busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:form.setEmail,testID:"records-consent-clinic-email"}),form.emailError?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",children:form.emailError}):null,
344
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,testID:"records-consent-review-note",children:RECORDS_CONSENT_COPY.newClinicDirectSendNote})]}):null,onCaptureSignature?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.signatureBlock,children:[form.signatures.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
346
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,testID:"records-consent-review-note",children:directSendNote})]}):null,onCaptureSignature?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.signatureBlock,children:[form.signatures.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
345
347
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.reuseSignature}),
346
348
  /* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:local.gallery,children:form.signatures.map(sig=>{let selected=form.reuseSignatureId===sig.signatureId;/* @__PURE__ */
347
349
  return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>form.pickReuseSignature(selected?null:sig.signatureId),accessibilityRole:"button",accessibilityLabel:selected?RECORDS_CONSENT_COPY.reuseTileSelectedA11y:RECORDS_CONSENT_COPY.reuseTileA11y,style:[local.tile,selected?local.tileSelected:null],testID:`records-consent-reuse-${sig.signatureId}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:sig.previewUrl},style:local.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},sig.signatureId)})}),
@@ -433,7 +435,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[local.conflictCard,{borderColor:
433
435
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowMuted,children:[candidate.docId?record.documents[candidate.docId]?.title??RECORD_SCREEN_COPY.uploadedDocument:RECORD_SCREEN_COPY.uploadedDocument,candidate.collectedAt?formatRecordsDate(candidate.collectedAt):null].filter(Boolean).join(" · ")})]},index)),ask(()=>buildConflictAskPrompt(petName,{scopeLabel:scope,severity:conflict.severity,candidates:conflict.candidates.map(c=>({value:c.value,clinicName:c.docId?record.documents[c.docId]?.title??null:null}))},conflict.conflictId),RECORD_SCREEN_COPY.askConflict,`records-ask-conflict-${conflict.conflictId}`)]},conflict.conflictId)})]}):null,depth?.completeness?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-completeness",children:[
434
436
  /* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.whatsOnFile}),
435
437
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
436
- /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.coverageRow,children:[[RECORD_SCREEN_COPY.coverage.labs,depth.completeness.hasLabHistory],[RECORD_SCREEN_COPY.coverage.vaccines,depth.completeness.hasVaccinationHistory],[RECORD_SCREEN_COPY.coverage.weight,depth.completeness.hasWeightHistory],[RECORD_SCREEN_COPY.coverage.vitals,depth.completeness.hasVitalsHistory],[RECORD_SCREEN_COPY.coverage.exams,depth.completeness.hasPhysicalExamHistory],[RECORD_SCREEN_COPY.coverage.procedures,depth.completeness.hasProcedureHistory],[RECORD_SCREEN_COPY.coverage.genetics,depth.completeness.hasGeneticHistory],[RECORD_SCREEN_COPY.coverage.parasite,depth.completeness.hasParasitePreventionHistory],[RECORD_SCREEN_COPY.coverage.reproductive,depth.completeness.hasReproductiveHistory]].map(([label,present])=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.coveragePill,present?styles.chipTones.positive.bg:styles.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.coverageText,present?styles.chipTones.positive.fg:{color:styles.rowMuted.color}],children:label})},label))}),
438
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.coverageRow,children:[[RECORD_SCREEN_COPY.coverage.labs,depth.completeness.hasLabHistory],[RECORD_SCREEN_COPY.coverage.vaccines,depth.completeness.hasVaccinationHistory],[RECORD_SCREEN_COPY.coverage.weight,depth.completeness.hasWeightHistory],[RECORD_SCREEN_COPY.coverage.vitals,depth.completeness.hasVitalsHistory],[RECORD_SCREEN_COPY.coverage.exams,depth.completeness.hasPhysicalExamHistory],[RECORD_SCREEN_COPY.coverage.procedures,depth.completeness.hasProcedureHistory],[RECORD_SCREEN_COPY.coverage.genetics,depth.completeness.hasGeneticHistory],[RECORD_SCREEN_COPY.coverage.parasite,depth.completeness.hasParasitePreventionHistory],[RECORD_SCREEN_COPY.coverage.reproductive,depth.completeness.hasReproductiveHistory]].map(([label,present])=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.coveragePill,present?[styles.chipTones.positive.bg,local.coverageOnFile]:[styles.chipTones.neutral.bg,local.coverageRest]],accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.coverageText,present?styles.chipTones.positive.fg:[{color:styles.rowMuted.color},local.coverageRestText]],children:label})},label))}),
437
439
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.metaRow,children:[
438
440
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,children:RECORD_SCREEN_COPY.documentsOnFile(depth.completeness.documentsIngested)}),depth.completeness.documentsInReview>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.inReviewChip(depth.completeness.documentsInReview),tone:"warning"}):null,heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:RECORD_SCREEN_COPY.beingVerifiedA11y(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.beingVerified(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),depth.completeness.earliestRecordAt||depth.completeness.latestRecordAt?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.metaRow,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,children:RECORD_SCREEN_COPY.dateRange(depth.completeness.earliestRecordAt,depth.completeness.latestRecordAt)})}):null,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).length>0?/* @__PURE__ */jsxRuntime.jsxs(Text,{style:local.pendingText,children:[RECORD_SCREEN_COPY.pendingReview,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).map(([type,count])=>`${entityTypeLabel(type)} (${count})`).join(", ")]}):null]})]}):null,documents.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-documents",children:[
439
441
  /* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.documents,count:documents.length}),
@@ -481,7 +483,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDiv
481
483
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:depth.encounters.map((encounter,index)=>{let detail=[encounter.date?formatRecordsDate(encounter.date):null,encounter.clinicName,encounter.veterinarian].filter(p=>p&&p!=="-").join(" · ");/* @__PURE__ */
482
484
  return jsxRuntime.jsx(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
483
485
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:encounter.type?humanize(encounter.type):DEPTH_COPY.visit}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:detail}):null]})},encounter.encounterId)})})]}):null]}),
484
- /* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=reactNative.Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label,meta){return`${label} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct2=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct2}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=react.useState(""),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),[confirmingRevoke,setConfirmingRevoke]=react.useState(false),[settled,setSettled]=react.useState(null),locked=react.useRef(false),active=react.useRef(false),generation=react.useRef(0);react.useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&&current.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&&current.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),WIRE_FROM_STATUS=/* @__PURE__ */Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){case"submitted":case"sent":return 1;case"awaiting_response":return 2;case"records_received":return 3;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 4;case"published":return 5;default:return-1}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){case"awaiting_upload":return 3;case"records_received":return 4;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 5;case"published":return 6;default:return 3}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){case"submitted":case"sent":return 0;case"awaiting_upload":return 1;case"records_received":return 2;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 3;case"published":return 4;default:return-1}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null)}function inArtifactWords(events,request,petName){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),events=buildRequestTimeline(request,{petName:petName??null});/* @__PURE__ */
486
+ /* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},coverageRest:slotBox(theme.slots.chip),coverageRestText:slotText(theme.slots.chip),coverageOnFile:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=reactNative.Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label,meta){return`${label} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct2=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct2}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=react.useState(""),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),[confirmingRevoke,setConfirmingRevoke]=react.useState(false),[settled,setSettled]=react.useState(null),locked=react.useRef(false),active=react.useRef(false),generation=react.useRef(0);react.useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&&current.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&&current.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),WIRE_FROM_STATUS=/* @__PURE__ */Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){case"submitted":case"sent":return 1;case"awaiting_response":return 2;case"records_received":return 3;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 4;case"published":return 5;default:return-1}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){case"awaiting_upload":return 3;case"records_received":return 4;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 5;case"published":return 6;default:return 3}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){case"submitted":case"sent":return 0;case"awaiting_upload":return 1;case"records_received":return 2;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 3;case"published":return 4;default:return-1}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null,options.sandbox===true)}function inArtifactWords(events,request,petName,sandbox){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;if(sandbox&&event.key==="sent_to_clinic")return{...event,title:RECORDS_SANDBOX_COPY.clinicNotContacted,detail:email2.length>0?RECORDS_SANDBOX_COPY.notEmailed(email2):null};let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});/* @__PURE__ */
485
487
  return jsxRuntime.jsx(reactNative.View,{style:styles.container,accessibilityRole:"summary",children:events.map((event,idx)=>/* @__PURE__ */jsxRuntime.jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let date=event.at?formatRecordsDate(event.at):null,a11yParts=[event.title,event.detail,date,A11Y_STATE[event.state]].filter(Boolean);/* @__PURE__ */
486
488
  return jsxRuntime.jsxs(reactNative.View,{style:styles.row,accessible:true,accessibilityRole:"text",accessibilityLabel:a11yParts.join(", "),testID:`records-timeline-${event.key}`,children:[
487
489
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.railColumn,children:[
@@ -500,7 +502,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRow,testID:`records-
500
502
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRowHead,children:[
501
503
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowLabel,children:item.name??""}),
502
504
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:uploadItemStatusLabel(item)})]}),item.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:pct2},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.progressFill,{width:`${pct2}%`}]})}):null,item.status==="failed"&&item.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:item.error.displayMessage}):null]},item.key)})}):null]})}function ConsentRequiredState({onGrant:onGrant,consentText:consentText}){let styles=useStyles9(),text3=presentConsentText(consentText);return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(RECORDS_COPY.consentRequired)},[]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,testID:"records-consent-gate",children:[
503
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:RECORDS_COPY.consentRequired}),text3!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.disclaimer,testID:"records-consent-gate-body",children:text3}):null,
505
+ /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.askText,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:RECORDS_COPY.consentRequired}),text3!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.disclaimer,testID:"records-consent-gate-body",children:text3}):null,
504
506
  /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onGrant,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.allow,style:styles.primaryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.primaryLabel,children:RECORDS_COPY.allow})})]})}function AlertState({label:label,glyph:glyph}){let styles=useStyles9();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(label)},[label]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:label,children:[
505
507
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:glyph==="withheld"?styles.withheldGlyph:styles.emptyGlyph}),
506
508
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:label})]})}function ConsentUnavailableState(){/* @__PURE__ */
@@ -511,7 +513,7 @@ return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.recordUnavailable,glyph:"wi
511
513
  return jsxRuntime.jsxs(reactNative.View,{style:styles.callCard,accessibilityRole:"summary",children:[
512
514
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineLabel,children:CALL_CLINIC_COPY.heading}),
513
515
  /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:intro}),
514
- /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{reactNative.Linking?.openURL?.(call.dial)},accessibilityRole:"button",accessibilityLabel:CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,testID:"records-call-clinic",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.linkLabel,children:CALL_CLINIC_COPY.call})})]})}function useStyles9(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles11(theme),[theme])}function makeStyles11(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight,letterSpacing:letterSpacing}=type,card=slotBox(recordCardSlot(slots),reactNative.StyleSheet.hairlineWidth),cardText=slotText(recordCardSlot(slots)),lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,glyphSize=space.xxl+space.sm,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,softShadow={shadowColor:color.brand,shadowOffset:{width:0,height:space.xs},shadowRadius:space.sm,shadowOpacity:.08,elevation:space.xs};return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},withheldGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.sm,backgroundColor:color.badgeBgCaution,borderWidth:hairline,borderColor:color.cautionAccent},errorText:{...face(theme,"regular"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:errorColor,textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},linkButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},linkLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},disabledButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.brandBorder},disabledLabel:{...face(theme,"bold"),color:color.text.muted,fontSize:size.body,letterSpacing:letterSpacing.tight},list:{flex:1},listContent:{padding:space.lg,gap:space.md},timeline:{paddingVertical:space.md,paddingHorizontal:space.lg,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,gap:space.xs,...softShadow,...card},timelineTitle:{...headingFace(theme,"bold"),fontSize:size.heading,lineHeight:lh(size.heading,lineHeight.snug),color:color.text.primary,letterSpacing:letterSpacing.tight,...cardText},timelineLabel:{...headingFace(theme,"bold"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:color.text.secondary,letterSpacing:letterSpacing.tight,...cardText},callCard:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...card},timelineMeta:{...face(theme,"regular"),fontSize:size.bodyTight,lineHeight:lh(size.bodyTight,lineHeight.normal),color:color.text.muted,...cardText},recordBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...softShadow,...card},row:{flexDirection:"row",justifyContent:"space-between",gap:space.md,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},rowLabel:{...face(theme,"regular"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.muted,flexShrink:1,...cardText},rowValue:{...face(theme,"medium"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.primary,textAlign:"right",flexShrink:1,...cardText},disclaimer:{...face(theme,"regular"),fontSize:size.caption,lineHeight:lh(size.caption,lineHeight.normal),color:color.text.muted,marginTop:space.md},uploadRow:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},uploadRowHead:{flexDirection:"row",justifyContent:"space-between",gap:space.md},progressTrack:{height:space.xs,borderRadius:radius.pill,backgroundColor:color.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:color.brand}})}function EverfurRecordsRequests(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
516
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{reactNative.Linking?.openURL?.(call.dial)},accessibilityRole:"button",accessibilityLabel:CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,testID:"records-call-clinic",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.linkLabel,children:CALL_CLINIC_COPY.call})})]})}function useStyles9(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles11(theme),[theme])}function makeStyles11(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight,letterSpacing:letterSpacing}=type,card=slotBox(recordCardSlot(slots),reactNative.StyleSheet.hairlineWidth),cardText=slotText(recordCardSlot(slots)),lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,glyphSize=space.xxl+space.sm,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,softShadow={shadowColor:color.brand,shadowOffset:{width:0,height:space.xs},shadowRadius:space.sm,shadowOpacity:.08,elevation:space.xs};return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},withheldGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.sm,backgroundColor:color.badgeBgCaution,borderWidth:hairline,borderColor:color.cautionAccent},errorText:{...face(theme,"regular"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:errorColor,textAlign:"center",marginBottom:space.md},askText:{...headingFace(theme,"bold"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:color.text.primary,textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},linkButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},linkLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},disabledButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.brandBorder},disabledLabel:{...face(theme,"bold"),color:color.text.muted,fontSize:size.body,letterSpacing:letterSpacing.tight},list:{flex:1},listContent:{padding:space.lg,gap:space.md},timeline:{paddingVertical:space.md,paddingHorizontal:space.lg,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,gap:space.xs,...softShadow,...card},timelineTitle:{...headingFace(theme,"bold"),fontSize:size.heading,lineHeight:lh(size.heading,lineHeight.snug),color:color.text.primary,letterSpacing:letterSpacing.tight,...cardText},timelineLabel:{...headingFace(theme,"bold"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:color.text.secondary,letterSpacing:letterSpacing.tight,...cardText},callCard:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...card},timelineMeta:{...face(theme,"regular"),fontSize:size.bodyTight,lineHeight:lh(size.bodyTight,lineHeight.normal),color:color.text.muted,...cardText},recordBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...softShadow,...card},row:{flexDirection:"row",justifyContent:"space-between",gap:space.md,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},rowLabel:{...face(theme,"regular"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.muted,flexShrink:1,...cardText},rowValue:{...face(theme,"medium"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.primary,textAlign:"right",flexShrink:1,...cardText},disclaimer:{...face(theme,"regular"),fontSize:size.caption,lineHeight:lh(size.caption,lineHeight.normal),color:color.text.muted,marginTop:space.md},uploadRow:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},uploadRowHead:{flexDirection:"row",justifyContent:"space-between",gap:space.md},progressTrack:{height:space.xs,borderRadius:radius.pill,backgroundColor:color.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:color.brand}})}function EverfurRecordsRequests(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
515
517
  return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RequestsBody,{...rest,style:style})})}function RequestsBody({petRef:petRef,petName:petName,controller:controller,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,style:style}){let styles=useScreenStyles(),local=useLocalStyles5(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),requests=react.useMemo(()=>selectRequestList(records.requests.filter(r=>r.petRef===petRef)),[records.requests,petRef]),ask=onAsk?request=>{let built=buildRecordsRequestAskPrompt(petName,{clinicName:request.clinicName??null,statusLabel:selectPrimaryLabel(request),status:request.status,heldItemCount:request.heldItemCount},request.id);onAsk(built.prompt,built.entityRef)}:void 0,body;return records.status==="loading"&&requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-list-loading"}):records.status==="error"&&requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(records.error),message:records.error?.displayMessage,onAction:records.error?.retryable?records.refresh:void 0,testID:"records-list-error"}):requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-list-empty"}):body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:local.list,testID:"records-list-results",children:requests.map(request=>/* @__PURE__ */jsxRuntime.jsx(RequestRow,{request:request,onOpen:onNavigate?()=>onNavigate({name:"request",requestId:request.id}):void 0,onAsk:ask?()=>ask(request):void 0},request.id))}),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
516
518
  /* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:REQUEST_LIST_COPY.title,onBack:onBack,testID:"records-list-header"}),requests.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.subtitle,testID:"records-list-subtitle",children:REQUEST_LIST_COPY.subtitle(petName)}):null,
517
519
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.footer,children:[