@everfur/sdk 0.5.4 → 0.5.5

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 (105) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +8 -8
  3. package/dist/{Chat-Dfjegpf2.d.cts → Chat-BBnXSZQG.d.cts} +20 -3
  4. package/dist/{Chat-DXDS-MiC.d.ts → Chat-BzvoUe9L.d.ts} +20 -3
  5. package/dist/{DepthViews-BhBA6qiu.d.cts → DepthViews-BYEgUxDQ.d.ts} +1 -1
  6. package/dist/{DepthViews-meuqwdBv.d.cts → DepthViews-CsVphyQL.d.ts} +1 -1
  7. package/dist/{DepthViews-ru9SaVXz.d.ts → DepthViews-D-pleytA.d.cts} +1 -1
  8. package/dist/{DepthViews-DFODLIM2.d.ts → DepthViews-DKbfq4bX.d.cts} +1 -1
  9. package/dist/animations/index.d.cts +3 -3
  10. package/dist/animations/index.d.ts +3 -3
  11. package/dist/{attachments-DN0VDOBG.d.cts → attachments-BcD6K0IF.d.cts} +5 -5
  12. package/dist/{attachments-Cnz4Zqxq.d.ts → attachments-CFK3WPF4.d.ts} +5 -5
  13. package/dist/{attachments-hAjG4YGo.d.cts → attachments-CieUG7nB.d.cts} +2 -2
  14. package/dist/{attachments-D3i4WG5V.d.ts → attachments-DorefS77.d.ts} +2 -2
  15. package/dist/{bookingCopy-Bu1pMPh1.d.ts → bookingCopy-BUTs_nKf.d.ts} +2 -2
  16. package/dist/{bookingCopy-DP3k0iBn.d.cts → bookingCopy-Cl3RZ_k2.d.cts} +2 -2
  17. package/dist/{casesRepository-Bf8QDDPM.d.ts → casesRepository-C29WolRA.d.ts} +1 -1
  18. package/dist/{casesRepository-BIV6eQxW.d.cts → casesRepository-Ct5MO1mM.d.cts} +1 -1
  19. package/dist/chat/index.cjs +1 -1
  20. package/dist/chat/index.d.cts +9 -9
  21. package/dist/chat/index.d.ts +9 -9
  22. package/dist/chat/index.js +1 -1
  23. package/dist/client/index.cjs +2 -2
  24. package/dist/client/index.d.cts +6 -6
  25. package/dist/client/index.d.ts +6 -6
  26. package/dist/client/index.js +2 -2
  27. package/dist/{config-3jJR8fVC.d.cts → config-BBeF3kv5.d.cts} +1 -1
  28. package/dist/{config-FhlcRHRe.d.ts → config-Dl8Iqs1i.d.ts} +1 -1
  29. package/dist/consent/index.d.cts +5 -5
  30. package/dist/consent/index.d.ts +5 -5
  31. package/dist/{context-BVGuiYob.d.cts → context-DGZrfVkE.d.cts} +5 -5
  32. package/dist/{context-BqfAkCov.d.ts → context-DXj75_Lo.d.ts} +5 -5
  33. package/dist/{copy-DBbgO9g4.d.cts → copy-CQHEQwW7.d.cts} +2 -2
  34. package/dist/{copy-BDfIOo5Z.d.ts → copy-CSbMmuCV.d.ts} +2 -2
  35. package/dist/core/index.cjs +7 -7
  36. package/dist/core/index.d.cts +15 -13
  37. package/dist/core/index.d.ts +15 -13
  38. package/dist/core/index.js +7 -7
  39. package/dist/{depth-Cwmumplg.d.cts → depth-Bb2yphTT.d.cts} +2 -2
  40. package/dist/{depth-VpVaDj5I.d.ts → depth-DRzDoKeE.d.ts} +2 -2
  41. package/dist/{entitlementRepository-Cys2DfuQ.d.ts → entitlementRepository-S4bU03Ld.d.ts} +9 -2
  42. package/dist/{entitlementRepository-CCIj0Z0c.d.cts → entitlementRepository-lwXYn-lq.d.cts} +9 -2
  43. package/dist/{identity-BMPu-Kg6.d.ts → identity-C0r18khM.d.ts} +1 -1
  44. package/dist/{identity-DkVFMcyL.d.cts → identity-d2lu16uc.d.cts} +1 -1
  45. package/dist/index.cjs +6 -6
  46. package/dist/index.d.cts +12 -12
  47. package/dist/index.d.ts +12 -12
  48. package/dist/index.js +6 -6
  49. package/dist/notifications/index.d.cts +2 -2
  50. package/dist/notifications/index.d.ts +2 -2
  51. package/dist/{pets-B6QnvZi2.d.cts → pets-BZ0384Do.d.cts} +1 -1
  52. package/dist/{pets-BCgVJlJD.d.ts → pets-CJdq4rRX.d.ts} +1 -1
  53. package/dist/{petsRepository-CwIyiIvt.d.cts → petsRepository-BHooDwb1.d.cts} +1 -1
  54. package/dist/{petsRepository-I9vZvRpE.d.ts → petsRepository-DE8scL1O.d.ts} +1 -1
  55. package/dist/{ports-D0DaSL3j.d.cts → ports-CcUYur16.d.cts} +4 -4
  56. package/dist/{ports-BtrM61nV.d.ts → ports-DWL3Nl3j.d.ts} +4 -4
  57. package/dist/records/depth/index.d.cts +7 -7
  58. package/dist/records/depth/index.d.ts +7 -7
  59. package/dist/records/index.d.cts +9 -9
  60. package/dist/records/index.d.ts +9 -9
  61. package/dist/{requestFunnel-C1Fp7waD.d.ts → requestFunnel-C5LPty-S.d.ts} +2 -2
  62. package/dist/{requestFunnel-CR8wGfpV.d.cts → requestFunnel-TtUvlQS1.d.cts} +2 -2
  63. package/dist/{runtimeTypes-BCXujmD6.d.cts → runtimeTypes-BbLoCs-9.d.cts} +12 -4
  64. package/dist/{runtimeTypes-CuwgMArF.d.ts → runtimeTypes-CiJ6Y_wP.d.ts} +12 -4
  65. package/dist/server/events/index.cjs +1 -1
  66. package/dist/server/events/index.d.cts +2 -2
  67. package/dist/server/events/index.d.ts +2 -2
  68. package/dist/server/events/index.js +1 -1
  69. package/dist/server/index.cjs +2 -2
  70. package/dist/server/index.d.cts +3 -3
  71. package/dist/server/index.d.ts +3 -3
  72. package/dist/server/index.js +2 -2
  73. package/dist/televet/booking/index.cjs +1 -1
  74. package/dist/televet/booking/index.d.cts +6 -6
  75. package/dist/televet/booking/index.d.ts +6 -6
  76. package/dist/televet/booking/index.js +1 -1
  77. package/dist/testing/index.d.cts +1 -1
  78. package/dist/testing/index.d.ts +1 -1
  79. package/dist/testing/rn/index.d.cts +7 -7
  80. package/dist/testing/rn/index.d.ts +7 -7
  81. package/dist/testing/web/index.d.cts +7 -7
  82. package/dist/testing/web/index.d.ts +7 -7
  83. package/dist/{timelineRows-EaAqBcX2.d.cts → timelineRows-BZ4YqN5G.d.cts} +1 -1
  84. package/dist/{timelineRows-DFmwWHyj.d.ts → timelineRows-Bv7nr5Oz.d.ts} +1 -1
  85. package/dist/{useRecordsDepth-DgQrho7p.d.cts → useRecordsDepth-BYVOh123.d.cts} +1 -1
  86. package/dist/{useRecordsDepth-Bo2d27fm.d.ts → useRecordsDepth-DuylsLXR.d.ts} +1 -1
  87. package/dist/{view-DwYhyFC2.d.cts → view-Cqtik97G.d.cts} +2 -2
  88. package/dist/{view-DGIjZtq8.d.ts → view-Uv0dWIQH.d.ts} +2 -2
  89. package/dist/web/consent/index.d.cts +5 -5
  90. package/dist/web/consent/index.d.ts +5 -5
  91. package/dist/web/index.cjs +7 -7
  92. package/dist/web/index.d.cts +14 -14
  93. package/dist/web/index.d.ts +14 -14
  94. package/dist/web/index.js +7 -7
  95. package/dist/web/notifications/index.d.cts +3 -3
  96. package/dist/web/notifications/index.d.ts +3 -3
  97. package/dist/web/records/depth/index.d.cts +7 -7
  98. package/dist/web/records/depth/index.d.ts +7 -7
  99. package/dist/web/records/index.d.cts +9 -9
  100. package/dist/web/records/index.d.ts +9 -9
  101. package/dist/web/televet/booking/index.cjs +2 -2
  102. package/dist/web/televet/booking/index.d.cts +6 -6
  103. package/dist/web/televet/booking/index.d.ts +6 -6
  104. package/dist/web/televet/booking/index.js +2 -2
  105. package/package.json +5 -4
