@everfur/sdk 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +17 -8
  3. package/dist/{Chat-Cugs9Dsl.d.ts → Chat-DwGk5APA.d.ts} +3 -3
  4. package/dist/{Chat-B7oN62ww.d.cts → Chat-Ml-HlOiV.d.cts} +3 -3
  5. package/dist/{DepthViews-GxV7wSzT.d.cts → DepthViews-DAJySZqL.d.cts} +1 -1
  6. package/dist/{DepthViews-CiYBIBEZ.d.ts → DepthViews-DwCS5KKh.d.ts} +1 -1
  7. package/dist/{DepthViews-CUNmy99u.d.cts → DepthViews-PgA2KvTE.d.cts} +1 -1
  8. package/dist/{DepthViews-C6qFJ3fV.d.ts → DepthViews-kM-_Mn2x.d.ts} +1 -1
  9. package/dist/animations/index.cjs +1 -1
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/animations/index.js +1 -1
  13. package/dist/{attachments-20X7Vuip.d.ts → attachments-BH0vdghi.d.ts} +2 -2
  14. package/dist/{attachments-HXFmzk-D.d.cts → attachments-BV1Mbqm-.d.cts} +5 -5
  15. package/dist/{attachments-DN2cNGwe.d.ts → attachments-DWv9stp1.d.ts} +5 -5
  16. package/dist/{attachments-CkaPnIUw.d.cts → attachments-DaWeeeBW.d.cts} +2 -2
  17. package/dist/{bookingCopy-B5igVNE0.d.ts → bookingCopy-Cc3Cl-IJ.d.ts} +2 -2
  18. package/dist/{bookingCopy-pJpizqgz.d.cts → bookingCopy-DRwrhDUe.d.cts} +2 -2
  19. package/dist/{casesRepository-DFoK5N1O.d.cts → casesRepository-BhfPDWhY.d.cts} +1 -1
  20. package/dist/{casesRepository-qAkKKgji.d.ts → casesRepository-DMkRRKr8.d.ts} +1 -1
  21. package/dist/chat/index.cjs +16 -15
  22. package/dist/chat/index.d.cts +9 -9
  23. package/dist/chat/index.d.ts +9 -9
  24. package/dist/chat/index.js +16 -15
  25. package/dist/client/index.cjs +2 -2
  26. package/dist/client/index.d.cts +6 -6
  27. package/dist/client/index.d.ts +6 -6
  28. package/dist/client/index.js +2 -2
  29. package/dist/{config-BB7e52FP.d.ts → config-CuOczZUI.d.ts} +1 -1
  30. package/dist/{config-u6rK4mKt.d.cts → config-lilR0260.d.cts} +1 -1
  31. package/dist/consent/index.cjs +1 -1
  32. package/dist/consent/index.d.cts +5 -5
  33. package/dist/consent/index.d.ts +5 -5
  34. package/dist/consent/index.js +1 -1
  35. package/dist/{context-BZ1k4qE3.d.cts → context-BA6X6ZHd.d.cts} +13 -5
  36. package/dist/{context-CJYmubjx.d.ts → context-CL3cR0MA.d.ts} +13 -5
  37. package/dist/{copy-CtfctY-J.d.ts → copy-A2n7xXsL.d.ts} +2 -2
  38. package/dist/{copy-DCO_lUXd.d.cts → copy-DkoUo0VR.d.cts} +2 -2
  39. package/dist/core/index.cjs +6 -7
  40. package/dist/core/index.d.cts +12 -12
  41. package/dist/core/index.d.ts +12 -12
  42. package/dist/core/index.js +6 -7
  43. package/dist/{depth-_vMRMm4x.d.ts → depth-6_BYIt0s.d.ts} +2 -2
  44. package/dist/{depth-C_ym3qyi.d.cts → depth-DOPtk0vF.d.cts} +2 -2
  45. package/dist/{entitlementRepository-tSY9WWad.d.ts → entitlementRepository-BE-L6vX1.d.ts} +2 -2
  46. package/dist/{entitlementRepository-DA04yM54.d.cts → entitlementRepository-Blh38A2b.d.cts} +2 -2
  47. package/dist/{identity-D5uywCtp.d.ts → identity-4lohfP2L.d.ts} +8 -2
  48. package/dist/{identity-CUynm8S2.d.cts → identity-YXqHjBln.d.cts} +8 -2
  49. package/dist/index.cjs +16 -16
  50. package/dist/index.d.cts +15 -14
  51. package/dist/index.d.ts +15 -14
  52. package/dist/index.js +16 -16
  53. package/dist/notifications/index.cjs +1 -1
  54. package/dist/notifications/index.d.cts +2 -2
  55. package/dist/notifications/index.d.ts +2 -2
  56. package/dist/notifications/index.js +1 -1
  57. package/dist/{pets-mnbN0kZG.d.ts → pets-DzXi_9hY.d.ts} +1 -1
  58. package/dist/{pets-BrdkpNJH.d.cts → pets-m61lisZt.d.cts} +1 -1
  59. package/dist/{petsRepository-RGI_xPK1.d.ts → petsRepository-B1I6Lq_m.d.ts} +1 -1
  60. package/dist/{petsRepository-CQgzEFyz.d.cts → petsRepository-CQeuDdDC.d.cts} +1 -1
  61. package/dist/photo/index.cjs +1 -1
  62. package/dist/photo/index.js +1 -1
  63. package/dist/{ports-Cu_Wc5Aw.d.ts → ports-CrGAcey9.d.ts} +6 -4
  64. package/dist/{ports-DibY-h60.d.cts → ports-DUqO_XX0.d.cts} +6 -4
  65. package/dist/records/depth/index.cjs +3 -3
  66. package/dist/records/depth/index.d.cts +7 -7
  67. package/dist/records/depth/index.d.ts +7 -7
  68. package/dist/records/depth/index.js +3 -3
  69. package/dist/records/index.cjs +7 -7
  70. package/dist/records/index.d.cts +9 -9
  71. package/dist/records/index.d.ts +9 -9
  72. package/dist/records/index.js +7 -7
  73. package/dist/{requestFunnel-BkSFsLKh.d.ts → requestFunnel-B86gQFka.d.ts} +2 -2
  74. package/dist/{requestFunnel-nmhlEdbM.d.cts → requestFunnel-hXkP5T7K.d.cts} +2 -2
  75. package/dist/{runtimeTypes-CWG1Cm4N.d.cts → runtimeTypes-Bt_tIj3h.d.cts} +29 -5
  76. package/dist/{runtimeTypes-CU2xVmiQ.d.ts → runtimeTypes-DXKxY2yq.d.ts} +29 -5
  77. package/dist/server/events/index.cjs +2 -2
  78. package/dist/server/events/index.d.cts +25 -6
  79. package/dist/server/events/index.d.ts +25 -6
  80. package/dist/server/events/index.js +2 -2
  81. package/dist/server/index.cjs +4 -4
  82. package/dist/server/index.d.cts +5 -4
  83. package/dist/server/index.d.ts +5 -4
  84. package/dist/server/index.js +4 -4
  85. package/dist/televet/booking/index.cjs +18 -15
  86. package/dist/televet/booking/index.d.cts +6 -6
  87. package/dist/televet/booking/index.d.ts +6 -6
  88. package/dist/televet/booking/index.js +19 -16
  89. package/dist/televet/index.cjs +1 -1
  90. package/dist/televet/index.js +1 -1
  91. package/dist/testing/index.d.cts +1 -1
  92. package/dist/testing/index.d.ts +1 -1
  93. package/dist/testing/rn/index.cjs +1 -1
  94. package/dist/testing/rn/index.d.cts +7 -7
  95. package/dist/testing/rn/index.d.ts +7 -7
  96. package/dist/testing/rn/index.js +1 -1
  97. package/dist/testing/web/index.cjs +1 -1
  98. package/dist/testing/web/index.d.cts +7 -7
  99. package/dist/testing/web/index.d.ts +7 -7
  100. package/dist/testing/web/index.js +1 -1
  101. package/dist/{timelineRows-PWRoTntZ.d.ts → timelineRows-C2ObTmfN.d.ts} +1 -1
  102. package/dist/{timelineRows-CYF_I5Aq.d.cts → timelineRows-CrA-ePrQ.d.cts} +1 -1
  103. package/dist/{useRecordsDepth-Cg4cc4bQ.d.cts → useRecordsDepth-Dcr9y6i-.d.cts} +1 -1
  104. package/dist/{useRecordsDepth-eS9BJv_a.d.ts → useRecordsDepth-NQNJaGyk.d.ts} +1 -1
  105. package/dist/video/index.cjs +1 -1
  106. package/dist/video/index.js +1 -1
  107. package/dist/{view-n_oSGiiT.d.ts → view-DWJa2L0U.d.ts} +2 -2
  108. package/dist/{view-D4UOm-yo.d.cts → view-Dk7xpBJ4.d.cts} +2 -2
  109. package/dist/web/consent/index.cjs +1 -1
  110. package/dist/web/consent/index.d.cts +5 -5
  111. package/dist/web/consent/index.d.ts +5 -5
  112. package/dist/web/consent/index.js +1 -1
  113. package/dist/web/index.cjs +13 -12
  114. package/dist/web/index.d.cts +17 -16
  115. package/dist/web/index.d.ts +17 -16
  116. package/dist/web/index.js +13 -12
  117. package/dist/web/notifications/index.cjs +1 -1
  118. package/dist/web/notifications/index.d.cts +3 -3
  119. package/dist/web/notifications/index.d.ts +3 -3
  120. package/dist/web/notifications/index.js +1 -1
  121. package/dist/web/records/depth/index.cjs +3 -3
  122. package/dist/web/records/depth/index.d.cts +7 -7
  123. package/dist/web/records/depth/index.d.ts +7 -7
  124. package/dist/web/records/depth/index.js +3 -3
  125. package/dist/web/records/index.cjs +7 -7
  126. package/dist/web/records/index.d.cts +9 -9
  127. package/dist/web/records/index.d.ts +9 -9
  128. package/dist/web/records/index.js +7 -7
  129. package/dist/web/televet/booking/index.cjs +4 -4
  130. package/dist/web/televet/booking/index.d.cts +6 -6
  131. package/dist/web/televet/booking/index.d.ts +6 -6
  132. package/dist/web/televet/booking/index.js +4 -4
  133. package/dist/web/televet/index.cjs +1 -1
  134. package/dist/web/televet/index.js +1 -1
  135. package/package.json +1 -1
package/dist/web/index.js CHANGED
@@ -96,7 +96,7 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
96
96
  return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
97
97
  return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
98
98
  return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