@@ -1,13 +1,13 @@
1
- import {z as z$1}from'zod';var li=Object.defineProperty;var i=(e,t)=>li(e,"name",{value:t,configurable:true});function _(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_,"ok");function p(e){return Object.freeze({ok:false,error:e})}i(p,"err");var Fe=class Fe extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fe.prototype);}};i(Fe,"EverfurConfigError");var K=Fe;var uu=Object.freeze({isAvailable:false,async getSecret(){return null},async setSecret(){throw new K("not-initialized","EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort")},async deleteSecret(){}});var Me=Object.freeze({track(){},trackExpectedFailure(){}});var tt=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(tt.map(e=>e.wireCode));var ui=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),cr=Object.freeze(tt.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:ui[e.wireCode]}))),di=new Map(cr.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ci=Object.freeze(["http_envelope",...[...new Set(cr.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function De(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...ci]){let o=di.get(n+r);if(o)return o}}i(De,"contractErrorFor");function pi(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(pi,"contractDocUrl");function pr(e){return null}i(pr,"publishedDocUrl");var fi=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function fr(e){return fi[e]}i(fr,"categoryFor");function Y(e){let t=De(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":case "TELEVETRATELIMITED":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Y,"fromWire");function mr(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(mr,"fromHttpStatus");var mi=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function ee(e){return mi.has(e)}i(ee,"isAutoRetryable");var yi=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function yr(e){return ee(e)||yi.has(e)}i(yr,"isRetryableCode");function je(e,t=false){return t||ee(e)}i(je,"shouldRetry");var hi=500,rt=8e3,pe=4;function ze(e,t=Math.random){let r=Math.max(0,e),n=Math.min(hi*2**r,rt);return Math.floor(t()*n)}i(ze,"backoffDelayMs");function hr(e){return e==="conversationNotFound"}i(hr,"canRecreateOnNotFound");var gr=Object.freeze({shouldRetry(e,t){return ee(e)&&t<pe},maxAttempts(){return pe}});var br=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function ku(e,t,r){let n;try{n=t();}catch(s){return nt(`optional peer '${e}' is not installed: ${bi(s)}`)}let o=gi(n);return o==null?nt(`optional peer '${e}' resolved to no module`):r&&!r(o)?nt(`optional peer '${e}' is present but failed its shape check`):Object.freeze({available:true,module:o})}i(ku,"optionalModule");function gi(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}i(gi,"unwrapDefault");function nt(e){return Object.freeze({available:false,module:null,reason:e})}i(nt,"frozenUnavailable");function bi(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}i(bi,"describe");function Le(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Le,"assertNever");function vr(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(vr,"acceptedFrame");function _r(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(_r,"heartbeatFrame");function Rr(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Rr,"deltaFrame");function Er(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(Er,"doneFrame");function N(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(N,"errorFrame");function Cr(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Cr,"analysisStartedFrame");function Sr(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Sr,"analysisCompleteFrame");function wr(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(wr,"unknownFrame");var Ri=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function ot(e){return Ri[e]}i(ot,"userFacingError");function kr(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(kr,"defineHidden");var Ei=/^[a-z][a-z0-9_]{0,63}$/;function S(e,t){let r=De(t?.wireCode,t?.wireEnvelope),n={code:e,category:fr(e),retryable:t?.retryable??yr(e),displayMessage:ot(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Ei.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&kr(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&kr(n,"raw",t.raw),Object.freeze(n)}i(S,"makeEverfurError");function Tr(e,t,r){let n=null,o=null,s=false,l=i(()=>o||(o=(async()=>{try{let u=await t(),a=typeof u=="string"?u:u?.token;if(typeof a!="string"||a.length===0)throw new K("invalid-argument","TokenProvider returned an empty token");return n=a,r?.(typeof u=="string"?null:Ci(u.expiresAt)),a}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(u){if(s)throw new K("not-initialized","This identity was cleared (sign-out); mint a new one.");return u?.forceRefresh&&(n=null),n!==null?n:l()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(Tr,"createIdentityProvider");function Ci(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(Ci,"expiryMs");function st(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(st,"newSessionId");function Si(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(Si,"authHeaders");function fe(e,t){return {...e,headers:{...wi(e.headers),...Si(t)}}}i(fe,"withAuthHeaders");function wi(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(wi,"stripAuthHeaders");async function Pr(e,t){if(t.mode==="anonymous")return t.transport.request(fe(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return p(it())}let n=await t.transport.request(fe(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return p(it())}let s=await t.transport.request(fe(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?p(it(s.error.httpStatus)):s}i(Pr,"authedSend");function it(e){return S("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(it,"authRejectedError");var xr=`
1
+ import {z as z$1}from'zod';var ui=Object.defineProperty;var i=(e,t)=>ui(e,"name",{value:t,configurable:true});function _(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_,"ok");function p(e){return Object.freeze({ok:false,error:e})}i(p,"err");var Fe=class Fe extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fe.prototype);}};i(Fe,"EverfurConfigError");var K=Fe;var du=Object.freeze({isAvailable:false,async getSecret(){return null},async setSecret(){throw new K("not-initialized","EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort")},async deleteSecret(){}});var Me=Object.freeze({track(){},trackExpectedFailure(){}});var rt=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(rt.map(e=>e.wireCode));var di=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"}),fr=Object.freeze(rt.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:di[e.wireCode]}))),ci=new Map(fr.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),pi=Object.freeze(["http_envelope",...[...new Set(fr.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function De(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...pi]){let o=ci.get(n+r);if(o)return o}}i(De,"contractErrorFor");function fi(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(fi,"contractDocUrl");function mr(e){return null}i(mr,"publishedDocUrl");var mi=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function yr(e){return mi[e]}i(yr,"categoryFor");function Y(e){let t=De(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":case "TELEVETRATELIMITED":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Y,"fromWire");function hr(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(hr,"fromHttpStatus");var yi=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function ee(e){return yi.has(e)}i(ee,"isAutoRetryable");var hi=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function gr(e){return ee(e)||hi.has(e)}i(gr,"isRetryableCode");function je(e,t=false){return t||ee(e)}i(je,"shouldRetry");var gi=500,nt=8e3,pe=4;function ze(e,t=Math.random){let r=Math.max(0,e),n=Math.min(gi*2**r,nt);return Math.floor(t()*n)}i(ze,"backoffDelayMs");function br(e){return e==="conversationNotFound"}i(br,"canRecreateOnNotFound");var vr=Object.freeze({shouldRetry(e,t){return ee(e)&&t<pe},maxAttempts(){return pe}});var _r=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Tu(e,t,r){let n;try{n=t();}catch(s){return ot(`optional peer '${e}' is not installed: ${vi(s)}`)}let o=bi(n);return o==null?ot(`optional peer '${e}' resolved to no module`):r&&!r(o)?ot(`optional peer '${e}' is present but failed its shape check`):Object.freeze({available:true,module:o})}i(Tu,"optionalModule");function bi(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}i(bi,"unwrapDefault");function ot(e){return Object.freeze({available:false,module:null,reason:e})}i(ot,"frozenUnavailable");function vi(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}i(vi,"describe");function Le(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Le,"assertNever");function Rr(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Rr,"acceptedFrame");function Er(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(Er,"heartbeatFrame");function Cr(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Cr,"deltaFrame");function Sr(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(Sr,"doneFrame");function N(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(N,"errorFrame");function wr(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(wr,"analysisStartedFrame");function kr(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(kr,"analysisCompleteFrame");function Tr(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Tr,"unknownFrame");var Ei=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function it(e){return Ei[e]}i(it,"userFacingError");function Pr(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Pr,"defineHidden");var Ci=/^[a-z][a-z0-9_]{0,63}$/;function S(e,t){let r=De(t?.wireCode,t?.wireEnvelope),n={code:e,category:yr(e),retryable:t?.retryable??gr(e),displayMessage:it(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&Ci.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&Pr(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Pr(n,"raw",t.raw),Object.freeze(n)}i(S,"makeEverfurError");function xr(e,t,r){let n=null,o=null,s=false,l=i(()=>o||(o=(async()=>{try{let u=await t(),a=typeof u=="string"?u:u?.token;if(typeof a!="string"||a.length===0)throw new K("invalid-argument","TokenProvider returned an empty token");return n=a,r?.(typeof u=="string"?null:Si(u.expiresAt)),a}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(u){if(s)throw new K("not-initialized","This identity was cleared (sign-out); mint a new one.");return u?.forceRefresh&&(n=null),n!==null?n:l()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(xr,"createIdentityProvider");function Si(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(Si,"expiryMs");function at(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(at,"newSessionId");function wi(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(wi,"authHeaders");function fe(e,t){return {...e,headers:{...ki(e.headers),...wi(t)}}}i(fe,"withAuthHeaders");function ki(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(ki,"stripAuthHeaders");async function Ir(e,t){if(t.mode==="anonymous")return t.transport.request(fe(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return p(st())}let n=await t.transport.request(fe(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return p(st())}let s=await t.transport.request(fe(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?p(st(s.error.httpStatus)):s}i(Ir,"authedSend");function st(e){return S("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(st,"authRejectedError");var Or=`
2
2
 
3
- `,ki=1048576,Ti=z$1.record(z$1.string(),z$1.unknown()),Pi=["emergency","schedule_soon","home_care"];async function*Ue(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",l=0,u=false;for await(let a of e){for(s+=o.decode(a,{stream:true});;){let d=s.indexOf(xr,l);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+xr.length),l=0;let f=Ir(c,n());if(f!==null&&(f.kind==="delta"&&(u=true),yield f,f.terminal))return}if(l=s.length>0?s.length-1:0,s.length>ki){yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let a=Ir(s,n());if(a!==null&&(a.kind==="delta"&&(u=true),yield a,a.terminal))return}yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Ue,"parseSse");function Ir(e,t){let r=null,n=[];for(let l of e.split(`
3
+ `,Ti=1048576,Pi=z$1.record(z$1.string(),z$1.unknown()),xi=["emergency","schedule_soon","home_care"];async function*Ue(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",l=0,u=false;for await(let a of e){for(s+=o.decode(a,{stream:true});;){let d=s.indexOf(Or,l);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+Or.length),l=0;let f=Ar(c,n());if(f!==null&&(f.kind==="delta"&&(u=true),yield f,f.terminal))return}if(l=s.length>0?s.length-1:0,s.length>Ti){yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let a=Ar(s,n());if(a!==null&&(a.kind==="delta"&&(u=true),yield a,a.terminal))return}yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Ue,"parseSse");function Ar(e,t){let r=null,n=[];for(let l of e.split(`
4
4
  `)){let u=l.replace(/\s+$/,"");u.length===0||u.startsWith(":")||(u.startsWith("id:")?r=u.slice(3).trim():u.startsWith("data:")&&n.push(u.slice(5).replace(/^ /,"")));}if(n.length===0)return null;let o;try{o=JSON.parse(n.join(`
5
- `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=Ti.safeParse(o);return s.success?xi(s.data,r,t):null}i(Ir,"parseBlock");function xi(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return N({code:z(e.code)??"unknown",retryable:e.retryable===true,wireMessage:z(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Er({conversationId:z(e.conversation_id)??"",messageId:z(e.message_id),title:z(e.title),followUpQuestions:Ai(e.follow_up_questions),citations:Or(e.citations),citationStatus:z(e.citation_status),urgencyLevel:Ar(e.urgency_level),urgencyReason:z(e.urgency_reason),urgencyProvided:Oi(e),resultId:z(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return vr(z(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return _r(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=z(e.delta)??z(e.token)??"";return Rr(s,t,r)}return o==="analysis_started"?Cr(z(e.request_id),t,r):o==="analysis_complete"?Sr({resultId:z(e.result_id),analysisType:z(e.analysis_type),modelVersion:z(e.model_version),confidence:Ii(e.confidence),detections:Or(e.detections),interpretation:z(e.interpretation),lastEventId:t},r):wr(e,t,r)}i(xi,"frameFromWire");function z(e){return typeof e=="string"?e:null}i(z,"asString");function Ii(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Ii,"asNumber");function Ar(e){return typeof e=="string"&&Pi.includes(e)?e:null}i(Ar,"asUrgency");function Oi(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Ar(t)!==null}i(Oi,"urgencySlotProvided");function Ai(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Ai,"asStringList");function Fi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Fi,"isPlainObject");function Or(e){return Array.isArray(e)?e.filter(Fi):[]}i(Or,"asMapList");var Mi="0.5.4",Di="react-native",ji="2026-09-19",Fr="EVERFUR_API_BASE_URL";function me(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(me,"configFailure");function lt(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(lt,"checkPublishableKey");function Mr(e,t){let r=lt(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=zi(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||ji;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Mi,platform:t?.platform??Di,debug:e.debug===true})})}i(Mr,"tryResolveClientConfig");function zi(e){let t=e?.trim(),r=t&&t.length>0?t:$i(Fr);return r?Hi(r):me("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Fr}. The SDK never ships a hardcoded host.`)}i(zi,"tryResolveApiBaseUrl");function Dr(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(Dr,"buildBaseHeaders");var Li=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Ui(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Ui,"hostOf");function Ni(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Ni,"isPrintableHost");function Bi(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Ni(t)}i(Bi,"canEchoOrigin");function qi(e,t){return `${e}://${t}`}i(qi,"safeOrigin");function Hi(e){let t=e.trim(),r=Li.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=Ui(r[2]);if(o.length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=Bi(t,o)?`: ${qi(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&Ki(o)))return n==="http"?me("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):me("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let l=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:l})}i(Hi,"normalizeBaseUrl");function Ki(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(Ki,"isLoopbackHost");function $i(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i($i,"readEnv");var Vi=3e4,Ur="x-request-id";async function*jr(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(jr,"fetchByteSource");function Wi(e){let t=new TextEncoder,r=Yi(),n=false,o=i(a=>{let d="";a.lastEventId&&(d+=`id: ${a.lastEventId}
5
+ `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=Pi.safeParse(o);return s.success?Ii(s.data,r,t):null}i(Ar,"parseBlock");function Ii(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return N({code:z(e.code)??"unknown",retryable:e.retryable===true,wireMessage:z(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Sr({conversationId:z(e.conversation_id)??"",messageId:z(e.message_id),title:z(e.title),followUpQuestions:Fi(e.follow_up_questions),citations:Fr(e.citations),citationStatus:z(e.citation_status),urgencyLevel:Mr(e.urgency_level),urgencyReason:z(e.urgency_reason),urgencyProvided:Ai(e),resultId:z(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return Rr(z(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return Er(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=z(e.delta)??z(e.token)??"";return Cr(s,t,r)}return o==="analysis_started"?wr(z(e.request_id),t,r):o==="analysis_complete"?kr({resultId:z(e.result_id),analysisType:z(e.analysis_type),modelVersion:z(e.model_version),confidence:Oi(e.confidence),detections:Fr(e.detections),interpretation:z(e.interpretation),lastEventId:t},r):Tr(e,t,r)}i(Ii,"frameFromWire");function z(e){return typeof e=="string"?e:null}i(z,"asString");function Oi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Oi,"asNumber");function Mr(e){return typeof e=="string"&&xi.includes(e)?e:null}i(Mr,"asUrgency");function Ai(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Mr(t)!==null}i(Ai,"urgencySlotProvided");function Fi(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Fi,"asStringList");function Mi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Mi,"isPlainObject");function Fr(e){return Array.isArray(e)?e.filter(Mi):[]}i(Fr,"asMapList");var Di="0.5.5",ut="react-native",ji="2026-09-19",Ne="EVERFUR_API_BASE_URL";function me(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(me,"configFailure");function dt(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(dt,"checkPublishableKey");function Dr(e,t){let r=dt(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=zi(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||ji;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Di,platform:t?.platform??ut,debug:e.debug===true})})}i(Dr,"tryResolveClientConfig");function zi(e){let t=e?.trim(),r=t&&t.length>0?t:$i(Ne);return r?Hi(r):me("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Ne}. The SDK never ships a hardcoded host.`)}i(zi,"tryResolveApiBaseUrl");function jr(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(jr,"buildBaseHeaders");var Li=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Ui(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Ui,"hostOf");function Ni(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Ni,"isPrintableHost");function Bi(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Ni(t)}i(Bi,"canEchoOrigin");function qi(e,t){return `${e}://${t}`}i(qi,"safeOrigin");function Hi(e){let t=e.trim(),r=Li.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=Ui(r[2]);if(o.length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=Bi(t,o)?`: ${qi(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&Ki(o)))return n==="http"?me("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):me("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let l=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:l})}i(Hi,"normalizeBaseUrl");function Ki(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(Ki,"isLoopbackHost");function $i(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i($i,"readEnv");var Vi=3e4,Nr="x-request-id";async function*zr(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(zr,"fetchByteSource");function Wi(e){let t=new TextEncoder,r=Yi(),n=false,o=i(a=>{let d="";a.lastEventId&&(d+=`id: ${a.lastEventId}
6
6
  `);let c=a.data??"";for(let f of c.split(`
7
7
  `))d+=`data: ${f}
8
8
  `;d+=`
9
- `,r.push(t.encode(d));},"onMessage"),s=i(()=>{u(),r.end();},"onDone"),l=i(a=>{let d=typeof a.xhrStatus=="number"?a.xhrStatus:0;if(d>=400){let c=qr(d),f=ee(Y(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:f})}
9
+ `,r.push(t.encode(d));},"onMessage"),s=i(()=>{u(),r.end();},"onDone"),l=i(a=>{let d=typeof a.xhrStatus=="number"?a.xhrStatus:0;if(d>=400){let c=Hr(d),f=ee(Y(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:f})}
10
10
 
11
- `));}u(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",l);function u(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",l);try{e.close();}catch{}}}return i(u,"cleanup"),Gi(r.source,u)}i(Wi,"eventSourceByteSource");async function*Gi(e,t){try{yield*e;}finally{t();}}i(Gi,"sourceWithCleanup");function Yi(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(l=>{r=l;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(Yi,"createByteQueue");async function Xi(e,t){let r=t.fetchImpl??Hr(),n=Kr(t.config.apiBaseUrl,e.path,e.query),o=$r(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=rs(Vi),l=ns(s.signal,e.signal),u;try{u=await r(n,Vr({...e,signal:l},o));}catch(d){return p(ut(d))}finally{s.cancel();}let a=await Wr(u);return u.ok?_(a):p(Zi(u.status,a,Br(u)))}i(Xi,"requestJson");function Nr(e){return {request:i(t=>Xi(t,e),"request"),stream:i((t,r)=>Qi(ts(t,r),e),"stream")}}i(Nr,"createHttpTransport");async function*Qi(e,t){let r=Kr(t.config.apiBaseUrl,e.path,e.query),n=$r(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let u=t.eventSourceFactory(r,Ji(e,n));yield*Ue(Wi(u),()=>es(u));return}let o=t.fetchImpl??Hr(),s;try{s=await o(r,Vr(e,n));}catch(u){yield zr("",true,Qr(u));return}let l=Br(s);if(!s.ok){let u=await Wr(s),a=Gr(u)??qr(s.status),d=Xr(u)||ee(Y(a));yield zr(a,d,Yr(u),l);return}if(s.body){yield*Ue(jr(s.body),l);return}yield*Ue(jr(null),l);}i(Qi,"streamFrames");function Ji(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Ji,"buildEventSourceInit");function Zi(e,t,r){let n=Gr(t),o=n?Y(n):mr(e),s=Yr(t);return S(o,{httpStatus:e,...Xr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Lr(t)?{reasonCode:Lr(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Zi,"errorFromResponse");function ut(e){return S("internalError",{retryable:true,wireMessage:Qr(e)})}i(ut,"networkError");function Br(e){let t=e.headers.get(Ur);return typeof t=="string"&&t.length>0?t:null}i(Br,"requestIdOf");function es(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Ur);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(es,"eventSourceRequestId");function qr(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(qr,"statusToWireCode");function zr(e,t,r,n=null){return N({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(zr,"syntheticErrorFrame");function Hr(){let e=globalThis.fetch;if(typeof e!="function")throw new K("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Hr,"getGlobalFetch");function Kr(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(l=>l[1]!==void 0).map(([l,u])=>`${encodeURIComponent(l)}=${encodeURIComponent(String(u))}`).join("&");s&&(o+=`?${s}`);}return o}i(Kr,"buildUrl");function $r(e,t,r,n){let o={...Dr(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i($r,"mergeHeaders");function Vr(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(Vr,"buildInit");function ts(e,t){return e.signal?e:{...e,signal:t}}i(ts,"withSignal");function rs(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(rs,"timeoutSignal");function ns(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(ns,"mergeAbortSignals");async function Wr(e){try{return await e.json()}catch{return null}}i(Wr,"safeJson");function Lr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Lr,"extractReasonCode");function Gr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Gr,"extractWireCode");function Yr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Yr,"extractWireMessage");function Xr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Xr,"extractRetryable");function Qr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Qr,"describeCause");var os=3e4,is=rt*2,ss="idempotency-key",as=new Set(["POST","PUT","PATCH","DELETE"]),ls=Object.freeze({onEvent(){}}),us=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ds(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(ds,"seededIdempotencyKey");function $(e){let t=e.observer??ls,r=e.timers??us,n=e.rng??Math.random,o=e.sleep??((g,y)=>Ss(g,r,y)),s=e.maxAttempts??pe,l=e.unaryTimeoutMs??os,u=e.newIdempotencyKey??ps(),a=i(g=>{try{t.onEvent(g);}catch{}},"emit");async function d(g,y,R){let T=R?.maxAttempts,C=Math.max(1,T??s),P=R?.idempotent??as.has(y.method),O=R?.idempotencyKey===void 0?null:ds(R.idempotencyKey),D=P?O??u():null,A=cs(y,D),v=0;for(;;){let w=i(ue=>Object.freeze({call:g,method:y.method,path:y.path,attempt:v,...D?{idempotencyKey:D}:{},...ue}),"stamp");a(w({phase:"attempt"}));let j=Es(l,r),B=Cs(j.signal,y.signal),q;try{q=await Pr({...A,signal:B.signal},e.auth);}catch(ue){q=p(ut(ue));}finally{B.dispose(),j.cancel();}if(q.ok)return a(w({phase:"settled",ok:true,reason:"ok"})),q;let H=q.error,ie=ms(H,v,{maxAttempts:C,rng:n,now:r.now(),aborted:y.signal?.aborted===true,...T!==void 0?{perCallMaxAttempts:T}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),ce={ok:false,code:H.code,reason:ie.reason,...H.httpStatus!==void 0?{httpStatus:H.httpStatus}:{},...H.requestId!==void 0?{requestId:H.requestId}:{}};if(!ie.retry)return a(w({phase:"settled",...ce})),p(H);if(a(w({phase:"retry",...ce,delayMs:ie.delayMs})),await o(ie.delayMs,y.signal),y.signal?.aborted===true)return a(w({phase:"settled",...ce,reason:"aborted"})),p(H);v+=1;}}i(d,"send");async function c(g){return fe(g,await Rs(e.auth))}i(c,"authorize");async function*f(g,y,R){a(Object.freeze({call:g,phase:"stream.open",method:y.method,path:y.path,attempt:0}));try{yield*e.auth.transport.stream(y,R);}catch{yield N({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(f,"stream"),Object.freeze({send:d,authorize:c,stream:f})}i($,"createRequestFunnel");function cs(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==ss&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(cs,"assembleHeaders");function ps(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(ps,"defaultIdempotencyKeyFactory");var fs=10;function ms(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=ys(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!ee(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let l=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(fs,Math.floor(d)))},"policyCeiling"),u=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=u)return {retry:false,reason:"attempts-exhausted"};let a=hs(e,r.now);return a!==null?a>is?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:a}:{retry:true,reason:o,delayMs:ze(t,r.rng)}}i(ms,"decideRetry");function ys(e){let t=e.code==="unknown"?Y(_s(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(ys,"throttleKind");function hs(e,t){let r=bs(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=gs(e.raw);return n===null?null:Math.round(n*1e3)}i(hs,"retryOverrideMs");function gs(e){for(let t of dt(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(gs,"findRetryAfterSeconds");function bs(e){for(let t of dt(e)){let r=t.resets_at,n=vs(r);if(n!==null)return n}return null}i(bs,"findResetsAt");function dt(e){if(!Jr(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Jr(n)&&t.push(n);}return t}i(dt,"candidateScopes");function vs(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(vs,"parseInstantMs");function _s(e){for(let t of dt(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(_s,"rawWireCode");function Jr(e){return typeof e=="object"&&e!==null}i(Jr,"isRecord");async function Rs(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Rs,"resolveDeviceAuth");function Es(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Es,"boundedSignal");function Cs(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(Cs,"mergeSignals");function Ss(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(Ss,"delayAbortable");function L(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(L,"hasLoneSurrogate");function Ne(e){return [...e].length}i(Ne,"serverLength");var nn=Object.freeze(["better","same","worse"]),pt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Zr(e){return p(S("validationFailed",{retryable:false,wireMessage:e}))}i(Zr,"invalid");function ct(){return p(S("internalError",{retryable:false}))}i(ct,"malformed");function en(e){return typeof e!="string"||e.trim().length===0?S("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):L(e)?S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(en,"petPath");var te=i(e=>typeof e=="string"?e:null,"str"),tn=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function rn(e){if(typeof e!="object"||e===null)return null;let t=e,r=te(t.case_id),n=te(t.status);if(r===null||n===null)return null;let o=te(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:te(t.body_location),lastResponse:o!==null&&nn.includes(o)?o:null,checkInDueAt:te(t.check_in_due_at),openedAt:te(t.opened_at),resolvedAt:te(t.resolved_at),resolutionText:te(t.resolution_text),checkinAskCount:tn(t.checkin_ask_count),checkinAnswerCount:tn(t.checkin_answer_count)})}i(rn,"caseFromWire");function on(e){return {async list(t,r){let n=en(t);if(typeof n!="string")return p(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return p(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return ct();let l=s.map(rn);return l.every(u=>u!==null)?_(Object.freeze(l)):ct()},async checkin(t,r,n,o){let s=en(t);if(typeof s!="string")return p(s);if(typeof r!="string"||!pt.test(r))return Zr("case_id must be a UUID");if(!nn.includes(n))return Zr("response must be one of better, same, worse");let l=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!l.ok)return p(l.error);let u=typeof l.value=="object"&&l.value!==null?l.value:{},a=rn(u.case);return a===null?ct():_(Object.freeze({case:a,ctaDeepLink:te(u.cta_deep_link)}))}}}i(on,"createCasesRepositoryOver");var sn=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var an=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function qe(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(qe,"delayAbortable");function He(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(He,"mergeSignals");var ft=class ft{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?He(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(ft,"MediaStore");var Be=ft;function yt(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(yt,"makeUser");function ht(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(ht,"makeAssistant");function he(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(he,"stripPending");function ln(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(ln,"appendText");function gt(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(gt,"finalizeAssistant");function un(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(un,"freezeSnapshot");function E(e,t,r){return S(e,{retryable:t,...r?{wireMessage:r}:{}})}i(E,"makeError");function bt(e){let t=Y(e.code);return S(t,{retryable:e.retryable||je(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(bt,"errorFromFrame");function X(e){return N({code:ws(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(X,"synthErrorFrame");function ws(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Le(e)}}i(ws,"canonicalWireCode");function dn(e){let t=Array.isArray(e)?e:mt(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!mt(n))continue;let o=ye(n.category)??ye(n.title)??"",s=ks(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(dn,"parsePromptCategories");function vt(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(vt,"flattenPrompts");function mt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(mt,"isPlainObject");function ye(e){return typeof e=="string"?e:null}i(ye,"asStr");function ks(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(mt(r)){let n=ye(r.text)??ye(r.prompt)??ye(r.title);n!==null&&t.push(n);}return t}i(ks,"asPromptTextList");function cn(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(cn,"defaultIdFactory");function pn(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(pn,"defaultIdempotencyFactory");var mn={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*yn(e,t,r,n){let o=e[Symbol.asyncIterator](),s=fn(t.overallMs,n),l=fn(t.idleMs,n),u=xs(r);try{for(;;){if(r.aborted)return;let a=o.next().then(f=>({tag:"next",value:f}),()=>({tag:"streamError"})),d=await Promise.race([a,l.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),u.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Ps();return}if(d.tag==="idle"||d.tag==="overall"){yield Ts();return}let c=d.value;if(c.done||(l.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{l.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(yn,"withWatchdog");function Ts(){return N({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ts,"synthTimeoutFrame");function Ps(){return N({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ps,"synthStreamErrorFrame");function fn(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(fn,"deadline");function xs(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(xs,"abortPromise");var Is="checkin",Os=/^\d{4}-\d{2}-\d{2}$/,ge="watching";function As(e){return e.status!=null&&e.status!==ge}i(As,"isCheckinSettled");function hn(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(hn,"isLiveAskAnswered");function Fs(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Is||n===void 0||o===void 0||!pt.test(n)||!Os.test(o)?null:{caseId:n,dueDay:o}}i(Fs,"parseCheckinOrigin");function gn(e){return Fs(e)?.caseId??null}i(gn,"parseCheckinOriginRef");function _t(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return p(S("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||L(o))return p(S("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),_(r.length?`?${r.join("&")}`:"")}i(_t,"historyQuery");function _e(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(_e,"validConversationId");function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(ve,"object");function bn(e){return e==null||typeof e=="string"&&e.length>0&&!L(e)}i(bn,"cursor");function be(){return p(S("internalError",{retryable:false}))}i(be,"malformed");function vn(e){let t=ve(e);if(!t||!Array.isArray(t.conversations)||!bn(t.next_cursor))return be();let r=[];for(let n of t.conversations){let o=ve(n);if(!o||typeof o.conversation_id!="string"||!_e(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return be();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return be();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return _(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(vn,"mapConversationPage");function _n(e){let t=ve(e);if(!t||!Array.isArray(t.messages)||!bn(t.next_cursor))return be();let r=[],n=new Set;for(let o of t.messages){let s=ve(o);if(!s||typeof s.message_id!="string"||!_e(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return be();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let l=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,u=s.role==="assistant"?gn(l):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Ms(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Ds(s.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...u!==null?{checkin:Object.freeze({caseId:u,answer:null,resolutionText:null,status:null})}:{}}));}return _(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(_n,"mapMessagePage");function Ms(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ms,"normalizeUrgency");function Ds(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=ve(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let l=n[s];(typeof l=="string"||l===null)&&(o[s]=l);}return [Object.freeze(o)]}))}i(Ds,"historyCitations");var Ke=5,Rt=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Et=4e3;var Ct=4e3;function Rn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:E("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:E("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(Rn,"validateImageKeys");function St(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:E("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Ct?{reason:"too_long",error:E("validationFailed",false,`message is ${r} characters; the server accepts at most ${Ct}`)}:null}i(St,"validateMessageText");function En(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(En,"urgencyTier");async function*Re(e){yield e;}i(Re,"singleFrameStream");async function*Cn(){}i(Cn,"emptyStream");var js=6e4,zs=18e4,Ls=24,Us=512,Ns=false;function Sn(e){return new wt(e)}i(Sn,"createChatController");var kt=class kt extends Be{constructor(r){super(un({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??$({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=on(this.funnel),this.telemetry=r.telemetry??Me,this.errorPolicy=r.errorPolicy??gr,this.timers=r.timers??mn,this.rng=r.rng??Math.random,this.newId=r.newId??cn(),this.makeIdempotencyKey=r.makeIdempotencyKey??pn(),this.budget={idleMs:r.budget?.idleMs??js,overallMs:r.budget?.overallMs??zs};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let a=E(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(a),()=>{}):Re(X(a))}let l=St(r)??Rn(s.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),o?(o.onError(l.error),()=>{}):Re(X(l.error));if(o)return this.driveWithHandlers(r,s,o);let u=this.beginTurn(r,s);return this.runTurn(u,s.signal)}askEverfur(r,n){if(this.disposed)return Re(X(E("accessDenied",false)));let o=St(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Re(X(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):Cn()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,yt(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?he(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(r=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=r,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:r,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}newConversation(){this.disposed||this.resetThread(this.scopePrompts);}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(vt(r));this.bootstrapPrompts=n,this.scopePrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=_t(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(E("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return p(E("accessDenied",false));if(!l.ok)return l;let u=vn(l.value);if(u.ok){for(let c of u.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let a=this.snapshot.conversationId,d=a===null?void 0:this.unreadByConversation.get(a);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return u}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return p(E("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let a=await this.resumeConversation(n);return a.ok?_(n):p(a.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return p(s.error);let l=s.value.conversations[0];if(l===void 0)return _(null);let u=await this.resumeConversation(l.id);return u.ok?_(l.id):p(u.error)}async markRead(r){if(this.disposed)return p(E("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return _(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?p(E("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),_(void 0)):p(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return p(E("accessDenied",false));if(typeof r!="string"||r.trim().length===0||L(r))return p(E("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Rt.includes(n))return p(E("validationFailed",false,`feedback_type must be one of ${Rt.join(", ")}`));let l=typeof o=="string"?o.trim():"";if([...l].length>Et)return p(E("validationFailed",false,`notes is over ${Et} characters`));let u={feedback_type:n};l.length>0&&(u.notes=l);let a=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:u},s?.signal);if(!this.alive(a)||this.disposed)return p(E("accessDenied",false));if(!d.ok)return p(d.error);let c=d.value?.feedback_id;return _(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return p(E("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return p(E("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,u=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(l)||this.disposed)return p(E("accessDenied",false));if(!u.ok)return u;let a=u.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:u.value.case.resolutionText,status:u.value.case.status??null,...a!==null?{openedAt:a}:{}}),c=i(f=>f.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(f=>c(f)?Object.freeze({...f,checkin:d}):f)}),u}async getMessages(r,n){if(!_e(r))return p(E("validationFailed",false));let o=_t(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(E("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?p(E("accessDenied",false)):l.ok?_n(l.value):l}async resumeConversation(r){if(this.disposed)return p(E("accessDenied",false));if(!_e(r))return p(E("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return p(E("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),_(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===ge).map(d=>d.caseId)),l=new Map(o.value.map(d=>[d.caseId,d])),u=false,a=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;u=true;let f=l.get(c.caseId),g=c.openedAt??f?.openedAt??null,y=s.has(c.caseId),R=f!==void 0&&(!y||hn({askCount:f.checkinAskCount,answerCount:f.checkinAnswerCount}))?f.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:y?ge:f?.status??"resolved",answer:c.answer??R,resolutionText:c.resolutionText??f?.resolutionText??null,...g!==null?{openedAt:g}:{}})})});u&&this.patch({messages:a});}async refreshActiveThread(){if(this.disposed)return p(E("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return _(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return p(E("accessDenied",false));if(!o.ok)return p(o.error);let s=new Set(this.snapshot.messages.map(u=>u.id)),l=o.value.messages.filter(u=>!s.has(u.id));return l.length>0&&this.patch({messages:[...this.snapshot.messages,...l]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),_(void 0)}async loadOlderMessages(){if(this.disposed)return p(E("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return _(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return p(E("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let l=new Set(this.snapshot.messages.map(a=>a.id)),u=s.value.messages.filter(a=>!l.has(a.id));return this.patch({messages:[...u,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),_(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield X(n.error));}async primeConversation(r){if(this.disposed)return p(E("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?p(E("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return _(n);let o=this.snapshot.conversationId;return o!==null?_(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return p(E("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let l=await s.settled;return !this.alive(n)||this.disposed?p(E("accessDenied",false)):(!l.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),l)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return p(s.error);let l=s.value?.conversation_id??s.value?.id;return typeof l!="string"||l.length===0?p(E("internalError",true)):_(l)}async getPrompts(r){let n=this.epoch;if(this.disposed)return p(E("accessDenied",false));let o=r?.petRef??null;if(o!==null&&L(o))return p(S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?p(E("accessDenied",false)):l.ok?_(dn(l.value)):p(l.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,l=He(s.signal,n.signal),u=this.beginTurn(r,n),a=this.runTurn(u,l),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let f of a){if(d)break;o.onFrame(f),f.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,yt(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,l=false,u=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let a=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=a?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let C=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;C.ok&&this.snapshot.conversationId===null&&this.adoptConversation(C.value);}if(a&&this.snapshot.conversationId===null){let C=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!C.ok){yield*this.emitTerminal(r,C.error,X(C.error));return}this.adoptConversation(C.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let C=E("internalError",!0);yield*this.emitTerminal(r,C,X(C));return}this.clearAssistantInProgress(r);let f=new AbortController,g=He(o.signal,f.signal),y=null;try{let C;try{C=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let O=this.authRejected();yield*this.emitTerminal(r,O,X(O));return}if(o.signal.aborted||!this.alive(o.epoch))return;let P=this.funnel.stream("chat.send",C,g);for await(let O of yn(P,this.budget,g,this.timers)){if(!this.alive(o.epoch))return;if(O.kind==="error"&&O.terminal){y=O;break}if(this.applyFrame(O,r),yield O,O.terminal){o.settle();return}}}finally{f.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(y===null){if(this.snapshot.status==="complete")return;let C=E("streamIncomplete",!0);yield*this.emitTerminal(r,C,X(C));return}let R=Y(y.code);if(R==="authExpired"&&this.auth.mode==="personalized"&&!u){u=!0,this.telemetry.track("chat.auth.refresh",{});let C=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!C){let P=this.authRejected();yield*this.emitTerminal(r,P,y);return}this.patch({reconnecting:!0});continue}if(R==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let C=this.authRejected();yield*this.emitTerminal(r,C,y);return}if(R==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,bt(y),y);return}if(hr(R)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let T=y.retryable&&je(R,!0);if(Ns&&T&&s+1<this.errorPolicy.maxAttempts(R));yield*this.emitTerminal(r,bt(y),y);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Le(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(l=>l.id===n.userMessageId&&l.pending===true?he(l):l);this.patch({status:"streaming",isStreaming:true,messages:[...s,ht(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Us){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},Ls);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(l=>l.id===o?ln(l,n):l);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(u=>u.id===n.assistantMessageId?gt(u,r):u);else {let u=this.newId();n.assistantMessageId=u,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?he(d):d),gt(ht(u,"",this.stamp()),r)];}let l=vt([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=l.length>0?Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,l=this.historyGeneration,u=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!u.ok||!this.alive(s)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==r)return;let a=En(u.value?.urgency),d=typeof u.value?.reason=="string"?u.value.reason:null,c=i(f=>f.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(f=>c(f)?Object.freeze({...f,urgencyLevel:a,urgencyReason:d,urgencyProvided:true}):f)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?he(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return E("authRejected",false)}};i(kt,"ChatControllerImpl");var wt=kt;async function Tn(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],l=false,u=false,a=false,d=null,c=null,f=o?r.resumeConversation(o).then(A=>A.ok?_(o):A):r.primeConversation(n?{petRef:n}:void 0),g=r.getPrompts(n!==null?{petRef:n}:void 0),[y,R]=await Promise.all([f,g]),T=null;if(y.ok)T=y.value,s.push(y.value),r.getSnapshot().conversationId===null&&r.adoptConversation(y.value);else {let A=y.error;c=A,wn(A)?(u=true,d=A):(kn(A)&&(l=true),a=true);}let C=[];R.ok?C=R.value:P(R.error);function P(A){wn(A)?(u=true,d===null&&(d=A)):kn(A)&&(l=true);}i(P,"recordAuthSignals");let O=d!==null?d.displayMessage:null;return Object.freeze({conversationId:T,petRef:n,suggestedPrompts:C,error:O,warning:O===null&&T===null&&a?Bs:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:l,sawUnauthorized:u,sawConversationInitFailure:a})})}i(Tn,"bootstrapChat");var Bs="Chat is ready. Your first message will start the conversation.";function wn(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(wn,"isUnauthorized");function kn(e){return e.httpStatus===403||e.code==="accessDenied"}i(kn,"isForbidden");var Tt=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Pn(e){return e!==Tt}i(Pn,"isUploadTransportAvailable");var xn=128,oe=128;var qs=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),mc="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",On=10*1024*1024,Hs=5,Ee=120,Ks="/widget/v1/uploads/initiate";function $s(e){return typeof e=="string"&&qs.includes(e.trim().toLowerCase())}i($s,"isAttachmentMime");function Vs(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=Ee)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Ee);let n=t.slice(r);return n.length>=Ee?t.slice(0,Ee):`${t.slice(0,r).slice(0,Ee-n.length)}${n}`}i(Vs,"sanitizeFilename");function yc(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(yc,"formatBytes");var Ce=i(e=>Object.freeze({ok:true,value:e}),"ok"),V=i(e=>Object.freeze({ok:false,error:e}),"err");function M(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(M,"failure");function Ws(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i(Ws,"attachmentSize");function Gs(e){let t=Vs(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!$s(r))return V(M("unsupported_type",false,t));let n=Ws(e);return n===null?V(M("unknown",false,t)):n>On?V(M("too_large",false,t,{sizeBytes:n})):Ce(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Gs,"validateAttachment");function Ys(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),l=r(t.s3_key);if(o===null||s===null||l===null)return null;let u={},a=t.upload_fields;if(typeof a=="object"&&a!==null)for(let[d,c]of Object.entries(a))typeof c=="string"&&(u[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(u),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??On,s3_key:l,purpose:r(t.purpose)})}i(Ys,"parsePolicy");function Xs(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return M("quota_exceeded",false,t,{cause:e});case "rateLimited":return M("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return M("idempotency_conflict",true,t,{cause:e});case "validationFailed":return M("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return M("network",true,t,{cause:e});default:return r===429?M("rate_limited",true,t,{cause:e}):r===503?M("network",true,t,{cause:e}):r===void 0?M("network",true,t,{cause:e}):M("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Xs,"initiateFailure");async function Qs(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Ks,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return V(Xs(n.error,t.filename));let o=Ys(n.value);return o===null?V(M("server",false,t.filename)):Ce(o)}i(Qs,"initiateAttachmentUpload");async function Js(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return V(M("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Ce(void 0)}catch{return o()?V(M("cancelled",true,r.filename)):V(M("server",true,r.filename))}}i(Js,"uploadAttachmentBytes");var Zs=2,ea=3,ta=Object.freeze([1e3,2e3,4e3]),In=0;function ra(){return In+=1,`attachment-${In}`}i(ra,"defaultNewId");function hc(e){let t=Math.max(1,e.concurrency??Zs),r=Math.max(1,e.maxAttempts??ea),n=e.backoffMs??ta,o=Math.max(1,e.maxPerMessage??Hs),s=e.timers??an,l=e.newId??ra,u=Pn(e.transport),a=new Map,d=[],c=[],f=new Set,g=new Set,y=Object.freeze({attachments:Object.freeze([])}),R=false,T=i(()=>{y=Object.freeze({attachments:Object.freeze(d.flatMap(v=>{let w=a.get(v);return w===void 0?[]:[w.state]}))});for(let v of g)v();},"publish"),C=i((v,w)=>{v.state=Object.freeze({...v.state,...w}),T();},"patch"),P=i(()=>{for(;!R&&f.size<t&&c.length>0;){let v=c.shift(),w=a.get(v);w!==void 0&&(f.add(v),O(w).finally(()=>{f.delete(v),P();}));}},"pump"),O=i(async v=>{let{attachment:w}=v;for(;v.attempts<r;){if(R||v.controller.signal.aborted)return;v.attempts+=1;let j=v.controller.signal;C(v,{status:"uploading",error:null,progress:0});let B=await Qs(e.funnel,w,{signal:j});if(R||j.aborted)return;let q;if(!B.ok)q=V(B.error);else {let ue=await Js(e.transport,B.value,w,{signal:j,onProgress:i(ai=>{!j.aborted&&v.state.status==="uploading"&&C(v,{progress:na(ai)});},"onProgress")});if(R||j.aborted)return;q=ue.ok?Ce(B.value.s3_key):V(ue.error);}if(q.ok){C(v,{status:"uploaded",s3Key:q.value,error:null,progress:1});return}let H=q.error,ie=H.retryable&&v.attempts<r;if(C(v,{status:ie?"uploading":"failed",error:H,progress:0}),!ie)return;let ce=n[Math.min(v.attempts-1,n.length-1)]??0;await qe(ce,j,s);}},"run"),D=i(v=>{c.push(v.state.id),P();},"enqueue"),A={available:u,subscribe(v){return g.add(v),()=>{g.delete(v);}},getSnapshot:i(()=>y,"getSnapshot"),get uploading(){return y.attachments.some(v=>v.status==="uploading")},get s3Keys(){return y.attachments.flatMap(v=>v.status==="uploaded"&&v.s3Key!==null?[v.s3Key]:[])},add(v){let w=Gs(v);if(!w.ok)return w;if(R||d.length>=o)return V(M("too_many",false,w.value.filename));let j=l(),B={attachment:w.value,controller:new AbortController,attempts:0,state:Object.freeze({id:j,filename:w.value.filename,previewUri:v.uri,contentType:w.value.contentType,sizeBytes:w.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(j,B),d.push(j),T(),D(B),Ce(B.state)},retry(v){let w=a.get(v);w===void 0||R||w.state.status!=="failed"||(w.controller=new AbortController,w.attempts=0,C(w,{status:"uploading",error:null,progress:0,s3Key:null}),D(w));},remove(v){let w=a.get(v);if(w===void 0)return;w.controller.abort(),a.delete(v);let j=d.indexOf(v);j>=0&&d.splice(j,1);let B=c.indexOf(v);B>=0&&c.splice(B,1),T();},clear(){for(let v of [...d])A.remove(v);},dispose(){R=true;for(let v of a.values())v.controller.abort();a.clear(),d.length=0,c.length=0,g.clear(),y=Object.freeze({attachments:Object.freeze([])});}};return A}i(hc,"createAttachmentQueue");function na(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(na,"clamp");var An=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function Fn(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(An,t)?An[t]:null}i(Fn,"canonicalPetSpecies");var Mn=50,oa=128,Pt=120,Dn=120,ia=2e3,jn=120,sa=80,Un=new Set(["male","female","unknown"]),Nn=new Set(["day","month","year"]),Bn=new Set(["low","medium","high","athletic"]),qn=new Set(["indoor","outdoor","both"]),Hn=new Set(["mild","moderate","severe"]),aa=/^(\d{4})-(\d{2})-(\d{2})$/,Kn=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],$n=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Kn,...$n].map(([e])=>e));function la(e){let t=aa.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(la,"isRealDate");var we=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),ua=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Ve=i((e,t)=>typeof t=="string"&&la(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Q=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(L(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=Ne(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),da={sex:we(Un),spayedNeutered:ua,birthDate:Ve,birthDatePrecision:we(Nn),activityLevel:we(Bn),indoorOutdoor:we(qn),foodBrand:Q(jn),foodType:Q(jn),microchipId:Q(sa)},xt=["ref","ref",false,Q(oa,{required:true,trimmed:true})],It=["notes","notes",false,Q(ia,{trimmed:true})],zn=[xt,["name","name",true,Q(Pt,{required:true,trimmed:true})],["dose","dose",false,Q(Dn,{trimmed:true})],["frequency","frequency",false,Q(Dn,{trimmed:true})],["startDate","start_date",false,Ve],["endDate","end_date",false,Ve],It],ca={allergies:[xt,["allergen","allergen",true,Q(Pt,{required:true,trimmed:true})],["severity","severity",false,we(Hn)],It],medications:zn,supplements:zn,conditions:[xt,["conditionName","condition_name",true,Q(Pt,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ve],It]};function pa(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[a,d,c,f]of ca[e]){let g=o[a];if(g==null){if(c)return {error:`${n}.${a} is required`};g===null&&(s[d]=null);continue}let y=f(`${n}.${a}`,g);if(y!==null)return {error:y};s[d]=g;}let l=s.start_date,u=s.end_date;return typeof l=="string"&&typeof u=="string"&&u<l?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(pa,"itemToWire");function fa(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>Mn)return {error:`${e} has ${t.length} items; the server accepts at most ${Mn}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=pa(e,o,t[o]);if("error"in s)return s;let l=s.item.ref;if(typeof l=="string"){let u=l.trim();if(n.has(u))return {error:`${e}: ref ${JSON.stringify(u)} is used twice; a ref names one item`};n.add(u);}r.push(s.item);}return {items:r}}i(fa,"listToWire");function Vn(e,t){let r=e,n={};for(let[l,u]of Kn){let a=r[l];if(a!==void 0){if(a!==null){let d=da[l](l,a);if(d!==null)return {error:d}}n[u]=a;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[l,u]of $n){let a=r[l];if(a===void 0)continue;let d=fa(l,a);if("error"in d)return d;n[u]=d.items;}return Object.keys(n).length>0&&t!==void 0&&Fn(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(Vn,"petHealthToWire");var F=i(e=>typeof e=="string"?e:null,"str"),Se=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),ma=i(e=>typeof e=="boolean"?e:null,"bool");function $e(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i($e,"itemsFromWire");function Ln(e){let t=F(e.name);return t===null||t.length===0?null:Object.freeze({ref:F(e.ref),name:t,dose:F(e.dose),frequency:F(e.frequency),startDate:F(e.start_date),endDate:F(e.end_date),notes:F(e.notes)})}i(Ln,"medicationFromWire");function Wn(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Se(Un,e.sex),spayedNeutered:ma(e.spayed_neutered),birthDate:F(e.birth_date),birthDatePrecision:Se(Nn,e.birth_date_precision),activityLevel:Se(Bn,e.activity_level),indoorOutdoor:Se(qn,e.indoor_outdoor),foodBrand:F(e.food_brand),foodType:F(e.food_type),microchipId:F(e.microchip_id),allergies:$e(e.allergies,r=>{let n=F(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),allergen:n,severity:Se(Hn,r.severity),notes:F(r.notes)})}),medications:$e(e.medications,Ln),supplements:$e(e.supplements,Ln),conditions:$e(e.conditions,r=>{let n=F(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),conditionName:n,diagnosedDate:F(r.diagnosed_date),notes:F(r.notes)})})})}i(Wn,"petHealthFromWire");var Xn=100,Qn=50,Jn=100,Zn=50,eo=500,ya=128,ha=6e4;function Z(e){return S("validationFailed",{retryable:false,wireMessage:e})}i(Z,"invalid");function se(e,t,r){if(typeof t!="string")return Z(`${e} must be a string`);let n=Ne(t);return n<=r?null:Z(`${e} is ${n} characters; the server accepts at most ${r}`)}i(se,"checkString");function We(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Z(`${e} must be a finite number between 0 and ${r}`)}i(We,"outOfRange");function Gn(e,t){if(typeof e!="string")return Z("pet_ref must be a string");if(e.trim().length===0)return Z("pet_ref must not be blank");if(L(e))return Z("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Z("profile must be an object");let r=[se("pet_ref",e,ya)];return t?.name!==void 0&&r.push(se("name",t.name,Xn)),t?.species!==void 0&&r.push(se("species",t.species,Qn)),t?.breed!==void 0&&r.push(se("breed",t.breed,Jn)),t?.ageYears!==void 0&&r.push(We("age_years",t.ageYears,Zn)),t?.weightKg!==void 0&&r.push(We("weight_kg",t.weightKg,eo)),r.find(n=>n!==null)??null}i(Gn,"validate");function to(e,t){let r=Vn(e,t);return "error"in r?{error:Z(r.error)}:r}i(to,"healthToWire");function ga(e){if(typeof e!="object"||e===null)return {error:Z("patch must be an object")};let t=e,r=[["name","name",s=>se("name",s,Xn)],["species","species",s=>se("species",s,Qn)],["breed","breed",s=>se("breed",s,Jn)],["ageYears","age_years",s=>We("age_years",s,Zn)],["weightKg","weight_kg",s=>We("weight_kg",s,eo)]],n={};for(let[s,l,u]of r){let a=t[s];if(a!==void 0){if(a!==null){let d=u(a);if(d!==null)return {error:d}}n[l]=a;}}let o=to(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Z("patch must change at least one field")}:{body:n})}i(ga,"patchToWire");function ba(e){if(e==null)return {body:{}};let t=to(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(ba,"toWire");var J=i(e=>typeof e=="string"?e:null,"str"),Ge=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Yn(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:J(r.pet_ref)??t,name:J(r.name),species:J(r.species),breed:J(r.breed),ageYears:Ge(r.age_years),weightKg:Ge(r.weight_kg)})}i(Yn,"fromWire");function ro(e){if(typeof e!="object"||e===null)return null;let t=e,r=J(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:J(t.pet_id),petRef:r,name:J(t.name),species:J(t.species),breed:J(t.breed),ageYears:Ge(t.age_years),weightKg:Ge(t.weight_kg),updatedAt:J(t.updated_at)})}i(ro,"widgetPetFromWire");function va(e){let t=ro(e);return t===null?null:Object.freeze({...t,...Wn(e)})}i(va,"widgetPetProfileFromWire");function _a(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=ro(r);return n===null?[]:[n]}))}i(_a,"petListFromWire");function no(e){return Ra($({auth:e}),$({auth:e,unaryTimeoutMs:ha}))}i(no,"createPetsRepository");function Ra(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Gn(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?_(_a(s.value)):p(s.error)},async registerPet(o,s,l){let u=Gn(o,s);if(u!==null)return p(u);let a=ba(s);if("error"in a)return p(a.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:a.body},f=await e.send("pets.registerPet",l?.signal?{...c,signal:l.signal}:c);return f.ok?_(Yn(f.value,o)):p(f.error)},async updatePet(o,s,l){let u=n(o);if(typeof u!="string")return p(u);let a=ga(s);if("error"in a)return p(a.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:u,body:a.body},l?.signal));return d.ok?_(Yn(d.value,o)):p(d.error)},async getPetProfile(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},s?.signal));if(!u.ok)return p(u.error);let a=va(u.value);return a===null?p(S("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):_(a)},async deletePet(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.deletePet",r({method:"DELETE",path:l},s?.signal));return u.ok?_(void 0):p(u.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?_(void 0):p(s.error)}}}i(Ra,"createPetsRepositoryOver");var oo=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function io(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(oo))for(let l of oo[s])o.has(l)||(o.add(l),n.push(Object.freeze({resource:l,granted:false,disabled:r})));return Object.freeze(n)}i(io,"deniedDecisionsFor");function re(e){let t=Ea(e);return t===null?null:Sa(t)}i(re,"parseColor");function Ea(e){if(typeof e=="number")return so(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Ot(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Ot(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ca(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=Ot(t);if(r!==null)return r}return /^\d+$/.test(t)?so(Number.parseInt(t,10)):null}i(Ea,"toRgba");function Ot(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:At(t[0]),g:At(t[1]),b:At(t[2]),a:1};if(t.length===6)return {r:ae(t,0),g:ae(t,2),b:ae(t,4),a:1};if(t.length===8){let r=ae(t,0);return {r:ae(t,2),g:ae(t,4),b:ae(t,6),a:r/255}}return null}i(Ot,"fromHex");function Ca(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(a=>a.trim());if(n.length<3)return null;let o=Ft(Number(n[0])),s=Ft(Number(n[1])),l=Ft(Number(n[2]));if(o===null||s===null||l===null)return null;let u=1;if(n.length>=4){let a=Number(n[3]);if(!Number.isFinite(a))return null;u=Math.min(1,Math.max(0,a));}return {r:o,g:s,b:l,a:u}}i(Ca,"fromRgbFunc");function so(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(so,"argbIntToRgba");function ae(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ae,"byte");function At(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(At,"dup");function Ft(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Ft,"clampByte");function Sa(e){if(e.a>=1)return wa(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Sa,"normalizeRgba");function wa(e,t,r){return `#${Mt(e)}${Mt(t)}${Mt(r)}`.toUpperCase()}i(wa,"rgbToHex");function Mt(e){return e.toString(16).padStart(2,"0")}i(Mt,"hex2");var Dt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]);function ka(e){return Dt.includes(e)}i(ka,"isSlotName");function Ta(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Ta,"parseRadius");function ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!ka(n)||o===null||typeof o!="object")continue;let s=Pa(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(ao,"parseThemeSlots");function Ye(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Ye,"pick");function Pa(e){let t={},r=re(Ye(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=re(Ye(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Ta(Ye(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=re(Ye(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Pa,"parseSlot");var co=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),Xe="slots.";function po(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(po,"isEmptyBranding");function Ia(e){return e==="hide_powered_by"||co.includes(e)?true:e.startsWith(Xe)&&Dt.includes(e.slice(Xe.length))}i(Ia,"isThemeLockName");function ke(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:le(x(t,"display_name","displayName")),logoUrl:le(x(t,"logo_url","logoUrl")),primaryColor:re(x(t,"primary_color","primaryColor")),accentColor:re(x(t,"accent_color","accentColor")),brightness:Ma(x(t,"brightness","color_scheme","colorScheme")),fontFamily:le(x(t,"font_family","fontFamily")),fontUrl:le(x(t,"font_url","fontUrl")),fonts:lo(x(t,"fonts")),fontUrls:lo(x(t,"font_urls","fontUrls")),placeholder:le(x(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Oa(x(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:re(x(t,"primary_color_dark","primaryColorDark")),accentColorDark:re(x(t,"accent_color_dark","accentColorDark")),surfaceStyle:uo(x(t,"surface_style","surfaceStyle"),Aa),radiusScale:uo(x(t,"radius_scale","radiusScale"),Fa),logoUrlDark:le(x(t,"logo_url_dark","logoUrlDark")),slots:ao(x(t,"slots")),accessibilityMaxFontScale:ja(x(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:La(x(t,"locked_fields","lockedFields")),schemaVersion:za(x(t,"schema_version","schemaVersion"))};return po(r)?null:Object.freeze(r)}i(ke,"parseClientBranding");function Oa(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(Oa,"parseBool");function x(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(x,"pick");function le(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(le,"parseNonEmptyString");var fo=["regular","medium","bold","mono","monoMedium","monoBold"];function lo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of fo){let o=le(x(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(lo,"parseFaceMap");var Aa=["white","cream","subtle"],Fa=["sharp","default","round"];function uo(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(uo,"parseEnum");function Ma(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(Ma,"parseBrightness");function mo(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(mo,"parseNumber");var Da=1,yo=3.1;function ja(e){let t=mo(e);return t===null?null:t<=0?0:Math.min(yo,Math.max(Da,t))}i(ja,"parseMaxFontScale");function za(e){if(e==null)return null;let t=mo(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(za,"parseSchemaVersion");function ho(e){let t=e.trim();return t.startsWith(Xe)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(ho,"toWireName");function La(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=ho(r);Ia(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(La,"parseLockedFields");var go="/widget/v1/entitlements",Ua=304,Na=Object.freeze({kind:"notModified"});async function vo(e,t={},r=$({auth:e})){let n=await r.send("entitlements.fetch",qa(t));return n.ok?Ha(n.value):n.error.httpStatus===Ua?Na:{kind:"failed",error:n.error}}i(vo,"fetchEntitlements");var Ba=64;function qa(e){let t={};return jt(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Ba?{method:"GET",path:go,headers:t,query:{region:e.region}}:{method:"GET",path:go,headers:t}}i(qa,"buildRequest");function Ha(e){if(e===null||typeof e!="object"||!jt(e.revision))return bo();let t=typeof e.region=="string"?e.region:"",r=jt(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:$a(e.capabilities),branding:Ka(e)})}i(Ha,"parseUpdated");function Ka(e){let t=ke(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=ke(r.branding);return n!==null?n:ke(r)}return null}i(Ka,"parseBranding");function $a(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Va(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i($a,"mapCapabilities");function Va(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Va,"isEnabled");function bo(){return {kind:"failed",error:S("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(bo,"malformed");function jt(e){return typeof e=="number"&&Number.isFinite(e)}i(jt,"isFiniteNumber");var Wa=30;function _o(e){let t=e.scheduler??Ga,r=e.resolve??vo,n=Math.max(1,e.floorSeconds??Wa),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),l=false,u=false,a=null,d=null,c=n,f=0,g=i(()=>{a!==null&&(t.clear(a),a=null);},"clearTimer"),y=i(P=>{u||!l||(c=Math.max(n,P),a=t.set(()=>{a=null,C();},c*1e3));},"schedule"),R=null,T=i(async()=>{if(u)return null;let P=f;e.onFetch?.();let O=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},D;try{D=await r(e.authFor(),O);}catch(A){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Ya(A)}),!u&&P===f&&(e.onSettled?.(),y(s())),null}if(u||P!==f)return null;switch(D.kind){case "updated":d=D.revision,e.update(D.decisions,D.branding??null),y(D.ttlSeconds);break;case "notModified":y(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:D.error.code}),y(s());break;default:y(s());}return e.onSettled?.(),D},"tick"),C=i(()=>{let P=T().finally(()=>{R===P&&(R=null);});return R=P,P},"run");return {start(){l||u||(l=true,C());},prime(){return u?Promise.resolve(null):R??C()},stop(){u||(u=true,f++,g());},refresh(){u||!l||(f++,d=null,g(),C());}}}i(_o,"createEntitlementPoller");var Ga={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function Ya(e){return e instanceof Error?e.message:"poll failed"}i(Ya,"describe");var Ro="everfur.notifications.device";var Co=3e3,Eo=Object.freeze([Ro]);function So(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),l=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),u=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:l.length});}catch{}},"report"),a=Promise.allSettled(l).then(d=>{let c=d.filter(f=>f.status==="rejected").length;c>0&&u("failed",c);});return new Promise(d=>{let c=false,f=i(()=>{c||(c=true,clearTimeout(g),d());},"finish"),g=setTimeout(()=>{c||u("timeout",l.length),f();},Co);a.then(f,f);})}i(So,"startBeforeLogoutHooks");function wo(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let l={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:l,userRef:t.userRef,sessionId:o}}i(wo,"graceAuth");async function ko(e,t){if(Eo.length===0)return;let r=await Promise.allSettled(Eo.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(ko,"sweepPerUserKv");function Xa(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Xa,"compiledDefaultDecisions");function zt(e=Xa){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(zt,"createEntitlementStore");function Lt(e){return S("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Lt,"notConfiguredError");function To(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return Mr(r,t===void 0?void 0:{platform:t})}i(To,"tryResolveClient");function Po(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Po,"guardTelemetry");function xo(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
- [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(xo,"reportConfigFailure");function Ut(e){return Object.freeze({request(){return Promise.resolve(p(Lt(e)))},stream(t,r){let n=N({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(Ut,"refusingTransport");function Io(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Io,"createInMemoryKv");var Oo=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function Np(e,t){return new Bt(e,t)}i(Np,"createEverfurRuntime");var Qa=6e4,qt=class qt{constructor(t,r){this.sessionId=st();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new K("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Po(n.telemetry):Me;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=lt(n?.publishableKey),l=n.transport!==void 0,u,a=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)u=Ut(s);else if(n.transport!==void 0)u=n.transport;else {let c=To(n,r?.platform);c.ok?(a=c.config.apiBaseUrl,u=Nr({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,u=Ut(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=u,s!==null&&xo(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??br,this.upload=n.upload??sn,this.uploadTransport=n.uploadTransport??Tt,this.imageCache=n.imageCache??Oo,this.kv=n.storage??Io(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?zt():zt(()=>io("sdk_config",ot("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",Nt(c),()=>this.buildChatController(c),Ao),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Nt(c)}`)?.controller??null,"peekChat"),acquire:i((c,f,g,y)=>this.acquireInternal(c,f,g,y),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!l);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Tr(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Qa,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return _o({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let l=`${this.epoch}|${t}|${r}`,u=this.entries.get(l);if(u)return s||(u.warm?u.warm=false:u.refCount+=1),u.controller;let a=n();return this.entries.set(l,{controller:a,refCount:1,warm:s}),this.destroyers.set(a,o),a}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=Sn({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Tn(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=st(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await ko(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return So({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>wo({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?p(Fo(t)):r(no(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(l=>(s.result=l,l))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Fo("prepare"):n===null?null:Lt(n),s=this.identity,[l,u,a]=await Promise.all([o?p(o):s===null?_(void 0):s.currentToken().then(()=>_(void 0),()=>p(S("authRejected",{retryable:false}))),o?p(o):this.primeEntitlements(),t===null?void 0:o?p(o):this.primeChat(t)]),d=l.ok?u.ok&&(a?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:l,entitlements:u,...a?{chat:a}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?p(t.error):_(void 0):p(S("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Nt(r),()=>this.buildChatController(r),Ao,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?p(o.cause):_(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(qt,"EverfurRuntimeImpl");var Bt=qt;function Nt(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Nt,"chatScopeKey");function Ao(e){e.dispose();}i(Ao,"disposeChat");function Fo(e){return S("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Fo,"disposedError");var jo=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Mo=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function Ja(e){let t=Object.prototype.hasOwnProperty.call(Mo,e)?Mo[e]:void 0;if(t!==void 0)return t;let r=e;return jo.has(r)?r:"parsing"}i(Ja,"normalizeStatus");function Za(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Za,"normalizeOrigin");var el=z$1.object({request_id:z$1.string().min(1),pet_ref:z$1.string().min(1),status:z$1.string(),simple_status:z$1.string().nullish(),simple_status_detail:z$1.string().nullish(),status_label:z$1.string().optional(),dispatch_status:z$1.string().nullish(),can_retry_send:z$1.boolean().optional(),can_revoke:z$1.boolean().optional(),can_convert_to_upload:z$1.boolean().optional(),can_update_clinic_email:z$1.boolean().optional(),reminder_count:z$1.number().int().nonnegative().optional(),last_reminder_at:z$1.string().nullish(),waiting_expectation:z$1.string().nullish(),document_count:z$1.number().optional(),held_item_count:z$1.number().optional(),received_at:z$1.string().nullish(),parsing_started_at:z$1.string().nullish(),review_started_at:z$1.string().nullish(),created_at:z$1.string().optional(),updated_at:z$1.string().optional(),source:z$1.string().nullish().catch(null),action_needed_label:z$1.string().nullish().catch(null),failure_reason:z$1.string().nullish().catch(null),failure_code:z$1.string().nullish().catch(null),recovery_stage:z$1.string().nullish().catch(null),show_clinic_phone:z$1.boolean().optional().catch(void 0),clinic_name:z$1.string().nullish().catch(null),clinic_email:z$1.string().nullish().catch(null),clinic_phone:z$1.string().nullish().catch(null),converted_to_upload_at:z$1.string().nullish().catch(null),request_group_id:z$1.string().nullish().catch(null)}).passthrough();function zo(e){let t=el.safeParse(e);if(!t.success)return null;let r=t.data,n=tl(r.simple_status),o=n==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":n==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":n??Ja(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:o,simpleStatus:n,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:Do(r.document_count,0),heldItemCount:Do(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(zo,"mapRequestView");z$1.object({request_group_id:z$1.string().min(1),pet_ref:z$1.string().min(1),total:z$1.number().int().nonnegative(),responded:z$1.number().int().nonnegative(),pending:z$1.number().int().nonnegative(),members:z$1.array(z$1.unknown())});function tl(e){return !e||e==="awaiting_upload"||e==="in_review"?null:jo.has(e)?e:null}i(tl,"normalizeSimpleStatus");z$1.object({source_doc_id:z$1.string().min(1),request_id:z$1.string().min(1)});var rl=z$1.object({label:z$1.string(),value:z$1.string()}),Ht=z$1.object({key:z$1.string(),category:z$1.string().optional(),label:z$1.string().optional(),value:z$1.string().nullish(),unit:z$1.string().nullish(),observed_at:z$1.string().nullish(),status:z$1.string().nullish(),origin:z$1.string().nullish(),canonical_key:z$1.string().nullish()}),nl=z$1.object({at:z$1.string(),value:z$1.number().nullish(),display:z$1.string().nullish(),origin:z$1.string().nullish()}),ol=z$1.object({key:z$1.string(),label:z$1.string().optional(),points:z$1.array(nl).optional()}),il=z$1.object({title:z$1.string(),detail:z$1.string().nullish(),due_at:z$1.string().nullish()}),Kt=z$1.object({doc_id:z$1.string(),title:z$1.string().nullish(),page_count:z$1.number().nullish(),received_at:z$1.string().nullish()});function Lo(e){return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:Za(e.origin),canonicalKey:e.canonical_key??null})}i(Lo,"mapEntityRow");function Uo(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Uo,"mapDocumentRow");z$1.object({identity:z$1.array(rl).optional(),entities:z$1.array(Ht).optional(),entity_series:z$1.array(ol).optional(),forward_looking:z$1.array(il).optional(),documents:z$1.array(Kt).optional()});z$1.object({pet_ref:z$1.string().optional(),granted:z$1.boolean().optional(),version:z$1.string().nullish(),granted_at:z$1.string().nullish()});function Do(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Do,"numberOr");var Bo=10,Qe=z$1.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Te=i((e,t=1)=>z$1.string().refine(r=>!L(r)&&[...r].length>=t&&[...r].length<=e),"text"),qo=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),sl=z$1.object({clinicId:Qe.optional(),clinicFreeText:Te(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Te(320,3).refine(e=>!qo(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Qe.optional(),signaturePngBase64:z$1.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z$1.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),al=z$1.object({petRef:Te(128),ownerName:Te(200).refine(e=>e.trim().length>0&&!qo(e)),authorizationVersion:Te(64),clinics:z$1.array(sl).min(1).max(Bo)}).strict(),ll=z$1.object({request_group_id:Qe,pet_ref:z$1.string(),created_count:z$1.number().int().nonnegative(),failed_count:z$1.number().int().nonnegative(),results:z$1.array(z$1.object({idempotency_key:z$1.string(),clinic_id:Qe.nullable().optional(),clinic_free_text:z$1.string().nullable().optional(),created:z$1.boolean(),request:z$1.unknown().optional(),failure_code:z$1.string().nullable().optional(),failure_reason:z$1.string().nullable().optional()}))});function ul(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!al.safeParse(r).success)return p(S("validationFailed",{retryable:false}));let n=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(l=>({...l.clinicId!==void 0?{clinic_id:l.clinicId}:{clinic_free_text:l.clinicFreeText},...l.clinicEmail!==void 0?{clinic_email:l.clinicEmail}:{},...l.signatureId!==void 0?{signature_id:l.signatureId}:{signature_png_base64:l.signaturePngBase64},idempotency_key:l.idempotencyKey}))}});if(!n.ok)return n;let o=ll.safeParse(n.value);if(!o.success||o.data.pet_ref!==r.petRef)return No();let s=[];for(let l of o.data.results){let u=l.request===void 0||l.request===null?null:zo(l.request);if(l.created!==(u!==null))return No();s.push(Object.freeze({idempotencyKey:l.idempotency_key,clinicId:l.clinic_id??null,clinicFreeText:l.clinic_free_text??null,created:l.created,request:u,failureCode:l.failure_code??null,failureReason:l.failure_reason??null}));}return _(Object.freeze({requestGroupId:o.data.request_group_id,petRef:o.data.pet_ref,results:Object.freeze(s),createdCount:o.data.created_count,failedCount:o.data.failed_count}))}}}i(ul,"createRecordsClinicBatchClient");function No(){return p(S("internalError",{retryable:false}))}i(No,"malformed");var dl="records_consent_required";function cl(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,n=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof n=="string"&&n.length>0?n:null}i(cl,"recordsWireCodeOf");function Ho(e){return e===null||e.httpStatus!==409?false:cl(e)===dl}i(Ho,"isRecordsConsentRequired");var $t="value_text",Ko=64,$o=512;function pl(e){return e!==null&&e.httpStatus===409&&!Ho(e)}i(pl,"isFactReviewerLocked");function fl(e){return Object.freeze({[$t]:e.trim()})}i(fl,"factValueCorrection");var Pe=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:$t}),Vo=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Wo=/^\d{4}-\d{2}-\d{2}$/;function Go(e){if(e==null)return "text";let t=e.trim();return Vo.test(t)?"num":Wo.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(Go,"inferFactValueKind");function ml(e,t){let r=t.trim(),n=Go(e);if(n==="num"&&Vo.test(r)){let o=Number(r);if(Number.isFinite(o))return Object.freeze({[Pe.num]:o})}return n==="date"&&Wo.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Pe.date]:r}):Object.freeze(n==="bool"&&(r==="true"||r==="false")?{[Pe.bool]:r==="true"}:{[Pe.text]:r})}i(ml,"factCorrectionFor");var k=z$1.string().nullish(),Je=z$1.number().nullish(),yl=z$1.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,ref_low:Je,ref_high:Je,status:k,source_clinic:k,source_doc_id:k,doc_id:k,reviewed:z$1.boolean().nullish()}),hl=z$1.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,status:k}),gl=z$1.object({marker_id:z$1.string().min(1),canonical_name:k,name:k,loinc_code:k,canonical_unit:k,unit:k,panel_name:k,panel:k,meaning_text:k,meaning:k,latest:hl.nullish(),trajectory:k,points:z$1.array(yl).optional()}),bl=z$1.object({total_markers:z$1.number().int().nonnegative(),in_range_count:z$1.number().int().nonnegative(),out_of_range_count:z$1.number().int().nonnegative(),unknown_count:z$1.number().int().nonnegative()}),vl=z$1.object({markers:z$1.array(gl).optional(),summary:bl.nullish(),disclaimer:z$1.string().optional(),featured_marker_id:k});function _l(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(_l,"isObject");function Yo(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Yo,"withheldMarkers");function Vt(e,t){let r=_l(t)?t:{},n=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Yo(n);let o=vl.safeParse(r);if(!o.success)return Yo(n);let s=o.data,l=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),u=(s.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(l))}));return Object.freeze({petRef:n,withheld:false,markers:Object.freeze(u),summary:s.summary?Object.freeze({totalMarkers:s.summary.total_markers,inRangeCount:s.summary.in_range_count,outOfRangeCount:s.summary.out_of_range_count,unknownCount:s.summary.unknown_count}):null,disclaimer:s.disclaimer??"",featuredMarkerId:s.featured_marker_id??null})}i(Vt,"mapRecordMarkers");var Rl=z$1.string().min(1).refine(e=>e.startsWith("https://")),El=z$1.object({source_doc_id:z$1.string().min(1),file_name:z$1.string().nullish(),doc_format:z$1.string().nullish(),byte_size:z$1.number().int().nonnegative().nullish(),received_at:z$1.string().nullish(),download_url:Rl,expires_in_seconds:z$1.number().int().nonnegative().nullish()}),Cl=z$1.object({items:z$1.array(z$1.unknown()).optional()});function Xo(e){let t=Cl.safeParse(e);if(!t.success)return null;let r=[];for(let n of t.data.items??[]){let o=El.safeParse(n);o.success&&r.push(Object.freeze({sourceDocId:o.data.source_doc_id,fileName:o.data.file_name??null,docFormat:o.data.doc_format??null,byteSize:o.data.byte_size??null,receivedAt:o.data.received_at??null,downloadUrl:o.data.download_url,expiresInSeconds:o.data.expires_in_seconds??0}));}return Object.freeze(r)}i(Xo,"mapRequestDocuments");var Sl=z$1.string().min(1).refine(e=>e.startsWith("https://")),xe=z$1.string().nullish(),wl=z$1.object({share_id:z$1.string().min(1),share_url:z$1.string().min(1),expires_at:xe}),kl=z$1.object({shares:z$1.array(z$1.object({share_id:z$1.string().min(1),expires_at:xe,created_at:xe,view_count:z$1.number().int().nonnegative().nullish(),last_viewed_at:xe})).optional()}),Tl=z$1.object({download_url:Sl,expires_at:xe});function Qo(e,t){let r=e.trim();if(r.length===0)return null;try{let n=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return n===null||n.protocol!=="https:"?null:n.toString()}catch{return null}}i(Qo,"resolveShareUrl");function Wt(e,t){let r=wl.safeParse(e);if(!r.success)return null;let n=Qo(r.data.share_url,t);return n===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:n,expiresAt:r.data.expires_at??null})}i(Wt,"mapRecordShareLink");function Gt(e){let t=kl.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(Gt,"mapRecordShareList");function Yt(e){let t=Tl.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Yt,"mapRecordPdfLink");var Pl=z$1.object({signatures:z$1.array(z$1.object({signature_id:z$1.string().min(1),preview_url:z$1.string().min(1).refine(e=>e.startsWith("https://")),created_at:z$1.string().nullish()})).optional()});function Xt(e){let t=Pl.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(Xt,"mapSignatureSuggestions");var b=z$1.string().nullish(),Ie=z$1.number().nullish(),xl=z$1.object({at:b,value:Ie,unit:b,qualitative_result:b,ref_low:Ie,ref_high:Ie,status:b,doc_id:b}),Il=z$1.object({marker_id:z$1.string(),name:z$1.string(),loinc_code:b,unit:b,panel:b,meaning:b,latest:z$1.object({at:b,value:Ie,unit:b,qualitative_result:b,status:b}).nullish(),trajectory:b,points:z$1.array(xl).optional()}),Ol=z$1.object({encounter_id:z$1.string(),date:b,type:b,clinic_name:b,veterinarian:b,doc_id:b}),Al=z$1.object({note_id:z$1.string(),encounter_id:b,observed_on:b,sections:z$1.array(z$1.object({section:z$1.string(),text:z$1.string()})).optional()}),Fl=z$1.object({exam_id:z$1.string(),encounter_id:b,observed_on:b,doc_id:b,systems:z$1.record(z$1.object({finding_status:b,finding:b})).optional()}),Ml=z$1.object({has_lab_history:z$1.boolean().optional(),has_vaccination_history:z$1.boolean().optional(),has_weight_history:z$1.boolean().optional(),has_vitals_history:z$1.boolean().optional(),has_physical_exam_history:z$1.boolean().optional(),has_procedure_history:z$1.boolean().optional(),has_genetic_history:z$1.boolean().optional(),has_reproductive_history:z$1.boolean().optional(),has_parasite_prevention_history:z$1.boolean().optional(),earliest_record_at:b,latest_record_at:b,documents_ingested:z$1.number().int().nonnegative().optional(),documents_in_review:z$1.number().int().nonnegative().optional(),entities_pending_review:z$1.record(z$1.number().int().nonnegative()).optional(),held_total:z$1.number().int().nonnegative().optional()}),Dl=z$1.object({conflict_id:z$1.string(),entity_type:z$1.string(),field:b,severity:b,candidates:z$1.array(z$1.object({value:z$1.string(),source_doc_id:b,doc_id:b,collected_at:b})).optional()}),jl=z$1.object({lab_results:z$1.array(Il).optional(),encounters:z$1.array(Ol).optional(),clinician_notes:z$1.array(Al).optional(),physical_exams:z$1.array(Fl).optional(),completeness:Ml.nullish(),conflicts:z$1.array(Dl).optional()}),zl=z$1.object({visits:z$1.array(z$1.object({visit_id:z$1.string(),visit_date:b,veterinarian:b,summary:b,doc_id:b})),vaccines:z$1.array(z$1.object({vaccine_id:z$1.string(),product:b,lot:b,administered_on:b,expires_on:b,doc_id:b})),weights:z$1.array(z$1.object({weight_id:z$1.string(),observed_on:b,weight_kg:Ie,doc_id:b})),medications:z$1.array(z$1.object({medication_id:z$1.string(),drug_name:b,dose:b,route:b,frequency:b,sig:b,rx_number:b,started_on:b,stopped_on:b,doc_id:b})),disclaimer:z$1.string().optional()}),Ll=z$1.object({document:Kt,contributions:z$1.array(Ht),contribution_count:z$1.number().int().nonnegative().optional()});function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Jt,"isObject");function Zt(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Zt,"petOf");function Qt(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(Qt,"emptyDepth");function Zo(e,t){let r=Jt(t)?t:{},n=Zt(r,e);if(r.withheld===true)return Qt(n,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Qt(n,false);let s=jl.safeParse(r);if(!s.success)return Qt(n,true);let l=s.data,u=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:n,available:true,withheld:false,labResults:Object.freeze((l.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(u))}))),encounters:Object.freeze((l.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((l.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((l.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,c])=>Object.freeze({system:d,findingStatus:c.finding_status??null,finding:c.finding??null})))}))),completeness:l.completeness?Object.freeze({hasLabHistory:l.completeness.has_lab_history===true,hasVaccinationHistory:l.completeness.has_vaccination_history===true,hasWeightHistory:l.completeness.has_weight_history===true,hasVitalsHistory:l.completeness.has_vitals_history===true,hasPhysicalExamHistory:l.completeness.has_physical_exam_history===true,hasProcedureHistory:l.completeness.has_procedure_history===true,hasGeneticHistory:l.completeness.has_genetic_history===true,hasReproductiveHistory:l.completeness.has_reproductive_history===true,hasParasitePreventionHistory:l.completeness.has_parasite_prevention_history===true,earliestRecordAt:l.completeness.earliest_record_at??null,latestRecordAt:l.completeness.latest_record_at??null,documentsIngested:l.completeness.documents_ingested??0,documentsInReview:l.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...l.completeness.entities_pending_review??{}}),heldTotal:l.completeness.held_total??0}):null,conflicts:Object.freeze((l.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(Zo,"mapRecordDepth");function Jo(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Jo,"withheldTimeline");function ei(e,t){let r=Jt(t)?t:{},n=Zt(r,e);if(r.withheld===true)return Jo(n);let o=zl.safeParse(r);if(!o.success)return Jo(n);let s=o.data,l=s.visits.map(c=>Object.freeze({visitId:c.visit_id,visitDate:c.visit_date??null,veterinarian:c.veterinarian??null,summary:c.summary??null,docId:c.doc_id??null})),u=s.vaccines.map(c=>Object.freeze({vaccineId:c.vaccine_id,product:c.product??null,lot:c.lot??null,administeredOn:c.administered_on??null,expiresOn:c.expires_on??null,docId:c.doc_id??null})),a=s.weights.map(c=>Object.freeze({weightId:c.weight_id,observedOn:c.observed_on??null,weightKg:c.weight_kg??null,docId:c.doc_id??null})),d=s.medications.map(c=>Object.freeze({medicationId:c.medication_id,drugName:c.drug_name??null,dose:c.dose??null,route:c.route??null,frequency:c.frequency??null,sig:c.sig??null,rxNumber:c.rx_number??null,startedOn:c.started_on??null,stoppedOn:c.stopped_on??null,docId:c.doc_id??null}));return Object.freeze({petRef:n,withheld:false,isEmpty:l.length===0&&u.length===0&&a.length===0&&d.length===0,visits:Object.freeze(l),vaccines:Object.freeze(u),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:s.disclaimer??""})}i(ei,"mapRecordsTimeline");function ti(e,t){let r=Jt(t)?t:{},n=Zt(r,e),o=i(()=>Object.freeze({petRef:n,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return o();let s=Ll.safeParse(r);if(!s.success)return o();let l=Object.freeze(s.data.contributions.map(Lo));return Object.freeze({petRef:n,withheld:false,document:Uo(s.data.document),contributions:l,contributionCount:s.data.contribution_count??l.length})}i(ti,"mapDocumentContributions");var Ul="/widget/v1/records/pets";function Nl(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!L(a)&&[...a].length<=d,"segment"),n=i(async(a,d,c,f)=>{if(!r(d,oe))return ne();let g=await t.send(a,{method:"GET",path:c});if(!g.ok)return g;let y=f(g.value);return y.petRef===d?_(y):p(S("internalError",{retryable:false}))},"read"),o=i(a=>`${Ul}/${encodeURIComponent(a)}`,"pet"),s=i(a=>`${o(a)}/everfur_record`,"record"),l=i(async(a,d,c)=>{let f=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!f.ok)return f;let g=c(f.value);return g===null?p(S("internalError",{retryable:false})):_(g)},"parsed"),u=i((a,d)=>!r(a.entityType,Ko)||!r(a.canonicalKey,$o)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,xn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>n("records.depth.record",a,`${o(a)}/record`,d=>Zo(a,d)),"getRecordDepth"),getTimeline:i(a=>n("records.depth.timeline",a,`${o(a)}/timeline`,d=>ei(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?n("records.depth.contributions",a,`${o(a)}/documents/${encodeURIComponent(d)}/contributions`,c=>ti(a,c)):ne()},getMarkers:i(a=>n("records.depth.markers",a,`${o(a)}/markers`,d=>Vt(a,d)),"getMarkers"),createShare(a){return r(a,oe)?l("records.share.create",{method:"POST",path:`${s(a)}/share`},d=>Wt(d,e.apiBaseUrl)):ne()},listShares(a){return r(a,oe)?l("records.share.list",{method:"GET",path:`${s(a)}/shares`},Gt):ne()},async revokeShare(a,d){if(!r(a,oe)||!r(d,64))return ne();let c=await t.send("records.share.revoke",{method:"DELETE",path:`${s(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return c.ok?_(void 0):c},getPdfLink(a){return r(a,oe)?l("records.pdf.link",{method:"GET",path:`${s(a)}/pdf-link`},Yt):ne()},async editFact(a,d){let c=r(a,oe)?u(d,d.correctedFields):null;if(c===null)return ne();let f=await t.send("records.fact.edit",{method:"POST",path:`${s(a)}/facts/edit`,body:c},{idempotent:false,maxAttempts:1});return f.ok?_(void 0):f},async removeFact(a,d){let c=r(a,oe)?u(d):null;if(c===null)return ne();let f=await t.send("records.fact.remove",{method:"POST",path:`${s(a)}/facts/remove`,body:c},{idempotent:false,maxAttempts:1});return f.ok?_(void 0):f},listRequestDocuments(a){return r(a,64)?l("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},Xo):ne()},listAuthorizationSignatures:i(()=>l("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Xt),"listAuthorizationSignatures")}}i(Nl,"createRecordsDepthClient");function ne(){return Promise.resolve(p(S("validationFailed",{retryable:false})))}i(ne,"invalid");var Ae=Object.freeze({width:360,height:120});function ii(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(ii,"blank");function si(e,t,r,n){for(let o=-n;o<=n;o+=1)for(let s=-n;s<=n;s+=1){if(s*s+o*o>n*n+n)continue;let l=t+s,u=r+o;l<0||u<0||l>=e.width||u>=e.height||(e.pixels[u*e.width+l]=1);}}i(si,"stamp");var Bl=16384;function ql(e,t){let[r,n]=e;if(!Number.isFinite(r)||!Number.isFinite(n))return null;let o=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),s=Math.min(2*t.height,Math.max(-t.height,Math.round(n)));return [o,s]}i(ql,"padPoint");function Hl(e,t,r,n,o){let[s,l]=t,[u,a]=r,d=Math.abs(u-s),c=-Math.abs(a-l),f=s<u?1:-1,g=l<a?1:-1,y=d+c,R=0;for(;R<o&&(si(e,s,l,n),R+=1,!(s===u&&l===a));){let T=2*y;T>=c&&(y+=c,s+=f),T<=d&&(y+=d,l+=g);}return R}i(Hl,"line");function Kl(e,t=1){let r=ii(Ae.width,Ae.height);for(let n of e){let o=[];for(let l of n){let u=ql(l,r);u!==null&&o.push(u);}if(o.length===0)continue;if(o.length===1){let[l,u]=o[0];si(r,l,u,t);continue}let s=Bl;for(let l=1;l<o.length&&s>0;l+=1)s-=Hl(r,o[l-1],o[l],t,s);}return r}i(Kl,"rasterizeStrokes");var $l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",Vl="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",Wl="0123456789abcdefghijklmnopqrstuv",ir=5,sr=7,er=ir+1;function Gl(e,t){let r=$l.indexOf(e);return r<0?0:Wl.indexOf(Vl.charAt(r*sr+t))}i(Gl,"glyphRow");function Yl(e){let t=ii(Ae.width,Ae.height),r=e.trim();if(r.length===0)return t;let n=[...r],o=4;for(;o>1&&(n.length*er-1)*o>t.width-8;)o-=1;let s=(n.length*er-1)*o,l=Math.max(0,Math.floor((t.width-s)/2)),u=Math.floor((t.height-sr*o)/2);return n.forEach((a,d)=>{let c=l+d*er*o;for(let f=0;f<sr;f+=1){let g=Gl(a,f);for(let y=0;y<ir;y+=1)if((g>>ir-1-y&1)!==0)for(let R=0;R<o;R+=1)for(let T=0;T<o;T+=1){let C=c+y*o+T,P=u+f*o+R;C<t.width&&P<t.height&&(t.pixels[P*t.width+C]=1);}}}),t}i(Yl,"rasterizeTypedName");var ur=class ur{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let n=0;for(let o=0;o<r;o+=1)n=n<<1|t>>o&1;this.writeBits(n,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(ur,"BitWriter");var ar=ur;function lr(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(lr,"writeLiteral");var tr=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ri=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],rr=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ni=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function Xl(e,t,r){let n=tr.length-1;for(;tr[n]>t;)n-=1;lr(e,257+n),ri[n]>0&&e.writeBits(t-tr[n],ri[n]);let o=rr.length-1;for(;rr[o]>r;)o-=1;e.writeCode(o,5),ni[o]>0&&e.writeBits(r-rr[o],ni[o]);}i(Xl,"writeMatch");var Ql=32768,nr=3,Jl=258,oi=15,Zl=64;function eu(e){let t=new ar;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<oi).fill(-1),n=new Int32Array(e.length).fill(-1),o=i(u=>(e[u]<<10^e[u+1]<<5^e[u+2])&(1<<oi)-1,"hashAt"),s=i(u=>{if(u+nr>e.length)return;let a=o(u);n[u]=r[a],r[a]=u;},"insert"),l=0;for(;l<e.length;){let u=0,a=0;if(l+nr<=e.length){let d=r[o(l)],c=0,f=Math.min(Jl,e.length-l);for(;d>=0&&c<Zl&&l-d<=Ql;){let g=0;for(;g<f&&e[d+g]===e[l+g];)g+=1;if(g>u&&(u=g,a=l-d,g===f))break;d=n[d],c+=1;}}if(u>=nr){Xl(t,u,a);for(let d=0;d<u;d+=1)s(l+d);l+=u;}else lr(t,e[l]),s(l),l+=1;}return lr(t,256),t.finish()}i(eu,"deflate");function tu(e){let t=1,r=0;for(let n of e)t=(t+n)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(tu,"adler32");var Ze=null;function ru(e){if(Ze===null){Ze=new Uint32Array(256);for(let r=0;r<256;r+=1){let n=r;for(let o=0;o<8;o+=1)n=n&1?3988292384^n>>>1:n>>>1;Ze[r]=n>>>0;}}let t=4294967295;for(let r of e)t=Ze[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(ru,"crc32");function Oe(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(Oe,"u32");function or(e,t){let r=Uint8Array.from([...e].map(o=>o.charCodeAt(0))),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),[...Oe(t.length),...n,...Oe(ru(n))]}i(or,"chunk");var et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function nu(e){let t="";for(let r=0;r<e.length;r+=3){let n=e[r],o=r+1<e.length?e[r+1]:0,s=r+2<e.length?e[r+2]:0,l=n<<16|o<<8|s;t+=et.charAt(l>>18&63)+et.charAt(l>>12&63),t+=r+1<e.length?et.charAt(l>>6&63):"=",t+=r+2<e.length?et.charAt(l&63):"=";}return t}i(nu,"toBase64");function ou(e){let{width:t,height:r,pixels:n}=e,o=Math.ceil(t/8)+1,s=new Uint8Array(o*r);for(let c=0;c<r;c+=1){let f=c*o;s[f]=0,s.fill(255,f+1,f+o);for(let g=0;g<t;g+=1)if(n[c*t+g]===1){let y=f+1+(g>>3);s[y]=s[y]&~(128>>(g&7));}}let l=eu(s),u=new Uint8Array(2+l.length+4);u[0]=120,u[1]=1,u.set(l,2),u.set(Oe(tu(s)),2+l.length);let a=Uint8Array.from([...Oe(t),...Oe(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...or("IHDR",a),...or("IDAT",u),...or("IEND",new Uint8Array(0))]);return nu(d)}i(ou,"encodeSignaturePng");
13
- export{mc as ATTACHMENT_ACCEPT,ta as ATTACHMENT_BACKOFF_MS,Ks as ATTACHMENT_INITIATE_PATH,ea as ATTACHMENT_MAX_ATTEMPTS,qs as ATTACHMENT_MIME_TYPES,Zs as ATTACHMENT_QUEUE_CONCURRENCY,Rt as CHAT_FEEDBACK_TYPES,ge as CHECKIN_ANSWERABLE_STATUS,Pe as FACT_FIELD_BY_KIND,$t as FACT_VALUE_FIELD,Et as FEEDBACK_NOTES_MAX_CHARS,Co as LOGOUT_HOOK_BUDGET_MS,Hs as MAX_ATTACHMENTS_PER_MESSAGE,On as MAX_ATTACHMENT_BYTES,Ee as MAX_FILENAME_LENGTH,Ke as MAX_IMAGE_KEYS_PER_MESSAGE,Ct as MESSAGE_MAX_CHARS,Wa as MIN_POLL_INTERVAL_SECONDS,uu as NULL_SECURE_STORE,Bo as RECORDS_CLINIC_BATCH_MAX,Ae as SIGNATURE_CANVAS,Ws as attachmentSize,Tn as bootstrapChat,hc as createAttachmentQueue,Sn as createChatController,_o as createEntitlementPoller,Np as createEverfurRuntime,ul as createRecordsClinicBatchClient,Nl as createRecordsDepthClient,gr as defaultErrorPolicy,ou as encodeSignaturePng,ml as factCorrectionFor,fl as factValueCorrection,yc as formatBytes,Go as inferFactValueKind,Qs as initiateAttachmentUpload,$s as isAttachmentMime,As as isCheckinSettled,pl as isFactReviewerLocked,ti as mapDocumentContributions,Zo as mapRecordDepth,Vt as mapRecordMarkers,Yt as mapRecordPdfLink,Wt as mapRecordShareLink,Gt as mapRecordShareList,ei as mapRecordsTimeline,Xt as mapSignatureSuggestions,Me as noopTelemetry,ku as optionalModule,Kl as rasterizeStrokes,Yl as rasterizeTypedName,Qo as resolveShareUrl,Vs as sanitizeFilename,br as unavailableCamera,Js as uploadAttachmentBytes,Gs as validateAttachment};
11
+ `));}u(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",l);function u(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",l);try{e.close();}catch{}}}return i(u,"cleanup"),Gi(r.source,u)}i(Wi,"eventSourceByteSource");async function*Gi(e,t){try{yield*e;}finally{t();}}i(Gi,"sourceWithCleanup");function Yi(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(l=>{r=l;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(Yi,"createByteQueue");async function Xi(e,t){let r=t.fetchImpl??Kr(),n=$r(t.config.apiBaseUrl,e.path,e.query),o=Vr(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=rs(Vi),l=ns(s.signal,e.signal),u;try{u=await r(n,Wr({...e,signal:l},o));}catch(d){return p(ct(d))}finally{s.cancel();}let a=await Gr(u);return u.ok?_(a):p(Zi(u.status,a,qr(u)))}i(Xi,"requestJson");function Br(e){return {request:i(t=>Xi(t,e),"request"),stream:i((t,r)=>Qi(ts(t,r),e),"stream")}}i(Br,"createHttpTransport");async function*Qi(e,t){let r=$r(t.config.apiBaseUrl,e.path,e.query),n=Vr(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let u=t.eventSourceFactory(r,Ji(e,n));yield*Ue(Wi(u),()=>es(u));return}let o=t.fetchImpl??Kr(),s;try{s=await o(r,Wr(e,n));}catch(u){yield Lr("",true,Jr(u));return}let l=qr(s);if(!s.ok){let u=await Gr(s),a=Yr(u)??Hr(s.status),d=Qr(u)||ee(Y(a));yield Lr(a,d,Xr(u),l);return}if(s.body){yield*Ue(zr(s.body),l);return}yield*Ue(zr(null),l);}i(Qi,"streamFrames");function Ji(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Ji,"buildEventSourceInit");function Zi(e,t,r){let n=Yr(t),o=n?Y(n):hr(e),s=Xr(t);return S(o,{httpStatus:e,...Qr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Ur(t)?{reasonCode:Ur(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Zi,"errorFromResponse");function ct(e){return S("internalError",{retryable:true,wireMessage:Jr(e)})}i(ct,"networkError");function qr(e){let t=e.headers.get(Nr);return typeof t=="string"&&t.length>0?t:null}i(qr,"requestIdOf");function es(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Nr);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(es,"eventSourceRequestId");function Hr(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(Hr,"statusToWireCode");function Lr(e,t,r,n=null){return N({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(Lr,"syntheticErrorFrame");function Kr(){let e=globalThis.fetch;if(typeof e!="function")throw new K("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Kr,"getGlobalFetch");function $r(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(l=>l[1]!==void 0).map(([l,u])=>`${encodeURIComponent(l)}=${encodeURIComponent(String(u))}`).join("&");s&&(o+=`?${s}`);}return o}i($r,"buildUrl");function Vr(e,t,r,n){let o={...jr(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Vr,"mergeHeaders");function Wr(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(Wr,"buildInit");function ts(e,t){return e.signal?e:{...e,signal:t}}i(ts,"withSignal");function rs(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(rs,"timeoutSignal");function ns(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(ns,"mergeAbortSignals");async function Gr(e){try{return await e.json()}catch{return null}}i(Gr,"safeJson");function Ur(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Ur,"extractReasonCode");function Yr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Yr,"extractWireCode");function Xr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Xr,"extractWireMessage");function Qr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Qr,"extractRetryable");function Jr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Jr,"describeCause");var os=3e4,is=nt*2,ss="idempotency-key",as=new Set(["POST","PUT","PATCH","DELETE"]),ls=Object.freeze({onEvent(){}}),us=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ds(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(ds,"seededIdempotencyKey");function $(e){let t=e.observer??ls,r=e.timers??us,n=e.rng??Math.random,o=e.sleep??((g,y)=>Ss(g,r,y)),s=e.maxAttempts??pe,l=e.unaryTimeoutMs??os,u=e.newIdempotencyKey??ps(),a=i(g=>{try{t.onEvent(g);}catch{}},"emit");async function d(g,y,R){let T=R?.maxAttempts,C=Math.max(1,T??s),P=R?.idempotent??as.has(y.method),O=R?.idempotencyKey===void 0?null:ds(R.idempotencyKey),M=P?O??u():null,A=cs(y,M),v=0;for(;;){let w=i(ue=>Object.freeze({call:g,method:y.method,path:y.path,attempt:v,...M?{idempotencyKey:M}:{},...ue}),"stamp");a(w({phase:"attempt"}));let j=Es(l,r),B=Cs(j.signal,y.signal),q;try{q=await Ir({...A,signal:B.signal},e.auth);}catch(ue){q=p(ct(ue));}finally{B.dispose(),j.cancel();}if(q.ok)return a(w({phase:"settled",ok:true,reason:"ok"})),q;let H=q.error,ie=ms(H,v,{maxAttempts:C,rng:n,now:r.now(),aborted:y.signal?.aborted===true,...T!==void 0?{perCallMaxAttempts:T}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),ce={ok:false,code:H.code,reason:ie.reason,...H.httpStatus!==void 0?{httpStatus:H.httpStatus}:{},...H.requestId!==void 0?{requestId:H.requestId}:{}};if(!ie.retry)return a(w({phase:"settled",...ce})),p(H);if(a(w({phase:"retry",...ce,delayMs:ie.delayMs})),await o(ie.delayMs,y.signal),y.signal?.aborted===true)return a(w({phase:"settled",...ce,reason:"aborted"})),p(H);v+=1;}}i(d,"send");async function c(g){return fe(g,await Rs(e.auth))}i(c,"authorize");async function*f(g,y,R){a(Object.freeze({call:g,phase:"stream.open",method:y.method,path:y.path,attempt:0}));try{yield*e.auth.transport.stream(y,R);}catch{yield N({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(f,"stream"),Object.freeze({send:d,authorize:c,stream:f})}i($,"createRequestFunnel");function cs(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==ss&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(cs,"assembleHeaders");function ps(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(ps,"defaultIdempotencyKeyFactory");var fs=10;function ms(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=ys(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!ee(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let l=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(fs,Math.floor(d)))},"policyCeiling"),u=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=u)return {retry:false,reason:"attempts-exhausted"};let a=hs(e,r.now);return a!==null?a>is?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:a}:{retry:true,reason:o,delayMs:ze(t,r.rng)}}i(ms,"decideRetry");function ys(e){let t=e.code==="unknown"?Y(_s(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(ys,"throttleKind");function hs(e,t){let r=bs(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=gs(e.raw);return n===null?null:Math.round(n*1e3)}i(hs,"retryOverrideMs");function gs(e){for(let t of pt(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(gs,"findRetryAfterSeconds");function bs(e){for(let t of pt(e)){let r=t.resets_at,n=vs(r);if(n!==null)return n}return null}i(bs,"findResetsAt");function pt(e){if(!Zr(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Zr(n)&&t.push(n);}return t}i(pt,"candidateScopes");function vs(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(vs,"parseInstantMs");function _s(e){for(let t of pt(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(_s,"rawWireCode");function Zr(e){return typeof e=="object"&&e!==null}i(Zr,"isRecord");async function Rs(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Rs,"resolveDeviceAuth");function Es(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(Es,"boundedSignal");function Cs(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(Cs,"mergeSignals");function Ss(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(Ss,"delayAbortable");function L(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(L,"hasLoneSurrogate");function Be(e){return [...e].length}i(Be,"serverLength");var on=Object.freeze(["better","same","worse"]),mt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function en(e){return p(S("validationFailed",{retryable:false,wireMessage:e}))}i(en,"invalid");function ft(){return p(S("internalError",{retryable:false}))}i(ft,"malformed");function tn(e){return typeof e!="string"||e.trim().length===0?S("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):L(e)?S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(tn,"petPath");var te=i(e=>typeof e=="string"?e:null,"str"),rn=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function nn(e){if(typeof e!="object"||e===null)return null;let t=e,r=te(t.case_id),n=te(t.status);if(r===null||n===null)return null;let o=te(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:te(t.body_location),lastResponse:o!==null&&on.includes(o)?o:null,checkInDueAt:te(t.check_in_due_at),openedAt:te(t.opened_at),resolvedAt:te(t.resolved_at),resolutionText:te(t.resolution_text),checkinAskCount:rn(t.checkin_ask_count),checkinAnswerCount:rn(t.checkin_answer_count)})}i(nn,"caseFromWire");function sn(e){return {async list(t,r){let n=tn(t);if(typeof n!="string")return p(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return p(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return ft();let l=s.map(nn);return l.every(u=>u!==null)?_(Object.freeze(l)):ft()},async checkin(t,r,n,o){let s=tn(t);if(typeof s!="string")return p(s);if(typeof r!="string"||!mt.test(r))return en("case_id must be a UUID");if(!on.includes(n))return en("response must be one of better, same, worse");let l=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!l.ok)return p(l.error);let u=typeof l.value=="object"&&l.value!==null?l.value:{},a=nn(u.case);return a===null?ft():_(Object.freeze({case:a,ctaDeepLink:te(u.cta_deep_link)}))}}}i(sn,"createCasesRepositoryOver");var an=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ln=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function He(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(He,"delayAbortable");function Ke(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Ke,"mergeSignals");var yt=class yt{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?Ke(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(yt,"MediaStore");var qe=yt;function gt(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(gt,"makeUser");function bt(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(bt,"makeAssistant");function he(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(he,"stripPending");function un(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(un,"appendText");function vt(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(vt,"finalizeAssistant");function dn(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(dn,"freezeSnapshot");function E(e,t,r){return S(e,{retryable:t,...r?{wireMessage:r}:{}})}i(E,"makeError");function _t(e){let t=Y(e.code);return S(t,{retryable:e.retryable||je(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(_t,"errorFromFrame");function X(e){return N({code:ws(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(X,"synthErrorFrame");function ws(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Le(e)}}i(ws,"canonicalWireCode");function cn(e){let t=Array.isArray(e)?e:ht(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!ht(n))continue;let o=ye(n.category)??ye(n.title)??"",s=ks(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(cn,"parsePromptCategories");function Rt(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(Rt,"flattenPrompts");function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ht,"isPlainObject");function ye(e){return typeof e=="string"?e:null}i(ye,"asStr");function ks(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(ht(r)){let n=ye(r.text)??ye(r.prompt)??ye(r.title);n!==null&&t.push(n);}return t}i(ks,"asPromptTextList");function pn(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(pn,"defaultIdFactory");function fn(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(fn,"defaultIdempotencyFactory");var yn={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*hn(e,t,r,n){let o=e[Symbol.asyncIterator](),s=mn(t.overallMs,n),l=mn(t.idleMs,n),u=xs(r);try{for(;;){if(r.aborted)return;let a=o.next().then(f=>({tag:"next",value:f}),()=>({tag:"streamError"})),d=await Promise.race([a,l.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),u.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield Ps();return}if(d.tag==="idle"||d.tag==="overall"){yield Ts();return}let c=d.value;if(c.done||(l.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{l.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(hn,"withWatchdog");function Ts(){return N({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ts,"synthTimeoutFrame");function Ps(){return N({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ps,"synthStreamErrorFrame");function mn(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(mn,"deadline");function xs(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(xs,"abortPromise");var Is="checkin",Os=/^\d{4}-\d{2}-\d{2}$/,ge="watching";function As(e){return e.status!=null&&e.status!==ge}i(As,"isCheckinSettled");function gn(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(gn,"isLiveAskAnswered");function Fs(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Is||n===void 0||o===void 0||!mt.test(n)||!Os.test(o)?null:{caseId:n,dueDay:o}}i(Fs,"parseCheckinOrigin");function bn(e){return Fs(e)?.caseId??null}i(bn,"parseCheckinOriginRef");function Et(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return p(S("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||L(o))return p(S("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),_(r.length?`?${r.join("&")}`:"")}i(Et,"historyQuery");function _e(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(_e,"validConversationId");function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(ve,"object");function vn(e){return e==null||typeof e=="string"&&e.length>0&&!L(e)}i(vn,"cursor");function be(){return p(S("internalError",{retryable:false}))}i(be,"malformed");function _n(e){let t=ve(e);if(!t||!Array.isArray(t.conversations)||!vn(t.next_cursor))return be();let r=[];for(let n of t.conversations){let o=ve(n);if(!o||typeof o.conversation_id!="string"||!_e(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return be();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return be();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return _(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(_n,"mapConversationPage");function Rn(e){let t=ve(e);if(!t||!Array.isArray(t.messages)||!vn(t.next_cursor))return be();let r=[],n=new Set;for(let o of t.messages){let s=ve(o);if(!s||typeof s.message_id!="string"||!_e(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return be();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let l=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,u=s.role==="assistant"?bn(l):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Ms(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Ds(s.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...u!==null?{checkin:Object.freeze({caseId:u,answer:null,resolutionText:null,status:null})}:{}}));}return _(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(Rn,"mapMessagePage");function Ms(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Ms,"normalizeUrgency");function Ds(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=ve(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let l=n[s];(typeof l=="string"||l===null)&&(o[s]=l);}return [Object.freeze(o)]}))}i(Ds,"historyCitations");var $e=5,Ct=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),St=4e3;var wt=4e3;function En(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:E("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:E("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(En,"validateImageKeys");function kt(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:E("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>wt?{reason:"too_long",error:E("validationFailed",false,`message is ${r} characters; the server accepts at most ${wt}`)}:null}i(kt,"validateMessageText");function Cn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Cn,"urgencyTier");async function*Re(e){yield e;}i(Re,"singleFrameStream");async function*Sn(){}i(Sn,"emptyStream");var js=6e4,zs=18e4,Ls=24,Us=512,Ns=false;function wn(e){return new Tt(e)}i(wn,"createChatController");var Pt=class Pt extends qe{constructor(r){super(dn({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??$({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=sn(this.funnel),this.telemetry=r.telemetry??Me,this.errorPolicy=r.errorPolicy??vr,this.timers=r.timers??yn,this.rng=r.rng??Math.random,this.newId=r.newId??pn(),this.makeIdempotencyKey=r.makeIdempotencyKey??fn(),this.budget={idleMs:r.budget?.idleMs??js,overallMs:r.budget?.overallMs??zs};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let a=E(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(a),()=>{}):Re(X(a))}let l=kt(r)??En(s.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),o?(o.onError(l.error),()=>{}):Re(X(l.error));if(o)return this.driveWithHandlers(r,s,o);let u=this.beginTurn(r,s);return this.runTurn(u,s.signal)}askEverfur(r,n){if(this.disposed)return Re(X(E("accessDenied",false)));let o=kt(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Re(X(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):Sn()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,gt(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?he(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(r=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=r,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:r,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}newConversation(){this.disposed||this.resetThread(this.scopePrompts);}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(Rt(r));this.bootstrapPrompts=n,this.scopePrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=Et(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(E("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return p(E("accessDenied",false));if(!l.ok)return l;let u=_n(l.value);if(u.ok){for(let c of u.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let a=this.snapshot.conversationId,d=a===null?void 0:this.unreadByConversation.get(a);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return u}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return p(E("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let a=await this.resumeConversation(n);return a.ok?_(n):p(a.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return p(s.error);let l=s.value.conversations[0];if(l===void 0)return _(null);let u=await this.resumeConversation(l.id);return u.ok?_(l.id):p(u.error)}async markRead(r){if(this.disposed)return p(E("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return _(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?p(E("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),_(void 0)):p(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return p(E("accessDenied",false));if(typeof r!="string"||r.trim().length===0||L(r))return p(E("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Ct.includes(n))return p(E("validationFailed",false,`feedback_type must be one of ${Ct.join(", ")}`));let l=typeof o=="string"?o.trim():"";if([...l].length>St)return p(E("validationFailed",false,`notes is over ${St} characters`));let u={feedback_type:n};l.length>0&&(u.notes=l);let a=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:u},s?.signal);if(!this.alive(a)||this.disposed)return p(E("accessDenied",false));if(!d.ok)return p(d.error);let c=d.value?.feedback_id;return _(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return p(E("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return p(E("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,u=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(l)||this.disposed)return p(E("accessDenied",false));if(!u.ok)return u;let a=u.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:u.value.case.resolutionText,status:u.value.case.status??null,...a!==null?{openedAt:a}:{}}),c=i(f=>f.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(f=>c(f)?Object.freeze({...f,checkin:d}):f)}),u}async getMessages(r,n){if(!_e(r))return p(E("validationFailed",false));let o=Et(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(E("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?p(E("accessDenied",false)):l.ok?Rn(l.value):l}async resumeConversation(r){if(this.disposed)return p(E("accessDenied",false));if(!_e(r))return p(E("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return p(E("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),_(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===ge).map(d=>d.caseId)),l=new Map(o.value.map(d=>[d.caseId,d])),u=false,a=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;u=true;let f=l.get(c.caseId),g=c.openedAt??f?.openedAt??null,y=s.has(c.caseId),R=f!==void 0&&(!y||gn({askCount:f.checkinAskCount,answerCount:f.checkinAnswerCount}))?f.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:y?ge:f?.status??"resolved",answer:c.answer??R,resolutionText:c.resolutionText??f?.resolutionText??null,...g!==null?{openedAt:g}:{}})})});u&&this.patch({messages:a});}async refreshActiveThread(){if(this.disposed)return p(E("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return _(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return p(E("accessDenied",false));if(!o.ok)return p(o.error);let s=new Set(this.snapshot.messages.map(u=>u.id)),l=o.value.messages.filter(u=>!s.has(u.id));return l.length>0&&this.patch({messages:[...this.snapshot.messages,...l]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),_(void 0)}async loadOlderMessages(){if(this.disposed)return p(E("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return _(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return p(E("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let l=new Set(this.snapshot.messages.map(a=>a.id)),u=s.value.messages.filter(a=>!l.has(a.id));return this.patch({messages:[...u,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),_(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield X(n.error));}async primeConversation(r){if(this.disposed)return p(E("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?p(E("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return _(n);let o=this.snapshot.conversationId;return o!==null?_(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return p(E("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let l=await s.settled;return !this.alive(n)||this.disposed?p(E("accessDenied",false)):(!l.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),l)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return p(s.error);let l=s.value?.conversation_id??s.value?.id;return typeof l!="string"||l.length===0?p(E("internalError",true)):_(l)}async getPrompts(r){let n=this.epoch;if(this.disposed)return p(E("accessDenied",false));let o=r?.petRef??null;if(o!==null&&L(o))return p(S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?p(E("accessDenied",false)):l.ok?_(cn(l.value)):p(l.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,l=Ke(s.signal,n.signal),u=this.beginTurn(r,n),a=this.runTurn(u,l),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let f of a){if(d)break;o.onFrame(f),f.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,gt(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,l=false,u=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let a=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=a?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let C=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;C.ok&&this.snapshot.conversationId===null&&this.adoptConversation(C.value);}if(a&&this.snapshot.conversationId===null){let C=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!C.ok){yield*this.emitTerminal(r,C.error,X(C.error));return}this.adoptConversation(C.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let C=E("internalError",!0);yield*this.emitTerminal(r,C,X(C));return}this.clearAssistantInProgress(r);let f=new AbortController,g=Ke(o.signal,f.signal),y=null;try{let C;try{C=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let O=this.authRejected();yield*this.emitTerminal(r,O,X(O));return}if(o.signal.aborted||!this.alive(o.epoch))return;let P=this.funnel.stream("chat.send",C,g);for await(let O of hn(P,this.budget,g,this.timers)){if(!this.alive(o.epoch))return;if(O.kind==="error"&&O.terminal){y=O;break}if(this.applyFrame(O,r),yield O,O.terminal){o.settle();return}}}finally{f.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(y===null){if(this.snapshot.status==="complete")return;let C=E("streamIncomplete",!0);yield*this.emitTerminal(r,C,X(C));return}let R=Y(y.code);if(R==="authExpired"&&this.auth.mode==="personalized"&&!u){u=!0,this.telemetry.track("chat.auth.refresh",{});let C=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!C){let P=this.authRejected();yield*this.emitTerminal(r,P,y);return}this.patch({reconnecting:!0});continue}if(R==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let C=this.authRejected();yield*this.emitTerminal(r,C,y);return}if(R==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,_t(y),y);return}if(br(R)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let T=y.retryable&&je(R,!0);if(Ns&&T&&s+1<this.errorPolicy.maxAttempts(R));yield*this.emitTerminal(r,_t(y),y);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Le(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(l=>l.id===n.userMessageId&&l.pending===true?he(l):l);this.patch({status:"streaming",isStreaming:true,messages:[...s,bt(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Us){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},Ls);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(l=>l.id===o?un(l,n):l);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(u=>u.id===n.assistantMessageId?vt(u,r):u);else {let u=this.newId();n.assistantMessageId=u,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?he(d):d),vt(bt(u,"",this.stamp()),r)];}let l=Rt([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=l.length>0?Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,l=this.historyGeneration,u=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!u.ok||!this.alive(s)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==r)return;let a=Cn(u.value?.urgency),d=typeof u.value?.reason=="string"?u.value.reason:null,c=i(f=>f.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(f=>c(f)?Object.freeze({...f,urgencyLevel:a,urgencyReason:d,urgencyProvided:true}):f)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?he(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return E("authRejected",false)}};i(Pt,"ChatControllerImpl");var Tt=Pt;async function Pn(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],l=false,u=false,a=false,d=null,c=null,f=o?r.resumeConversation(o).then(A=>A.ok?_(o):A):r.primeConversation(n?{petRef:n}:void 0),g=r.getPrompts(n!==null?{petRef:n}:void 0),[y,R]=await Promise.all([f,g]),T=null;if(y.ok)T=y.value,s.push(y.value),r.getSnapshot().conversationId===null&&r.adoptConversation(y.value);else {let A=y.error;c=A,kn(A)?(u=true,d=A):(Tn(A)&&(l=true),a=true);}let C=[];R.ok?C=R.value:P(R.error);function P(A){kn(A)?(u=true,d===null&&(d=A)):Tn(A)&&(l=true);}i(P,"recordAuthSignals");let O=d!==null?d.displayMessage:null;return Object.freeze({conversationId:T,petRef:n,suggestedPrompts:C,error:O,warning:O===null&&T===null&&a?Bs:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:l,sawUnauthorized:u,sawConversationInitFailure:a})})}i(Pn,"bootstrapChat");var Bs="Chat is ready. Your first message will start the conversation.";function kn(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(kn,"isUnauthorized");function Tn(e){return e.httpStatus===403||e.code==="accessDenied"}i(Tn,"isForbidden");var xt=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function xn(e){return e!==xt}i(xn,"isUploadTransportAvailable");var In=128,oe=128;var qs=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),yc="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",An=10*1024*1024,Hs=5,Ee=120,Ks="/widget/v1/uploads/initiate";function $s(e){return typeof e=="string"&&qs.includes(e.trim().toLowerCase())}i($s,"isAttachmentMime");function Vs(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=Ee)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Ee);let n=t.slice(r);return n.length>=Ee?t.slice(0,Ee):`${t.slice(0,r).slice(0,Ee-n.length)}${n}`}i(Vs,"sanitizeFilename");function hc(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(hc,"formatBytes");var Ce=i(e=>Object.freeze({ok:true,value:e}),"ok"),V=i(e=>Object.freeze({ok:false,error:e}),"err");function D(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(D,"failure");function Ws(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i(Ws,"attachmentSize");function Gs(e){let t=Vs(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!$s(r))return V(D("unsupported_type",false,t));let n=Ws(e);return n===null?V(D("unknown",false,t)):n>An?V(D("too_large",false,t,{sizeBytes:n})):Ce(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Gs,"validateAttachment");function Ys(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),l=r(t.s3_key);if(o===null||s===null||l===null)return null;let u={},a=t.upload_fields;if(typeof a=="object"&&a!==null)for(let[d,c]of Object.entries(a))typeof c=="string"&&(u[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(u),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??An,s3_key:l,purpose:r(t.purpose)})}i(Ys,"parsePolicy");function Xs(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return D("quota_exceeded",false,t,{cause:e});case "rateLimited":return D("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return D("idempotency_conflict",true,t,{cause:e});case "validationFailed":return D("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return D("network",true,t,{cause:e});default:return r===429?D("rate_limited",true,t,{cause:e}):r===503?D("network",true,t,{cause:e}):r===void 0?D("network",true,t,{cause:e}):D("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Xs,"initiateFailure");async function Qs(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Ks,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return V(Xs(n.error,t.filename));let o=Ys(n.value);return o===null?V(D("server",false,t.filename)):Ce(o)}i(Qs,"initiateAttachmentUpload");async function Js(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return V(D("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Ce(void 0)}catch{return o()?V(D("cancelled",true,r.filename)):V(D("server",true,r.filename))}}i(Js,"uploadAttachmentBytes");var Zs=2,ea=3,ta=Object.freeze([1e3,2e3,4e3]),On=0;function ra(){return On+=1,`attachment-${On}`}i(ra,"defaultNewId");function gc(e){let t=Math.max(1,e.concurrency??Zs),r=Math.max(1,e.maxAttempts??ea),n=e.backoffMs??ta,o=Math.max(1,e.maxPerMessage??Hs),s=e.timers??ln,l=e.newId??ra,u=xn(e.transport),a=new Map,d=[],c=[],f=new Set,g=new Set,y=Object.freeze({attachments:Object.freeze([])}),R=false,T=i(()=>{y=Object.freeze({attachments:Object.freeze(d.flatMap(v=>{let w=a.get(v);return w===void 0?[]:[w.state]}))});for(let v of g)v();},"publish"),C=i((v,w)=>{v.state=Object.freeze({...v.state,...w}),T();},"patch"),P=i(()=>{for(;!R&&f.size<t&&c.length>0;){let v=c.shift(),w=a.get(v);w!==void 0&&(f.add(v),O(w).finally(()=>{f.delete(v),P();}));}},"pump"),O=i(async v=>{let{attachment:w}=v;for(;v.attempts<r;){if(R||v.controller.signal.aborted)return;v.attempts+=1;let j=v.controller.signal;C(v,{status:"uploading",error:null,progress:0});let B=await Qs(e.funnel,w,{signal:j});if(R||j.aborted)return;let q;if(!B.ok)q=V(B.error);else {let ue=await Js(e.transport,B.value,w,{signal:j,onProgress:i(li=>{!j.aborted&&v.state.status==="uploading"&&C(v,{progress:na(li)});},"onProgress")});if(R||j.aborted)return;q=ue.ok?Ce(B.value.s3_key):V(ue.error);}if(q.ok){C(v,{status:"uploaded",s3Key:q.value,error:null,progress:1});return}let H=q.error,ie=H.retryable&&v.attempts<r;if(C(v,{status:ie?"uploading":"failed",error:H,progress:0}),!ie)return;let ce=n[Math.min(v.attempts-1,n.length-1)]??0;await He(ce,j,s);}},"run"),M=i(v=>{c.push(v.state.id),P();},"enqueue"),A={available:u,subscribe(v){return g.add(v),()=>{g.delete(v);}},getSnapshot:i(()=>y,"getSnapshot"),get uploading(){return y.attachments.some(v=>v.status==="uploading")},get s3Keys(){return y.attachments.flatMap(v=>v.status==="uploaded"&&v.s3Key!==null?[v.s3Key]:[])},add(v){let w=Gs(v);if(!w.ok)return w;if(R||d.length>=o)return V(D("too_many",false,w.value.filename));let j=l(),B={attachment:w.value,controller:new AbortController,attempts:0,state:Object.freeze({id:j,filename:w.value.filename,previewUri:v.uri,contentType:w.value.contentType,sizeBytes:w.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(j,B),d.push(j),T(),M(B),Ce(B.state)},retry(v){let w=a.get(v);w===void 0||R||w.state.status!=="failed"||(w.controller=new AbortController,w.attempts=0,C(w,{status:"uploading",error:null,progress:0,s3Key:null}),M(w));},remove(v){let w=a.get(v);if(w===void 0)return;w.controller.abort(),a.delete(v);let j=d.indexOf(v);j>=0&&d.splice(j,1);let B=c.indexOf(v);B>=0&&c.splice(B,1),T();},clear(){for(let v of [...d])A.remove(v);},dispose(){R=true;for(let v of a.values())v.controller.abort();a.clear(),d.length=0,c.length=0,g.clear(),y=Object.freeze({attachments:Object.freeze([])});}};return A}i(gc,"createAttachmentQueue");function na(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(na,"clamp");var Fn=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function Mn(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Fn,t)?Fn[t]:null}i(Mn,"canonicalPetSpecies");var Dn=50,oa=128,It=120,jn=120,ia=2e3,zn=120,sa=80,Nn=new Set(["male","female","unknown"]),Bn=new Set(["day","month","year"]),qn=new Set(["low","medium","high","athletic"]),Hn=new Set(["indoor","outdoor","both"]),Kn=new Set(["mild","moderate","severe"]),aa=/^(\d{4})-(\d{2})-(\d{2})$/,$n=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],Vn=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...$n,...Vn].map(([e])=>e));function la(e){let t=aa.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(la,"isRealDate");var we=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),ua=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),We=i((e,t)=>typeof t=="string"&&la(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Q=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(L(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=Be(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),da={sex:we(Nn),spayedNeutered:ua,birthDate:We,birthDatePrecision:we(Bn),activityLevel:we(qn),indoorOutdoor:we(Hn),foodBrand:Q(zn),foodType:Q(zn),microchipId:Q(sa)},Ot=["ref","ref",false,Q(oa,{required:true,trimmed:true})],At=["notes","notes",false,Q(ia,{trimmed:true})],Ln=[Ot,["name","name",true,Q(It,{required:true,trimmed:true})],["dose","dose",false,Q(jn,{trimmed:true})],["frequency","frequency",false,Q(jn,{trimmed:true})],["startDate","start_date",false,We],["endDate","end_date",false,We],At],ca={allergies:[Ot,["allergen","allergen",true,Q(It,{required:true,trimmed:true})],["severity","severity",false,we(Kn)],At],medications:Ln,supplements:Ln,conditions:[Ot,["conditionName","condition_name",true,Q(It,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,We],At]};function pa(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[a,d,c,f]of ca[e]){let g=o[a];if(g==null){if(c)return {error:`${n}.${a} is required`};g===null&&(s[d]=null);continue}let y=f(`${n}.${a}`,g);if(y!==null)return {error:y};s[d]=g;}let l=s.start_date,u=s.end_date;return typeof l=="string"&&typeof u=="string"&&u<l?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(pa,"itemToWire");function fa(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>Dn)return {error:`${e} has ${t.length} items; the server accepts at most ${Dn}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=pa(e,o,t[o]);if("error"in s)return s;let l=s.item.ref;if(typeof l=="string"){let u=l.trim();if(n.has(u))return {error:`${e}: ref ${JSON.stringify(u)} is used twice; a ref names one item`};n.add(u);}r.push(s.item);}return {items:r}}i(fa,"listToWire");function Wn(e,t){let r=e,n={};for(let[l,u]of $n){let a=r[l];if(a!==void 0){if(a!==null){let d=da[l](l,a);if(d!==null)return {error:d}}n[u]=a;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[l,u]of Vn){let a=r[l];if(a===void 0)continue;let d=fa(l,a);if("error"in d)return d;n[u]=d.items;}return Object.keys(n).length>0&&t!==void 0&&Mn(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(Wn,"petHealthToWire");var F=i(e=>typeof e=="string"?e:null,"str"),Se=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),ma=i(e=>typeof e=="boolean"?e:null,"bool");function Ve(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(Ve,"itemsFromWire");function Un(e){let t=F(e.name);return t===null||t.length===0?null:Object.freeze({ref:F(e.ref),name:t,dose:F(e.dose),frequency:F(e.frequency),startDate:F(e.start_date),endDate:F(e.end_date),notes:F(e.notes)})}i(Un,"medicationFromWire");function Gn(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Se(Nn,e.sex),spayedNeutered:ma(e.spayed_neutered),birthDate:F(e.birth_date),birthDatePrecision:Se(Bn,e.birth_date_precision),activityLevel:Se(qn,e.activity_level),indoorOutdoor:Se(Hn,e.indoor_outdoor),foodBrand:F(e.food_brand),foodType:F(e.food_type),microchipId:F(e.microchip_id),allergies:Ve(e.allergies,r=>{let n=F(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),allergen:n,severity:Se(Kn,r.severity),notes:F(r.notes)})}),medications:Ve(e.medications,Un),supplements:Ve(e.supplements,Un),conditions:Ve(e.conditions,r=>{let n=F(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),conditionName:n,diagnosedDate:F(r.diagnosed_date),notes:F(r.notes)})})})}i(Gn,"petHealthFromWire");var Qn=100,Jn=50,Zn=100,eo=50,to=500,ya=128,ha=6e4;function Z(e){return S("validationFailed",{retryable:false,wireMessage:e})}i(Z,"invalid");function se(e,t,r){if(typeof t!="string")return Z(`${e} must be a string`);let n=Be(t);return n<=r?null:Z(`${e} is ${n} characters; the server accepts at most ${r}`)}i(se,"checkString");function Ge(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Z(`${e} must be a finite number between 0 and ${r}`)}i(Ge,"outOfRange");function Yn(e,t){if(typeof e!="string")return Z("pet_ref must be a string");if(e.trim().length===0)return Z("pet_ref must not be blank");if(L(e))return Z("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Z("profile must be an object");let r=[se("pet_ref",e,ya)];return t?.name!==void 0&&r.push(se("name",t.name,Qn)),t?.species!==void 0&&r.push(se("species",t.species,Jn)),t?.breed!==void 0&&r.push(se("breed",t.breed,Zn)),t?.ageYears!==void 0&&r.push(Ge("age_years",t.ageYears,eo)),t?.weightKg!==void 0&&r.push(Ge("weight_kg",t.weightKg,to)),r.find(n=>n!==null)??null}i(Yn,"validate");function ro(e,t){let r=Wn(e,t);return "error"in r?{error:Z(r.error)}:r}i(ro,"healthToWire");function ga(e){if(typeof e!="object"||e===null)return {error:Z("patch must be an object")};let t=e,r=[["name","name",s=>se("name",s,Qn)],["species","species",s=>se("species",s,Jn)],["breed","breed",s=>se("breed",s,Zn)],["ageYears","age_years",s=>Ge("age_years",s,eo)],["weightKg","weight_kg",s=>Ge("weight_kg",s,to)]],n={};for(let[s,l,u]of r){let a=t[s];if(a!==void 0){if(a!==null){let d=u(a);if(d!==null)return {error:d}}n[l]=a;}}let o=ro(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Z("patch must change at least one field")}:{body:n})}i(ga,"patchToWire");function ba(e){if(e==null)return {body:{}};let t=ro(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(ba,"toWire");var J=i(e=>typeof e=="string"?e:null,"str"),Ye=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Xn(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:J(r.pet_ref)??t,name:J(r.name),species:J(r.species),breed:J(r.breed),ageYears:Ye(r.age_years),weightKg:Ye(r.weight_kg)})}i(Xn,"fromWire");function no(e){if(typeof e!="object"||e===null)return null;let t=e,r=J(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:J(t.pet_id),petRef:r,name:J(t.name),species:J(t.species),breed:J(t.breed),ageYears:Ye(t.age_years),weightKg:Ye(t.weight_kg),updatedAt:J(t.updated_at)})}i(no,"widgetPetFromWire");function va(e){let t=no(e);return t===null?null:Object.freeze({...t,...Gn(e)})}i(va,"widgetPetProfileFromWire");function _a(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=no(r);return n===null?[]:[n]}))}i(_a,"petListFromWire");function oo(e){return Ra($({auth:e}),$({auth:e,unaryTimeoutMs:ha}))}i(oo,"createPetsRepository");function Ra(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Yn(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?_(_a(s.value)):p(s.error)},async registerPet(o,s,l){let u=Yn(o,s);if(u!==null)return p(u);let a=ba(s);if("error"in a)return p(a.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:a.body},f=await e.send("pets.registerPet",l?.signal?{...c,signal:l.signal}:c);return f.ok?_(Xn(f.value,o)):p(f.error)},async updatePet(o,s,l){let u=n(o);if(typeof u!="string")return p(u);let a=ga(s);if("error"in a)return p(a.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:u,body:a.body},l?.signal));return d.ok?_(Xn(d.value,o)):p(d.error)},async getPetProfile(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},s?.signal));if(!u.ok)return p(u.error);let a=va(u.value);return a===null?p(S("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):_(a)},async deletePet(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.deletePet",r({method:"DELETE",path:l},s?.signal));return u.ok?_(void 0):p(u.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?_(void 0):p(s.error)}}}i(Ra,"createPetsRepositoryOver");var io=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function so(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(io))for(let l of io[s])o.has(l)||(o.add(l),n.push(Object.freeze({resource:l,granted:false,disabled:r})));return Object.freeze(n)}i(so,"deniedDecisionsFor");function re(e){let t=Ea(e);return t===null?null:Sa(t)}i(re,"parseColor");function Ea(e){if(typeof e=="number")return ao(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Ft(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Ft(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ca(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=Ft(t);if(r!==null)return r}return /^\d+$/.test(t)?ao(Number.parseInt(t,10)):null}i(Ea,"toRgba");function Ft(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Mt(t[0]),g:Mt(t[1]),b:Mt(t[2]),a:1};if(t.length===6)return {r:ae(t,0),g:ae(t,2),b:ae(t,4),a:1};if(t.length===8){let r=ae(t,0);return {r:ae(t,2),g:ae(t,4),b:ae(t,6),a:r/255}}return null}i(Ft,"fromHex");function Ca(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(a=>a.trim());if(n.length<3)return null;let o=Dt(Number(n[0])),s=Dt(Number(n[1])),l=Dt(Number(n[2]));if(o===null||s===null||l===null)return null;let u=1;if(n.length>=4){let a=Number(n[3]);if(!Number.isFinite(a))return null;u=Math.min(1,Math.max(0,a));}return {r:o,g:s,b:l,a:u}}i(Ca,"fromRgbFunc");function ao(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(ao,"argbIntToRgba");function ae(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ae,"byte");function Mt(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Mt,"dup");function Dt(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Dt,"clampByte");function Sa(e){if(e.a>=1)return wa(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Sa,"normalizeRgba");function wa(e,t,r){return `#${jt(e)}${jt(t)}${jt(r)}`.toUpperCase()}i(wa,"rgbToHex");function jt(e){return e.toString(16).padStart(2,"0")}i(jt,"hex2");var zt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]);function ka(e){return zt.includes(e)}i(ka,"isSlotName");function Ta(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Ta,"parseRadius");function lo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!ka(n)||o===null||typeof o!="object")continue;let s=Pa(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(lo,"parseThemeSlots");function Xe(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Xe,"pick");function Pa(e){let t={},r=re(Xe(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=re(Xe(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Ta(Xe(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=re(Xe(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Pa,"parseSlot");var po=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),Qe="slots.";function fo(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(fo,"isEmptyBranding");function Ia(e){return e==="hide_powered_by"||po.includes(e)?true:e.startsWith(Qe)&&zt.includes(e.slice(Qe.length))}i(Ia,"isThemeLockName");function ke(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:le(x(t,"display_name","displayName")),logoUrl:le(x(t,"logo_url","logoUrl")),primaryColor:re(x(t,"primary_color","primaryColor")),accentColor:re(x(t,"accent_color","accentColor")),brightness:Ma(x(t,"brightness","color_scheme","colorScheme")),fontFamily:le(x(t,"font_family","fontFamily")),fontUrl:le(x(t,"font_url","fontUrl")),fonts:uo(x(t,"fonts")),fontUrls:uo(x(t,"font_urls","fontUrls")),placeholder:le(x(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Oa(x(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:re(x(t,"primary_color_dark","primaryColorDark")),accentColorDark:re(x(t,"accent_color_dark","accentColorDark")),surfaceStyle:co(x(t,"surface_style","surfaceStyle"),Aa),radiusScale:co(x(t,"radius_scale","radiusScale"),Fa),logoUrlDark:le(x(t,"logo_url_dark","logoUrlDark")),slots:lo(x(t,"slots")),accessibilityMaxFontScale:ja(x(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:La(x(t,"locked_fields","lockedFields")),schemaVersion:za(x(t,"schema_version","schemaVersion"))};return fo(r)?null:Object.freeze(r)}i(ke,"parseClientBranding");function Oa(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(Oa,"parseBool");function x(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(x,"pick");function le(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(le,"parseNonEmptyString");var mo=["regular","medium","bold","mono","monoMedium","monoBold"];function uo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of mo){let o=le(x(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(uo,"parseFaceMap");var Aa=["white","cream","subtle"],Fa=["sharp","default","round"];function co(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(co,"parseEnum");function Ma(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(Ma,"parseBrightness");function yo(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(yo,"parseNumber");var Da=1,ho=3.1;function ja(e){let t=yo(e);return t===null?null:t<=0?0:Math.min(ho,Math.max(Da,t))}i(ja,"parseMaxFontScale");function za(e){if(e==null)return null;let t=yo(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(za,"parseSchemaVersion");function go(e){let t=e.trim();return t.startsWith(Qe)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(go,"toWireName");function La(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=go(r);Ia(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(La,"parseLockedFields");var bo="/widget/v1/entitlements",Ua=304,Na=Object.freeze({kind:"notModified"});async function _o(e,t={},r=$({auth:e})){let n=await r.send("entitlements.fetch",qa(t));return n.ok?Ha(n.value):n.error.httpStatus===Ua?Na:{kind:"failed",error:n.error}}i(_o,"fetchEntitlements");var Ba=64;function qa(e){let t={};return Lt(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Ba?{method:"GET",path:bo,headers:t,query:{region:e.region}}:{method:"GET",path:bo,headers:t}}i(qa,"buildRequest");function Ha(e){if(e===null||typeof e!="object"||!Lt(e.revision))return vo();let t=typeof e.region=="string"?e.region:"",r=Lt(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:$a(e.capabilities),branding:Ka(e),livemode:e.livemode!==false})}i(Ha,"parseUpdated");function Ka(e){let t=ke(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=ke(r.branding);return n!==null?n:ke(r)}return null}i(Ka,"parseBranding");function $a(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Va(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i($a,"mapCapabilities");function Va(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Va,"isEnabled");function vo(){return {kind:"failed",error:S("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(vo,"malformed");function Lt(e){return typeof e=="number"&&Number.isFinite(e)}i(Lt,"isFiniteNumber");var Wa=30;function Ro(e){let t=e.scheduler??Ga,r=e.resolve??_o,n=Math.max(1,e.floorSeconds??Wa),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),l=false,u=false,a=null,d=null,c=n,f=0,g=i(()=>{a!==null&&(t.clear(a),a=null);},"clearTimer"),y=i(P=>{u||!l||(c=Math.max(n,P),a=t.set(()=>{a=null,C();},c*1e3));},"schedule"),R=null,T=i(async()=>{if(u)return null;let P=f;e.onFetch?.();let O=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},M;try{M=await r(e.authFor(),O);}catch(A){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Ya(A)}),!u&&P===f&&(e.onSettled?.(),y(s())),null}if(u||P!==f)return null;switch(M.kind){case "updated":d=M.revision,e.update(M.decisions,M.branding??null,M.livemode!==false),y(M.ttlSeconds);break;case "notModified":y(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:M.error.code}),y(s());break;default:y(s());}return e.onSettled?.(),M},"tick"),C=i(()=>{let P=T().finally(()=>{R===P&&(R=null);});return R=P,P},"run");return {start(){l||u||(l=true,C());},prime(){return u?Promise.resolve(null):R??C()},stop(){u||(u=true,f++,g());},refresh(){u||!l||(f++,d=null,g(),C());}}}i(Ro,"createEntitlementPoller");var Ga={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function Ya(e){return e instanceof Error?e.message:"poll failed"}i(Ya,"describe");var Eo="everfur.notifications.device";var So=3e3,Co=Object.freeze([Eo]);function wo(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),l=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),u=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:l.length});}catch{}},"report"),a=Promise.allSettled(l).then(d=>{let c=d.filter(f=>f.status==="rejected").length;c>0&&u("failed",c);});return new Promise(d=>{let c=false,f=i(()=>{c||(c=true,clearTimeout(g),d());},"finish"),g=setTimeout(()=>{c||u("timeout",l.length),f();},So);a.then(f,f);})}i(wo,"startBeforeLogoutHooks");function ko(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let l={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:l,userRef:t.userRef,sessionId:o}}i(ko,"graceAuth");async function To(e,t){if(Co.length===0)return;let r=await Promise.allSettled(Co.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(To,"sweepPerUserKv");function Xa(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Xa,"compiledDefaultDecisions");function Ut(e=Xa){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null,...o.livemode===false?{livemode:false}:{}}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Ut,"createEntitlementStore");function Nt(e){return S("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(Nt,"notConfiguredError");function Po(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return Dr(r,t===void 0?void 0:{platform:t})}i(Po,"tryResolveClient");function xo(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(xo,"guardTelemetry");var Qa=Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${Ne} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Io(e,t,r=ut){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
+ [everfur] Every Everfur capability will render its off-state until this is fixed. `+Qa[r]);}i(Io,"reportConfigFailure");function Bt(e){return Object.freeze({request(){return Promise.resolve(p(Nt(e)))},stream(t,r){let n=N({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(Bt,"refusingTransport");function Oo(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Oo,"createInMemoryKv");var Ao=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function Bp(e,t){return new Ht(e,t)}i(Bp,"createEverfurRuntime");var Ja=6e4,Kt=class Kt{constructor(t,r){this.sessionId=at();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new K("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?xo(n.telemetry):Me;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=dt(n?.publishableKey),l=n.transport!==void 0,u,a=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)u=Bt(s);else if(n.transport!==void 0)u=n.transport;else {let c=Po(n,r?.platform);c.ok?(a=c.config.apiBaseUrl,u=Br({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,u=Bt(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=u,s!==null&&Io(s,this.telemetry,r?.platform),this.errorPolicy=n.errorPolicy,this.camera=n.camera??_r,this.upload=n.upload??an,this.uploadTransport=n.uploadTransport??xt,this.imageCache=n.imageCache??Ao,this.kv=n.storage??Oo(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?Ut():Ut(()=>so("sdk_config",it("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",qt(c),()=>this.buildChatController(c),Fo),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${qt(c)}`)?.controller??null,"peekChat"),acquire:i((c,f,g,y)=>this.acquireInternal(c,f,g,y),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!l);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=xr(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Ja,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return Ro({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n,o)=>this.updateEntitlements({decisions:r,isPending:false,branding:n,...o===false?{livemode:o}:{}}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let l=`${this.epoch}|${t}|${r}`,u=this.entries.get(l);if(u)return s||(u.warm?u.warm=false:u.refCount+=1),u.controller;let a=n();return this.entries.set(l,{controller:a,refCount:1,warm:s}),this.destroyers.set(a,o),a}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=wn({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Pn(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=at(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await To(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return wo({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>ko({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?p(Mo(t)):r(oo(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(l=>(s.result=l,l))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Mo("prepare"):n===null?null:Nt(n),s=this.identity,[l,u,a]=await Promise.all([o?p(o):s===null?_(void 0):s.currentToken().then(()=>_(void 0),()=>p(S("authRejected",{retryable:false}))),o?p(o):this.primeEntitlements(),t===null?void 0:o?p(o):this.primeChat(t)]),d=l.ok?u.ok&&(a?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:l,entitlements:u,...a?{chat:a}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?p(t.error):_(void 0):p(S("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",qt(r),()=>this.buildChatController(r),Fo,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?p(o.cause):_(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Kt,"EverfurRuntimeImpl");var Ht=Kt;function qt(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(qt,"chatScopeKey");function Fo(e){e.dispose();}i(Fo,"disposeChat");function Mo(e){return S("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Mo,"disposedError");var zo=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Do=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 Za(e){let t=Object.prototype.hasOwnProperty.call(Do,e)?Do[e]:void 0;if(t!==void 0)return t;let r=e;return zo.has(r)?r:"parsing"}i(Za,"normalizeStatus");function el(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(el,"normalizeOrigin");var tl=z$1.object({request_id:z$1.string().min(1),pet_ref:z$1.string().min(1),status:z$1.string(),simple_status:z$1.string().nullish(),simple_status_detail:z$1.string().nullish(),status_label:z$1.string().optional(),dispatch_status:z$1.string().nullish(),can_retry_send:z$1.boolean().optional(),can_revoke:z$1.boolean().optional(),can_convert_to_upload:z$1.boolean().optional(),can_update_clinic_email:z$1.boolean().optional(),reminder_count:z$1.number().int().nonnegative().optional(),last_reminder_at:z$1.string().nullish(),waiting_expectation:z$1.string().nullish(),document_count:z$1.number().optional(),held_item_count:z$1.number().optional(),received_at:z$1.string().nullish(),parsing_started_at:z$1.string().nullish(),review_started_at:z$1.string().nullish(),created_at:z$1.string().optional(),updated_at:z$1.string().optional(),source:z$1.string().nullish().catch(null),action_needed_label:z$1.string().nullish().catch(null),failure_reason:z$1.string().nullish().catch(null),failure_code:z$1.string().nullish().catch(null),recovery_stage:z$1.string().nullish().catch(null),show_clinic_phone:z$1.boolean().optional().catch(void 0),clinic_name:z$1.string().nullish().catch(null),clinic_email:z$1.string().nullish().catch(null),clinic_phone:z$1.string().nullish().catch(null),converted_to_upload_at:z$1.string().nullish().catch(null),request_group_id:z$1.string().nullish().catch(null)}).passthrough();function Lo(e){let t=tl.safeParse(e);if(!t.success)return null;let r=t.data,n=rl(r.simple_status),o=n==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":n==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":n??Za(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:o,simpleStatus:n,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:jo(r.document_count,0),heldItemCount:jo(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(Lo,"mapRequestView");z$1.object({request_group_id:z$1.string().min(1),pet_ref:z$1.string().min(1),total:z$1.number().int().nonnegative(),responded:z$1.number().int().nonnegative(),pending:z$1.number().int().nonnegative(),members:z$1.array(z$1.unknown())});function rl(e){return !e||e==="awaiting_upload"||e==="in_review"?null:zo.has(e)?e:null}i(rl,"normalizeSimpleStatus");z$1.object({source_doc_id:z$1.string().min(1),request_id:z$1.string().min(1)});var nl=z$1.object({label:z$1.string(),value:z$1.string()}),$t=z$1.object({key:z$1.string(),category:z$1.string().optional(),label:z$1.string().optional(),value:z$1.string().nullish(),unit:z$1.string().nullish(),observed_at:z$1.string().nullish(),status:z$1.string().nullish(),origin:z$1.string().nullish(),canonical_key:z$1.string().nullish()}),ol=z$1.object({at:z$1.string(),value:z$1.number().nullish(),display:z$1.string().nullish(),origin:z$1.string().nullish()}),il=z$1.object({key:z$1.string(),label:z$1.string().optional(),points:z$1.array(ol).optional()}),sl=z$1.object({title:z$1.string(),detail:z$1.string().nullish(),due_at:z$1.string().nullish()}),Vt=z$1.object({doc_id:z$1.string(),title:z$1.string().nullish(),page_count:z$1.number().nullish(),received_at:z$1.string().nullish()});function Uo(e){return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:el(e.origin),canonicalKey:e.canonical_key??null})}i(Uo,"mapEntityRow");function No(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(No,"mapDocumentRow");z$1.object({identity:z$1.array(nl).optional(),entities:z$1.array($t).optional(),entity_series:z$1.array(il).optional(),forward_looking:z$1.array(sl).optional(),documents:z$1.array(Vt).optional()});z$1.object({pet_ref:z$1.string().optional(),granted:z$1.boolean().optional(),version:z$1.string().nullish(),granted_at:z$1.string().nullish()});function jo(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(jo,"numberOr");var qo=10,Je=z$1.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Te=i((e,t=1)=>z$1.string().refine(r=>!L(r)&&[...r].length>=t&&[...r].length<=e),"text"),Ho=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),al=z$1.object({clinicId:Je.optional(),clinicFreeText:Te(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Te(320,3).refine(e=>!Ho(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Je.optional(),signaturePngBase64:z$1.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z$1.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),ll=z$1.object({petRef:Te(128),ownerName:Te(200).refine(e=>e.trim().length>0&&!Ho(e)),authorizationVersion:Te(64),clinics:z$1.array(al).min(1).max(qo)}).strict(),ul=z$1.object({request_group_id:Je,pet_ref:z$1.string(),created_count:z$1.number().int().nonnegative(),failed_count:z$1.number().int().nonnegative(),results:z$1.array(z$1.object({idempotency_key:z$1.string(),clinic_id:Je.nullable().optional(),clinic_free_text:z$1.string().nullable().optional(),created:z$1.boolean(),request:z$1.unknown().optional(),failure_code:z$1.string().nullable().optional(),failure_reason:z$1.string().nullable().optional()}))});function dl(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!ll.safeParse(r).success)return p(S("validationFailed",{retryable:false}));let n=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(l=>({...l.clinicId!==void 0?{clinic_id:l.clinicId}:{clinic_free_text:l.clinicFreeText},...l.clinicEmail!==void 0?{clinic_email:l.clinicEmail}:{},...l.signatureId!==void 0?{signature_id:l.signatureId}:{signature_png_base64:l.signaturePngBase64},idempotency_key:l.idempotencyKey}))}});if(!n.ok)return n;let o=ul.safeParse(n.value);if(!o.success||o.data.pet_ref!==r.petRef)return Bo();let s=[];for(let l of o.data.results){let u=l.request===void 0||l.request===null?null:Lo(l.request);if(l.created!==(u!==null))return Bo();s.push(Object.freeze({idempotencyKey:l.idempotency_key,clinicId:l.clinic_id??null,clinicFreeText:l.clinic_free_text??null,created:l.created,request:u,failureCode:l.failure_code??null,failureReason:l.failure_reason??null}));}return _(Object.freeze({requestGroupId:o.data.request_group_id,petRef:o.data.pet_ref,results:Object.freeze(s),createdCount:o.data.created_count,failedCount:o.data.failed_count}))}}}i(dl,"createRecordsClinicBatchClient");function Bo(){return p(S("internalError",{retryable:false}))}i(Bo,"malformed");var cl="records_consent_required";function pl(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,n=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof n=="string"&&n.length>0?n:null}i(pl,"recordsWireCodeOf");function Ko(e){return e===null||e.httpStatus!==409?false:pl(e)===cl}i(Ko,"isRecordsConsentRequired");var Wt="value_text",$o=64,Vo=512;function fl(e){return e!==null&&e.httpStatus===409&&!Ko(e)}i(fl,"isFactReviewerLocked");function ml(e){return Object.freeze({[Wt]:e.trim()})}i(ml,"factValueCorrection");var Pe=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:Wt}),Wo=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Go=/^\d{4}-\d{2}-\d{2}$/;function Yo(e){if(e==null)return "text";let t=e.trim();return Wo.test(t)?"num":Go.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(Yo,"inferFactValueKind");function yl(e,t){let r=t.trim(),n=Yo(e);if(n==="num"&&Wo.test(r)){let o=Number(r);if(Number.isFinite(o))return Object.freeze({[Pe.num]:o})}return n==="date"&&Go.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Pe.date]:r}):Object.freeze(n==="bool"&&(r==="true"||r==="false")?{[Pe.bool]:r==="true"}:{[Pe.text]:r})}i(yl,"factCorrectionFor");var k=z$1.string().nullish(),Ze=z$1.number().nullish(),hl=z$1.object({collected_at:k,at:k,value:Ze,unit:k,qualitative_result:k,ref_low:Ze,ref_high:Ze,status:k,source_clinic:k,source_doc_id:k,doc_id:k,reviewed:z$1.boolean().nullish()}),gl=z$1.object({collected_at:k,at:k,value:Ze,unit:k,qualitative_result:k,status:k}),bl=z$1.object({marker_id:z$1.string().min(1),canonical_name:k,name:k,loinc_code:k,canonical_unit:k,unit:k,panel_name:k,panel:k,meaning_text:k,meaning:k,latest:gl.nullish(),trajectory:k,points:z$1.array(hl).optional()}),vl=z$1.object({total_markers:z$1.number().int().nonnegative(),in_range_count:z$1.number().int().nonnegative(),out_of_range_count:z$1.number().int().nonnegative(),unknown_count:z$1.number().int().nonnegative()}),_l=z$1.object({markers:z$1.array(bl).optional(),summary:vl.nullish(),disclaimer:z$1.string().optional(),featured_marker_id:k});function Rl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Rl,"isObject");function Xo(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Xo,"withheldMarkers");function Gt(e,t){let r=Rl(t)?t:{},n=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Xo(n);let o=_l.safeParse(r);if(!o.success)return Xo(n);let s=o.data,l=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),u=(s.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(l))}));return Object.freeze({petRef:n,withheld:false,markers:Object.freeze(u),summary:s.summary?Object.freeze({totalMarkers:s.summary.total_markers,inRangeCount:s.summary.in_range_count,outOfRangeCount:s.summary.out_of_range_count,unknownCount:s.summary.unknown_count}):null,disclaimer:s.disclaimer??"",featuredMarkerId:s.featured_marker_id??null})}i(Gt,"mapRecordMarkers");var El=z$1.string().min(1).refine(e=>e.startsWith("https://")),Cl=z$1.object({source_doc_id:z$1.string().min(1),file_name:z$1.string().nullish(),doc_format:z$1.string().nullish(),byte_size:z$1.number().int().nonnegative().nullish(),received_at:z$1.string().nullish(),download_url:El,expires_in_seconds:z$1.number().int().nonnegative().nullish()}),Sl=z$1.object({items:z$1.array(z$1.unknown()).optional()});function Qo(e){let t=Sl.safeParse(e);if(!t.success)return null;let r=[];for(let n of t.data.items??[]){let o=Cl.safeParse(n);o.success&&r.push(Object.freeze({sourceDocId:o.data.source_doc_id,fileName:o.data.file_name??null,docFormat:o.data.doc_format??null,byteSize:o.data.byte_size??null,receivedAt:o.data.received_at??null,downloadUrl:o.data.download_url,expiresInSeconds:o.data.expires_in_seconds??0}));}return Object.freeze(r)}i(Qo,"mapRequestDocuments");var wl=z$1.string().min(1).refine(e=>e.startsWith("https://")),xe=z$1.string().nullish(),kl=z$1.object({share_id:z$1.string().min(1),share_url:z$1.string().min(1),expires_at:xe}),Tl=z$1.object({shares:z$1.array(z$1.object({share_id:z$1.string().min(1),expires_at:xe,created_at:xe,view_count:z$1.number().int().nonnegative().nullish(),last_viewed_at:xe})).optional()}),Pl=z$1.object({download_url:wl,expires_at:xe});function Jo(e,t){let r=e.trim();if(r.length===0)return null;try{let n=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return n===null||n.protocol!=="https:"?null:n.toString()}catch{return null}}i(Jo,"resolveShareUrl");function Yt(e,t){let r=kl.safeParse(e);if(!r.success)return null;let n=Jo(r.data.share_url,t);return n===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:n,expiresAt:r.data.expires_at??null})}i(Yt,"mapRecordShareLink");function Xt(e){let t=Tl.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(Xt,"mapRecordShareList");function Qt(e){let t=Pl.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Qt,"mapRecordPdfLink");var xl=z$1.object({signatures:z$1.array(z$1.object({signature_id:z$1.string().min(1),preview_url:z$1.string().min(1).refine(e=>e.startsWith("https://")),created_at:z$1.string().nullish()})).optional()});function Jt(e){let t=xl.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(Jt,"mapSignatureSuggestions");var b=z$1.string().nullish(),Ie=z$1.number().nullish(),Il=z$1.object({at:b,value:Ie,unit:b,qualitative_result:b,ref_low:Ie,ref_high:Ie,status:b,doc_id:b}),Ol=z$1.object({marker_id:z$1.string(),name:z$1.string(),loinc_code:b,unit:b,panel:b,meaning:b,latest:z$1.object({at:b,value:Ie,unit:b,qualitative_result:b,status:b}).nullish(),trajectory:b,points:z$1.array(Il).optional()}),Al=z$1.object({encounter_id:z$1.string(),date:b,type:b,clinic_name:b,veterinarian:b,doc_id:b}),Fl=z$1.object({note_id:z$1.string(),encounter_id:b,observed_on:b,sections:z$1.array(z$1.object({section:z$1.string(),text:z$1.string()})).optional()}),Ml=z$1.object({exam_id:z$1.string(),encounter_id:b,observed_on:b,doc_id:b,systems:z$1.record(z$1.object({finding_status:b,finding:b})).optional()}),Dl=z$1.object({has_lab_history:z$1.boolean().optional(),has_vaccination_history:z$1.boolean().optional(),has_weight_history:z$1.boolean().optional(),has_vitals_history:z$1.boolean().optional(),has_physical_exam_history:z$1.boolean().optional(),has_procedure_history:z$1.boolean().optional(),has_genetic_history:z$1.boolean().optional(),has_reproductive_history:z$1.boolean().optional(),has_parasite_prevention_history:z$1.boolean().optional(),earliest_record_at:b,latest_record_at:b,documents_ingested:z$1.number().int().nonnegative().optional(),documents_in_review:z$1.number().int().nonnegative().optional(),entities_pending_review:z$1.record(z$1.number().int().nonnegative()).optional(),held_total:z$1.number().int().nonnegative().optional()}),jl=z$1.object({conflict_id:z$1.string(),entity_type:z$1.string(),field:b,severity:b,candidates:z$1.array(z$1.object({value:z$1.string(),source_doc_id:b,doc_id:b,collected_at:b})).optional()}),zl=z$1.object({lab_results:z$1.array(Ol).optional(),encounters:z$1.array(Al).optional(),clinician_notes:z$1.array(Fl).optional(),physical_exams:z$1.array(Ml).optional(),completeness:Dl.nullish(),conflicts:z$1.array(jl).optional()}),Ll=z$1.object({visits:z$1.array(z$1.object({visit_id:z$1.string(),visit_date:b,veterinarian:b,summary:b,doc_id:b})),vaccines:z$1.array(z$1.object({vaccine_id:z$1.string(),product:b,lot:b,administered_on:b,expires_on:b,doc_id:b})),weights:z$1.array(z$1.object({weight_id:z$1.string(),observed_on:b,weight_kg:Ie,doc_id:b})),medications:z$1.array(z$1.object({medication_id:z$1.string(),drug_name:b,dose:b,route:b,frequency:b,sig:b,rx_number:b,started_on:b,stopped_on:b,doc_id:b})),disclaimer:z$1.string().optional()}),Ul=z$1.object({document:Vt,contributions:z$1.array($t),contribution_count:z$1.number().int().nonnegative().optional()});function er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(er,"isObject");function tr(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(tr,"petOf");function Zt(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(Zt,"emptyDepth");function ei(e,t){let r=er(t)?t:{},n=tr(r,e);if(r.withheld===true)return Zt(n,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Zt(n,false);let s=zl.safeParse(r);if(!s.success)return Zt(n,true);let l=s.data,u=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:n,available:true,withheld:false,labResults:Object.freeze((l.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(u))}))),encounters:Object.freeze((l.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((l.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((l.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,c])=>Object.freeze({system:d,findingStatus:c.finding_status??null,finding:c.finding??null})))}))),completeness:l.completeness?Object.freeze({hasLabHistory:l.completeness.has_lab_history===true,hasVaccinationHistory:l.completeness.has_vaccination_history===true,hasWeightHistory:l.completeness.has_weight_history===true,hasVitalsHistory:l.completeness.has_vitals_history===true,hasPhysicalExamHistory:l.completeness.has_physical_exam_history===true,hasProcedureHistory:l.completeness.has_procedure_history===true,hasGeneticHistory:l.completeness.has_genetic_history===true,hasReproductiveHistory:l.completeness.has_reproductive_history===true,hasParasitePreventionHistory:l.completeness.has_parasite_prevention_history===true,earliestRecordAt:l.completeness.earliest_record_at??null,latestRecordAt:l.completeness.latest_record_at??null,documentsIngested:l.completeness.documents_ingested??0,documentsInReview:l.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...l.completeness.entities_pending_review??{}}),heldTotal:l.completeness.held_total??0}):null,conflicts:Object.freeze((l.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(ei,"mapRecordDepth");function Zo(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Zo,"withheldTimeline");function ti(e,t){let r=er(t)?t:{},n=tr(r,e);if(r.withheld===true)return Zo(n);let o=Ll.safeParse(r);if(!o.success)return Zo(n);let s=o.data,l=s.visits.map(c=>Object.freeze({visitId:c.visit_id,visitDate:c.visit_date??null,veterinarian:c.veterinarian??null,summary:c.summary??null,docId:c.doc_id??null})),u=s.vaccines.map(c=>Object.freeze({vaccineId:c.vaccine_id,product:c.product??null,lot:c.lot??null,administeredOn:c.administered_on??null,expiresOn:c.expires_on??null,docId:c.doc_id??null})),a=s.weights.map(c=>Object.freeze({weightId:c.weight_id,observedOn:c.observed_on??null,weightKg:c.weight_kg??null,docId:c.doc_id??null})),d=s.medications.map(c=>Object.freeze({medicationId:c.medication_id,drugName:c.drug_name??null,dose:c.dose??null,route:c.route??null,frequency:c.frequency??null,sig:c.sig??null,rxNumber:c.rx_number??null,startedOn:c.started_on??null,stoppedOn:c.stopped_on??null,docId:c.doc_id??null}));return Object.freeze({petRef:n,withheld:false,isEmpty:l.length===0&&u.length===0&&a.length===0&&d.length===0,visits:Object.freeze(l),vaccines:Object.freeze(u),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:s.disclaimer??""})}i(ti,"mapRecordsTimeline");function ri(e,t){let r=er(t)?t:{},n=tr(r,e),o=i(()=>Object.freeze({petRef:n,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return o();let s=Ul.safeParse(r);if(!s.success)return o();let l=Object.freeze(s.data.contributions.map(Uo));return Object.freeze({petRef:n,withheld:false,document:No(s.data.document),contributions:l,contributionCount:s.data.contribution_count??l.length})}i(ri,"mapDocumentContributions");var Nl="/widget/v1/records/pets";function Bl(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!L(a)&&[...a].length<=d,"segment"),n=i(async(a,d,c,f)=>{if(!r(d,oe))return ne();let g=await t.send(a,{method:"GET",path:c});if(!g.ok)return g;let y=f(g.value);return y.petRef===d?_(y):p(S("internalError",{retryable:false}))},"read"),o=i(a=>`${Nl}/${encodeURIComponent(a)}`,"pet"),s=i(a=>`${o(a)}/everfur_record`,"record"),l=i(async(a,d,c)=>{let f=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!f.ok)return f;let g=c(f.value);return g===null?p(S("internalError",{retryable:false})):_(g)},"parsed"),u=i((a,d)=>!r(a.entityType,$o)||!r(a.canonicalKey,Vo)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,In)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>n("records.depth.record",a,`${o(a)}/record`,d=>ei(a,d)),"getRecordDepth"),getTimeline:i(a=>n("records.depth.timeline",a,`${o(a)}/timeline`,d=>ti(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?n("records.depth.contributions",a,`${o(a)}/documents/${encodeURIComponent(d)}/contributions`,c=>ri(a,c)):ne()},getMarkers:i(a=>n("records.depth.markers",a,`${o(a)}/markers`,d=>Gt(a,d)),"getMarkers"),createShare(a){return r(a,oe)?l("records.share.create",{method:"POST",path:`${s(a)}/share`},d=>Yt(d,e.apiBaseUrl)):ne()},listShares(a){return r(a,oe)?l("records.share.list",{method:"GET",path:`${s(a)}/shares`},Xt):ne()},async revokeShare(a,d){if(!r(a,oe)||!r(d,64))return ne();let c=await t.send("records.share.revoke",{method:"DELETE",path:`${s(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return c.ok?_(void 0):c},getPdfLink(a){return r(a,oe)?l("records.pdf.link",{method:"GET",path:`${s(a)}/pdf-link`},Qt):ne()},async editFact(a,d){let c=r(a,oe)?u(d,d.correctedFields):null;if(c===null)return ne();let f=await t.send("records.fact.edit",{method:"POST",path:`${s(a)}/facts/edit`,body:c},{idempotent:false,maxAttempts:1});return f.ok?_(void 0):f},async removeFact(a,d){let c=r(a,oe)?u(d):null;if(c===null)return ne();let f=await t.send("records.fact.remove",{method:"POST",path:`${s(a)}/facts/remove`,body:c},{idempotent:false,maxAttempts:1});return f.ok?_(void 0):f},listRequestDocuments(a){return r(a,64)?l("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},Qo):ne()},listAuthorizationSignatures:i(()=>l("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Jt),"listAuthorizationSignatures")}}i(Bl,"createRecordsDepthClient");function ne(){return Promise.resolve(p(S("validationFailed",{retryable:false})))}i(ne,"invalid");var Ae=Object.freeze({width:360,height:120});function si(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(si,"blank");function ai(e,t,r,n){for(let o=-n;o<=n;o+=1)for(let s=-n;s<=n;s+=1){if(s*s+o*o>n*n+n)continue;let l=t+s,u=r+o;l<0||u<0||l>=e.width||u>=e.height||(e.pixels[u*e.width+l]=1);}}i(ai,"stamp");var ql=16384;function Hl(e,t){let[r,n]=e;if(!Number.isFinite(r)||!Number.isFinite(n))return null;let o=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),s=Math.min(2*t.height,Math.max(-t.height,Math.round(n)));return [o,s]}i(Hl,"padPoint");function Kl(e,t,r,n,o){let[s,l]=t,[u,a]=r,d=Math.abs(u-s),c=-Math.abs(a-l),f=s<u?1:-1,g=l<a?1:-1,y=d+c,R=0;for(;R<o&&(ai(e,s,l,n),R+=1,!(s===u&&l===a));){let T=2*y;T>=c&&(y+=c,s+=f),T<=d&&(y+=d,l+=g);}return R}i(Kl,"line");function $l(e,t=1){let r=si(Ae.width,Ae.height);for(let n of e){let o=[];for(let l of n){let u=Hl(l,r);u!==null&&o.push(u);}if(o.length===0)continue;if(o.length===1){let[l,u]=o[0];ai(r,l,u,t);continue}let s=ql;for(let l=1;l<o.length&&s>0;l+=1)s-=Kl(r,o[l-1],o[l],t,s);}return r}i($l,"rasterizeStrokes");var Vl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",Wl="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",Gl="0123456789abcdefghijklmnopqrstuv",ar=5,lr=7,rr=ar+1;function Yl(e,t){let r=Vl.indexOf(e);return r<0?0:Gl.indexOf(Wl.charAt(r*lr+t))}i(Yl,"glyphRow");function Xl(e){let t=si(Ae.width,Ae.height),r=e.trim();if(r.length===0)return t;let n=[...r],o=4;for(;o>1&&(n.length*rr-1)*o>t.width-8;)o-=1;let s=(n.length*rr-1)*o,l=Math.max(0,Math.floor((t.width-s)/2)),u=Math.floor((t.height-lr*o)/2);return n.forEach((a,d)=>{let c=l+d*rr*o;for(let f=0;f<lr;f+=1){let g=Yl(a,f);for(let y=0;y<ar;y+=1)if((g>>ar-1-y&1)!==0)for(let R=0;R<o;R+=1)for(let T=0;T<o;T+=1){let C=c+y*o+T,P=u+f*o+R;C<t.width&&P<t.height&&(t.pixels[P*t.width+C]=1);}}}),t}i(Xl,"rasterizeTypedName");var cr=class cr{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let n=0;for(let o=0;o<r;o+=1)n=n<<1|t>>o&1;this.writeBits(n,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(cr,"BitWriter");var ur=cr;function dr(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(dr,"writeLiteral");var nr=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ni=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],or=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],oi=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function Ql(e,t,r){let n=nr.length-1;for(;nr[n]>t;)n-=1;dr(e,257+n),ni[n]>0&&e.writeBits(t-nr[n],ni[n]);let o=or.length-1;for(;or[o]>r;)o-=1;e.writeCode(o,5),oi[o]>0&&e.writeBits(r-or[o],oi[o]);}i(Ql,"writeMatch");var Jl=32768,ir=3,Zl=258,ii=15,eu=64;function tu(e){let t=new ur;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<ii).fill(-1),n=new Int32Array(e.length).fill(-1),o=i(u=>(e[u]<<10^e[u+1]<<5^e[u+2])&(1<<ii)-1,"hashAt"),s=i(u=>{if(u+ir>e.length)return;let a=o(u);n[u]=r[a],r[a]=u;},"insert"),l=0;for(;l<e.length;){let u=0,a=0;if(l+ir<=e.length){let d=r[o(l)],c=0,f=Math.min(Zl,e.length-l);for(;d>=0&&c<eu&&l-d<=Jl;){let g=0;for(;g<f&&e[d+g]===e[l+g];)g+=1;if(g>u&&(u=g,a=l-d,g===f))break;d=n[d],c+=1;}}if(u>=ir){Ql(t,u,a);for(let d=0;d<u;d+=1)s(l+d);l+=u;}else dr(t,e[l]),s(l),l+=1;}return dr(t,256),t.finish()}i(tu,"deflate");function ru(e){let t=1,r=0;for(let n of e)t=(t+n)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(ru,"adler32");var et=null;function nu(e){if(et===null){et=new Uint32Array(256);for(let r=0;r<256;r+=1){let n=r;for(let o=0;o<8;o+=1)n=n&1?3988292384^n>>>1:n>>>1;et[r]=n>>>0;}}let t=4294967295;for(let r of e)t=et[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(nu,"crc32");function Oe(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(Oe,"u32");function sr(e,t){let r=Uint8Array.from([...e].map(o=>o.charCodeAt(0))),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),[...Oe(t.length),...n,...Oe(nu(n))]}i(sr,"chunk");var tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function ou(e){let t="";for(let r=0;r<e.length;r+=3){let n=e[r],o=r+1<e.length?e[r+1]:0,s=r+2<e.length?e[r+2]:0,l=n<<16|o<<8|s;t+=tt.charAt(l>>18&63)+tt.charAt(l>>12&63),t+=r+1<e.length?tt.charAt(l>>6&63):"=",t+=r+2<e.length?tt.charAt(l&63):"=";}return t}i(ou,"toBase64");function iu(e){let{width:t,height:r,pixels:n}=e,o=Math.ceil(t/8)+1,s=new Uint8Array(o*r);for(let c=0;c<r;c+=1){let f=c*o;s[f]=0,s.fill(255,f+1,f+o);for(let g=0;g<t;g+=1)if(n[c*t+g]===1){let y=f+1+(g>>3);s[y]=s[y]&~(128>>(g&7));}}let l=tu(s),u=new Uint8Array(2+l.length+4);u[0]=120,u[1]=1,u.set(l,2),u.set(Oe(ru(s)),2+l.length);let a=Uint8Array.from([...Oe(t),...Oe(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...sr("IHDR",a),...sr("IDAT",u),...sr("IEND",new Uint8Array(0))]);return ou(d)}i(iu,"encodeSignaturePng");
13
+ export{yc as ATTACHMENT_ACCEPT,ta as ATTACHMENT_BACKOFF_MS,Ks as ATTACHMENT_INITIATE_PATH,ea as ATTACHMENT_MAX_ATTEMPTS,qs as ATTACHMENT_MIME_TYPES,Zs as ATTACHMENT_QUEUE_CONCURRENCY,Ct as CHAT_FEEDBACK_TYPES,ge as CHECKIN_ANSWERABLE_STATUS,Pe as FACT_FIELD_BY_KIND,Wt as FACT_VALUE_FIELD,St as FEEDBACK_NOTES_MAX_CHARS,So as LOGOUT_HOOK_BUDGET_MS,Hs as MAX_ATTACHMENTS_PER_MESSAGE,An as MAX_ATTACHMENT_BYTES,Ee as MAX_FILENAME_LENGTH,$e as MAX_IMAGE_KEYS_PER_MESSAGE,wt as MESSAGE_MAX_CHARS,Wa as MIN_POLL_INTERVAL_SECONDS,du as NULL_SECURE_STORE,qo as RECORDS_CLINIC_BATCH_MAX,Ae as SIGNATURE_CANVAS,Ws as attachmentSize,Pn as bootstrapChat,gc as createAttachmentQueue,wn as createChatController,Ro as createEntitlementPoller,Bp as createEverfurRuntime,dl as createRecordsClinicBatchClient,Bl as createRecordsDepthClient,vr as defaultErrorPolicy,iu as encodeSignaturePng,yl as factCorrectionFor,ml as factValueCorrection,hc as formatBytes,Yo as inferFactValueKind,Qs as initiateAttachmentUpload,$s as isAttachmentMime,As as isCheckinSettled,fl as isFactReviewerLocked,ri as mapDocumentContributions,ei as mapRecordDepth,Gt as mapRecordMarkers,Qt as mapRecordPdfLink,Yt as mapRecordShareLink,Xt as mapRecordShareList,ti as mapRecordsTimeline,Jt as mapSignatureSuggestions,Me as noopTelemetry,Tu as optionalModule,$l as rasterizeStrokes,Xl as rasterizeTypedName,Jo as resolveShareUrl,Vs as sanitizeFilename,_r as unavailableCamera,Js as uploadAttachmentBytes,Gs as validateAttachment};