99
- return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function createIdentityProvider(userRef2,getToken,onMinted){let cached=null,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.9.2",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
99
+ return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.10.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
100
100
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{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}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
101
101
  return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
102
102
  return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
@@ -110,8 +110,8 @@ return Object.freeze({id:m.id,role:m.role,text:m.text,createdAt:m.createdAt})}fu
110
110
  return Object.freeze({status:s.status,messages:/* @__PURE__ */Object.freeze([...s.messages]),conversationId:s.conversationId,error:s.error,isStreaming:s.isStreaming,isBootstrapping:s.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...s.suggestedPrompts]),unreadCount:s.unreadCount})}function makeError(code,retryable,wireMessage){return makeEverfurError(code,{retryable:retryable,...wireMessage?{wireMessage:wireMessage}:{}})}function errorFromFrame(frame){let code=fromWire(frame.code);return makeEverfurError(code,{retryable:frame.retryable||shouldRetry(code),wireCode:frame.code,wireEnvelope:"sse_frame",...frame.serverRequestId?{requestId:frame.serverRequestId}:{},...frame.wireMessage?{wireMessage:frame.wireMessage}:{},raw:frame})}function synthErrorFrame(error){return errorFrame({code:canonicalWireCode(error.code),retryable:error.retryable,wireMessage:error.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:error.requestId??null})}function canonicalWireCode(code){switch(code){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"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(code)}}function parsePromptCategories(raw){let list=Array.isArray(raw)?raw:isPlainObject2(raw)&&Array.isArray(raw.categories)?raw.categories:[],out=[];for(let entry of list){if(!isPlainObject2(entry))continue;let category=asStr(entry.category)??asStr(entry.title)??"",prompts=asPromptTextList(entry.prompts??entry.questions);category.length===0&&prompts.length===0||out.push(/* @__PURE__ */Object.freeze({category:category,prompts:/* @__PURE__ */Object.freeze(prompts)}))}/* @__PURE__ */
111
111
  return Object.freeze(out)}function flattenPrompts(categories){let seen=/* @__PURE__ */new Set,out=[];for(let category of categories)for(let prompt of category.prompts){let trimmed=prompt.trim();trimmed.length===0||seen.has(trimmed)||(seen.add(trimmed),out.push(trimmed))}return out}function isPlainObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asStr(v){return typeof v=="string"?v:null}function asPromptTextList(v){if(!Array.isArray(v))return[];let out=[];for(let entry of v)if(typeof entry=="string")out.push(entry);else if(isPlainObject2(entry)){let text3=asStr(entry.text)??asStr(entry.prompt)??asStr(entry.title);text3!==null&&out.push(text3)}return out}function defaultIdFactory(){let counter=0;return()=>`m-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function defaultIdempotencyFactory(){let counter=0;return()=>`chat-send-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var defaultTimers2={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()};async function*withWatchdog(source,budget,signal,timers){let it=source[Symbol.asyncIterator](),overall=deadline(budget.overallMs,timers),idle=deadline(budget.idleMs,timers),abort=abortPromise(signal);try{for(;;){if(signal.aborted)return;let nextTagged=it.next().then(value=>({tag:"next",value:value}),()=>({tag:"streamError"})),outcome=await Promise.race([nextTagged,idle.promise.then(()=>({tag:"idle"})),overall.promise.then(()=>({tag:"overall"})),abort.then(()=>({tag:"abort"}))]);if(outcome.tag==="abort")return;if(outcome.tag==="streamError"){if(signal.aborted)return;yield synthStreamErrorFrame();return}if(outcome.tag==="idle"||outcome.tag==="overall"){yield synthTimeoutFrame();return}let result=outcome.value;if(result.done||(idle.reset(budget.idleMs),yield result.value,result.value.terminal))return}}finally{idle.cancel(),overall.cancel(),Promise.resolve(it.return?.(void 0)).catch(()=>{})}}function synthTimeoutFrame(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function synthStreamErrorFrame(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function deadline(ms,timers){let resolveFn=()=>{},promise=new Promise(resolve=>{resolveFn=resolve}),handle=timers.setTimeout(()=>resolveFn(),ms);return{promise:promise,reset(next){timers.clearTimeout(handle),handle=timers.setTimeout(()=>resolveFn(),next)},cancel(){timers.clearTimeout(handle)}}}function abortPromise(signal){return new Promise(resolve=>{if(signal.aborted){resolve();return}signal.addEventListener("abort",()=>resolve(),{once:true})})}var MAX_USER_REF_LEN=128,MAX_PET_REF_LEN=128,CONTROL_CHAR=/[\u0000-\u001F\u007F]/,UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_PET_REF_LEN)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${MAX_PET_REF_LEN} characters`);if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","petRef must be printable (no control characters)");return v}function userRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_USER_REF_LEN)throw new EverfurConfigError("invalid-argument",`userRef must be 1..${MAX_USER_REF_LEN} characters`);if(v.includes("@"))throw new EverfurConfigError("invalid-argument","userRef must not contain '@'");if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","userRef must be printable (no control characters)");return v}function conversationId(raw){if(!UUID_RE.test(raw))throw new EverfurConfigError("invalid-argument","conversationId must be a UUID");return raw}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function isLiveAskAnswered(counts){let{askCount:askCount,answerCount:answerCount}=counts;return typeof askCount!="number"||!Number.isFinite(askCount)||typeof answerCount!="number"||!Number.isFinite(answerCount)||askCount<=0?true:answerCount>=askCount}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}function parseCheckinOriginRef(ref){return parseCheckinOrigin(ref)?.caseId??null}function historyQuery(opts,max){if(opts?.limit!==void 0&&(!Number.isInteger(opts.limit)||opts.limit<1||opts.limit>max))return err(makeEverfurError("validationFailed"));let query=[];for(let[key,value]of[["cursor",opts?.cursor],["pet_ref",opts?.petRef]])if(value!==void 0){if(typeof value!="string"||value.length===0||hasLoneSurrogate(value))return err(makeEverfurError("validationFailed"));query.push(`${key}=${encodeURIComponent(value)}`)}return opts?.limit!==void 0&&query.push(`limit=${opts.limit}`),ok(query.length?`?${query.join("&")}`:"")}function validConversationId(id){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)}function object(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function cursor(value){return value==null||typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}function mapConversationPage(value){let page=object(value);if(!page||!Array.isArray(page.conversations)||!cursor(page.next_cursor))return malformed2();let conversations=[];for(let raw of page.conversations){let row=object(raw);if(!row||typeof row.conversation_id!="string"||!validConversationId(row.conversation_id)||!(row.title==null||typeof row.title=="string")||typeof row.created_at!="string"||typeof row.updated_at!="string")return malformed2();let unread=row.unread_message_count;if(!(unread==null||Number.isInteger(unread)&&unread>=0))return malformed2();conversations.push(/* @__PURE__ */Object.freeze({id:row.conversation_id,title:row.title??null,createdAt:row.created_at,updatedAt:row.updated_at,unreadCount:unread??null}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(conversations),nextCursor:page.next_cursor??null}))}function mapMessagePage(value){let page=object(value);if(!page||!Array.isArray(page.messages)||!cursor(page.next_cursor))return malformed2();let messages=[],seen=/* @__PURE__ */new Set;for(let raw of page.messages){let row=object(raw);if(!row||typeof row.message_id!="string"||!validConversationId(row.message_id)||typeof row.role!="string"||typeof row.content!="string"||typeof row.created_at!="string")return malformed2();if(row.role!=="user"&&row.role!=="assistant"&&row.role!=="vet"||seen.has(row.message_id))continue;if(seen.add(row.message_id),row.role==="vet"){messages.push(vetMessage(row,row.message_id,row.content,row.created_at));continue}let origin=typeof row.proactive_origin_ref=="string"?row.proactive_origin_ref:null,caseId=row.role==="assistant"?parseCheckinOriginRef(origin):null;messages.push(/* @__PURE__ */Object.freeze({id:row.message_id,role:row.role,text:row.content,createdAt:row.created_at,...row.role==="assistant"?{responseId:row.message_id}:{},...row.urgency_level!==void 0?{urgencyLevel:normalizeUrgency(row.urgency_level)}:{},...Array.isArray(row.citations)?{citations:historyCitations(row.citations)}:{},...origin!==null?{proactiveOriginRef:origin}:{},...caseId!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:caseId,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(messages),nextCursor:page.next_cursor??null}))}function vetMessage(row,id,text3,createdAt){let sender=object(row.sender),displayName=trimmedText(sender?.display_name)??trimmedText(row.sender_display_name),specialty=trimmedText(sender?.specialty);/* @__PURE__ */
112
112
  return Object.freeze({id:id,role:"vet",text:text3,createdAt:createdAt,sender:/* @__PURE__ */Object.freeze({displayName:displayName,specialty:specialty})})}function trimmedText(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&!hasLoneSurrogate(trimmed)?trimmed:null}function normalizeUrgency(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}function historyCitations(values){let keys=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
113
- return Object.freeze(values.flatMap(value=>{let row=object(value);if(!row||typeof row.source_name!="string"||typeof row.authority_tier!="string")return[];let citation={};for(let key of keys){let item=row[key];(typeof item=="string"||item===null)&&(citation[key]=item)}return[/* @__PURE__ */Object.freeze(citation)]}))}var CHAT_FEEDBACK_TYPES=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;function validateImageKeys(keys){return keys===void 0?null:!Array.isArray(keys)||keys.length>5?{reason:"too_many_images",error:makeError("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:keys.some(key=>typeof key!="string"||key.trim().length===0)?{reason:"bad_image_key",error:makeError("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function validateMessageText(text3){let raw=typeof text3=="string"?text3:"";if(raw.trim().length===0)return{reason:"empty",error:makeError("validationFailed",false,"message is empty or whitespace-only")};let codePoints=[...raw].length;return codePoints>MESSAGE_MAX_CHARS?{reason:"too_long",error:makeError("validationFailed",false,`message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`)}:null}function urgencyTier(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}async function*singleFrameStream(frame){yield frame}async function*emptyStream(){}var DEFAULT_IDLE_MS=6e4,DEFAULT_OVERALL_MS=18e4,DELTA_FLUSH_MS=24,DELTA_FLUSH_CHARS=512,SEND_IS_SERVER_DEDUPED=false;function createChatController(deps){return new ChatControllerImpl(deps)}var ChatControllerImpl=class extends MediaStore{constructor(deps){super(freezeSnapshot({status:"idle",messages:[],conversationId:deps.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */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=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingDelta="";this.flushHandle=null;this.auth=deps.auth,this.funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),this.petRef=deps.petRef??null,this.cases=createCasesRepositoryOver(this.funnel),this.telemetry=deps.telemetry??noopTelemetry,this.errorPolicy=deps.errorPolicy??defaultErrorPolicy,this.timers=deps.timers??defaultTimers2,this.rng=deps.rng??Math.random,this.newId=deps.newId??defaultIdFactory(),this.makeIdempotencyKey=deps.makeIdempotencyKey??defaultIdempotencyFactory(),this.budget={idleMs:deps.budget?.idleMs??DEFAULT_IDLE_MS,overallMs:deps.budget?.overallMs??DEFAULT_OVERALL_MS}}patch(partial){if(partial.messages!==void 0){let frozen=/* @__PURE__ */Object.freeze([...partial.messages]);super.patch({...partial,messages:frozen});return}super.patch(partial)}send(text3,opts,handlers){let options=opts??{};if(this.disposed||this.snapshot.isBootstrapping){let error=makeError(this.disposed?"accessDenied":"internalError",!this.disposed);return handlers?(handlers.onError(error),()=>{}):singleFrameStream(synthErrorFrame(error))}let invalid4=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid4!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),this.patch({status:"error",isStreaming:false,error:invalid4.error}),handlers?(handlers.onError(invalid4.error),()=>{}):singleFrameStream(synthErrorFrame(invalid4.error));if(handlers)return this.driveWithHandlers(text3,options,handlers);let turn=this.beginTurn(text3,options);return this.runTurn(turn,options.signal)}askEverfur(prompt,opts){if(this.disposed)return singleFrameStream(synthErrorFrame(makeError("accessDenied",false)));let invalid4=validateMessageText(prompt);return invalid4!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),singleFrameStream(synthErrorFrame(invalid4.error))):(this.resetThread(),this.send(prompt,opts??{}))}retryLast(){let turn=this.lastTurn;if(turn===null){let id=this.snapshot.conversationId;return id!==null&&this.snapshot.status==="error"?this.retryHistory(id):emptyStream()}turn.assistantMessageId=null,turn.sawDelta=false,turn.conversationIdOverride=null,this.discardPendingDelta();let messages=this.snapshot.messages.some(m=>m.id===turn.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,makeUser(turn.userMessageId,turn.text,this.stamp())];return this.patch({error:null,stopped:false,messages:messages}),this.runTurn(turn,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let stopped=this.snapshot.messages.some(m=>m.role==="user"&&m.pending===true),messages=stopped?this.snapshot.messages.map(m=>m.pending===true?stripPending(m):m):this.snapshot.messages;(this.snapshot.status==="streaming"||stopped)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...stopped?{messages:messages,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot()}resetThread(prompts=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=prompts,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:prompts,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 teardown of this.handlerTeardowns)teardown();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(id){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==id&&this.patch({conversationId:id}))}adoptPrompts(categories){if(this.disposed)return;let prompts=/* @__PURE__ */Object.freeze(flattenPrompts(categories));this.bootstrapPrompts=prompts,this.scopePrompts=prompts,this.replyPrompts===null&&(prompts.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:prompts}))}async listConversations(opts){return this.listConversationsWith(opts)}async listConversationsWith(opts,funnelOpts){let query=historyQuery(opts,100);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},opts?.signal,funnelOpts);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let page=mapConversationPage(result.value);if(page.ok){for(let conversation of page.value.conversations)conversation.unreadCount!==null&&this.unreadByConversation.set(conversation.id,conversation.unreadCount);let active=this.snapshot.conversationId,count2=active===null?void 0:this.unreadByConversation.get(active);count2!==void 0&&count2!==this.snapshot.unreadCount&&this.patch({unreadCount:count2}),this.reflectUnreadDot()}return page}reflectUnreadDot(){let unread=false;for(let count2 of this.unreadByConversation.values())if(count2>0){unread=true;break}unread!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:unread})}async openCheckin(target){if(this.disposed)return err(makeError("accessDenied",false));let named=target?.conversationId??null;if(named!==null){let opened2=await this.resumeConversation(named);return opened2.ok?ok(named):err(opened2.error)}let petRef2=target?.petRef??this.petRef,listed=await this.listConversations({...petRef2===null?{}:{petRef:petRef2},limit:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0)return ok(null);let opened=await this.resumeConversation(head.id);return opened.ok?ok(head.id):err(opened.error)}async markRead(opts){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null)return ok(void 0);let epoch=this.epoch,result=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${id}/read`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?(this.unreadByConversation.set(id,0),this.snapshot.conversationId===id&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),ok(void 0)):err(result.error)}async submitFeedback(responseId,feedbackType,notes,opts){if(this.disposed)return err(makeError("accessDenied",false));if(typeof responseId!="string"||responseId.trim().length===0||hasLoneSurrogate(responseId))return err(makeError("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!CHAT_FEEDBACK_TYPES.includes(feedbackType))return err(makeError("validationFailed",false,`feedback_type must be one of ${CHAT_FEEDBACK_TYPES.join(", ")}`));let note=typeof notes=="string"?notes.trim():"";if([...note].length>FEEDBACK_NOTES_MAX_CHARS)return err(makeError("validationFailed",false,`notes is over ${FEEDBACK_NOTES_MAX_CHARS} characters`));let body={feedback_type:feedbackType};note.length>0&&(body.notes=note);let epoch=this.epoch,result=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(responseId)}/feedback`,body:body},opts?.signal);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let feedbackId=result.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof feedbackId=="string"?feedbackId:""}))}async answerCheckin(caseId,answer,opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??this.petRef;if(petRef2===null)return err(makeError("validationFailed",false,"a check-in needs the pet the case belongs to"));let epoch=this.epoch,result=await this.cases.checkin(petRef2,caseId,answer,opts?.signal?{signal:opts.signal}:{});if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let openedAt=result.value.case.openedAt,checkin=/* @__PURE__ */Object.freeze({caseId:caseId,answer:answer,resolutionText:result.value.case.resolutionText,status:result.value.case.status??null,...openedAt!==null?{openedAt:openedAt}:{}}),carries=m=>m.checkin?.caseId===caseId;return this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,checkin:checkin}):m)}),result}async getMessages(id,opts){if(!validConversationId(id))return err(makeError("validationFailed",false));let query=historyQuery(opts,200);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${id}/messages${query.value}`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?mapMessagePage(result.value):result}async resumeConversation(id){if(this.disposed)return err(makeError("accessDenied",false));if(!validConversationId(id))return err(makeError("validationFailed",false));this.resetThread();let generation=this.historyGeneration;this.patch({conversationId:id,isBootstrapping:true,isLoadingHistory:true});let result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return this.patch({status:"error",error:result.error,isBootstrapping:false,isLoadingHistory:false}),result;let unread=this.unreadByConversation.get(id)??null;return this.patch({messages:result.value.messages,historyCursor:result.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:unread}),this.stampCheckinStatuses(generation),unread!==null&&unread>0&&this.markRead(),ok(void 0)}async stampCheckinStatuses(generation){let petRef2=this.petRef;if(petRef2===null||!this.snapshot.messages.some(m=>m.checkin!==void 0&&m.checkin.status===null))return;let result=await this.cases.list(petRef2);if(!result.ok||generation!==this.historyGeneration||this.disposed)return;let open=new Set(result.value.filter(row=>row.status===CHECKIN_ANSWERABLE_STATUS).map(row=>row.caseId)),byCase=new Map(result.value.map(row=>[row.caseId,row])),changed=false,messages=this.snapshot.messages.map(message=>{let checkin=message.checkin;if(checkin===void 0||checkin.status!==null)return message;changed=true;let row=byCase.get(checkin.caseId),openedAt=checkin.openedAt??row?.openedAt??null,watching=open.has(checkin.caseId),answerOnRecord=row!==void 0&&(!watching||isLiveAskAnswered({askCount:row.checkinAskCount,answerCount:row.checkinAnswerCount}))?row.lastResponse:null;/* @__PURE__ */
114
- return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null||this.snapshot.isStreaming)return ok(void 0);let generation=this.historyGeneration,result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async primeBounded(petRef2){let head=await this.headThreadWithUnread(petRef2);return head.ok?head.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(head.value)).ok?ok(head.value):ok(this.snapshot.conversationId):head.error.code==="accessDenied"||head.error.httpStatus===403?ok(null):err(head.error)}async headThreadWithUnread(petRef2){let listed=await this.listConversationsWith({...petRef2===null?{}:{petRef:petRef2},limit:1},{maxAttempts:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];return head===void 0||head.unreadCount===null||head.unreadCount<=0?ok(null):ok(head.id)}async createConversation(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef2,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef2?{pet_ref:petRef2}:{}},res=await this.authedUnary("chat.createConversation",req,signal,{maxAttempts:1});if(!res.ok)return err(res.error);let raw=res.value?.conversation_id??res.value?.id;return typeof raw!="string"||raw.length===0?err(makeError("internalError",true)):ok(raw)}async getPrompts(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null;if(petRef2!==null&&hasLoneSurrogate(petRef2))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef2!==null?`?pet_ref=${encodeURIComponent(petRef2)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending=needsConversation?this.unadoptedCreate:null;if(pending!==null&&(turn.petRef===null||turn.petRef===pending.petRef)){let primed=await pending.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&this.adoptConversation(primed.value)}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk):m);this.patch({messages:messages})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(done,turn){this.flushPendingDelta(turn),this.lastResponseIdValue=done.messageId?done.messageId:null;let nextConv=done.conversationId?done.conversationId:this.snapshot.conversationId,messages;if(turn.assistantMessageId!==null)messages=this.snapshot.messages.map(m=>m.id===turn.assistantMessageId?finalizeAssistant(m,done):m);else{let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true,messages=[...this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m),finalizeAssistant(makeAssistant(assistantId,"",this.stamp()),done)]}let followUps=flattenPrompts([{category:"",prompts:done.followUpQuestions}]);this.replyPrompts=followUps.length>0?/* @__PURE__ */Object.freeze(followUps):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:nextConv,messages:messages,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!done.urgencyProvided&&nextConv!==null&&this.classifyTurn(nextConv,this.lastResponseIdValue)}async classifyTurn(conversationId2,responseId){if(responseId===null||this.disposed)return;let messageId=String(responseId);if(this.classifiedMessageIds.has(messageId))return;this.classifiedMessageIds.add(messageId);let epoch=this.epoch,generation=this.historyGeneration,result=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId2}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId2)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.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 makeError("authRejected",false)}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef2=input.petRef??null,resume=input.resumeConversationId??null,candidateConversationIds=[],sawForbidden=false,sawUnauthorized=false,sawConversationInitFailure=false,authBlock=null,initFailure=null,conversationPromise=resume?controller.resumeConversation(resume).then(result=>result.ok?ok(resume):err(result.error)):controller.primeConversation(petRef2?{petRef:petRef2}:void 0),promptsPromise=controller.getPrompts(petRef2!==null?{petRef:petRef2}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId2=null;if(conversationRes.ok)conversationId2=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
113
+ return Object.freeze(values.flatMap(value=>{let row=object(value);if(!row||typeof row.source_name!="string"||typeof row.authority_tier!="string")return[];let citation={};for(let key of keys){let item=row[key];(typeof item=="string"||item===null)&&(citation[key]=item)}return[/* @__PURE__ */Object.freeze(citation)]}))}var CHAT_FEEDBACK_TYPES=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;function validateImageKeys(keys){return keys===void 0?null:!Array.isArray(keys)||keys.length>5?{reason:"too_many_images",error:makeError("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:keys.some(key=>typeof key!="string"||key.trim().length===0)?{reason:"bad_image_key",error:makeError("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function validateMessageText(text3){let raw=typeof text3=="string"?text3:"";if(raw.trim().length===0)return{reason:"empty",error:makeError("validationFailed",false,"message is empty or whitespace-only")};let codePoints=[...raw].length;return codePoints>MESSAGE_MAX_CHARS?{reason:"too_long",error:makeError("validationFailed",false,`message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`)}:null}function urgencyTier(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}async function*singleFrameStream(frame){yield frame}async function*emptyStream(){}var DEFAULT_IDLE_MS=6e4,DEFAULT_OVERALL_MS=18e4,DELTA_FLUSH_MS=24,DELTA_FLUSH_CHARS=512,SEND_IS_SERVER_DEDUPED=false;function createChatController(deps){return new ChatControllerImpl(deps)}var ChatControllerImpl=class extends MediaStore{constructor(deps){super(freezeSnapshot({status:"idle",messages:[],conversationId:deps.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */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=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingDelta="";this.flushHandle=null;this.auth=deps.auth,this.funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),this.petRef=deps.petRef??null,this.cases=createCasesRepositoryOver(this.funnel),this.telemetry=deps.telemetry??noopTelemetry,this.onConversationStarted=deps.onConversationStarted,this.errorPolicy=deps.errorPolicy??defaultErrorPolicy,this.timers=deps.timers??defaultTimers2,this.rng=deps.rng??Math.random,this.newId=deps.newId??defaultIdFactory(),this.makeIdempotencyKey=deps.makeIdempotencyKey??defaultIdempotencyFactory(),this.budget={idleMs:deps.budget?.idleMs??DEFAULT_IDLE_MS,overallMs:deps.budget?.overallMs??DEFAULT_OVERALL_MS}}patch(partial){if(partial.messages!==void 0){let frozen=/* @__PURE__ */Object.freeze([...partial.messages]);super.patch({...partial,messages:frozen});return}super.patch(partial)}send(text3,opts,handlers){let options=opts??{};if(this.disposed||this.snapshot.isBootstrapping){let error=makeError(this.disposed?"accessDenied":"internalError",!this.disposed);return handlers?(handlers.onError(error),()=>{}):singleFrameStream(synthErrorFrame(error))}let invalid4=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid4!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),this.patch({status:"error",isStreaming:false,error:invalid4.error}),handlers?(handlers.onError(invalid4.error),()=>{}):singleFrameStream(synthErrorFrame(invalid4.error));if(handlers)return this.driveWithHandlers(text3,options,handlers);let turn=this.beginTurn(text3,options);return this.runTurn(turn,options.signal)}askEverfur(prompt,opts){if(this.disposed)return singleFrameStream(synthErrorFrame(makeError("accessDenied",false)));let invalid4=validateMessageText(prompt);return invalid4!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid4.reason}),singleFrameStream(synthErrorFrame(invalid4.error))):(this.resetThread(),this.send(prompt,opts??{}))}retryLast(){let turn=this.lastTurn;if(turn===null){let id=this.snapshot.conversationId;return id!==null&&this.snapshot.status==="error"?this.retryHistory(id):emptyStream()}turn.assistantMessageId=null,turn.sawDelta=false,turn.conversationIdOverride=null,this.discardPendingDelta();let messages=this.snapshot.messages.some(m=>m.id===turn.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,makeUser(turn.userMessageId,turn.text,this.stamp())];return this.patch({error:null,stopped:false,messages:messages}),this.runTurn(turn,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let stopped=this.snapshot.messages.some(m=>m.role==="user"&&m.pending===true),messages=stopped?this.snapshot.messages.map(m=>m.pending===true?stripPending(m):m):this.snapshot.messages;(this.snapshot.status==="streaming"||stopped)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...stopped?{messages:messages,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot()}resetThread(prompts=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=prompts,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:prompts,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 teardown of this.handlerTeardowns)teardown();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(id){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==id&&this.patch({conversationId:id}))}adoptPrompts(categories){if(this.disposed)return;let prompts=/* @__PURE__ */Object.freeze(flattenPrompts(categories));this.bootstrapPrompts=prompts,this.scopePrompts=prompts,this.replyPrompts===null&&(prompts.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:prompts}))}async listConversations(opts){return this.listConversationsWith(opts)}async listConversationsWith(opts,funnelOpts){let query=historyQuery(opts,100);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},opts?.signal,funnelOpts);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let page=mapConversationPage(result.value);if(page.ok){for(let conversation of page.value.conversations)conversation.unreadCount!==null&&this.unreadByConversation.set(conversation.id,conversation.unreadCount);let active=this.snapshot.conversationId,count2=active===null?void 0:this.unreadByConversation.get(active);count2!==void 0&&count2!==this.snapshot.unreadCount&&this.patch({unreadCount:count2}),this.reflectUnreadDot()}return page}reflectUnreadDot(){let unread=false;for(let count2 of this.unreadByConversation.values())if(count2>0){unread=true;break}unread!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:unread})}async openCheckin(target){if(this.disposed)return err(makeError("accessDenied",false));let named=target?.conversationId??null;if(named!==null){let opened2=await this.resumeConversation(named);return opened2.ok?ok(named):err(opened2.error)}let petRef2=target?.petRef??this.petRef,listed=await this.listConversations({...petRef2===null?{}:{petRef:petRef2},limit:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0)return ok(null);let opened=await this.resumeConversation(head.id);return opened.ok?ok(head.id):err(opened.error)}async markRead(opts){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null)return ok(void 0);let epoch=this.epoch,result=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${id}/read`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?(this.unreadByConversation.set(id,0),this.snapshot.conversationId===id&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),ok(void 0)):err(result.error)}async submitFeedback(responseId,feedbackType,notes,opts){if(this.disposed)return err(makeError("accessDenied",false));if(typeof responseId!="string"||responseId.trim().length===0||hasLoneSurrogate(responseId))return err(makeError("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!CHAT_FEEDBACK_TYPES.includes(feedbackType))return err(makeError("validationFailed",false,`feedback_type must be one of ${CHAT_FEEDBACK_TYPES.join(", ")}`));let note=typeof notes=="string"?notes.trim():"";if([...note].length>FEEDBACK_NOTES_MAX_CHARS)return err(makeError("validationFailed",false,`notes is over ${FEEDBACK_NOTES_MAX_CHARS} characters`));let body={feedback_type:feedbackType};note.length>0&&(body.notes=note);let epoch=this.epoch,result=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(responseId)}/feedback`,body:body},opts?.signal);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let feedbackId=result.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof feedbackId=="string"?feedbackId:""}))}async answerCheckin(caseId,answer,opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??this.petRef;if(petRef2===null)return err(makeError("validationFailed",false,"a check-in needs the pet the case belongs to"));let epoch=this.epoch,result=await this.cases.checkin(petRef2,caseId,answer,opts?.signal?{signal:opts.signal}:{});if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let openedAt=result.value.case.openedAt,checkin=/* @__PURE__ */Object.freeze({caseId:caseId,answer:answer,resolutionText:result.value.case.resolutionText,status:result.value.case.status??null,...openedAt!==null?{openedAt:openedAt}:{}}),carries=m=>m.checkin?.caseId===caseId;return this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,checkin:checkin}):m)}),result}async getMessages(id,opts){if(!validConversationId(id))return err(makeError("validationFailed",false));let query=historyQuery(opts,200);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${id}/messages${query.value}`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?mapMessagePage(result.value):result}async resumeConversation(id){if(this.disposed)return err(makeError("accessDenied",false));if(!validConversationId(id))return err(makeError("validationFailed",false));this.resetThread();let generation=this.historyGeneration;this.patch({conversationId:id,isBootstrapping:true,isLoadingHistory:true});let result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return this.patch({status:"error",error:result.error,isBootstrapping:false,isLoadingHistory:false}),result;let unread=this.unreadByConversation.get(id)??null;return this.patch({messages:result.value.messages,historyCursor:result.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:unread}),this.stampCheckinStatuses(generation),unread!==null&&unread>0&&this.markRead(),ok(void 0)}async stampCheckinStatuses(generation){let petRef2=this.petRef;if(petRef2===null||!this.snapshot.messages.some(m=>m.checkin!==void 0&&m.checkin.status===null))return;let result=await this.cases.list(petRef2);if(!result.ok||generation!==this.historyGeneration||this.disposed)return;let open=new Set(result.value.filter(row=>row.status===CHECKIN_ANSWERABLE_STATUS).map(row=>row.caseId)),byCase=new Map(result.value.map(row=>[row.caseId,row])),changed=false,messages=this.snapshot.messages.map(message=>{let checkin=message.checkin;if(checkin===void 0||checkin.status!==null)return message;changed=true;let row=byCase.get(checkin.caseId),openedAt=checkin.openedAt??row?.openedAt??null,watching=open.has(checkin.caseId),answerOnRecord=row!==void 0&&(!watching||isLiveAskAnswered({askCount:row.checkinAskCount,answerCount:row.checkinAnswerCount}))?row.lastResponse:null;/* @__PURE__ */
114
+ return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null||this.snapshot.isStreaming)return ok(void 0);let generation=this.historyGeneration,result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async primeBounded(petRef2){let head=await this.headThreadWithUnread(petRef2);return head.ok?head.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(head.value)).ok?ok(head.value):ok(this.snapshot.conversationId):head.error.code==="accessDenied"||head.error.httpStatus===403?ok(null):err(head.error)}async headThreadWithUnread(petRef2){let listed=await this.listConversationsWith({...petRef2===null?{}:{petRef:petRef2},limit:1},{maxAttempts:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];return head===void 0||head.unreadCount===null||head.unreadCount<=0?ok(null):ok(head.id)}async createConversation(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef2,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef2?{pet_ref:petRef2}:{}},res=await this.authedUnary("chat.createConversation",req,signal,{maxAttempts:1});if(!res.ok)return err(res.error);let raw=res.value?.conversation_id??res.value?.id;return typeof raw!="string"||raw.length===0?err(makeError("internalError",true)):ok(raw)}async getPrompts(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null;if(petRef2!==null&&hasLoneSurrogate(petRef2))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef2!==null?`?pet_ref=${encodeURIComponent(petRef2)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending=needsConversation?this.unadoptedCreate:null;if(pending!==null&&(turn.petRef===null||turn.petRef===pending.petRef)){let primed=await pending.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(primed.value),this.reportConversationStarted(primed.value))}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value),this.reportConversationStarted(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{this.reportSessionRejected();let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){this.reportSessionRejected();let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let e=this.authRejected();yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk):m);this.patch({messages:messages})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(done,turn){this.flushPendingDelta(turn),this.lastResponseIdValue=done.messageId?done.messageId:null;let nextConv=done.conversationId?done.conversationId:this.snapshot.conversationId,messages;if(turn.assistantMessageId!==null)messages=this.snapshot.messages.map(m=>m.id===turn.assistantMessageId?finalizeAssistant(m,done):m);else{let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true,messages=[...this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m),finalizeAssistant(makeAssistant(assistantId,"",this.stamp()),done)]}let followUps=flattenPrompts([{category:"",prompts:done.followUpQuestions}]);this.replyPrompts=followUps.length>0?/* @__PURE__ */Object.freeze(followUps):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:nextConv,messages:messages,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!done.urgencyProvided&&nextConv!==null&&this.classifyTurn(nextConv,this.lastResponseIdValue)}async classifyTurn(conversationId2,responseId){if(responseId===null||this.disposed)return;let messageId=String(responseId);if(this.classifiedMessageIds.has(messageId))return;this.classifiedMessageIds.add(messageId);let epoch=this.epoch,generation=this.historyGeneration,result=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId2}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId2)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(id){try{this.onConversationStarted?.(id)}catch{}}authRejected(){return makeError("authRejected",false)}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef2=input.petRef??null,resume=input.resumeConversationId??null,candidateConversationIds=[],sawForbidden=false,sawUnauthorized=false,sawConversationInitFailure=false,authBlock=null,initFailure=null,conversationPromise=resume?controller.resumeConversation(resume).then(result=>result.ok?ok(resume):err(result.error)):controller.primeConversation(petRef2?{petRef:petRef2}:void 0),promptsPromise=controller.getPrompts(petRef2!==null?{petRef:petRef2}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId2=null;if(conversationRes.ok)conversationId2=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
115
115
  return Object.freeze({conversationId:conversationId2,petRef:petRef2,suggestedPrompts:suggestedPrompts,error:error,warning:error===null&&conversationId2===null&&sawConversationInitFailure?CONVERSATION_NOT_PRIMED_WARNING:null,cause:authBlock??initFailure,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...candidateConversationIds]),sawForbidden:sawForbidden,sawUnauthorized:sawUnauthorized,sawConversationInitFailure:sawConversationInitFailure})})}var CONVERSATION_NOT_PRIMED_WARNING="Chat is ready. Your first message will start the conversation.";function isUnauthorized(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function isForbidden(e){return e.httpStatus===403||e.code==="accessDenied"}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),ATTACHMENT_ACCEPT="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",MAX_ATTACHMENT_BYTES=10*1024*1024,MAX_ATTACHMENTS_PER_MESSAGE=5,MAX_FILENAME_LENGTH=120,ATTACHMENT_INITIATE_PATH="/widget/v1/uploads/initiate";function isAttachmentMime(mime){return typeof mime=="string"&&ATTACHMENT_MIME_TYPES.includes(mime.trim().toLowerCase())}function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
116
116
  return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str4=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str4(o.upload_id),uploadUrl=str4(o.upload_url),s3Key=str4(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
117
117
  return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str4(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight3=/* @__PURE__ */new Set,listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed=false,publish2=()=>{snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners2)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed&&inFlight3.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight3.add(id),run(row).finally(()=>{inFlight3.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot:()=>snapshot,get uploading(){return snapshot.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners2.clear(),snapshot=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["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"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str2=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str2(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(o.ref),name:name,dose:str2(o.dose),frequency:str2(o.frequency),startDate:str2(o.start_date),endDate:str2(o.end_date),notes:str2(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
@@ -119,15 +119,14 @@ return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(
119
119
  return Object.freeze({petRef:str3(o.pet_ref)??petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef2=str3(o.pet_ref);return petRef2===null||petRef2.length===0?null:/* @__PURE__ */Object.freeze({petId:str3(o.pet_id),petRef:petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str3(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
120
120
  return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal2=(req,signal)=>signal?{...req,signal:signal}:req,petPath2=petRef2=>validate(petRef2,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef2)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal2({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef2,profile,opts){let invalid4=validate(petRef2,profile);if(invalid4!==null)return err(invalid4);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef2)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async updatePet(petRef2,patch,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal2({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async getPetProfile(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal2({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal2({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal2({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function deniedDecisionsFor(level,reason){let disabled=/* @__PURE__ */Object.freeze({reason:reason,level:level,recoverable:false}),rows=[],seen=/* @__PURE__ */new Set;for(let name of Object.keys(REQUIRES))for(let resource of REQUIRES[name])seen.has(resource)||(seen.add(resource),rows.push(/* @__PURE__ */Object.freeze({resource:resource,granted:false,disabled:disabled}))/* @__PURE__ */);return Object.freeze(rows)}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
121
121
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
122
- return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef2,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef2}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending=inFlight2.get(scope);if(pending!==void 0)return pending;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel2){return channel2<=.03928?channel2/12.92:Math.pow((channel2+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function rgbToHsl(r,g,b){let rn=r/255,gn=g/255,bn=b/255,mx=Math.max(rn,gn,bn),mn=Math.min(rn,gn,bn),l=(mx+mn)/2;if(mx===mn)return{h:0,s:0,l:l};let d=mx-mn,s=d/(1-Math.abs(2*l-1)),h;return mx===rn?(h=(gn-bn)/d*60,h<0&&(h=h+360)):mx===gn?h=((bn-rn)/d+2)*60:h=((rn-gn)/d+4)*60,{h:h,s:s,l:l}}function hslToRgb(hsl){let{h:h,s:s,l:l}=hsl,c=(1-Math.abs(2*l-1))*s,hp=h/60,x=c*(1-Math.abs(hp%2-1)),m=l-c/2,sector=Math.floor(hp)%6,rgb1=[[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]],[r1,g1,b1]=rgb1[sector];return{r:channel(r1+m),g:channel(g1+m),b:channel(b1+m)}}function channel(v){return Math.min(255,Math.max(0,Math.floor(v*255+.5)))}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog"]),THEME_SLOT_KEYS=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),SLOT_MIN_CONTRAST=4.5,EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let text3=typeof value=="string"&&value.length<=16?value.trim().replace(/ ?px$/i,""):null,n=typeof value=="number"?value:text3!==null&&text3.length>0?Number(text3):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let slot=parseSlot(raw);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function pick2(raw,snake,camel){return raw[snake]!==void 0?raw[snake]:raw[camel]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base,over){return over===null||Object.keys(over).length===0?base??EMPTY:base===null||Object.keys(base).length===0?over:/* @__PURE__ */Object.freeze({...base,...over})}function isOpaque(color){let rgba=toRgba(color);return rgba!==null&&rgba.a>=1}var SLOT_MIN_BORDER_CONTRAST=3,DECORATIVE_EDGE_SLOTS=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep"]);function sameColor(a,b){let left=parseColor(a);return left!==null&&left===parseColor(b)}function boundaryFor(fill,surrounds,seats=[]){if(surrounds.length===0)return null;let shown=surrounds.map(ground=>flattenOnto(fill,ground)??fill);if(surrounds.every((ground,index)=>contrastRatio(shown[index],ground)>=SLOT_MIN_BORDER_CONTRAST))return null;let against=[...surrounds,...shown,...seats];return pushToContrast(shown[0],against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST)}function seatsOf(background,defaults){return background===void 0?defaults:defaults.length===0?[background]:defaults.map(ground=>flattenOnto(background,ground)??ground)}function someInkReads(seats,target){let pole=poleForGrounds(seats);return seats.every(seat=>contrastRatio(pole,seat)>=target)}function collapseUnsatisfiableFill(background,defaults){let ground=defaults[0];return ground===void 0?null:flattenOnto(background,ground)}function inkFor(seats){let pick5=legibleOn(seats[0],SLOT_MIN_CONTRAST);return seats.every(seat=>contrastRatio(pick5,seat)>=SLOT_MIN_CONTRAST)?pick5:poleForGrounds(seats)}function edgeShowsTheControl(name,edge,fill,around,melts){return DECORATIVE_EDGE_SLOTS.has(name)?false:melts?true:fill!==void 0&&sameColor(edge,fill)?false:!(around!==void 0&&fill!==void 0&&isOpaque(fill))}function guardSlotContrast(slots,grounds2,surrounds){let changed=false,out={};for(let name of THEME_SLOT_NAMES){let slot=slots[name];if(slot===void 0)continue;let bg=slot.backgroundColor,defaults=grounds2?.[name]??[],seats=seatsOf(bg,defaults),next={...slot},fixed=false;if(bg!==void 0&&seats.length>1&&!someInkReads(seats,SLOT_MIN_CONTRAST)){let opaque=collapseUnsatisfiableFill(bg,defaults);opaque!==null&&(next.backgroundColor=opaque,seats=[opaque],fixed=true)}let around=surrounds?.[name],fill=next.backgroundColor,melts=around!==void 0&&fill!==void 0&&isOpaque(fill)&&boundaryFor(fill,around,seats)!==null;if(seats.length>0){let ink=slot.textColor;if(bg!==void 0)(ink===void 0||seats.some(seat=>contrastRatio(ink,seat)<SLOT_MIN_CONTRAST))&&(next.textColor=inkFor(seats),fixed=true);else if(ink!==void 0){let legible=pushToContrast(ink,seats,poleForGrounds(seats),SLOT_MIN_CONTRAST);legible!==ink&&(next.textColor=legible,fixed=true)}if(slot.borderColor!==void 0&&edgeShowsTheControl(name,slot.borderColor,fill,around,melts)){let against=melts?[...seats,...around??[]]:seats,edge=pushToContrast(slot.borderColor,against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST);edge!==slot.borderColor&&(next.borderColor=edge,fixed=true)}}if(melts&&fill!==void 0&&around!==void 0&&next.borderColor===void 0){let edge=boundaryFor(fill,around,seats);edge!==null&&(next.borderColor=edge,fixed=true)}out[name]=fixed?/* @__PURE__ */Object.freeze(next):slot,changed=changed||fixed}return changed?/* @__PURE__ */Object.freeze(out):slots}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});function textGrounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function controlGrounds(c){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill]}function brandReadsOnControls(c){return controlGrounds(c).every(ground=>contrastRatio(c.brand,ground)>=SLOT_MIN_BORDER_CONTRAST)}function linkGrounds(c){return[c.chatGround,c.surface,c.surfaceCream]}function statusGrounds(c,wash2){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill,...washGrounds(c,wash2)]}function washGrounds(c,wash2){return[flattenOnto(wash2,c.surface)??c.surface,flattenOnto(wash2,c.surfaceCream)??c.surfaceCream]}function composerGrounds(c){return[c.composerFill,c.chatGround]}var AUTHORED_AS_IS=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function onCompiledGrounds(c,compiled){let own=new Set(textGrounds(compiled));return textGrounds(c).every(ground=>own.has(ground))}function guardInks(theme){let c=theme.color,compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,other=(theme.brightness==="dark"?EVERFUR_LIGHT:EVERFUR_DARK).color,grounds2=textGrounds(c),flipped=poleForGrounds(grounds2)!==poleForGrounds(textGrounds(compiled)),keepCompiled=onCompiledGrounds(c,compiled),dangerIsCompiled=c.danger===compiled.danger&&c.badgeBgCritical===compiled.badgeBgCritical,ink=(name,value,authored,twin,on,target)=>{let untouched=value===authored&&(name!=="errorRed"||dangerIsCompiled);return untouched&&keepCompiled&&AUTHORED_AS_IS.has(name)?value:pushToContrast(untouched&&flipped?twin:value,on,poleForGrounds(on),target)},text3=(key,on,target)=>ink(`text.${key}`,c.text[key],compiled.text[key],other.text[key],on,target),token=(key,value,on,target)=>ink(key,value,compiled[key],other[key],on,target),tint=key=>flipped&&c[key]===compiled[key]?other[key]:c[key],primary=c.primary,onPrimary=legibleOn(primary,SLOT_MIN_CONTRAST),danger=token("danger",c.danger,[...grounds2,...washGrounds(c,c.badgeBgCritical)],SLOT_MIN_CONTRAST),guarded={...c,onPrimary:onPrimary,onAccent:legibleOn(c.accent,SLOT_MIN_CONTRAST),onDanger:contrastRatio(onPrimary,danger)>=SLOT_MIN_CONTRAST?onPrimary:legibleOn(danger,SLOT_MIN_CONTRAST),brandSoft:tint("brandSoft"),brandSofter:tint("brandSofter"),brandBorder:tint("brandBorder"),borderHairlineGreen:tint("borderHairlineGreen"),brandInk:token("brandInk",c.brandInk,grounds2,SLOT_MIN_CONTRAST),linkInk:token("linkInk",theme.slots.link?.textColor??c.accent,linkGrounds(c),SLOT_MIN_CONTRAST),text:{...c.text,primary:text3("primary",grounds2,SLOT_MIN_CONTRAST),secondary:text3("secondary",grounds2,SLOT_MIN_CONTRAST),muted:text3("muted",grounds2,SLOT_MIN_CONTRAST),metaCool:text3("metaCool",grounds2,SLOT_MIN_CONTRAST),timestamp:text3("timestamp",grounds2,SLOT_MIN_CONTRAST),placeholder:text3("placeholder",controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},danger:danger,errorRed:token("errorRed",c.errorRed,statusGrounds(c,c.badgeBgCritical),SLOT_MIN_CONTRAST),warningStrong:token("warningStrong",c.warningStrong,statusGrounds(c,c.badgeBgCaution),SLOT_MIN_CONTRAST),composerBorder:token("composerBorder",c.composerBorder,composerGrounds(c),SLOT_MIN_BORDER_CONTRAST),brandBorderStrong:token("brandBorderStrong",c.brandBorderStrong,controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},accented={...guarded,...accentFamily(guarded,compiled,keepCompiled)};return{...accented,...statusInks(c,accented,compiled)}}function statusInks(merged,g,compiled){let out={},push=(value,on,target)=>pushToContrast(value,on,poleForGrounds(on),target);if((!same(merged.success,compiled.success)||!same(merged.badgeBgPositive,compiled.badgeBgPositive))&&(out.success=push(merged.success,statusGrounds(g,merged.badgeBgPositive),SLOT_MIN_CONTRAST)),(!same(merged.cautionAccent,compiled.cautionAccent)||!same(merged.badgeBgCaution,compiled.badgeBgCaution))&&(out.cautionAccent=push(merged.cautionAccent,statusGrounds(g,merged.badgeBgCaution),SLOT_MIN_CONTRAST)),isPartnerInfo(merged,compiled)){out.info=push(merged.info,statusGrounds(g,merged.badgeBgInfo),SLOT_MIN_CONTRAST);let edgeGrounds=[g.surface,g.chatGround,...washGrounds(g,merged.badgeBgInfo)];out.infoEdge=push(merged.infoEdge,edgeGrounds,SLOT_MIN_BORDER_CONTRAST)}else out.info=g.brandInk,out.badgeBgInfo=g.brandSoft,out.infoEdge=g.structureEdge;return out}function isPartnerInfo(c,compiled){return!same(c.info,compiled.info)||!same(c.badgeBgInfo,compiled.badgeBgInfo)}var HIGHLIGHT_LIGHT_TINT=.24,HIGHLIGHT_DARK_TINT=.3;function same(a,b){return parseColor(a)===parseColor(b)}function partnerHue(c,compiled){return same(c.accent,compiled.accent)?same(c.brand,compiled.brand)?null:c.brand:c.accent}function tintOver(hue,surface,tint){let wash2=withAlpha(hue,tint);return(wash2===null?null:flattenOnto(wash2,surface))??surface}function accentFamily(c,compiled,keepCompiled){let hue=partnerHue(c,compiled),controls=controlGrounds(c),controlPole=poleForGrounds(controls),darkGround=poleForGrounds([c.surface])===WHITE,everfurMarks=hue===null&&keepCompiled,highlight;everfurMarks?highlight=compiled.highlight:hue===null?highlight=darkGround?tintOver(EVERFUR_LIGHT.color.highlight,c.surface,HIGHLIGHT_DARK_TINT):EVERFUR_LIGHT.color.highlight:highlight=tintOver(hue,c.surface,darkGround?HIGHLIGHT_DARK_TINT:HIGHLIGHT_LIGHT_TINT);let onHighlight=everfurMarks?compiled.onHighlight:pushToContrast(c.text.primary,[highlight],poleForGrounds([highlight]),SLOT_MIN_CONTRAST),mark=hue===null?compiled.mark:pushToContrast(hue,controls,controlPole,SLOT_MIN_BORDER_CONTRAST),toward=brandReadsOnControls(c)?c.brand:controlPole,edge=(value,authored,compiledEdge)=>keepCompiled&&same(value,authored)?compiledEdge:pushToContrast(value,controls,toward,SLOT_MIN_BORDER_CONTRAST),primaryGrounds=[c.chatGround,c.composerFill,c.surface,c.surfaceCream],primaryEdge=primaryGrounds.every(ground=>contrastRatio(c.primary,ground)>=SLOT_MIN_BORDER_CONTRAST)?c.primary:pushToContrast(c.primary,primaryGrounds,poleForGrounds(primaryGrounds),SLOT_MIN_BORDER_CONTRAST);return{highlight:highlight,onHighlight:onHighlight,mark:mark,controlEdge:edge(c.brandBorder,compiled.brandBorder,compiled.controlEdge),structureEdge:edge(c.borderHairlineGreen,compiled.borderHairlineGreen,compiled.structureEdge),primaryEdge:primaryEdge}}var same2=(a,b)=>a!==void 0&&b!==void 0&&parseColor(a)===parseColor(b);function diffThemeAdjustments(merged,resolved){let compiled=(merged.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,m=merged.color,r=resolved.color,out=[],add=(field,role,requested,painted)=>{out.push(/* @__PURE__ */Object.freeze({field:field,role:role,requested:requested,painted:painted}))},own=(value,compiledValue)=>!same2(value,compiledValue);own(m.text.primary,compiled.text.primary)&&!same2(r.text.primary,m.text.primary)&&add("text_color","body text",m.text.primary,r.text.primary),own(m.brand,compiled.brand)&&(same2(r.brandInk,m.brand)||add("primary_color","brand text and icons",m.brand,r.brandInk),same2(r.primaryEdge,m.primary)||add("primary_color","edge of a filled control",m.primary,r.primaryEdge),!same2(r.controlEdge,m.brandBorder)&&!brandReadsOnControls({...r,brand:m.brand})&&add("primary_color","control outline",m.brand,r.controlEdge)),own(m.accent,compiled.accent)&&merged.slots.link?.textColor===void 0&&!same2(r.linkInk,m.accent)&&add("accent_color","link text",m.accent,r.linkInk),own(m.danger,compiled.danger)&&!same2(r.danger,m.danger)&&add("danger_color","error text",m.danger,r.danger),own(m.success,compiled.success)&&!same2(r.success,m.success)&&add("success_color","positive status",m.success,r.success),own(m.warningStrong,compiled.warningStrong)&&!same2(r.warningStrong,m.warningStrong)&&add("warning_color","caution text",m.warningStrong,r.warningStrong),own(m.cautionAccent,compiled.cautionAccent)&&!same2(r.cautionAccent,m.cautionAccent)&&add("warning_color","caution accent",m.cautionAccent,r.cautionAccent),(own(m.info,compiled.info)||own(m.badgeBgInfo,compiled.badgeBgInfo))&&(same2(r.info,m.info)||add("info_color","information text",m.info,r.info),same2(r.infoEdge,m.infoEdge)||add("info_color","information outline",m.infoEdge,r.infoEdge));for(let name of THEME_SLOT_NAMES){let before=merged.slots[name],after=resolved.slots[name];before===void 0||after===void 0||before===after||(after.backgroundColor!==void 0&&!same2(after.backgroundColor,before.backgroundColor)&&add(`slots.${name}.background_color`,"fill",before.backgroundColor??null,after.backgroundColor),before.textColor!==void 0&&after.textColor!==void 0&&!same2(after.textColor,before.textColor)&&add(`slots.${name}.text_color`,"text",before.textColor??null,after.textColor),after.borderColor!==void 0&&!same2(after.borderColor,before.borderColor)&&add(`slots.${name}.border_color`,"outline",before.borderColor??null,after.borderColor))}/* @__PURE__ */
122
+ return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function deliverClientEvent(handler,event){if(typeof handler=="function")try{let result=handler(event);result!==null&&typeof result=="object"&&typeof result.then=="function"&&result.then(void 0,reportHandlerFailure)}catch(error){reportHandlerFailure(error)}}function reportHandlerFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] onEvent threw; the SDK ignored it.",error)}catch{}}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef2,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef2}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending=inFlight2.get(scope);if(pending!==void 0)return pending;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel2){return channel2<=.03928?channel2/12.92:Math.pow((channel2+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function rgbToHsl(r,g,b){let rn=r/255,gn=g/255,bn=b/255,mx=Math.max(rn,gn,bn),mn=Math.min(rn,gn,bn),l=(mx+mn)/2;if(mx===mn)return{h:0,s:0,l:l};let d=mx-mn,s=d/(1-Math.abs(2*l-1)),h;return mx===rn?(h=(gn-bn)/d*60,h<0&&(h=h+360)):mx===gn?h=((bn-rn)/d+2)*60:h=((rn-gn)/d+4)*60,{h:h,s:s,l:l}}function hslToRgb(hsl){let{h:h,s:s,l:l}=hsl,c=(1-Math.abs(2*l-1))*s,hp=h/60,x=c*(1-Math.abs(hp%2-1)),m=l-c/2,sector=Math.floor(hp)%6,rgb1=[[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]],[r1,g1,b1]=rgb1[sector];return{r:channel(r1+m),g:channel(g1+m),b:channel(b1+m)}}function channel(v){return Math.min(255,Math.max(0,Math.floor(v*255+.5)))}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog"]),THEME_SLOT_KEYS=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),SLOT_MIN_CONTRAST=4.5,EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let text3=typeof value=="string"&&value.length<=16?value.trim().replace(/ ?px$/i,""):null,n=typeof value=="number"?value:text3!==null&&text3.length>0?Number(text3):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let slot=parseSlot(raw);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function pick2(raw,snake,camel){return raw[snake]!==void 0?raw[snake]:raw[camel]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base,over){return over===null||Object.keys(over).length===0?base??EMPTY:base===null||Object.keys(base).length===0?over:/* @__PURE__ */Object.freeze({...base,...over})}function isOpaque(color){let rgba=toRgba(color);return rgba!==null&&rgba.a>=1}var SLOT_MIN_BORDER_CONTRAST=3,DECORATIVE_EDGE_SLOTS=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep"]);function sameColor(a,b){let left=parseColor(a);return left!==null&&left===parseColor(b)}function boundaryFor(fill,surrounds,seats=[]){if(surrounds.length===0)return null;let shown=surrounds.map(ground=>flattenOnto(fill,ground)??fill);if(surrounds.every((ground,index)=>contrastRatio(shown[index],ground)>=SLOT_MIN_BORDER_CONTRAST))return null;let against=[...surrounds,...shown,...seats];return pushToContrast(shown[0],against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST)}function seatsOf(background,defaults){return background===void 0?defaults:defaults.length===0?[background]:defaults.map(ground=>flattenOnto(background,ground)??ground)}function someInkReads(seats,target){let pole=poleForGrounds(seats);return seats.every(seat=>contrastRatio(pole,seat)>=target)}function collapseUnsatisfiableFill(background,defaults){let ground=defaults[0];return ground===void 0?null:flattenOnto(background,ground)}function inkFor(seats){let pick5=legibleOn(seats[0],SLOT_MIN_CONTRAST);return seats.every(seat=>contrastRatio(pick5,seat)>=SLOT_MIN_CONTRAST)?pick5:poleForGrounds(seats)}function edgeShowsTheControl(name,edge,fill,around,melts){return DECORATIVE_EDGE_SLOTS.has(name)?false:melts?true:fill!==void 0&&sameColor(edge,fill)?false:!(around!==void 0&&fill!==void 0&&isOpaque(fill))}function guardSlotContrast(slots,grounds2,surrounds){let changed=false,out={};for(let name of THEME_SLOT_NAMES){let slot=slots[name];if(slot===void 0)continue;let bg=slot.backgroundColor,defaults=grounds2?.[name]??[],seats=seatsOf(bg,defaults),next={...slot},fixed=false;if(bg!==void 0&&seats.length>1&&!someInkReads(seats,SLOT_MIN_CONTRAST)){let opaque=collapseUnsatisfiableFill(bg,defaults);opaque!==null&&(next.backgroundColor=opaque,seats=[opaque],fixed=true)}let around=surrounds?.[name],fill=next.backgroundColor,melts=around!==void 0&&fill!==void 0&&isOpaque(fill)&&boundaryFor(fill,around,seats)!==null;if(seats.length>0){let ink=slot.textColor;if(bg!==void 0)(ink===void 0||seats.some(seat=>contrastRatio(ink,seat)<SLOT_MIN_CONTRAST))&&(next.textColor=inkFor(seats),fixed=true);else if(ink!==void 0){let legible=pushToContrast(ink,seats,poleForGrounds(seats),SLOT_MIN_CONTRAST);legible!==ink&&(next.textColor=legible,fixed=true)}if(slot.borderColor!==void 0&&edgeShowsTheControl(name,slot.borderColor,fill,around,melts)){let against=melts?[...seats,...around??[]]:seats,edge=pushToContrast(slot.borderColor,against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST);edge!==slot.borderColor&&(next.borderColor=edge,fixed=true)}}if(melts&&fill!==void 0&&around!==void 0&&next.borderColor===void 0){let edge=boundaryFor(fill,around,seats);edge!==null&&(next.borderColor=edge,fixed=true)}out[name]=fixed?/* @__PURE__ */Object.freeze(next):slot,changed=changed||fixed}return changed?/* @__PURE__ */Object.freeze(out):slots}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});function textGrounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function controlGrounds(c){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill]}function brandReadsOnControls(c){return controlGrounds(c).every(ground=>contrastRatio(c.brand,ground)>=SLOT_MIN_BORDER_CONTRAST)}function linkGrounds(c){return[c.chatGround,c.surface,c.surfaceCream]}function statusGrounds(c,wash2){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill,...washGrounds(c,wash2)]}function washGrounds(c,wash2){return[flattenOnto(wash2,c.surface)??c.surface,flattenOnto(wash2,c.surfaceCream)??c.surfaceCream]}function composerGrounds(c){return[c.composerFill,c.chatGround]}var AUTHORED_AS_IS=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function onCompiledGrounds(c,compiled){let own=new Set(textGrounds(compiled));return textGrounds(c).every(ground=>own.has(ground))}function guardInks(theme){let c=theme.color,compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,other=(theme.brightness==="dark"?EVERFUR_LIGHT:EVERFUR_DARK).color,grounds2=textGrounds(c),flipped=poleForGrounds(grounds2)!==poleForGrounds(textGrounds(compiled)),keepCompiled=onCompiledGrounds(c,compiled),dangerIsCompiled=c.danger===compiled.danger&&c.badgeBgCritical===compiled.badgeBgCritical,ink=(name,value,authored,twin,on,target)=>{let untouched=value===authored&&(name!=="errorRed"||dangerIsCompiled);return untouched&&keepCompiled&&AUTHORED_AS_IS.has(name)?value:pushToContrast(untouched&&flipped?twin:value,on,poleForGrounds(on),target)},text3=(key,on,target)=>ink(`text.${key}`,c.text[key],compiled.text[key],other.text[key],on,target),token=(key,value,on,target)=>ink(key,value,compiled[key],other[key],on,target),tint=key=>flipped&&c[key]===compiled[key]?other[key]:c[key],primary=c.primary,onPrimary=legibleOn(primary,SLOT_MIN_CONTRAST),danger=token("danger",c.danger,[...grounds2,...washGrounds(c,c.badgeBgCritical)],SLOT_MIN_CONTRAST),guarded={...c,onPrimary:onPrimary,onAccent:legibleOn(c.accent,SLOT_MIN_CONTRAST),onDanger:contrastRatio(onPrimary,danger)>=SLOT_MIN_CONTRAST?onPrimary:legibleOn(danger,SLOT_MIN_CONTRAST),brandSoft:tint("brandSoft"),brandSofter:tint("brandSofter"),brandBorder:tint("brandBorder"),borderHairlineGreen:tint("borderHairlineGreen"),brandInk:token("brandInk",c.brandInk,grounds2,SLOT_MIN_CONTRAST),linkInk:token("linkInk",theme.slots.link?.textColor??c.accent,linkGrounds(c),SLOT_MIN_CONTRAST),text:{...c.text,primary:text3("primary",grounds2,SLOT_MIN_CONTRAST),secondary:text3("secondary",grounds2,SLOT_MIN_CONTRAST),muted:text3("muted",grounds2,SLOT_MIN_CONTRAST),metaCool:text3("metaCool",grounds2,SLOT_MIN_CONTRAST),timestamp:text3("timestamp",grounds2,SLOT_MIN_CONTRAST),placeholder:text3("placeholder",controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},danger:danger,errorRed:token("errorRed",c.errorRed,statusGrounds(c,c.badgeBgCritical),SLOT_MIN_CONTRAST),warningStrong:token("warningStrong",c.warningStrong,statusGrounds(c,c.badgeBgCaution),SLOT_MIN_CONTRAST),composerBorder:token("composerBorder",c.composerBorder,composerGrounds(c),SLOT_MIN_BORDER_CONTRAST),brandBorderStrong:token("brandBorderStrong",c.brandBorderStrong,controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},accented={...guarded,...accentFamily(guarded,compiled,keepCompiled)};return{...accented,...statusInks(c,accented,compiled)}}function statusInks(merged,g,compiled){let out={},push=(value,on,target)=>pushToContrast(value,on,poleForGrounds(on),target);if((!same(merged.success,compiled.success)||!same(merged.badgeBgPositive,compiled.badgeBgPositive))&&(out.success=push(merged.success,statusGrounds(g,merged.badgeBgPositive),SLOT_MIN_CONTRAST)),(!same(merged.cautionAccent,compiled.cautionAccent)||!same(merged.badgeBgCaution,compiled.badgeBgCaution))&&(out.cautionAccent=push(merged.cautionAccent,statusGrounds(g,merged.badgeBgCaution),SLOT_MIN_CONTRAST)),isPartnerInfo(merged,compiled)){out.info=push(merged.info,statusGrounds(g,merged.badgeBgInfo),SLOT_MIN_CONTRAST);let edgeGrounds=[g.surface,g.chatGround,...washGrounds(g,merged.badgeBgInfo)];out.infoEdge=push(merged.infoEdge,edgeGrounds,SLOT_MIN_BORDER_CONTRAST)}else out.info=g.brandInk,out.badgeBgInfo=g.brandSoft,out.infoEdge=g.structureEdge;return out}function isPartnerInfo(c,compiled){return!same(c.info,compiled.info)||!same(c.badgeBgInfo,compiled.badgeBgInfo)}var HIGHLIGHT_LIGHT_TINT=.24,HIGHLIGHT_DARK_TINT=.3;function same(a,b){return parseColor(a)===parseColor(b)}function partnerHue(c,compiled){return same(c.accent,compiled.accent)?same(c.brand,compiled.brand)?null:c.brand:c.accent}function tintOver(hue,surface,tint){let wash2=withAlpha(hue,tint);return(wash2===null?null:flattenOnto(wash2,surface))??surface}function accentFamily(c,compiled,keepCompiled){let hue=partnerHue(c,compiled),controls=controlGrounds(c),controlPole=poleForGrounds(controls),darkGround=poleForGrounds([c.surface])===WHITE,everfurMarks=hue===null&&keepCompiled,highlight;everfurMarks?highlight=compiled.highlight:hue===null?highlight=darkGround?tintOver(EVERFUR_LIGHT.color.highlight,c.surface,HIGHLIGHT_DARK_TINT):EVERFUR_LIGHT.color.highlight:highlight=tintOver(hue,c.surface,darkGround?HIGHLIGHT_DARK_TINT:HIGHLIGHT_LIGHT_TINT);let onHighlight=everfurMarks?compiled.onHighlight:pushToContrast(c.text.primary,[highlight],poleForGrounds([highlight]),SLOT_MIN_CONTRAST),mark=hue===null?compiled.mark:pushToContrast(hue,controls,controlPole,SLOT_MIN_BORDER_CONTRAST),toward=brandReadsOnControls(c)?c.brand:controlPole,edge=(value,authored,compiledEdge)=>keepCompiled&&same(value,authored)?compiledEdge:pushToContrast(value,controls,toward,SLOT_MIN_BORDER_CONTRAST),primaryGrounds=[c.chatGround,c.composerFill,c.surface,c.surfaceCream],primaryEdge=primaryGrounds.every(ground=>contrastRatio(c.primary,ground)>=SLOT_MIN_BORDER_CONTRAST)?c.primary:pushToContrast(c.primary,primaryGrounds,poleForGrounds(primaryGrounds),SLOT_MIN_BORDER_CONTRAST);return{highlight:highlight,onHighlight:onHighlight,mark:mark,controlEdge:edge(c.brandBorder,compiled.brandBorder,compiled.controlEdge),structureEdge:edge(c.borderHairlineGreen,compiled.borderHairlineGreen,compiled.structureEdge),primaryEdge:primaryEdge}}var same2=(a,b)=>a!==void 0&&b!==void 0&&parseColor(a)===parseColor(b);function diffThemeAdjustments(merged,resolved){let compiled=(merged.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,m=merged.color,r=resolved.color,out=[],add=(field,role,requested,painted)=>{out.push(/* @__PURE__ */Object.freeze({field:field,role:role,requested:requested,painted:painted}))},own=(value,compiledValue)=>!same2(value,compiledValue);own(m.text.primary,compiled.text.primary)&&!same2(r.text.primary,m.text.primary)&&add("text_color","body text",m.text.primary,r.text.primary),own(m.brand,compiled.brand)&&(same2(r.brandInk,m.brand)||add("primary_color","brand text and icons",m.brand,r.brandInk),same2(r.primaryEdge,m.primary)||add("primary_color","edge of a filled control",m.primary,r.primaryEdge),!same2(r.controlEdge,m.brandBorder)&&!brandReadsOnControls({...r,brand:m.brand})&&add("primary_color","control outline",m.brand,r.controlEdge)),own(m.accent,compiled.accent)&&merged.slots.link?.textColor===void 0&&!same2(r.linkInk,m.accent)&&add("accent_color","link text",m.accent,r.linkInk),own(m.danger,compiled.danger)&&!same2(r.danger,m.danger)&&add("danger_color","error text",m.danger,r.danger),own(m.success,compiled.success)&&!same2(r.success,m.success)&&add("success_color","positive status",m.success,r.success),own(m.warningStrong,compiled.warningStrong)&&!same2(r.warningStrong,m.warningStrong)&&add("warning_color","caution text",m.warningStrong,r.warningStrong),own(m.cautionAccent,compiled.cautionAccent)&&!same2(r.cautionAccent,m.cautionAccent)&&add("warning_color","caution accent",m.cautionAccent,r.cautionAccent),(own(m.info,compiled.info)||own(m.badgeBgInfo,compiled.badgeBgInfo))&&(same2(r.info,m.info)||add("info_color","information text",m.info,r.info),same2(r.infoEdge,m.infoEdge)||add("info_color","information outline",m.infoEdge,r.infoEdge));for(let name of THEME_SLOT_NAMES){let before=merged.slots[name],after=resolved.slots[name];before===void 0||after===void 0||before===after||(after.backgroundColor!==void 0&&!same2(after.backgroundColor,before.backgroundColor)&&add(`slots.${name}.background_color`,"fill",before.backgroundColor??null,after.backgroundColor),before.textColor!==void 0&&after.textColor!==void 0&&!same2(after.textColor,before.textColor)&&add(`slots.${name}.text_color`,"text",before.textColor??null,after.textColor),after.borderColor!==void 0&&!same2(after.borderColor,before.borderColor)&&add(`slots.${name}.border_color`,"outline",before.borderColor??null,after.borderColor))}/* @__PURE__ */
123
123
  return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAdjustments(adjustments){if(adjustments.length===0)return;let message=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${adjustments.map(a=>` ${a.field} (${a.role}): ${a.requested??"not set"} -> ${a.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(warned.has(message))return;warned.add(message);let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var DARK_VARIANT_GROUND="#23272C",DARK_VARIANT_TARGET_RATIO=4.5,DARK_VARIANT_LIGHTNESS_FLOOR=.6,DARK_VARIANT_LIGHTNESS_CEILING=.9,DARK_VARIANT_LIGHTNESS_STEP=.02,WHITE_INK="#FFFFFF",NEAR_BLACK_INK="#111111";function readsOnDark(candidate){return contrastRatio(candidate,DARK_VARIANT_GROUND)>=DARK_VARIANT_TARGET_RATIO&&Math.max(contrastRatio(candidate,WHITE_INK),contrastRatio(candidate,NEAR_BLACK_INK))>=DARK_VARIANT_TARGET_RATIO}function deriveDarkVariant(color){let rgba=toRgba(color);if(rgba===null)return null;let{h:h,s:s,l:l}=rgbToHsl(rgba.r,rgba.g,rgba.b),lDark=Math.min(Math.max(l,DARK_VARIANT_LIGHTNESS_FLOOR),DARK_VARIANT_LIGHTNESS_CEILING);for(let i=0;;i+=1){let li=lDark+i*DARK_VARIANT_LIGHTNESS_STEP;if(li>DARK_VARIANT_LIGHTNESS_CEILING)break;let rgb=hslToRgb({h:h,s:s,l:li}),candidate=rgbToHex(rgb.r,rgb.g,rgb.b);if(readsOnDark(candidate))return candidate}let ceiling=hslToRgb({h:h,s:s,l:DARK_VARIANT_LIGHTNESS_CEILING});return rgbToHex(ceiling.r,ceiling.g,ceiling.b)}var HIGH_CONTRAST_TARGET_RATIO=7,PUSH_STEP2=.05,BLACK2="#000000",WHITE2="#FFFFFF";function pushContrast(color,ground,pole,target){let flat=flattenOnto(color,ground);if(flat===null)return pole;if(contrastRatio(flat,ground)>=target)return flat;let from=toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP2;step+=1){let t=step*PUSH_STEP2,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(contrastRatio(candidate,ground)>=target)return candidate}return pole}function hardestGround(color,dark){let grounds2=textGrounds(color),pick5=grounds2[0],pickLum=luminanceOf(pick5);for(let ground of grounds2){let lum=luminanceOf(ground);(dark?lum>pickLum:lum<pickLum)&&(pick5=ground,pickLum=lum)}return pick5}function luminanceOf(color){let rgba=toRgba(color);return rgba===null?0:relativeLuminance(rgba)}function solid(wash2,surface){return flattenOnto(wash2,surface)??parseColor(wash2)??surface}function deriveHighContrast(theme){let c=theme.color,lightInk=poleForGrounds(textGrounds(c))===WHITE2,pole=lightInk?WHITE2:BLACK2,ground=hardestGround(c,lightInk),text3=color2=>pushContrast(color2,ground,pole,HIGH_CONTRAST_TARGET_RATIO),color={...c,brandSoft:solid(c.brandSoft,c.surface),brandSofter:solid(c.brandSofter,c.surface),brandBorder:text3(c.brandBorder),borderHairlineGreen:text3(c.borderHairlineGreen),brandBorderStrong:text3(c.brandBorderStrong),controlEdge:text3(c.controlEdge),structureEdge:text3(c.structureEdge),brandInk:text3(c.brandInk),linkInk:text3(c.linkInk),borderRingCream:text3(c.borderRingCream),composerBorder:text3(c.composerBorder),text:{primary:text3(c.text.primary),secondary:text3(c.text.secondary),muted:text3(c.text.muted),placeholder:text3(c.text.placeholder),onBrand:c.text.onBrand,metaCool:text3(c.text.metaCool),timestamp:text3(c.text.timestamp)},badgeBgPositive:solid(c.badgeBgPositive,c.surface),badgeBgCaution:solid(c.badgeBgCaution,c.surface),badgeBgCritical:solid(c.badgeBgCritical,c.surface),badgeBgNeutral:solid(c.badgeBgNeutral,c.surface),checkupCardLowRiskBg:solid(c.checkupCardLowRiskBg,c.surface),checkupCardConcernBg:solid(c.checkupCardConcernBg,c.surface),info:text3(c.info),infoEdge:text3(c.infoEdge),badgeBgInfo:solid(c.badgeBgInfo,c.surface)};return deepFreeze({...theme,highContrast:true,color:color})}var BACKGROUND_STEPS=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),CREAM_STEP=BACKGROUND_STEPS.cream,SUBTLE_STEP=BACKGROUND_STEPS.subtle,RING_STEP=BACKGROUND_STEPS.ring,MIN_DERIVED_TYPE_SIZE=10;function mix(color,toward,t){let from=toRgba(color),to=toRgba(toward);if(from===null||to===null)return null;let at=(a,b)=>Math.round(a+(b-a)*t);return rgbToHex(at(from.r,to.r),at(from.g,to.g),at(from.b,to.b))}function surfaceFamily(background){if(background===null)return{};let pole=poleForGrounds([background]),cream=mix(background,pole,CREAM_STEP),subtle=mix(background,pole,SUBTLE_STEP),ring=mix(background,pole,RING_STEP);return cream===null||subtle===null||ring===null?{}:{surface:background,background:background,chatGround:background,bubbleAssistant:background,surfaceCream:cream,composerFill:cream,surfaceSubtle:subtle,skeleton:subtle,borderRingCream:ring}}function dangerFamily(danger){if(danger===null)return{};let rgba=toRgba(danger);return rgba===null?{}:{danger:danger,errorRed:danger,badgeBgCritical:`rgba(${rgba.r},${rgba.g},${rgba.b},0.12)`}}function typeSizesFor(base,current,compiled){if(base===null)return current;let factor=base/compiled.type.size.body;if(factor===1)return compiled.type.size;let out={};for(let[key,value]of Object.entries(compiled.type.size))out[key]=Math.max(MIN_DERIVED_TYPE_SIZE,Math.round(value*factor*10)/10);return out}function spaceFor(unit,current,compiled){if(unit===null)return current;let factor=unit/compiled.space.xs,s=n=>Math.round(n*factor),c=compiled.space;return{xs:s(c.xs),sm:s(c.sm),md:s(c.md),lg:s(c.lg),xl:s(c.xl),xxl:s(c.xxl)}}function radiiFor(base,compiled){let factor=base/compiled.radius.md,s=n=>Math.round(n*factor),r=compiled.radius;return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var STATUS_WASH=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function wash(color,alpha){let rgba=toRgba(color);return rgba===null?null:`rgba(${rgba.r},${rgba.g},${rgba.b},${alpha})`}function successFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.success.dark:STATUS_WASH.success.light),card=wash(color,dark?STATUS_WASH.successCard.dark:STATUS_WASH.successCard.light);return badge===null||card===null?{}:{success:color,badgeBgPositive:badge,checkupCardLowRiskBg:card}}function warningFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.warning.dark:STATUS_WASH.warning.light);return badge===null?{}:{warningStrong:color,cautionAccent:color,badgeBgCaution:badge}}function infoFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.info.dark:STATUS_WASH.info.light);return badge===null?{}:{info:color,infoEdge:color,badgeBgInfo:badge}}function lineHeightsFor(lineHeight,current,compiled){if(lineHeight===null)return current;let c=compiled.type.lineHeight,factor=lineHeight/c.normal;if(factor===1)return c;let s=n=>Math.round(n*factor*100)/100;return{tight:s(c.tight),snug:s(c.snug),normal:s(c.normal),relaxed:s(c.relaxed)}}function slotGrounds(c){return{composerInput:[c.composerFill],sendButton:[c.composerFill],userBubble:[c.bubbleUser],assistantBubble:[c.chatGround,c.surfaceCream],vetBubble:[c.bubbleVet],recordCard:[c.surface],vetVisitButton:[c.primary],primaryButton:[c.brand],link:linkGrounds(c),header:[c.surface,c.background,c.chatGround],banner:[flattenOnto(c.badgeBgInfo,c.surface)??c.surface,flattenOnto(c.badgeBgCaution,c.surface)??c.surface,c.surface],chip:[c.chatGround,c.surface,c.background,c.surfaceCream],card:[c.surface],input:[c.surface,c.composerFill,c.surfaceCream,c.surfaceSubtle],tab:[c.surface,c.background],bookingStep:[c.surface,c.background],dialog:[c.surface]}}function slotSurrounds(c){return{userBubble:[c.chatGround],assistantBubble:[c.chatGround],vetBubble:[c.chatGround],sendButton:[c.composerFill],vetVisitButton:[c.surfaceCream,c.surface,c.chatGround],primaryButton:[c.surface,c.surfaceCream]}}var APPEARANCE_PRESET_NAMES=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),APPEARANCE_PRESETS=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),APPEARANCE_SIZE_RANGES=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function isRecord2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPreset(value){return typeof value=="string"&&APPEARANCE_PRESET_NAMES.includes(value.trim().toLowerCase())}function present(vars,key){let value=vars[key];return value??void 0}var PX_MAX_LENGTH=16;function parsePx(value){if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value!="string"||value.length>PX_MAX_LENGTH)return;let match=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(value.trim());return match===null?void 0:Number(match[1])}var COLOR_VARIABLES=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],STATUS_VARIABLES=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],PASSTHROUGH_VARIABLES=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],STRING_VARIABLES=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],SIZE_VARIABLES=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(appearance){if(!isRecord2(appearance))return null;let preset=isPreset(appearance.theme)?APPEARANCE_PRESETS[appearance.theme.trim().toLowerCase()]:{},own=isRecord2(appearance.variables)?appearance.variables:{},vars={...preset};for(let[key,value]of Object.entries(own))value!=null&&(vars[key]=value);let out={},scheme=present(vars,"colorScheme"),schemeName=typeof scheme=="string"?scheme.trim().toLowerCase():null;(schemeName==="light"||schemeName==="dark"||schemeName==="auto")&&(out.color_scheme=schemeName);let suffix=schemeName==="dark"?"_dark":"";for(let[variable,field]of COLOR_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STATUS_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STRING_VARIABLES){let value=present(vars,variable);typeof value=="string"&&value.trim().length>0&&(out[field]=value.trim())}for(let[variable,field]of SIZE_VARIABLES){let px=parsePx(present(vars,variable));px!==void 0&&(out[field]=px)}for(let[variable,field]of PASSTHROUGH_VARIABLES){let value=present(vars,variable);(typeof value=="number"||typeof value=="string")&&(out[field]=value)}let fonts=appearance.fonts;Array.isArray(fonts)&&fonts.length>0&&(out.font_sources=fonts);let rules=appearance.rules;if(isRecord2(rules)){let slots={};for(let name of THEME_SLOT_NAMES){let paint=rules[name];isRecord2(paint)&&(slots[name]=paint)}Object.keys(slots).length>0&&(out.slots=slots)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var LINE_HEIGHT_RANGE=/* @__PURE__ */Object.freeze({min:1,max:2}),FAMILY_MAX_LENGTH=100,URL_MAX_LENGTH=2048,WEIGHTS=["100","200","300","400","500","600","700","800","900"];function finiteNumber(value){if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value!="string"||value.trim().length===0||value.length>16)return null;let n=Number(value.trim());return Number.isFinite(n)?n:null}function parseFontWeight(value){let n=finiteNumber(value);if(n===null)return null;let name=String(n);return WEIGHTS.includes(name)?name:null}function parseLineHeight(value){let n=finiteNumber(value);return n===null?null:Math.min(LINE_HEIGHT_RANGE.max,Math.max(LINE_HEIGHT_RANGE.min,n))}function fontSourceUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>URL_MAX_LENGTH?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(trimmed)?trimmed:null}function familyName(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>FAMILY_MAX_LENGTH||/[\u0000-\u001F\u007F]/.test(trimmed)?null:trimmed}function isRecord3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function pick3(raw,...keys){for(let key of keys)if(raw[key]!==void 0&&raw[key]!==null)return raw[key]}function parseFontSource(raw){if(!isRecord3(raw))return null;let family=familyName(raw.family);if(family===null)return null;let srcRaw=pick3(raw,"src"),cssRaw=pick3(raw,"cssSrc","css_src");if(srcRaw===void 0==(cssRaw===void 0))return null;if(cssRaw!==void 0){let cssSrc=fontSourceUrl(cssRaw);return cssSrc===null?null:/* @__PURE__ */Object.freeze({family:family,cssSrc:cssSrc})}let src=fontSourceUrl(srcRaw);if(src===null)return null;let out={family:family,src:src},weight=parseFontWeight(raw.weight);weight!==null&&(out.weight=weight);let style=typeof raw.style=="string"?raw.style.trim().toLowerCase():null;return(style==="normal"||style==="italic")&&(out.style=style),/* @__PURE__ */Object.freeze(out)}function parseFontSources(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(out.length>=4)break;let source=parseFontSource(entry);source!==null&&out.push(source)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var LOCKABLE_THEME_FIELDS=/* @__PURE__ */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","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),SLOT_LOCK_PREFIX="slots.",THEME_SCHEMA_VERSIONS=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(b){return Object.keys(b).every(key=>key==="schemaVersion"||(b[key]??null)===null)}function isKnownBrandingSchema(b){let version=b?.schemaVersion??null;return version===null||THEME_SCHEMA_VERSIONS.includes(version)}function lockedFieldsOf(b){/* @__PURE__ */
124
124
  return new Set(["hide_powered_by",...b?.lockedFields??[]])}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)?true:name.startsWith(SLOT_LOCK_PREFIX)&&THEME_SLOT_NAMES.includes(name.slice(SLOT_LOCK_PREFIX.length))}function parseClientBranding(json){if(json===null||typeof json!="object")return null;let raw=json,flat=parseFlat(raw),expanded=expandAppearance(pick4(raw,"appearance")),branding=expanded===null?flat:overlayFlat(parseFlat(expanded),flat);return isEmptyBranding(branding)?null:/* @__PURE__ */Object.freeze(branding)}function overlayFlat(base,over){let out={...base};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base.slots??null,over.slots??null);return out.slots=Object.keys(slots).length===0?null:slots,out}function parseFlat(raw){return{displayName:parseNonEmptyString(pick4(raw,"display_name","displayName")),logoUrl:parseNonEmptyString(pick4(raw,"logo_url","logoUrl")),primaryColor:parseColor(pick4(raw,"primary_color","primaryColor")),accentColor:parseColor(pick4(raw,"accent_color","accentColor")),brightness:parseBrightness(pick4(raw,"brightness","color_scheme","colorScheme")),fontFamily:parseNonEmptyString(pick4(raw,"font_family","fontFamily")),fontUrl:parseNonEmptyString(pick4(raw,"font_url","fontUrl")),fonts:parseFaceMap(pick4(raw,"fonts")),fontUrls:parseFaceMap(pick4(raw,"font_urls","fontUrls")),placeholder:parseNonEmptyString(pick4(raw,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:parseBool(pick4(raw,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pick4(raw,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pick4(raw,"accent_color_dark","accentColorDark")),surfaceStyle:parseEnum(pick4(raw,"surface_style","surfaceStyle"),SURFACE_STYLES),radiusScale:parseEnum(pick4(raw,"radius_scale","radiusScale"),RADIUS_SCALES),logoUrlDark:parseNonEmptyString(pick4(raw,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pick4(raw,"slots")),accessibilityMaxFontScale:parseMaxFontScale(pick4(raw,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:parseLockedFields(pick4(raw,"locked_fields","lockedFields")),schemaVersion:parseSchemaVersion(pick4(raw,"schema_version","schemaVersion")),backgroundColor:parseColor(pick4(raw,"background_color","backgroundColor")),backgroundColorDark:parseColor(pick4(raw,"background_color_dark","backgroundColorDark")),textColor:parseColor(pick4(raw,"text_color","textColor")),textColorDark:parseColor(pick4(raw,"text_color_dark","textColorDark")),dangerColor:parseColor(pick4(raw,"danger_color","dangerColor")),dangerColorDark:parseColor(pick4(raw,"danger_color_dark","dangerColorDark")),fontSizeBase:parseClamped(pick4(raw,"font_size_base","fontSizeBase"),APPEARANCE_SIZE_RANGES.fontSizeBase),borderRadius:parseClamped(pick4(raw,"border_radius","borderRadius"),APPEARANCE_SIZE_RANGES.borderRadius),spacingUnit:parseClamped(pick4(raw,"spacing_unit","spacingUnit"),APPEARANCE_SIZE_RANGES.spacingUnit),successColor:parseColor(pick4(raw,"success_color","successColor")),successColorDark:parseColor(pick4(raw,"success_color_dark","successColorDark")),warningColor:parseColor(pick4(raw,"warning_color","warningColor")),warningColorDark:parseColor(pick4(raw,"warning_color_dark","warningColorDark")),infoColor:parseColor(pick4(raw,"info_color","infoColor")),infoColorDark:parseColor(pick4(raw,"info_color_dark","infoColorDark")),headingFontFamily:parseNonEmptyString(pick4(raw,"heading_font_family","headingFontFamily")),fontWeightBody:parseFontWeight(pick4(raw,"font_weight_body","fontWeightBody")),fontWeightHeading:parseFontWeight(pick4(raw,"font_weight_heading","fontWeightHeading")),lineHeight:parseLineHeight(pick4(raw,"line_height","lineHeight")),fontSources:parseFontSources(pick4(raw,"font_sources","fontSources")),assistantAvatarUrl:parseNonEmptyString(pick4(raw,"assistant_avatar_url","assistantAvatarUrl"))}}function parseClamped(value,range){let n=parseNumber(typeof value=="string"?value.trim().replace(/px$/i,""):value);return n===null?null:Math.min(range.max,Math.max(range.min,n))}function parseBool(value){if(typeof value=="boolean")return value;if(typeof value=="string"){let lower=value.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false}return null}function pick4(raw,...keys){for(let key of keys)if(Object.prototype.hasOwnProperty.call(raw,key)){let value=raw[key];if(value!==void 0)return value}}function parseNonEmptyString(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}var FONT_FACE_KEYS=["regular","medium","bold","mono","monoMedium","monoBold"];function parseFaceMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;let raw=value,out={};for(let key of FONT_FACE_KEYS){let entry=parseNonEmptyString(pick4(raw,key));entry!==null&&(out[key]=entry)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var SURFACE_STYLES=["white","cream","subtle"],RADIUS_SCALES=["sharp","default","round"];function parseEnum(value,allowed){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return allowed.includes(lower)?lower:null}function parseBrightness(value){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return lower==="light"||lower==="dark"||lower==="auto"?lower:null}function parseNumber(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)&&(typeof value!="string"||value.trim().length>0)?n:null}var MAX_FONT_SCALE_FLOOR=1,MAX_FONT_SCALE_CEILING=3.1;function parseMaxFontScale(value){let n=parseNumber(value);return n===null?null:n<=0?0:Math.min(MAX_FONT_SCALE_CEILING,Math.max(MAX_FONT_SCALE_FLOOR,n))}function parseSchemaVersion(value){if(value==null)return null;let n=parseNumber(value);return n!==null&&Number.isInteger(n)&&n>=1?n:0}function toWireName(name){let trimmed=name.trim();return trimmed.startsWith(SLOT_LOCK_PREFIX)?trimmed:trimmed.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function parseLockedFields(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(typeof entry!="string")continue;let name=toWireName(entry);isThemeLockName(name)&&!out.includes(name)&&out.push(name)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}var BRAND_ASSET_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/brand\/[0-9a-f]{16}\.(png|jpg|webp)$/;function hardenBrandAssetUrl(url){let https=hardenHttpsUrl(url);return https!==null&&BRAND_ASSET_URL.test(https)?https:null}function withServerBranding(base,b){if(b===null||isEmptyBranding(b))return base;let palette=(b.brightness==="light"||b.brightness==="dark")&&b.brightness!==base.brightness?b.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT:base,compiled=palette.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,dark=palette.brightness==="dark",primaryIn=dark?b.primaryColorDark??darkVariantOf(b.primaryColor):b.primaryColor,accentIn=dark?b.accentColorDark??darkVariantOf(b.accentColor):b.accentColor,primaryRaw=primaryIn??palette.color.primary,accent=accentIn??palette.color.accent,keepsCompiled=primaryIn!==null&&isCompiledPrimary(b,primaryRaw,compiled,dark),primary=keepsCompiled?compiled.color.primary:primaryRaw,pr=primaryIn!==null&&!keepsCompiled?toRgba(primary):null,lift=c=>Math.round(c+(255-c)*.4),brandFamily=pr!==null?{brand:primary,bubbleUser:primary,brandInk:primary,text:{...palette.color.text,secondary:primary},brandSoft:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,brandSofter:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,brandBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,borderHairlineGreen:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,brandBorderStrong:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.55)`,composerBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.75)`,accentEdge:`rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`}:keepsCompiled?compiledBrandFamily(compiled,palette.color.text):{},background=(dark?b.backgroundColorDark:b.backgroundColor)??null,grounds2=surfaceFamily(background),groundFamily={...palette.color,...grounds2},bodyInk=(dark?b.textColorDark:b.textColor)??null,status=(light,darkTwin)=>(dark?darkTwin??darkVariantOf(light??null):light)??null,next={brightness:palette.brightness,highContrast:palette.highContrast,meta:{displayName:b.displayName??palette.meta.displayName,logoUrl:(dark?b.logoUrlDark??b.logoUrl:b.logoUrl)??palette.meta.logoUrl,placeholder:b.placeholder??palette.meta.placeholder,hidePoweredBy:b.hidePoweredBy??palette.meta.hidePoweredBy,assistantAvatarUrl:b.assistantAvatarUrl??palette.meta.assistantAvatarUrl},color:{...palette.color,...brandFamily,...grounds2,...dangerFamily(status(b.dangerColor,b.dangerColorDark)),...successFamily(status(b.successColor,b.successColorDark),dark),...warningFamily(status(b.warningColor,b.warningColorDark),dark),...infoFamily(status(b.infoColor,b.infoColorDark),dark),...bodyInk!==null?{text:{...brandFamily.text??palette.color.text,primary:bodyInk}}:{},...surfaceOf(b.surfaceStyle??null,groundFamily),primary:primary,accent:accent,onPrimary:palette.color.onPrimary,onAccent:palette.color.onAccent},space:spaceFor(b.spacingUnit??null,palette.space,compiled),radius:b.borderRadius!=null?radiiFor(b.borderRadius,compiled):radiusOf(b.radiusScale??null,palette.radius,compiled),type:{...palette.type,...mergeFaces(palette.type,b),size:typeSizesFor(b.fontSizeBase??null,palette.type.size,compiled),maxScale:b.accessibilityMaxFontScale??palette.type.maxScale,lineHeight:lineHeightsFor(b.lineHeight??null,palette.type.lineHeight,compiled),weight:b.fontWeightBody==null?palette.type.weight:{...palette.type.weight,regular:b.fontWeightBody},headingFamily:b.headingFontFamily??palette.type.headingFamily,headingWeight:b.fontWeightHeading??palette.type.headingWeight,fontSources:b.fontSources??palette.type.fontSources},motion:palette.motion,slots:mergeThemeSlots(palette.slots,b.slots??null)};return deepFreeze(next)}var FACE_CHAIN={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},FACE_GROUPS=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function isMonoFace(face2){return face2==="mono"||face2==="monoMedium"||face2==="monoBold"}function mergeFaces(base,b){let fonts=b.fonts??{},urls=b.fontUrls??{},families={...base.families},namedFaces={...base.namedFaces},fontUrls={...base.fontUrls};for(let face2 of FONT_FACE_KEYS){let named=FACE_CHAIN[face2].map(key=>fonts[key]).find(name=>name!==void 0),legacy=isMonoFace(face2)?null:b.fontFamily;named!==void 0?(families[face2]=named,namedFaces[face2]=true):legacy!==null&&(families[face2]=legacy,namedFaces[face2]=false);let url=urls[face2]??(face2==="regular"?b.fontUrl:null)??null;url!==null?fontUrls[face2]=url:named!==void 0&&delete fontUrls[face2]}for(let group of FACE_GROUPS)for(let face2 of group)namedFaces[face2]&&group.some(other=>other!==face2&&families[other]===families[face2])&&(namedFaces[face2]=false);return{family:families.regular,mono:families.mono,fontUrl:fontUrls.regular??null,families:families,namedFaces:namedFaces,fontUrls:fontUrls}}function darkVariantOf(color){return color===null?null:deriveDarkVariant(color)}function surfaceOf(style,family){if(style===null)return{};let c=family;return{chatGround:style==="white"?c.surface:style==="subtle"?c.surfaceSubtle:c.surfaceCream}}function sameColor2(a,b){return a==null?false:parseColor(a)===parseColor(b)}function isCompiledPrimary(b,primary,compiled,dark){return sameColor2(primary,compiled.color.primary)?true:dark&&(b.primaryColorDark??null)===null&&sameColor2(b.primaryColor,EVERFUR_LIGHT.color.primary)}function compiledBrandFamily(compiled,text3){let c=compiled.color;return{text:{...text3,secondary:c.text.secondary},brand:c.brand,bubbleUser:c.bubbleUser,brandInk:c.brandInk,brandSoft:c.brandSoft,brandSofter:c.brandSofter,brandBorder:c.brandBorder,borderHairlineGreen:c.borderHairlineGreen,brandBorderStrong:c.brandBorderStrong,composerBorder:c.composerBorder,accentEdge:c.accentEdge}}var RADIUS_FACTOR={sharp:.5,default:1,round:1.5};function radiusOf(scale,base,compiled){if(scale===null)return base;let f=RADIUS_FACTOR[scale],r=compiled.radius,s=n=>Math.round(n*f);return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var DEFAULT_DISPLAY_NAME="Everfur",TEXT_SCALE_FLOOR=.5;function resolveTheme(input){return finalize(mergeLayers(input),input)}function themeAdjustments(input){let merged=mergeLayers(input);return diffThemeAdjustments(merged,finalize(merged,{...input,highContrast:false}))}function mergeLayers(input){let candidate=input?.branding??null,server=isKnownBrandingSchema(candidate)?candidate:null,client=withoutFields(input?.clientOverride??null,lockedFieldsOf(server)),device=input?.colorScheme==="dark"?"dark":"light",chosen=client?.brightness??server?.brightness??"light",withServer=withServerBranding((chosen==="auto"?device:chosen)==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,withoutBrightness(server));return withServerBranding(withServer,withoutBrightness(client))}function previewTheme(input,hints,options){return resolveTheme({...options,branding:parseClientBranding(hints),clientOverride:parseClientBranding(input)})}function wireNameOf(key){return key==="placeholder"?"chat_placeholder":toWireName(key)}var LOCK_ALIASES={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function isLocked(key,locked){return locked.has(wireNameOf(key))?true:(LOCK_ALIASES[key]??[]).some(name=>locked.has(name))}function withoutFields(b,locked){if(b===null)return null;let changed=false,out={...b};for(let key of Object.keys(b))(b[key]??null)!==null&&(isLocked(key,locked)||key==="lockedFields")&&(out[key]=null,changed=true);let slots=out.slots??null;if(slots!==null){let kept={},dropped=false;for(let name of THEME_SLOT_NAMES){let slot=slots[name];slot!==void 0&&(locked.has(`${SLOT_LOCK_PREFIX}${name}`)?dropped=true:kept[name]=slot)}dropped&&(out.slots=Object.keys(kept).length===0?null:/* @__PURE__ */Object.freeze(kept),changed=true)}if(!changed)return b;let stripped=/* @__PURE__ */Object.freeze(out);return isEmptyBranding(stripped)?null:stripped}function withoutBrightness(b){return b===null||b.brightness===null?b:/* @__PURE__ */Object.freeze({...b,brightness:null})}function scaledSizes(size,scale){if(scale===1)return size;let out={};for(let[key,value]of Object.entries(size))out[key]=Math.round(value*scale*10)/10;return out}function effectiveScale(textScale){return textScale===void 0||!Number.isFinite(textScale)?1:Math.max(TEXT_SCALE_FLOOR,textScale)}var SCALE_TIERS=["content","heading","control","compact","badge"];function tierCaps(maxScale){if(!(maxScale>0))return TEXT_SCALE_TIER_CAPS;let out={};for(let tier of SCALE_TIERS){let cap=TEXT_SCALE_TIER_CAPS[tier];out[tier]=cap===0?0:Math.min(cap,maxScale)}return out}function capped(scale,cap){return cap>0?Math.min(scale,cap):scale}function sizesByTier(size,scale,caps,scaleSizes){let out={};for(let tier of SCALE_TIERS)out[tier]=scaleSizes?scaledSizes(size,capped(scale,caps[tier])):size;return out}function registration(isFontRegistered,family){try{let answer=isFontRegistered(family);return answer===!0||answer===!1?answer:null}catch{return null}}function platformFaces(type,input){let isFontRegistered=input?.isFontRegistered,platformMono=input?.platformMonoFamily?.trim()||null;if(isFontRegistered===void 0&&platformMono===null)return{family:type.family,mono:type.mono,families:type.families,namedFaces:type.namedFaces,headingFamily:type.headingFamily};let headingFamily=type.headingFamily!==null&&isFontRegistered!==void 0&&registration(isFontRegistered,type.headingFamily)===false?null:type.headingFamily,families={...type.families},namedFaces={...type.namedFaces};for(let key of FONT_FACE_KEYS)!(families[key]===SYSTEM_FONT_FAMILY||families[key]===SYSTEM_MONO_FAMILY)&&isFontRegistered!==void 0&&registration(isFontRegistered,families[key])===false&&(families[key]=isMonoFace(key)?SYSTEM_MONO_FAMILY:SYSTEM_FONT_FAMILY,namedFaces[key]=false),platformMono!==null&&isMonoFace(key)&&families[key]===SYSTEM_MONO_FAMILY&&(families[key]=platformMono);return{family:families.regular,mono:families.mono,families:families,namedFaces:namedFaces,headingFamily:headingFamily}}function finalize(theme,input){let displayName=theme.meta.displayName.trim().length===0?DEFAULT_DISPLAY_NAME:theme.meta.displayName,logoUrl=hardenBrandAssetUrl(theme.meta.logoUrl),fontUrls={};for(let face2 of FONT_FACE_KEYS){let url=theme.type.fontUrls[face2];url!==void 0&&(fontUrls[face2]=hardenHttpsUrl(url))}let fontUrl=fontUrls.regular??null,motion=input?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:theme.motion.easing,reducedMotion:true}:theme.motion,maxScale=Number.isFinite(theme.type.maxScale)?theme.type.maxScale:DEFAULT_MAX_FONT_SCALE,scale=effectiveScale(input?.textScale),scaleCaps=tierCaps(maxScale),tierSizes=sizesByTier(theme.type.size,scale,scaleCaps,input?.scaleTypeSizes===true),color=guardInks(theme),finalized={brightness:theme.brightness,highContrast:false,meta:{displayName:displayName,logoUrl:logoUrl,placeholder:theme.meta.placeholder,hidePoweredBy:theme.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(theme.meta.assistantAvatarUrl)},color:color,space:theme.space,radius:theme.radius,type:{...theme.type,...platformFaces(theme.type,input),fontUrl:fontUrl,fontUrls:fontUrls,size:tierSizes.content,tierSizes:tierSizes,scale:scale,maxScale:maxScale,scaleCaps:scaleCaps},motion:motion,slots:guardSlotContrast(theme.slots,slotGrounds(color),slotSurrounds(color))};return input?.highContrast===true?deriveHighContrast(deepFreeze(finalized)):deepFreeze(finalized)}var ENTITLEMENTS_PATH="/widget/v1/entitlements",HTTP_NOT_MODIFIED=304,NOT_MODIFIED=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(auth,args={},funnel=createRequestFunnel({auth:auth})){let result=await funnel.send("entitlements.fetch",buildRequest(args));return result.ok?parseUpdated(result.value):result.error.httpStatus===HTTP_NOT_MODIFIED?NOT_MODIFIED:{kind:"failed",error:result.error}}var REGION_MAX=64;function buildRequest(args){let headers={};return isFiniteNumber(args.cachedRevision)&&(headers["if-none-match"]=`"${args.cachedRevision}"`),args.region&&args.region.length<=REGION_MAX?{method:"GET",path:ENTITLEMENTS_PATH,headers:headers,query:{region:args.region}}:{method:"GET",path:ENTITLEMENTS_PATH,headers:headers}}function parseUpdated(body){if(body===null||typeof body!="object"||!isFiniteNumber(body.revision))return malformed3();let region=typeof body.region=="string"?body.region:"",ttlSeconds=isFiniteNumber(body.ttl_seconds)?body.ttl_seconds:0;/* @__PURE__ */
125
125
  return Object.freeze({kind:"updated",revision:body.revision,region:region,ttlSeconds:ttlSeconds,decisions:mapCapabilities(body.capabilities),branding:parseBranding(body),livemode:body.livemode!==false})}function parseBranding(body){let direct=parseClientBranding(body.branding);if(direct!==null)return direct;let hints=body.render_hints;if(hints!==null&&typeof hints=="object"){let nested=parseClientBranding(hints.branding);return nested!==null?nested:parseClientBranding(hints)}return null}function mapCapabilities(capabilities){if(capabilities===null||typeof capabilities!="object")/* @__PURE__ */return Object.freeze([]);let out=[];for(let[resource,value]of Object.entries(capabilities))isEnabled(value)&&out.push(/* @__PURE__ */Object.freeze({resource:resource,granted:true}));/* @__PURE__ */
126
126
  return Object.freeze(out)}function isEnabled(value){return typeof value=="object"&&value!==null&&value.enabled===true}function malformed3(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}var MIN_POLL_INTERVAL_SECONDS=30;function createEntitlementPoller(deps){let scheduler=deps.scheduler??defaultScheduler,resolve=deps.resolve??fetchEntitlements,floorSeconds=Math.max(1,deps.floorSeconds??MIN_POLL_INTERVAL_SECONDS),rng=deps.rng??Math.random,jitteredFloorSeconds=()=>floorSeconds+rng()*floorSeconds,started=false,stopped=false,timer=null,cachedRevision=null,lastCadenceSeconds=floorSeconds,generation=0,clearTimer=()=>{timer!==null&&(scheduler.clear(timer),timer=null)},schedule=seconds=>{stopped||!started||(lastCadenceSeconds=Math.max(floorSeconds,seconds),timer=scheduler.set(()=>{timer=null,run()},lastCadenceSeconds*1e3))},inFlight3=null,tick=async()=>{if(stopped)return null;let myGen=generation;deps.onFetch?.();let args=deps.region?{cachedRevision:cachedRevision,region:deps.region}:{cachedRevision:cachedRevision},resolution;try{resolution=await resolve(deps.authFor(),args)}catch(cause){return deps.telemetry?.track("sdk.entitlements.poll_error",{reason:describe(cause)}),!stopped&&myGen===generation&&(deps.onSettled?.(),schedule(jitteredFloorSeconds())),null}if(stopped||myGen!==generation)return null;switch(resolution.kind){case"updated":cachedRevision=resolution.revision,deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false),schedule(resolution.ttlSeconds);break;case"notModified":schedule(lastCadenceSeconds);break;case"failed":deps.telemetry?.track("sdk.entitlements.poll_failed",{code:resolution.error.code}),schedule(jitteredFloorSeconds());break;default:schedule(jitteredFloorSeconds())}return deps.onSettled?.(),resolution},run=()=>{let current=tick().finally(()=>{inFlight3===current&&(inFlight3=null)});return inFlight3=current,current};return{start(){started||stopped||(started=true,run())},prime(){return stopped?Promise.resolve(null):inFlight3??run()},stop(){stopped||(stopped=true,generation++,clearTimer())},refresh(){stopped||!started||(generation++,cachedRevision=null,clearTimer(),run())}}}var defaultScheduler={set(callback,ms){let handle=setTimeout(callback,ms);return handle.unref?.(),handle},clear(handle){clearTimeout(handle)}};function describe(cause){return cause instanceof Error?cause.message:"poll failed"}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3,PER_USER_KV_KEYS=/* @__PURE__ */Object.freeze([NOTIFICATIONS_DEVICE_KV_KEY]);function startBeforeLogoutHooks(deps){let{leaving:leaving,identity:identity,hooks:hooks,telemetry:telemetry}=deps;if(leaving===null||identity===null||hooks.size===0)return null;let context=/* @__PURE__ */Object.freeze({userRef:leaving.userRef,auth:deps.graceAuth()}),runs=[...hooks].map(hook=>{try{return Promise.resolve(hook(context))}catch(cause){return Promise.reject(cause)}}),report=(reason,count2)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count2,totalCount:runs.length})}catch{}},settled=Promise.allSettled(runs).then(outcomes=>{let failed=outcomes.filter(outcome=>outcome.status==="rejected").length;failed>0&&report("failed",failed)});return new Promise(resolve=>{let done=false,finish=()=>{done||(done=true,clearTimeout(timer),resolve())},timer=setTimeout(()=>{done||report("timeout",runs.length),finish()},LOGOUT_HOOK_BUDGET_MS);settled.then(finish,finish)})}function graceAuth(deps){let{leaving:leaving,identity:identity,transport:transport,sessionId:sessionId}=deps,token=identity.currentToken();token.catch(()=>{});let frozen={userRef:leaving.userRef,currentToken:()=>token,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:transport,identity:frozen,userRef:leaving.userRef,sessionId:sessionId}}async function sweepPerUserKv(kv,telemetry){if(PER_USER_KV_KEYS.length===0)return;let results=await Promise.allSettled(PER_USER_KV_KEYS.map(key=>kv.removeItem(key))),failedCount=results.filter(result=>result.status==="rejected").length;failedCount>0&&telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:failedCount,totalCount:results.length})}function compiledDefaultDecisions(){/* @__PURE__ */
127
- return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners2)listener()};return{subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot(){return snapshot},set(next){snapshot=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{}}),emit()},reset(){snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit()},setPending(pending){snapshot.isPending!==pending&&(snapshot=/* @__PURE__ */Object.freeze({...snapshot,isPending:pending}),emit())}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
127
+ return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners2)listener()};return{subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot(){return snapshot},set(next){snapshot=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{}}),emit()},reset(){snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit()},setPending(pending){snapshot.isPending!==pending&&(snapshot=/* @__PURE__ */Object.freeze({...snapshot,isPending:pending}),emit())}}}var BRANDING_CACHE_KEY_PREFIX="everfur.branding.v1.";function utf8Bytes(text3){let out=[];for(let ch of text3){let cp=ch.codePointAt(0);cp<128?out.push(cp):cp<2048?out.push(192|cp>>6,128|cp&63):cp<65536?out.push(224|cp>>12,128|cp>>6&63,128|cp&63):out.push(240|cp>>18,128|cp>>12&63,128|cp>>6&63,128|cp&63)}return out}function fnv1a64Hex(text3){let hi=3421674724,lo=2216829733;for(let byte2 of utf8Bytes(text3)){lo=(lo^byte2)>>>0;let loProduct=lo*435,carry=Math.floor(loProduct/4294967296),nextLo=loProduct>>>0;hi=hi*435+carry+lo*256>>>0,lo=nextLo}return hi.toString(16).padStart(8,"0")+lo.toString(16).padStart(8,"0")}function brandingCacheKey(scope){return`${BRANDING_CACHE_KEY_PREFIX}${fnv1a64Hex(scope)}`}function serializeBranding(branding){return branding?JSON.stringify(branding):null}async function readCachedBranding(kv,scope){try{let raw=await kv.getItem(brandingCacheKey(scope));if(raw===null)return null;let parsed=parseClientBranding(JSON.parse(raw));return parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,logoUrl:hardenBrandAssetUrl(parsed.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(parsed.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(parsed.assistantAvatarUrl??null)})}catch{return null}}async function writeCachedBranding(kv,scope,serialized){try{serialized===null?await kv.removeItem(brandingCacheKey(scope)):await kv.setItem(brandingCacheKey(scope),serialized)}catch{}}function createBrandingCache(kv,scope){let lastWritten;return{restore(apply){readCachedBranding(kv,scope).then(branding=>{branding!==null&&apply(branding)})},persist(branding){let serialized=serializeBranding(branding);serialized!==lastWritten&&(lastWritten=serialized,writeCachedBranding(kv,scope,serialized))}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
128
128
  return Object.freeze({track(event,props){try{port.track(event,props)}catch{}},trackExpectedFailure(code,props){try{port.trackExpectedFailure(code,props)}catch{}}})}var ENV_HINT=/* @__PURE__ */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 ${ENV_API_BASE_URL} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function reportConfigFailure(failure2,telemetry,platform=SDK_PLATFORM){try{telemetry.trackExpectedFailure("sdk.config.invalid",{reason:failure2.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${failure2.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+ENV_HINT[platform])}function refusingTransport(failure2){/* @__PURE__ */
129
- return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}function createInMemoryKv(){let map=/* @__PURE__ */new Map;return{async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}}}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&reportConfigFailure(failure2,this.telemetry,opts?.platform),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store;let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs));return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,branding,livemode)=>this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{}}),onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){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:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&&notifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&&current.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),()=>err(makeEverfurError("authRejected",{retryable:false}))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}/* @__PURE__ */
130
- return Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll())}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}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 entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot.branding??null,theme=useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment=props.seams.isDevelopment;return useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=useRef(null),supersededRef=useRef(null),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=useRef(null),lastPropPetRef=useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:seams.withDefaults?seams.withDefaults(config):config,user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
129
+ return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}function createInMemoryKv(){let map=/* @__PURE__ */new Map;return{async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}}}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}if(this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&(reportConfigFailure(failure2,this.telemetry,opts?.platform),this.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store,failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,branding,livemode)=>{this.verdictLanded=true,this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{}}),this.brandingCache?.persist(branding??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2})});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){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:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&&notifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&&current.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),()=>(identity.reportRejected?.(),err(makeEverfurError("authRejected",{retryable:false})))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll())}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}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 entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot.branding??null,theme=useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment=props.seams.isDevelopment;return useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=useRef(null),lastPropPetRef=useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
131
130
  return Object.freeze(out)}catch{return[]}}}}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face2=>(fonts.add(face2),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok3=>(ok3||warnOnce(source,warn),ok3));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face2 of FACES){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){return createElement(EverfurProviderCore,{...props,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
132
131
  return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
133
132
  return jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
@@ -138,7 +137,7 @@ return jsx("div",{className:className,style:{...styles.offstate,...style},childr
138
137
  /* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
139
138
  /* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
140
139
  /* @__PURE__ */Object.freeze({sentiment:"neutral",label:CHAT_COPY.feedbackNeutral}),
141
- /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch]),[binding,setBinding]=useState(null),controller=binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,scope]);let subscribe=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot=useSyncExternalStore(subscribe,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return useMemo(()=>({status:snapshot.status,messages:snapshot.messages,conversationId:snapshot.conversationId,petRef:petRef2,error:snapshot.error,isStreaming:snapshot.isStreaming,isBootstrapping:snapshot.isBootstrapping,historyCursor:snapshot.historyCursor??null,isLoadingHistory:snapshot.isLoadingHistory??false,stopped:snapshot.stopped??false,reconnecting:snapshot.reconnecting??false,...history,suggestedPrompts:snapshot.suggestedPrompts,unreadCount:snapshot.unreadCount,hasUnreadThreads:snapshot.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot=controller.getSnapshot();return snapshot.status==="error"&&snapshot.error!==null?err(snapshot.error):ok(lastAssistantResponseId(snapshot.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return err(makeEverfurError("internalError",{retryable:true}))}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef2),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef2,scopeEpoch,maxPerMessage,options.transport]),scoped=useMemo(()=>options.queue??build(),[options.queue,build]),disposed=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;useEffect(()=>{if(queue!==options.queue){if(disposed.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot.attachments.some(row=>row.status==="uploading"),failed=snapshot.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt){let clean=sanitizeSeedPrompt(prompt),latest=useRef(askEverfur);latest.current=askEverfur;let asked=useRef(null);useEffect(()=>{if(clean===null||isBootstrapping||asked.current===clean)return;let ask=latest.current;ask!==void 0&&(asked.current=clean,Promise.resolve(ask(clean)).catch(()=>{}))},[clean,isBootstrapping])}function isCoalesced(trigger,conversationId2,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId2=state.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),isOffline=lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:isOffline,lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason()}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=useState(null),[expanded,setExpanded]=useState(false);useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView2(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
140
+ /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}function useStalePetHold(runtime,userRef2,petRef2,scopeEpoch){let[owner,setOwner]=useState({pet:petRef2,user:userRef2}),adopt=owner.pet!==petRef2||owner.user===null&&userRef2!==null;adopt&&setOwner({pet:petRef2,user:userRef2});let current=adopt?{user:userRef2}:owner,held=petRef2!==null&&current.user!==null&&current.user!==userRef2;return useEffect(()=>{if(!held||userRef2===null||petRef2===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef2)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef2)&&setOwner({pet:petRef2,user:userRef2})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef2,petRef2,scopeEpoch]),held}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,held=useStalePetHold(runtime,userRef2,petRef2,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held,scope]);let subscribe=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot=useSyncExternalStore(subscribe,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return useMemo(()=>({status:snapshot.status,messages:snapshot.messages,conversationId:snapshot.conversationId,petRef:petRef2,error:snapshot.error,isStreaming:snapshot.isStreaming,isBootstrapping:snapshot.isBootstrapping,historyCursor:snapshot.historyCursor??null,isLoadingHistory:snapshot.isLoadingHistory??false,stopped:snapshot.stopped??false,reconnecting:snapshot.reconnecting??false,...history,suggestedPrompts:snapshot.suggestedPrompts,unreadCount:snapshot.unreadCount,hasUnreadThreads:snapshot.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot=controller.getSnapshot();return snapshot.status==="error"&&snapshot.error!==null?err(snapshot.error):ok(lastAssistantResponseId(snapshot.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return err(makeEverfurError("internalError",{retryable:true}))}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef2),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef2,scopeEpoch,maxPerMessage,options.transport]),scoped=useMemo(()=>options.queue??build(),[options.queue,build]),disposed=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;useEffect(()=>{if(queue!==options.queue){if(disposed.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot.attachments.some(row=>row.status==="uploading"),failed=snapshot.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt){let clean=sanitizeSeedPrompt(prompt),latest=useRef(askEverfur);latest.current=askEverfur;let asked=useRef(null);useEffect(()=>{if(clean===null||isBootstrapping||asked.current===clean)return;let ask=latest.current;ask!==void 0&&(asked.current=clean,Promise.resolve(ask(clean)).catch(()=>{}))},[clean,isBootstrapping])}function isCoalesced(trigger,conversationId2,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId2=state.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),isOffline=lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:isOffline,lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason()}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=useState(null),[expanded,setExpanded]=useState(false);useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView2(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
142
141
  return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef2,conversationId2){let opts={};return petRef2!==void 0&&(opts.petRef=petRef2),conversationId2!==void 0&&(opts.conversationId=conversationId2),opts}function useEverfurPets(){let{runtime:runtime,userRef:userRef2,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var FOCUS_RING_WIDTH=2,SELF_FOCUS_RING_ATTRIBUTE="data-ef-focus-ring",FOCUS_RING_COLOR_ATTRIBUTE="data-ef-focus-ring-color";function focusRingStyle(color){return{outline:`${FOCUS_RING_WIDTH}px solid ${color}`,outlineOffset:FOCUS_RING_WIDTH}}var keyboardDriving=false,bound=0;function onKeyDown(event){event.metaKey||event.ctrlKey||event.altKey||(keyboardDriving=true)}function onPointerDown(){keyboardDriving=false}function bindModality(){return typeof document>"u"?()=>{}:(bound===0&&(document.addEventListener("keydown",onKeyDown,true),document.addEventListener("pointerdown",onPointerDown,true),document.addEventListener("mousedown",onPointerDown,true),document.addEventListener("touchstart",onPointerDown,true)),bound+=1,()=>{bound-=1,!(bound>0)&&(document.removeEventListener("keydown",onKeyDown,true),document.removeEventListener("pointerdown",onPointerDown,true),document.removeEventListener("mousedown",onPointerDown,true),document.removeEventListener("touchstart",onPointerDown,true),keyboardDriving=false)})}var TEXT_INPUT_TYPES=/* @__PURE__ */new Set(["","text","search","email","tel","url","password","number"]);function isTextField(element){return element.tagName==="TEXTAREA"||element.isContentEditable?true:element.tagName!=="INPUT"?false:TEXT_INPUT_TYPES.has((element.getAttribute("type")??"").toLowerCase())}function useKeyboardFocusRing(root,color){useEffect(()=>{let node=root.current;if(node===null)return;let unbind=bindModality(),painted=/* @__PURE__ */new Map,onFocusIn=event=>{let target=event.target;if(!(target instanceof HTMLElement)||painted.has(target)||target.closest(`[${SELF_FOCUS_RING_ATTRIBUTE}="self"]`)!==null||!keyboardDriving&&!isTextField(target))return;painted.set(target,{outline:target.style.outline,outlineOffset:target.style.outlineOffset});let region=target.closest(`[${FOCUS_RING_COLOR_ATTRIBUTE}]`),ring=focusRingStyle(region?.getAttribute(FOCUS_RING_COLOR_ATTRIBUTE)||color);target.style.outline=ring.outline,target.style.outlineOffset=`${ring.outlineOffset}px`},onFocusOut=event=>{let target=event.target;if(!(target instanceof HTMLElement))return;let before=painted.get(target);before!==void 0&&(painted.delete(target),target.style.outline=before.outline,target.style.outlineOffset=before.outlineOffset)};return node.addEventListener("focusin",onFocusIn),node.addEventListener("focusout",onFocusOut),()=>{node.removeEventListener("focusin",onFocusIn),node.removeEventListener("focusout",onFocusOut);for(let[element,before]of painted)element.style.outline=before.outline,element.style.outlineOffset=before.outlineOffset;painted.clear(),unbind()}},[root,color])}function chatVetVisitOptions(petRef2,vet){let options={entry:"chat",petRef:petRef2};return vet?.returnTo!==void 0&&(options.returnTo=vet.returnTo),vet?.usState!==void 0&&(options.usState=vet.usState),vet?.prefer!==void 0&&(options.prefer=vet.prefer),options}var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present2=televetGlobal().presenter;if(present2===null)return"absent";try{return present2(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=useState(null);useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot=useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot.activeHost===id?snapshot.request:null,[module,setModule]=useState(null),wanted=request!==null&&module===null;return useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>import("@everfur/sdk/web/televet/booking"));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetDialog:EverfurTelevetDialog}=host.module;/* @__PURE__ */
143
142
  return jsx(EverfurTelevetDialog,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef2,options){let body={};petRef2!==void 0&&(body.pet_ref=petRef2);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef2===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef2,options){let pet;if(petRef2!=null){let length=typeof petRef2=="string"?[...petRef2].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef2}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var warned3=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned3||(warned3=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=useState(null);if(useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef2!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef2),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef2,scopeEpoch,opts.controller]),preflightController=useRef(controller);preflightController.current=controller;let scope=useMemo(()=>({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}),[runtime,userRef2,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=useState(IDLE2),inFlight3=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=useCallback((petRef2,visit)=>{if(inFlight3.current)return inFlight3.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef2===void 0?defaultPet:petRef2;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight3.current===tracked&&(inFlight3.current=null)});return inFlight3.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=useCallback((petRef2,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef2===void 0?defaultPet:petRef2,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=useCallback(petRef2=>redirect?start(petRef2,null):openInApp(petRef2,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit}}function closeQuietly(tab){try{tab.closed||tab.close()}catch{}}var BROWSER_OPENER=/* @__PURE__ */Object.freeze({prepare(){let tab=null;try{tab=typeof window>"u"?null:window.open("about:blank","_blank")}catch{tab=null}if(tab===null)return{ok:false,reason:"popupBlocked"};try{tab.opener=null}catch{}return{ok:true,value:{tab:tab}}},async finish({tab:tab},handoff){if(tab.closed)return"cancelled";try{return tab.location.replace(handoff.url),null}catch{return closeQuietly(tab),"popupBlocked"}},abandon({tab:tab}){closeQuietly(tab)}});function useVetVisit(opts){return useVetVisitWith(BROWSER_OPENER,opts)}var FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=useRef(null),wasOpen=useRef(false),opener=useRef(null),trigger=useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||document.activeElement===target)&&(opener.current=null)},[]);useEffect(()=>{if(!open){restoreFocus();return}let node=dialogRef.current;if(!wasOpen.current){let active=typeof document>"u"?null:document.activeElement;active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(document.activeElement)||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),useEffect(()=>restoreFocus,[restoreFocus]),useEffect(()=>{let node=dialogRef.current;if(!open||node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&document.activeElement!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown2=useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=document.activeElement;event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown2,onCancel:onCancel}}var PATHS=/* @__PURE__ */Object.freeze({check:/* @__PURE__ */jsx("polyline",{points:"20 6 9 17 4 12"}),copy:/* @__PURE__ */jsxs(Fragment,{children:[
144
143
  /* @__PURE__ */jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),
@@ -200,14 +199,16 @@ return jsx("li",{children:/* @__PURE__ */jsxs("button",{type:"button","aria-curr
200
199
  /* @__PURE__ */jsx("button",{type:"button",onClick:onClose,style:styles.close,children:CHAT_COPY.close})]}):null}function makeStyles3(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return{sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:SHEET_MAX_HEIGHT,overflowY:"auto",padding:`${s.lg+4}px ${s.lg+4}px ${s.xxl}px`,border:0,borderRadius:`${SHEET_RADIUS}px ${SHEET_RADIUS}px 0 0`,backgroundColor:c.surface,color:c.text.primary,display:"flex",flexDirection:"column",gap:s.md+2,...sheetSlotCss(theme.slots.dialog)},title:{margin:0,...headingFaceCss(theme,"bold"),fontSize:t.tierSizes.heading.heading,lineHeight:`${Math.round(t.tierSizes.heading.heading*1.22)}px`,color:c.brandInk,...slotText(theme.slots.dialog)},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s.sm},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET2,display:"flex",flexDirection:"row",alignItems:"center",gap:s.md,margin:0,padding:s.md,borderRadius:r.md,border:`1px solid ${c.brandBorder}`,backgroundColor:c.surfaceCream,color:c.text.primary,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{border:`1px solid ${c.brandInk}`,backgroundColor:c.brandSoft},ring:{boxSizing:"border-box",flexShrink:0,width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,border:`2px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:ROW_AVATAR_SIZE,height:ROW_AVATAR_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(ROW_AVATAR_SIZE*.42),lineHeight:1,textTransform:"uppercase"},text:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:2},name:{...faceCss(theme,"bold"),fontSize:t.size.body+1,lineHeight:`${t.size.body+4}px`,color:c.text.primary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},meta:{...faceCss(theme,"monoBold"),fontSize:t.tierSizes.compact.tiny,lineHeight:`${t.tierSizes.compact.tiny+2}px`,letterSpacing:.4,textTransform:"uppercase",color:c.text.muted},addRow:{boxSizing:"border-box",display:"flex",alignItems:"center",gap:s.sm,width:"100%",minHeight:MIN_TOUCH_TARGET2,padding:`${s.xs}px ${s.sm}px`,background:"none",border:"none",borderRadius:r.lg,cursor:"pointer",textAlign:"left"},addDisc:{boxSizing:"border-box",width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",border:`2px dashed ${c.brandBorder}`,backgroundColor:c.surfaceCream,color:c.brandInk,fontSize:t.size.subtitle,lineHeight:1},addLabel:{...faceCss(theme,"bold"),fontSize:t.size.body,color:c.text.primary,...slotText(theme.slots.dialog)},close:{boxSizing:"border-box",alignSelf:"center",minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.xl}px`,borderRadius:r.pill,border:`1px solid ${c.brandBorder}`,backgroundColor:c.surface,color:c.text.primary,cursor:"pointer",...faceCss(theme,"medium"),fontSize:t.tierSizes.control.body}}}var HEADER_AVATAR_SIZE=35,RING_WIDTH=1.75,AVATAR_INNER_SIZE=HEADER_AVATAR_SIZE-RING_WIDTH*2,ADD_BADGE_SIZE=12.4,MENU_BUTTON_SIZE=36,HISTORY_GLYPH_SIZE=20,UNREAD_DOT_SIZE=9,UNREAD_DOT_RING=1.5,MIN_TOUCH_TARGET3=44;function ChatHeader(props){let{pets:pets,activePet:activePet,unread:unread,onOpenHistory:onOpenHistory,historyTriggerRef:historyTriggerRef,onSelectPet:onSelectPet,onAddPet:onAddPet=null,vetEntry:vetEntry=null}=props,{rail:rail=false,historyOpen:historyOpen=false,onNewChat:onNewChat}=props,theme=useEverfurTheme(),styles=useMemo(()=>makeStyles4(theme),[theme]),glyphInk=theme.slots.header?.textColor??theme.color.text.primary,historyControls=/* @__PURE__ */jsxs("div",{style:styles.historyControls,children:[onNewChat!==void 0?/* @__PURE__ */jsx("button",{type:"button",onClick:onNewChat,"aria-label":HISTORY_COPY.newChat,style:styles.menuButton,children:/* @__PURE__ */jsx(Glyph,{name:"squarePen",size:HISTORY_GLYPH_SIZE,color:glyphInk})}):null,
201
200
  /* @__PURE__ */jsx("button",{ref:historyTriggerRef,type:"button",onClick:onOpenHistory,"aria-label":historyControlLabel(rail,historyOpen,unread),"aria-expanded":historyOpen,style:styles.menuButton,children:/* @__PURE__ */jsxs("span",{"aria-hidden":"true",style:styles.menuDisc,children:[
202
201
  /* @__PURE__ */jsx(Glyph,{name:"history",size:HISTORY_GLYPH_SIZE,color:glyphInk}),unread?/* @__PURE__ */jsx("span",{style:styles.unreadDot}):null]})})]});/* @__PURE__ */
203
- return jsxs("header",{style:styles.bar,children:[rail?null:historyControls,
204
- /* @__PURE__ */jsx("div",{style:styles.centre,children:/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles})}),vetEntry!==null?/* @__PURE__ */jsx("button",{type:"button",onClick:vetEntry,style:styles.vetEntry,children:TELEVET_COPY.visitButton}):null,
205
- /* @__PURE__ */jsx(PetAvatarSlot,{pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}),rail?historyControls:null]})}function historyControlLabel(rail,open,unread){let base=rail?open?CHAT_COPY.hideChatsWeb:CHAT_COPY.showChatsWeb:CHAT_COPY.openHistoryWeb;return unread?`${base}${CHAT_COPY.newReplySuffix}`:base}function PetAvatarSlot({pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}){let[open,setOpen]=useState(false),triggerRef=useRef(null),name=activePet?.name?.trim()||CHAT_COPY.yourPet;return pets.length<2&&onAddPet===null||activePet===null?/* @__PURE__ */jsx("div",{role:"img","aria-label":name,style:styles.avatarSlot,children:/* @__PURE__ */jsx(AvatarRing,{pet:activePet,styles:styles})}):/* @__PURE__ */jsxs("div",{style:styles.avatarSlot,children:[
202
+ return jsxs("header",{style:styles.bar,children:[
203
+ /* @__PURE__ */jsx("div",{style:styles.leading,children:rail?null:historyControls}),
204
+ /* @__PURE__ */jsx("div",{style:styles.centre,children:/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles})}),
205
+ /* @__PURE__ */jsxs("div",{style:styles.trailing,children:[vetEntry!==null?/* @__PURE__ */jsx("button",{type:"button",onClick:vetEntry,style:styles.vetEntry,children:TELEVET_COPY.visitButton}):null,
206
+ /* @__PURE__ */jsx(PetAvatarSlot,{pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}),rail?historyControls:null]})]})}function historyControlLabel(rail,open,unread){let base=rail?open?CHAT_COPY.hideChatsWeb:CHAT_COPY.showChatsWeb:CHAT_COPY.openHistoryWeb;return unread?`${base}${CHAT_COPY.newReplySuffix}`:base}function PetAvatarSlot({pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}){let[open,setOpen]=useState(false),triggerRef=useRef(null),name=activePet?.name?.trim()||CHAT_COPY.yourPet;return pets.length<2&&onAddPet===null||activePet===null?/* @__PURE__ */jsx("div",{role:"img","aria-label":name,style:styles.avatarSlot,children:/* @__PURE__ */jsx(AvatarRing,{pet:activePet,styles:styles})}):/* @__PURE__ */jsxs("div",{style:styles.avatarSlot,children:[
206
207
  /* @__PURE__ */jsxs("button",{ref:triggerRef,type:"button","aria-haspopup":"dialog","aria-expanded":open,"aria-label":fillCopy(CHAT_COPY.switchActivePet,{name:name}),onClick:()=>setOpen(true),style:styles.avatarButton,children:[
207
208
  /* @__PURE__ */jsx(AvatarRing,{pet:activePet,styles:styles}),
208
209
  /* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.addBadge,children:/* @__PURE__ */jsx("span",{style:styles.addBadgeGlyph,children:"+"})})]}),
209
210
  /* @__PURE__ */jsx(PetSwitcherDialog,{open:open,pets:pets,activePetRef:activePet.petRef,returnFocusTo:triggerRef,onClose:()=>setOpen(false),onSelect:petRef2=>{setOpen(false),onSelectPet(petRef2)},onAddPet:onAddPet===null?null:()=>{setOpen(false),onAddPet()}})]})}function AvatarRing({pet:pet,styles:styles}){let theme=useEverfurTheme(),palette=pet===null?null:petDiscPaint(pet,isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight});/* @__PURE__ */
210
- return jsx("span",{style:styles.ring,children:/* @__PURE__ */jsx("span",{style:{...styles.disc,...palette===null?styles.discEmpty:{backgroundColor:palette.background,color:palette.foreground}},children:palette===null?getInitial(null):palette.initial})})}function makeStyles4(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,header=theme.slots.header;return{vetEntry:{boxSizing:"border-box",minHeight:44,padding:`0 ${s.md}px`,borderRadius:r.pill,backgroundColor:c.surfaceCream,border:`1px solid ${c.controlEdge}`,color:c.brandInk,cursor:"pointer",whiteSpace:"nowrap",...faceCss(theme,"bold"),fontSize:t.size.caption},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm+2}px ${s.lg}px`,backgroundColor:c.surfaceCream,...slotCss(header)},menuButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",cursor:"pointer",color:header?.textColor??c.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:MENU_BUTTON_SIZE,height:MENU_BUTTON_SIZE,borderRadius:r.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:r.pill,backgroundColor:c.danger,border:`${UNREAD_DOT_RING}px solid ${header?.backgroundColor??c.surfaceCream}`},centre:{flex:"1 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:LOGO_STYLE,avatarSlot:{position:"relative",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,borderRadius:r.pill,border:`${RING_WIDTH}px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:AVATAR_INNER_SIZE,height:AVATAR_INNER_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(AVATAR_INNER_SIZE*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:c.surfaceSubtle,color:c.text.muted},addBadge:{position:"absolute",bottom:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,right:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,boxSizing:"border-box",width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:r.pill,border:`0.5px solid ${c.mark}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...faceCss(theme,"bold"),fontSize:t.tierSizes.badge.small,lineHeight:1,color:c.brandInk}}}var STATIC=/* @__PURE__ */Object.freeze({kind:"static"}),CitationLinkContext=createContext(STATIC);function useCitationLinks(){return useContext(CitationLinkContext)}function useCitationLinkMode(onOpenUrl){return useMemo(()=>onOpenUrl===void 0?STATIC:/* @__PURE__ */Object.freeze({kind:"host",open:url=>{callHost(onOpenUrl,url,"citation")}}),[onOpenUrl])}function CitationLinksScope({onOpenUrl:onOpenUrl,children:children}){let mode=useCitationLinkMode(onOpenUrl);return createElement(CitationLinkContext.Provider,{value:mode},children)}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var HISTORY_PANEL_WIDTH=320,MIN_THREAD_WIDTH=480,RAIL_MIN_CONTAINER_WIDTH=HISTORY_PANEL_WIDTH+MIN_THREAD_WIDTH,DESKTOP_MIN_CONTAINER_WIDTH=1024,CHAT_COLUMN_MAX_WIDTH=768,ASSISTANT_MEASURE="72ch",NARROW_LAYOUT=/* @__PURE__ */Object.freeze({rail:false,desktop:false}),RAIL_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:false}),DESKTOP_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:true});function layoutFor(width){return width===null||width<RAIL_MIN_CONTAINER_WIDTH?NARROW_LAYOUT:width>=DESKTOP_MIN_CONTAINER_WIDTH?DESKTOP_LAYOUT:RAIL_LAYOUT}var ChatLayoutContext=createContext({layout:NARROW_LAYOUT,report:()=>{},headingLevel:headingLevel(void 0)});function useChatLayout(){return useContext(ChatLayoutContext).layout}function useChatHeadingLevel(){return useContext(ChatLayoutContext).headingLevel}function ChatLayoutScope({children:children,headingLevel:hostLevel}){let[layout,setLayout]=useState(NARROW_LAYOUT),level=headingLevel(hostLevel),value=useMemo(()=>({layout:layout,report:setLayout,headingLevel:level}),[layout,level]);return createElement(ChatLayoutContext.Provider,{value:value},children)}function useMeasuredLayout(root){let{report:report}=useContext(ChatLayoutContext);useEffect(()=>{let node=root.current;if(node===null||typeof ResizeObserver>"u")return;let read=()=>{let width=node.getBoundingClientRect().width;report(layoutFor(width>0?Math.round(width):null))};read();let observer=new ResizeObserver(read);return observer.observe(node),()=>observer.disconnect()},[root,report])}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])}),cubicBezier=cssCubicBezier,CHAT_MOTION=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return useMemo(()=>chatMotion(theme),[theme])}function canAnimate(node){return node!==null&&typeof node.animate=="function"}function animateEnter(node,motion){if(!canAnimate(node)||motion.durationMs<=0)return null;let translate=[motion.fromTranslateX!==void 0?`translateX(${motion.fromTranslateX})`:"",motion.fromTranslateY!==void 0&&motion.fromTranslateY!==0?`translateY(${motion.fromTranslateY}px)`:""].filter(part=>part.length>0).join(" "),from={...motion.fromOpacity!==void 0?{opacity:motion.fromOpacity}:{},...translate.length>0?{transform:translate}:{}},to={...motion.fromOpacity!==void 0?{opacity:1}:{},...translate.length>0?{transform:"none"}:{}};try{return node.animate([from,to],{duration:motion.durationMs,delay:motion.delayMs??0,easing:cubicBezier(CHAT_EASING.standard),fill:"backwards"})}catch{return null}}function popIn(node,motion){if(!canAnimate(node)||motion.bubbleInMs<=0)return null;try{return node.animate([{opacity:0,transform:`translateY(${motion.bubbleRisePx}px) scale(${motion.bubbleFromScale})`},{opacity:1,transform:"none"}],{duration:motion.bubbleInMs,easing:cubicBezier(CHAT_EASING.out),fill:"backwards"})}catch{return null}}function animateExit(node,durationMs,toTranslateX){if(!canAnimate(node)||durationMs<=0)return Promise.resolve();try{let animation=node.animate([{opacity:1,transform:"none"},{opacity:0,...toTranslateX!==void 0?{transform:`translateX(${toTranslateX})`}:{}}],{duration:durationMs,easing:cubicBezier(CHAT_EASING.exit),fill:"forwards"});return new Promise(resolve=>{animation.onfinish=()=>resolve(),animation.oncancel=()=>resolve()})}catch{return Promise.resolve()}}function usePresence(show,exitMs){let[present2,setPresent]=useState(show),exiting=present2&&!show;return useEffect(()=>{if(show){setPresent(true);return}if(!present2)return;if(exitMs<=0){setPresent(false);return}let handle=setTimeout(()=>setPresent(false),exitMs);return()=>clearTimeout(handle)},[show,exitMs,present2]),{present:present2,exiting:exiting}}function useRevealedText(text3,active,motion){let[visible,setVisible]=useState(active&&!motion.reduced?0:text3.length),latest=useRef({text:text3,active:active});return latest.current={text:text3,active:active},useEffect(()=>{if(!active||motion.reduced||motion.revealTickMs<=0){setVisible(latest.current.text.length);return}let handle=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.text.length))},motion.revealTickMs);return()=>clearInterval(handle)},[active,motion]),active&&!motion.reduced?text3.slice(0,Math.min(visible,text3.length)):text3}var MIN_TOUCH_TARGET4=44,DRAWER_MAX_WIDTH="85%",DRAWER_SHADOW={y:16,blur:48,alpha:.18},SCRIM_ALPHA=.32,UNREAD_DOT_SIZE2=8,ACTIVE_ROW_ALPHA=.22,SEARCH_EDGE_WIDTH=1.5,LOAD_MORE_MARGIN="50%";function HistoryDrawer({chat:chat,history:history,mode:mode,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles5(theme,mode==="dialog"),[theme,mode]),motion=useChatMotion(),dialog=useModalDialog(mode==="dialog"&&history.open,history.close,returnFocusTo),panelRef=useRef(null),open=history.open,slideMs=motion.drawerMs;if(useEffect(()=>{if(!open||mode!=="dialog")return;let animation=animateEnter(panelRef.current,{durationMs:slideMs,fromOpacity:0,fromTranslateX:"-100%"});return()=>animation?.cancel()},[open,mode,slideMs]),!open)return null;let body=/* @__PURE__ */jsx(PanelBody,{chat:chat,history:history,styles:styles,theme:theme,rail:mode==="rail"});return mode==="rail"?/* @__PURE__ */jsx("aside",{ref:node=>{panelRef.current=node},"aria-label":HISTORY_COPY.heading,style:styles.rail,children:body}):/* @__PURE__ */jsx("div",{style:styles.scrim,onClick:history.close,children:/* @__PURE__ */jsx("div",{ref:node=>{dialog.dialogRef.current=node,panelRef.current=node},role:"dialog","aria-modal":"true","aria-label":HISTORY_COPY.heading,tabIndex:-1,onKeyDown:dialog.onKeyDown,onClick:event=>event.stopPropagation(),style:styles.overlay,children:body})})}function PanelBody({chat:chat,history:history,styles:styles,theme:theme,rail:rail}){let{rows:rows,filtered:filtered,loading:loading,loadingMore:loadingMore,error:error,cursor:cursor2,emptyKind:emptyKind,searching:searching,query:query,setQuery:setQuery}=history,showRows=!loading&&error===null,[searchFocused,setSearchFocused]=useState(false),closeInk=(rail?void 0:theme.slots.dialog?.textColor)??theme.color.brandInk,searchInk=theme.slots.input?.textColor??theme.color.text.muted;/* @__PURE__ */
211
+ return jsx("span",{style:styles.ring,children:/* @__PURE__ */jsx("span",{style:{...styles.disc,...palette===null?styles.discEmpty:{backgroundColor:palette.background,color:palette.foreground}},children:palette===null?getInitial(null):palette.initial})})}function makeStyles4(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,header=theme.slots.header;return{vetEntry:{boxSizing:"border-box",minHeight:44,padding:`0 ${s.md}px`,borderRadius:r.pill,backgroundColor:c.surfaceCream,border:`1px solid ${c.controlEdge}`,color:c.brandInk,cursor:"pointer",whiteSpace:"nowrap",...faceCss(theme,"bold"),fontSize:t.size.caption},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm+2}px ${s.lg}px`,backgroundColor:c.surfaceCream,...slotCss(header)},menuButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",cursor:"pointer",color:header?.textColor??c.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:MENU_BUTTON_SIZE,height:MENU_BUTTON_SIZE,borderRadius:r.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:r.pill,backgroundColor:c.danger,border:`${UNREAD_DOT_RING}px solid ${header?.backgroundColor??c.surfaceCream}`},leading:{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"flex-start",gap:s.sm,flex:"1 1 0"},trailing:{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"flex-end",gap:s.sm,flex:"1 1 0"},centre:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:{...LOGO_STYLE,minWidth:0,flexShrink:1},avatarSlot:{position:"relative",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,borderRadius:r.pill,border:`${RING_WIDTH}px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:AVATAR_INNER_SIZE,height:AVATAR_INNER_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(AVATAR_INNER_SIZE*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:c.surfaceSubtle,color:c.text.muted},addBadge:{position:"absolute",bottom:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,right:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,boxSizing:"border-box",width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:r.pill,border:`0.5px solid ${c.mark}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...faceCss(theme,"bold"),fontSize:t.tierSizes.badge.small,lineHeight:1,color:c.brandInk}}}var STATIC=/* @__PURE__ */Object.freeze({kind:"static"}),CitationLinkContext=createContext(STATIC);function useCitationLinks(){return useContext(CitationLinkContext)}function useCitationLinkMode(onOpenUrl){return useMemo(()=>onOpenUrl===void 0?STATIC:/* @__PURE__ */Object.freeze({kind:"host",open:url=>{callHost(onOpenUrl,url,"citation")}}),[onOpenUrl])}function CitationLinksScope({onOpenUrl:onOpenUrl,children:children}){let mode=useCitationLinkMode(onOpenUrl);return createElement(CitationLinkContext.Provider,{value:mode},children)}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var HISTORY_PANEL_WIDTH=320,MIN_THREAD_WIDTH=480,RAIL_MIN_CONTAINER_WIDTH=HISTORY_PANEL_WIDTH+MIN_THREAD_WIDTH,DESKTOP_MIN_CONTAINER_WIDTH=1024,CHAT_COLUMN_MAX_WIDTH=768,ASSISTANT_MEASURE="72ch",NARROW_LAYOUT=/* @__PURE__ */Object.freeze({rail:false,desktop:false}),RAIL_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:false}),DESKTOP_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:true});function layoutFor(width){return width===null||width<RAIL_MIN_CONTAINER_WIDTH?NARROW_LAYOUT:width>=DESKTOP_MIN_CONTAINER_WIDTH?DESKTOP_LAYOUT:RAIL_LAYOUT}var ChatLayoutContext=createContext({layout:NARROW_LAYOUT,report:()=>{},headingLevel:headingLevel(void 0)});function useChatLayout(){return useContext(ChatLayoutContext).layout}function useChatHeadingLevel(){return useContext(ChatLayoutContext).headingLevel}function ChatLayoutScope({children:children,headingLevel:hostLevel}){let[layout,setLayout]=useState(NARROW_LAYOUT),level=headingLevel(hostLevel),value=useMemo(()=>({layout:layout,report:setLayout,headingLevel:level}),[layout,level]);return createElement(ChatLayoutContext.Provider,{value:value},children)}function useMeasuredLayout(root){let{report:report}=useContext(ChatLayoutContext);useEffect(()=>{let node=root.current;if(node===null||typeof ResizeObserver>"u")return;let read=()=>{let width=node.getBoundingClientRect().width;report(layoutFor(width>0?Math.round(width):null))};read();let observer=new ResizeObserver(read);return observer.observe(node),()=>observer.disconnect()},[root,report])}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])}),cubicBezier=cssCubicBezier,CHAT_MOTION=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return useMemo(()=>chatMotion(theme),[theme])}function canAnimate(node){return node!==null&&typeof node.animate=="function"}function animateEnter(node,motion){if(!canAnimate(node)||motion.durationMs<=0)return null;let translate=[motion.fromTranslateX!==void 0?`translateX(${motion.fromTranslateX})`:"",motion.fromTranslateY!==void 0&&motion.fromTranslateY!==0?`translateY(${motion.fromTranslateY}px)`:""].filter(part=>part.length>0).join(" "),from={...motion.fromOpacity!==void 0?{opacity:motion.fromOpacity}:{},...translate.length>0?{transform:translate}:{}},to={...motion.fromOpacity!==void 0?{opacity:1}:{},...translate.length>0?{transform:"none"}:{}};try{return node.animate([from,to],{duration:motion.durationMs,delay:motion.delayMs??0,easing:cubicBezier(CHAT_EASING.standard),fill:"backwards"})}catch{return null}}function popIn(node,motion){if(!canAnimate(node)||motion.bubbleInMs<=0)return null;try{return node.animate([{opacity:0,transform:`translateY(${motion.bubbleRisePx}px) scale(${motion.bubbleFromScale})`},{opacity:1,transform:"none"}],{duration:motion.bubbleInMs,easing:cubicBezier(CHAT_EASING.out),fill:"backwards"})}catch{return null}}function animateExit(node,durationMs,toTranslateX){if(!canAnimate(node)||durationMs<=0)return Promise.resolve();try{let animation=node.animate([{opacity:1,transform:"none"},{opacity:0,...toTranslateX!==void 0?{transform:`translateX(${toTranslateX})`}:{}}],{duration:durationMs,easing:cubicBezier(CHAT_EASING.exit),fill:"forwards"});return new Promise(resolve=>{animation.onfinish=()=>resolve(),animation.oncancel=()=>resolve()})}catch{return Promise.resolve()}}function usePresence(show,exitMs){let[present2,setPresent]=useState(show),exiting=present2&&!show;return useEffect(()=>{if(show){setPresent(true);return}if(!present2)return;if(exitMs<=0){setPresent(false);return}let handle=setTimeout(()=>setPresent(false),exitMs);return()=>clearTimeout(handle)},[show,exitMs,present2]),{present:present2,exiting:exiting}}function useRevealedText(text3,active,motion){let[visible,setVisible]=useState(active&&!motion.reduced?0:text3.length),latest=useRef({text:text3,active:active});return latest.current={text:text3,active:active},useEffect(()=>{if(!active||motion.reduced||motion.revealTickMs<=0){setVisible(latest.current.text.length);return}let handle=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.text.length))},motion.revealTickMs);return()=>clearInterval(handle)},[active,motion]),active&&!motion.reduced?text3.slice(0,Math.min(visible,text3.length)):text3}var MIN_TOUCH_TARGET4=44,DRAWER_MAX_WIDTH="85%",DRAWER_SHADOW={y:16,blur:48,alpha:.18},SCRIM_ALPHA=.32,UNREAD_DOT_SIZE2=8,ACTIVE_ROW_ALPHA=.22,SEARCH_EDGE_WIDTH=1.5,LOAD_MORE_MARGIN="50%";function HistoryDrawer({chat:chat,history:history,mode:mode,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles5(theme,mode==="dialog"),[theme,mode]),motion=useChatMotion(),dialog=useModalDialog(mode==="dialog"&&history.open,history.close,returnFocusTo),panelRef=useRef(null),open=history.open,slideMs=motion.drawerMs;if(useEffect(()=>{if(!open||mode!=="dialog")return;let animation=animateEnter(panelRef.current,{durationMs:slideMs,fromOpacity:0,fromTranslateX:"-100%"});return()=>animation?.cancel()},[open,mode,slideMs]),!open)return null;let body=/* @__PURE__ */jsx(PanelBody,{chat:chat,history:history,styles:styles,theme:theme,rail:mode==="rail"});return mode==="rail"?/* @__PURE__ */jsx("aside",{ref:node=>{panelRef.current=node},"aria-label":HISTORY_COPY.heading,style:styles.rail,children:body}):/* @__PURE__ */jsx("div",{style:styles.scrim,onClick:history.close,children:/* @__PURE__ */jsx("div",{ref:node=>{dialog.dialogRef.current=node,panelRef.current=node},role:"dialog","aria-modal":"true","aria-label":HISTORY_COPY.heading,tabIndex:-1,onKeyDown:dialog.onKeyDown,onClick:event=>event.stopPropagation(),style:styles.overlay,children:body})})}function PanelBody({chat:chat,history:history,styles:styles,theme:theme,rail:rail}){let{rows:rows,filtered:filtered,loading:loading,loadingMore:loadingMore,error:error,cursor:cursor2,emptyKind:emptyKind,searching:searching,query:query,setQuery:setQuery}=history,showRows=!loading&&error===null,[searchFocused,setSearchFocused]=useState(false),closeInk=(rail?void 0:theme.slots.dialog?.textColor)??theme.color.brandInk,searchInk=theme.slots.input?.textColor??theme.color.text.muted;/* @__PURE__ */
211
212
  return jsxs(Fragment,{children:[
212
213
  /* @__PURE__ */jsxs("div",{style:styles.head,children:[
213
214
  /* @__PURE__ */jsx("p",{style:styles.heading,children:HISTORY_COPY.heading}),