@everfur/sdk 1.5.2 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{bookingCopy.d-BL2-URcv.d.ts → bookingCopy.d-Bn8bdo89.d.ts} +4 -4
- package/dist/{bookingCopy.d-Dfew1pjY.d.cts → bookingCopy.d-Dg7bPM-U.d.cts} +4 -4
- package/dist/chat/index.cjs +1 -1
- package/dist/chat/index.js +1 -1
- package/dist/chat/lite/index.cjs +1 -1
- package/dist/chat/lite/index.js +1 -1
- package/dist/{chunk-K7YHXFPQ.js → chunk-CFEHTNKX.js} +1 -1
- package/dist/{chunk-2T5CB5MW.js → chunk-OU5RMGKD.js} +8 -8
- package/dist/{chunk-ASE36WGP.js → chunk-XGF2HYNN.js} +14 -14
- package/dist/{chunk-CMDCBYUH.js → chunk-ZGL2GEEI.js} +1 -1
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.js +1 -1
- package/dist/{idempotency.d-dOFfV91-.d.ts → idempotency.d-CbB07p64.d.ts} +10 -8
- package/dist/{idempotency.d-CFVMhWcv.d.cts → idempotency.d-DrxKLPPe.d.cts} +10 -8
- package/dist/index.cjs +2 -2
- package/dist/index.js +2 -2
- package/dist/{optInView.d-ByDJMrMv.d.cts → optInView.d-ChJyJMBA.d.cts} +4 -1
- package/dist/{optInView.d-DVshLxbD.d.ts → optInView.d-Cps7aLQN.d.ts} +4 -1
- package/dist/records/index.cjs +1 -1
- package/dist/records/index.js +1 -1
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.js +1 -1
- package/dist/shop/index.cjs +1 -1
- package/dist/shop/index.d.cts +2 -2
- package/dist/shop/index.d.ts +2 -2
- package/dist/shop/index.js +1 -1
- package/dist/televet/booking/index.cjs +156 -156
- package/dist/televet/booking/index.d.cts +2 -2
- package/dist/televet/booking/index.d.ts +2 -2
- package/dist/televet/booking/index.js +156 -156
- package/dist/texting/index.cjs +8 -8
- package/dist/texting/index.d.cts +2 -2
- package/dist/texting/index.d.ts +2 -2
- package/dist/texting/index.js +8 -8
- package/dist/web/health-plan/index.cjs +1 -1
- package/dist/web/health-plan/index.js +1 -1
- package/dist/web/index.cjs +3 -3
- package/dist/web/index.js +3 -3
- package/dist/web/records-sheet/index.cjs +1 -1
- package/dist/web/records-sheet/index.js +1 -1
- package/dist/web/shop/index.cjs +2 -2
- package/dist/web/shop/index.d.cts +2 -2
- package/dist/web/shop/index.d.ts +2 -2
- package/dist/web/shop/index.js +3 -3
- package/dist/web/televet/booking/index.cjs +185 -185
- package/dist/web/televet/booking/index.d.cts +2 -2
- package/dist/web/televet/booking/index.d.ts +2 -2
- package/dist/web/televet/booking/index.js +185 -185
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/texting/index.cjs +3 -4
- package/dist/web/texting/index.d.cts +2 -2
- package/dist/web/texting/index.d.ts +2 -2
- package/dist/web/texting/index.js +3 -4
- package/dist/web/ui/index.cjs +1 -1
- package/dist/web/ui/index.js +33 -33
- package/package.json +1 -1
package/dist/web/index.cjs
CHANGED
|
@@ -11,7 +11,7 @@ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryab
|
|
|
11
11
|
return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
|
|
12
12
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
|
|
13
13
|
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var S="/widget/v1/anon-identity",j="x-everfur-anon-token",_="anonTokenInvalid";function R(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let l=null,i=null,o=null,a=null,s=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs-2592e5),d=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,a={method:"POST",path:S,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},s=await e.request(a),u=s.ok?s.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(l={token:c,mintedAtMs:n(),ttlMs:R(u?.expires_at,i)},o=null,c)}catch{return o=n(),d()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(a,3e4)?Promise.resolve(l?.token??null):(a=n(),l=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function E(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}var I="This feature isn't available on your account right now.",z="Something in that request was not right. Check the details and try again.",T=/* @__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:I,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:z,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:I,runtimeDisposed:z,unknown:"Something went wrong. Please try again."}),P="This session has ended. Please sign in again.",O="linked_account_read_only";function F(e,t,r){return e==="conflict"&&r===O?I:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?P:userFacingError(e)}function userFacingError(e){return T[e]}function M(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var A=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===O,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:F(e,t?.wireCode,n?O:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&A.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&M(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&M(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}function $(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let l=null,i=false,o=null,a=false,u=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new s("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:D(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(a)throw new s("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:u()},hasToken(){return!a&&l!==null},clear(){a=true,l=null},reportRejected(){a||i||(i=true,n?.())}}}function D(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[j]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...B(e.headers),...authHeaders(t)}}}function B(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===j||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await E(t),n=await t.transport.request(withAuthHeaders(e,N(t,r)));if(n.ok||U(n.error.raw)!==_||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,N(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err($(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err($(e,{wireCode:U(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(L(i.error))):i}function N(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function L(e){let t=e.raw,r=U(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function U(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var H="DAILY_QUOTA_EXCEEDED",W=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function q(e,t){if(!W.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?H:e}var V="free_cap_reached";function K(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function G(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==V&&n.code!==V)return null;let l=K(n.limit),i=K(n.used);if(l===null||i===null)return null;let o=n.resets_at,a=n.emergency_guidance;/* @__PURE__ */
|
|
14
|
-
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function Y(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:G(t)}function Q(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function Z(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):Q()}var X=`\n\n`,J=1048576,ee=/* @__PURE__ */t.z.record(/* @__PURE__ */t.z.string(),/* @__PURE__ */t.z.unknown()),te=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=Z(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(X,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+X.length),o=0;let r=re(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>J){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=re(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function re(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=ee.safeParse(l);return i.success?ne(i.data,r,t):null}function ne(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:le(e.code)??"unknown",retryable:e.retryable===true,wireMessage:le(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:G(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:se(e.follow_up_questions),citations:ce(e.citations),citationStatus:le(e.citation_status),urgencyLevel:oe(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:ae(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(le(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=le(e.delta)??le(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(le(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:ie(e.confidence),detections:ce(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function le(e){return typeof e=="string"?e:null}function ie(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function oe(e){return typeof e=="string"&&te.includes(e)?e:null}function ae(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||oe(t)!==null}function se(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ce(e){return Array.isArray(e)?e.filter(ue):[]}var de=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function fe(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return me(e)}var pe=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,he=/[\s\u0000-\u001f\u007f\\]/,ge={"http:":"80","https:":"443"};function me(e,t){let r=e.trim();let n=he.test(r)?null:pe.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,p=Number(s);if(p>65535)return null;let h=s===""||String(p)===ge[f]?"":String(p),g=ge[f]!==void 0,m=a.toLowerCase()+(h&&`:${h}`),b=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:h,origin:g?`${f}//${m}`:"null",pathname:b,search:c==="?"?"":c,hash:d==="#"?"":d}}function be(e,t,r){return{...e,surface:t,requestId:r||null}}var ye=64,ve=/^[A-Za-z0-9._+() -]+$/;function xe(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>ye?null:ve.test(t)?t:null}var ke="1.5.
|
|
14
|
+
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function Y(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:G(t)}function Q(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?a:128,r=c===1?s:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function Z(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):Q()}var X=`\n\n`,J=1048576,ee=/* @__PURE__ */t.z.record(/* @__PURE__ */t.z.string(),/* @__PURE__ */t.z.unknown()),te=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=Z(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(X,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+X.length),o=0;let r=re(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>J){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=re(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function re(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=ee.safeParse(l);return i.success?ne(i.data,r,t):null}function ne(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:le(e.code)??"unknown",retryable:e.retryable===true,wireMessage:le(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:G(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:se(e.follow_up_questions),citations:ce(e.citations),citationStatus:le(e.citation_status),urgencyLevel:oe(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:ae(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(le(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=le(e.delta)??le(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(le(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:ie(e.confidence),detections:ce(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function le(e){return typeof e=="string"?e:null}function ie(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function oe(e){return typeof e=="string"&&te.includes(e)?e:null}function ae(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||oe(t)!==null}function se(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ce(e){return Array.isArray(e)?e.filter(ue):[]}var de=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function fe(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return me(e)}var pe=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,he=/[\s\u0000-\u001f\u007f\\]/,ge={"http:":"80","https:":"443"};function me(e,t){let r=e.trim();let n=he.test(r)?null:pe.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,p=Number(s);if(p>65535)return null;let h=s===""||String(p)===ge[f]?"":String(p),g=ge[f]!==void 0,m=a.toLowerCase()+(h&&`:${h}`),b=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${c}${d}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:h,origin:g?`${f}//${m}`:"null",pathname:b,search:c==="?"?"":c,hash:d==="#"?"":d}}function be(e,t,r){return{...e,surface:t,requestId:r||null}}var ye=64,ve=/^[A-Za-z0-9._+() -]+$/;function xe(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>ye?null:ve.test(t)?t:null}var ke="1.5.3";var we="react-native",Ce="2026-09-19",Se="EVERFUR_API_BASE_URL";function je(e,t){/* @__PURE__ */
|
|
15
15
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
|
|
16
16
|
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||Ce,o=xe(e.appVersion);/* @__PURE__ */
|
|
17
17
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:ke,platform:t?.platform??we,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:Pe(Se);return r?ze(r):je("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Se}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function _e(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function Re(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function Ee(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Re(t)}function Ie(e,t){return`${e}://${t}`}function ze(e){let t=e.trim(),r=de.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return je("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=_e(r[2]);if(l.length===0)return je("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=Ee(t,l)?`: ${Ie(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&Te(l)))return n==="http"?je("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):je("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
@@ -46,7 +46,7 @@ return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.creat
|
|
|
46
46
|
return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:Zu(r,n,t))}catch{}}})}function Zu(e,t,r){let n=e.indexOf("."),l=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",i=typeof t?.requestId=="string"?t.requestId:null;return{...be(r,l,i),...t}}function Xu(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(l,i)=>n.call(e,l,i??be(t,r,l.requestId))}:{}}}var Ju=/* @__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 ${Se} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function ec(e,t,r=we){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+Ju[r])}function tc(e){/* @__PURE__ */
|
|
47
47
|
return Object.freeze({request(){return Promise.resolve(err(Gu(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return async function*(){r.aborted||(yield n)}()}})}var rc=/* @__PURE__ */new WeakSet;function nc(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return rc.add(t),t}var lc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new oc(e,t)}var ic=6e4,oc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;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 r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new s("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.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:ke,platform:t?.platform??we,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:xe(r?.appVersion)}),this.telemetry=r.telemetry?Qu(r.telemetry,this.errorContext):u,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=tc(l);else if(r.transport!==void 0)o=r.transport;else{let e=Yu(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=tc(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Al(this,this.mintScope),this.transport=o,l!==null&&(ec(l,this.telemetry,t?.platform),this.emit({type:"error",code:Gu(l).code,requestId:null,context:be(this.errorContext,"runtime",null)})),this.errorPolicy=Xu(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??C,this.upload=r.upload??Lt,this.uploadTransport=r.uploadTransport??sn,this.imageCache=r.imageCache??lc,this.kv=r.storage??nc(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?$u():$u(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",ac(e),()=>this.buildChatController(e),sc),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${ac(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=_u({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Ru(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=qu(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?Ku({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let c=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,c&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=Wl(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-ic,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Pl(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&Uu(l)===Uu(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:Xu(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){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:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await Mu(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return Ou({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>Fu({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>Dl($l(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(uc(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&Ul(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?uc("prepare"):r===null?null:Gu(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err($(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}if(s==="ready")this.emit({type:"ready"});else if(s==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:be(this.errorContext,"runtime",e)})}/* @__PURE__ */
|
|
48
48
|
return Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",ac(t),()=>this.buildChatController(t),sc,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function ac(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function sc(e){e.dispose()}function uc(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function cc(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function dc(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function fc(e){return e.ok?e:err(dc(e.error))}function pc(e){return{send:async(...t)=>fc(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var hc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),gc=globalThis,mc=gc[hc]??(gc[hc]=e.createContext(null));mc.displayName??="EverfurContext";function bc(){let t=e.useContext(mc);if(t===null)throw new s("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return t}function useEverfur(){return bc().handle}var yc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),vc=globalThis,xc=vc[yc]??(vc[yc]=e.createContext(io));xc.displayName??="EverfurThemeContext";function useEverfurTheme(){return e.useContext(xc)}var kc=()=>()=>{},wc=()=>null;function Cc(t,r){return e.useSyncExternalStore(r?.subscribe??kc,r?.get??wc,r?.get??wc)??t}function EverfurThemeProviderCore(t){let{runtime:r}=bc(),n=r.entitlements,l=e.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot),i=t.seams.useColorScheme(),o=t.seams.useReducedMotion(),a=t.seams.useTextScale(),s=t.seams.useHighContrast(),u=t.seams.scaleTypeSizes,c=t.seams.typeProfile,d=t.seams.platformMonoFamily?.(),f=t.seams.isFontRegistered,p=t.clientTheme?Sc(t.clientTheme):"",h=e.useMemo(()=>t.clientTheme?parseClientBranding(t.clientTheme):null,[p]),g=Cc(l.branding??null,r.sdkConfigHost?.branding),m=e.useMemo(()=>resolveTheme({branding:g,clientOverride:h,colorScheme:i,reducedMotion:o,textScale:a,scaleTypeSizes:u,highContrast:s,...c===void 0?{}:{typeProfile:c},...d===void 0?{}:{platformMonoFamily:d},...f===void 0?{}:{isFontRegistered:f}}),[g,h,i,o,a,u,c,s,d,f]);t.seams.useResolvedTheme?.(m);let b=t.seams.isDevelopment;return e.useEffect(()=>{b===void 0||!jc(b)||zo(themeAdjustments({branding:g,clientOverride:h,colorScheme:i}))},[b,g,h,i]),e.createElement(xc.Provider,{value:m},t.children)}function Sc(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function jc(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(t){let{config:r,user:n,activePet:l,theme:i,warmUp:o,children:a,seams:s}=t,u=`${r?.publishableKey??""}|${r?.apiBaseUrl??""}|${r?.contractVersion??""}`,c=e.useRef(null),d=e.useRef(null),f=e.useRef(r?.onEvent);f.current=r?.onEvent;let p=e.useRef(e=>{f.current?.(e)}),[h,g]=e.useReducer(e=>e+1,0),m=e.useRef(null),b=e.useRef(void 0),y=n?.userRef??null;b.current!==y&&(b.current!==void 0&&(m.current=null),b.current=y);let v=m.current!==null?m.current.user:n??null,x=e.useRef(null),k=e.useRef(void 0),w=l??null;k.current!==w&&(k.current!==void 0&&(x.current=null),k.current=w);let C=x.current!==null?x.current.pet:l??null;(c.current===null||c.current.key!==u||c.current.runtime.isDisposed)&&(c.current!==null&&!c.current.runtime.isDisposed&&(d.current=c.current.runtime),c.current={key:u,runtime:createEverfurRuntime({config:_c(s.withDefaults?s.withDefaults(r):r,p.current),user:v,activePet:C,theme:i??null},{platform:s.platform,...s.eventSourceFactory?{eventSourceFactory:s.eventSourceFactory}:{}})});let S=c.current.runtime,j=e.useRef(null);e.useEffect(()=>{let e=c.current?.runtime;e===void 0||!e.isDisposed||j.current!==e&&(j.current=e,g())}),e.useEffect(()=>{let e=d.current;e!==null&&(d.current=null,e.dispose())});let _=v?.userRef??null;e.useLayoutEffect(()=>{S.setUser(v)},[S,_]),e.useLayoutEffect(()=>{S.setActivePet(C)},[S,C]);let R=e.useRef(null);e.useEffect(()=>(R.current===S&&(R.current=null),()=>{R.current=S,Rc(()=>{R.current===S&&(R.current=null,S.dispose())})}),[S]),e.useEffect(()=>{o==="onMount"&&S.prepare(C===null?{}:{petRef:C})},[S,o,_,C]);let E=e.useMemo(()=>({setUser:e=>{m.current={user:e},S.setUser(e),g()},setActivePet:e=>{x.current={pet:e},S.setActivePet(e),g()},open:e=>S.open(e),prepare:e=>S.prepare(e),registerPet:(e,t)=>S.registerPet(e,t),updatePet:(e,t)=>S.updatePet(e,t),deletePet:e=>S.deletePet(e),eraseUserData:()=>S.eraseUserData(),logout:()=>{m.current={user:null};let e=S.logout();return g(),e}}),[S,g]),I=e.useMemo(()=>({runtime:S,handle:E,userRef:_,activePet:C,scopeEpoch:S.scopeEpoch,publishableKey:Ec(r)}),[S,E,_,C,h,u]),z=e.createElement(EverfurThemeProviderCore,{clientTheme:i??null,seams:s.theme,children:a});return e.createElement(mc.Provider,{value:I},s.wrap?s.wrap(z):z)}function _c(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Rc(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Ec(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Ic="everfur:";function zc(){try{if(typeof window>"u")return null;let e=window.localStorage;return e&&typeof e.getItem=="function"?e:null}catch{return null}}function createLocalStorageKv(){return{async getItem(e){try{return zc()?.getItem(Ic+e)??null}catch{return null}},async setItem(e,t){try{zc()?.setItem(Ic+e,t)}catch{}},async removeItem(e){try{zc()?.removeItem(Ic+e)}catch{}},async keys(e){try{let t=zc();if(t===null)return[];let r=[],n=Ic+e;for(let e=0;e<t.length;e+=1){let l=t.key(e);l!==null&&l.startsWith(n)&&r.push(l.slice(Ic.length))}/* @__PURE__ */
|
|
49
|
-
return Object.freeze(r)}catch{return[]}}}}var Tc="https://sdk.everfur.com",Pc=/* @__PURE__ */Object.freeze({k1:"X4wc1hwVONs4I9Vmclo9ExrfPZlH8-tgY7NmzxuA5lI"}),Oc=/* @__PURE__ */Object.freeze(["health-plan","health-plan-today","shop","shop-orders-v2","ui","televet-booking","televet-call"]),Fc=/* @__PURE__ */Object.freeze({"@everfur/sdk/web/health-plan":"health-plan","@everfur/sdk/web/health-plan/today":"health-plan-today","@everfur/sdk/web/shop":"shop","@everfur/sdk/web/shop/orders-v2":"shop-orders-v2","@everfur/sdk/web/ui":"ui","@everfur/sdk/web/televet/booking":"televet-booking","@everfur/sdk/web/televet/call":"televet-call"}),Mc=1794988926e3,Ac=3e3,$c=8e3,Dc=256*1024,Bc=4*1024*1024,Nc="web_runtime.fallback";var Lc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBridge@v${1}`);function Uc(){let e=globalThis,t=e[Lc];if(t!==void 0)return t;let r={major:1,host:null,defined:/* @__PURE__ */new Map,waiters:/* @__PURE__ */new Map,importSubpath:null};return e[Lc]=r,r}function Hc(e){if(typeof e!="string")return null;let t=/^(\d+)\./.exec(e);return t===null?null:Number(t[1])}function Wc(e){let t=Hc(e.React?.version);if(t===null||typeof e.React.createElement!="function")return null;let r=Uc();return r.host===null?(r.host={...e,reactMajor:t},{reactMajor:t}):r.host.React.createElement===e.React.createElement&&r.host.reactMajor===t?{reactMajor:t}:null}function qc(){return Uc().host}var Vc=(e,t)=>`${e}@${t}`;function Kc(e,t){return Uc().defined.get(Vc(e,t))??null}function Gc(e,t,r){let n=Uc(),l=n.ran??=/* @__PURE__ */new Map,i=Vc(e,t),o=l.get(i);return o===void 0?n.defined.has(i)?false:(l.set(i,r),true):o===r}function Yc(e,t,r){let n=Kc(e,t);if(n!==null)return Promise.resolve(n);let l=Uc(),i=Vc(e,t);return new Promise(e=>{let t=l.waiters.get(i)??/* @__PURE__ */new Set;l.waiters.set(i,t);let n=r=>{clearTimeout(a),t.delete(o),e(r)},o=e=>n(e),a=setTimeout(()=>n(null),r);t.add(o)})}function Qc(e){Uc().importSubpath=e}function Zc(e,t){let r=Object.keys(t).sort().map(e=>`${e}=${t[e]}`).join(",");return`v${1}|${e}|${r}`}var Xc=Zc(ke,Pc);var Jc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBundledOnly@v${1}`),ed=globalThis,td=()=>ed[Jc]===true,rd=()=>{ed[Jc]=true};var nd=/^\d{1,4}\.\d{1,5}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,64})?$/,ld=/^[a-z0-9][a-z0-9.-]{0,80}\.js$/,id=/^sha384-[A-Za-z0-9+/]{64}$/,od=/^[0-9a-f]{32}$/,ad=/^[A-Za-z0-9_-]+$/,sd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ud(e){if(typeof e!="string"||e.length===0||!ad.test(e))return null;let t=e.replace(/-/g,"+").replace(/_/g,"/");try{let e=atob(t+"=".repeat((4-t.length%4)%4)),r=new Uint8Array(e.length);for(let t=0;t<e.length;t+=1)r[t]=e.charCodeAt(t);return r}catch{return null}}var cd=/^\d{4}(-\d\d){2}T\d\d(:\d\d){2}(\.\d{1,3})?Z$/,dd=14*864e5;function fd(e){if(typeof e!="string"||!cd.test(e))return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function pd(e){if(!sd(e)||!Array.isArray(e.react)||!sd(e.parts))return null;let t=e.react.filter(e=>Number.isInteger(e)&&e>0);if(t.length===0||t.length!==e.react.length)return null;let r={};for(let[t,n]of Object.entries(e.parts))if(Oc.includes(t)){if(!sd(n)||typeof n.path!="string"||typeof n.integrity!="string"||!ld.test(n.path)||!id.test(n.integrity))return null;r[t]={path:n.path,integrity:n.integrity}}return{react:t,parts:r}}function hd(e){if(!sd(e)||e.schema!==1||!Number.isInteger(e.major))return null;let t=fd(e.issuedAt),r=fd(e.expiresAt);if(t===null||r===null||typeof e.stable!="string"||!nd.test(e.stable)||r<=t||r-t>dd||!sd(e.versions))return null;let n={};for(let[t,r]of Object.entries(e.versions)){let e=pd(r);if(!nd.test(t)||e===null)return null;n[t]=e}let l=null;if(e.canary!==void 0&&e.canary!==null){let t=e.canary;if(!sd(t)||typeof t.version!="string"||!nd.test(t.version)||typeof t.percent!="number"||!Number.isFinite(t.percent)||t.percent<0||t.percent>100)return null;l={version:t.version,percent:t.percent}}let i={};if(e.pins!==void 0){if(!sd(e.pins))return null;for(let[t,r]of Object.entries(e.pins)){if(!od.test(t)||typeof r!="string"||!nd.test(r))return null;i[t]=r}}let o=[];if(e.revoked!==void 0){if(!Array.isArray(e.revoked)||!e.revoked.every(e=>typeof e=="string"&&nd.test(e)))return null;o=e.revoked}return{schema:1,major:e.major,issuedAt:t,expiresAt:r,stable:e.stable,canary:l,pins:i,revoked:o,versions:n}}async function gd(e,t,r,n,l=Mc){if(!sd(e)||e.v!==1||typeof e.keyId!="string")return{ok:false,reason:"manifest-shape"};let i=ud(e.payload),o=ud(e.signature);if(i===null||o===null||o.length!==64)return{ok:false,reason:"manifest-shape"};let a=Object.prototype.hasOwnProperty.call(t,e.keyId)?ud(t[e.keyId]):null;if(a===null||a.length!==32)return{ok:false,reason:"signature-key"};let s;try{let e=await r.subtle.importKey("raw",a,{name:"Ed25519"},!1,["verify"]);s=await r.subtle.verify({name:"Ed25519"},e,o,i)}catch{return{ok:false,reason:"signature-unsupported"}}if(!s)return{ok:false,reason:"signature-invalid"};let u;try{u=JSON.parse((new TextDecoder).decode(i))}catch{return{ok:false,reason:"manifest-shape"}}let c=hd(u);return c===null?{ok:false,reason:"manifest-shape"}:c.major!==1?{ok:false,reason:"manifest-major"}:n>=c.expiresAt?{ok:false,reason:"manifest-expired"}:c.issuedAt<l?{ok:false,reason:"manifest-stale"}:{ok:true,manifest:c}}function md(e,t){let[r="",n]=e.split(/-(.*)/s,2),[l="",i]=t.split(/-(.*)/s,2),o=r.split(".").map(Number),a=l.split(".").map(Number);for(let e=0;e<3;e+=1){let t=(o[e]??0)-(a[e]??0);if(t!==0)return t<0?-1:1}if(n===i)return 0;if(n===void 0)return 1;if(i===void 0)return-1;let s=n.split("."),u=i.split(".");for(let e=0;;e+=1){let t=s[e],r=u[e];if(t===r)continue;if(t===void 0||r===void 0)return t===void 0?-1:1;let n=/^\d+$/.test(t),l=/^\d+$/.test(r);return n!==l?n?-1:1:(n?Number(t)<Number(r):t<r)?-1:1}}function bd(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0}function yd(e,t){return bd(`${e??"-"}:${t}`)%100}async function vd(e,t){try{let r=await t.subtle.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,"0")).join("").slice(0,32)}catch{return null}}function xd(e,t){let r=t.tenantKey===null?void 0:e.pins[t.tenantKey],n,l;if(r!==void 0?(n=r,l="pin"):e.canary!==null&&yd(t.tenantKey,t.sessionBucket)<e.canary.percent?(n=e.canary.version,l="canary"):(n=e.stable,l="stable"),e.revoked.includes(n))return{use:"bundled",reason:"revoked"};if(l!=="pin"&&md(n,t.bundledVersion)<0&&!e.revoked.includes(t.bundledVersion))return{use:"bundled",reason:"bundled-newer"};let i=e.versions[n];return i===void 0?{use:"bundled",reason:"version-missing"}:{use:"remote",version:n,entry:i,reason:l}}var kd=/^manifest-(fetch|timeout)$/,wd="everfur:web-runtime:unreachable",Cd=10*6e4;function Sd(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function jd(e,t,r,n,l="default"){let i=typeof AbortController=="function"?new AbortController:null,o=null,a=()=>{},s=new Promise(e=>{a=e}),u=setTimeout(()=>{a("timeout"),i?.abort(),o?.()},r),c=e=>Promise.race([e,s]);try{let r=await c(e(t,{mode:"cors",credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",cache:l,...i?{signal:i.signal}:{}}));if(r==="timeout")return{ok:!1,why:"timeout"};if(!r.ok)return{ok:!1,why:"http"};let a=Number(r.headers.get("content-length")??Number.NaN),s=r.body?.getReader()??null;if(o=()=>{s!==null&&s.cancel().catch(()=>{})},Number.isFinite(a)&&a>n)return o(),{ok:!1,why:"too-large"};if(s===null){let e=await c(r.arrayBuffer());return e==="timeout"?{ok:!1,why:"timeout"}:e.byteLength>n?{ok:!1,why:"too-large"}:{ok:!0,bytes:new Uint8Array(e)}}let u=[],d=0;for(;;){let e=await c(s.read());if(e==="timeout")return{ok:!1,why:"timeout"};if(e.done)break;if(d+=e.value.byteLength,d>n)return o(),{ok:!1,why:"too-large"};u.push(e.value)}let f=new Uint8Array(d),p=0;for(let e of u)f.set(e,p),p+=e.byteLength;return{ok:!0,bytes:f}}catch{return{ok:false,why:i?.signal.aborted?"timeout":"error"}}finally{clearTimeout(u)}}function _d(e){let t=e.hasDom&&Object.keys(e.keys).length>0&&e.fetch!==null&&e.crypto!==null,r=e.manifestTimeoutMs??Ac,n=e.partTimeoutMs??$c,l=e.manifestMaxBytes??Dc,i=e.partMaxBytes??Bc,o=`${e.origin}/web-runtime`,a=null,s=/* @__PURE__ */new Map,u=/* @__PURE__ */new Map,c=/* @__PURE__ */new Map,d=/* @__PURE__ */new Map,f=null,p=null;async function h(){let t=await jd(e.fetch,`${o}/${1}/manifest.json`,r,l,"no-store");if(!t.ok){let r=t.why==="timeout"?"manifest-timeout":t.why==="too-large"?"manifest-too-large":"manifest-fetch";if(t.why==="error"||t.why==="timeout")try{e.unreachable?.()?.setItem(wd,`${e.now()+Cd}|${r}`)}catch{}return{ok:false,reason:r}}let n;try{n=JSON.parse((new TextDecoder).decode(t.bytes))}catch{return{ok:false,reason:"manifest-shape"}}return gd(n,e.keys,e.crypto,e.now(),e.minIssuedAt??Mc)}function g(t){let r=t??"",n=s.get(r);if(n)return n;let l=(async()=>{a??=h();let r=await a;if(!r.ok)return{ok:false,reason:r.reason};let n=t===null?null:await vd(t,e.crypto),l=xd(r.manifest,{tenantKey:n,sessionBucket:e.sessionBucket(),bundledVersion:e.bundledVersion});return l.use==="remote"?{ok:true,choice:l}:{ok:false,reason:l.reason}})();return s.set(r,l),l}async function m(t,r){if(await Promise.resolve(),td())return{ok:false,reason:"disabled",version:null};let l=qc();if(l===null)return{ok:false,reason:"react-unregistered",version:null};let a=await g(r);if(!a.ok)return{ok:false,reason:a.reason,version:null};let{version:s,entry:u}=a.choice;if(!u.react.includes(l.reactMajor))return{ok:false,reason:"react-mismatch",version:s};let c=u.parts[t];if(c===void 0)return{ok:false,reason:"part-missing",version:s};if(!Gc(t,s,c.integrity))return{ok:false,reason:"part-integrity",version:s};let d=Kc(t,s);if(d!==null)return{ok:true,namespace:d,version:s};let f=`${o}/${s}/${c.path}`;if(td())return{ok:false,reason:"disabled",version:s};let h=await jd(e.fetch,f,n,i);if(!h.ok)return{ok:false,reason:h.why==="timeout"?"part-timeout":h.why==="too-large"?"part-too-large":"part-fetch",version:s};let m=h.bytes,b;try{b=`sha384-${Sd(new Uint8Array(await e.crypto.subtle.digest("SHA-384",m)))}`}catch{return{ok:false,reason:"part-integrity",version:s}}if(b!==c.integrity)return{ok:false,reason:"part-integrity",version:s};if(td())return{ok:false,reason:"disabled",version:s};let y=e.createBlobUrl?.(m)??null,v="error";if(y!==null&&(v=await e.runScript(y,c.integrity,"blob",p),e.revokeBlobUrl(y)),v==="error"&&(v=await e.runScript(f,c.integrity,"cdn",p)),v==="error")return{ok:false,reason:"part-load",version:s};let x=await Yc(t,s,50);return x===null?{ok:false,reason:"part-load",version:s}:{ok:true,namespace:x,version:s}}let b=t?null:e.hasDom?"disabled":"server";try{let[t,r]=(e.unreachable?.()?.getItem(wd)??"").split("|");Number(t)>e.now()&&kd.test(String(r))&&(b??=r)}catch{}function y(e,t){if(b!==null)return Promise.resolve({ok:false,reason:b,version:null});f??=t;let r=`${t??""}|${e}`,n=u.get(r);if(n)return n;let l=m(e,t).then(e=>e,()=>({ok:false,reason:"part-load",version:null}));return l.then(e=>c.set(r,e)),u.set(r,l),l}return t&&Qc(e=>{let t=Object.prototype.hasOwnProperty.call(Fc,e)?Fc[e]:void 0,r=()=>{let t=d.get(e);return t?t():Promise.reject(new TypeError(`${e} is not available to the Everfur web runtime`))};return t===void 0?r():y(t,f).then(e=>e.ok?e.namespace:r())}),{enabled:t,peek:(e,t)=>b!==null?{ok:false,reason:b,version:null}:c.get(`${t??""}|${e}`)??null,load:y,registerHostSubpaths:e=>{for(let[t,r]of Object.entries(e))d.has(t)||d.set(t,r)},setCspNonce:e=>{p=e===null||e===""?null:e}}}var Rd="everfur:web-runtime:bucket",Ed=null;function Id(){try{let e=globalThis.sessionStorage?.getItem(Rd);if(e)return e}catch{}Ed??=Math.floor(Math.random()*4294967296).toString(16);try{globalThis.sessionStorage?.setItem(Rd,Ed)}catch{}return Ed}function zd(e){return(t,r,n,l)=>new Promise(i=>{let o;try{o=e.createElement("script"),o.type="module",n==="cdn"&&(o.integrity=r,o.crossOrigin="anonymous"),l!==null&&(o.nonce=l),o.addEventListener("load",()=>{o.remove(),i("load")}),o.addEventListener("error",()=>{o.remove(),i("error")}),o.src=t,(e.head??e.documentElement).appendChild(o)}catch{i("error")}})}function Td(){let e=typeof document>"u"?null:document,t=globalThis.crypto;return{origin:Tc,keys:Pc,bundledVersion:ke,fetch:typeof fetch=="function"?fetch.bind(globalThis):null,crypto:t?.subtle?t:null,hasDom:e!==null&&typeof window<"u",runScript:e===null?()=>Promise.resolve("error"):zd(e),createBlobUrl:typeof Blob=="function"&&typeof URL.createObjectURL=="function"?e=>{try{return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}catch{return null}}:null,revokeBlobUrl:e=>{try{URL.revokeObjectURL(e)}catch{}},now:()=>Date.now(),sessionBucket:Id,unreachable:()=>globalThis.sessionStorage}}var Pd=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeLoader@${Xc}`);function Od(){let e=globalThis;return e[Pd]??=_d(Td())}var Fd=/* @__PURE__ */new Set(["disabled","server","bundled-newer"]),Md=/* @__PURE__ */new Set;function Ad(e,t,r,n){if(Fd.has(r))return;let l=`${t}|${r}`;if(!Md.has(l)){Md.add(l);try{e?.trackExpectedFailure(Nc,{part:t,reason:r,version:n,bundled:ke})}catch{}}}var $d=/* @__PURE__ */new Set,Dd=class extends e.Component{constructor(){super(...arguments);this.state={failed:false}}static getDerivedStateFromError(){return{failed:true}}componentDidCatch(){this.props.onError()}render(){return this.state.failed?this.props.fallback():this.props.children}},Bd=/* @__PURE__ */new Map;function Nd(t,r,n){let l=`${r??""}|${t.part}|${t.name}`,i=Bd.get(l);return i===void 0&&(i=e.lazy(async()=>{let e=await Od().load(t.part,r),l=e.ok?e.namespace[t.name]:void 0;return e.ok&&typeof l!="function"&&(typeof l!="object"||l===null)?(Ad(n.current,t.part,"part-missing",e.version),{default:t.bundled}):(e.ok||Ad(n.current,t.part,e.reason,e.version),{default:e.ok?l:t.bundled})}),Bd.set(l,i)),i}var Ld=()=>()=>{},Ud=()=>false,Hd=()=>true;function RuntimeSurface({spec:t,props:r}){let n=e.useContext(mc),l=td(),a=n?.publishableKey?n.publishableKey:null,s=e.useRef(null);s.current=n?.runtime.registry?.services?.telemetry??null;let u=e.useSyncExternalStore(Ld,Ud,Hd),c=e.useRef(null),[,d]=e.useState(0),f=l?null:Od();if(t.hostSubpaths!==void 0&&f?.enabled&&f.registerHostSubpaths(t.hostSubpaths),u)c.current=t.wait==="bundled"&&f!==null?"hydrate":"bundled";else if(c.current===null)if(!f?.enabled||$d.has(t.part))c.current="bundled";else if(Wc({React:i,ReactDOM:o})===null)Ad(s.current,t.part,"react-mismatch",null),c.current="bundled";else{let e=f.peek(t.part,a);c.current=e===null?"suspense":e.ok?"direct":"bundled"}let p=c.current,h=u||p!=="hydrate"?null:f?.peek(t.part,a)??null,g=!u&&p==="hydrate"&&h===null&&f?.enabled===true&&!$d.has(t.part);e.useEffect(()=>{if(!g||f===null)return;if(Wc({React:i,ReactDOM:o})===null){Ad(s.current,t.part,"react-mismatch",null);return}let e=true;return f.load(t.part,a).then(r=>{r.ok||Ad(s.current,t.part,r.reason,r.version),e&&d(e=>e+1)}),()=>{e=false}},[g,f,t.part,a]);let m=()=>e.createElement(t.bundled,r),b=r=>e.createElement(Dd,{fallback:m,onError:()=>{$d.add(t.part),Ad(s.current,t.part,"render",null)},children:r});if(u||p==="bundled")return m();if(p==="hydrate"||p==="direct"){let n=h??f?.peek(t.part,a),l=n?.ok?n.namespace[t.name]:void 0;return l===void 0||$d.has(t.part)?m():b(e.createElement(l,r))}let y=Nd(t,a,s),v=t.wait==="bundled"?m():e.createElement("div",{"data-everfur-runtime":"loading","aria-busy":true});return b(e.createElement(e.Suspense,{fallback:v},e.createElement(y,r)))}var Wd=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${Xc}`),qd=globalThis;function Vd(e,t=false){e===null?delete qd[Wd]:(t||qd[Wd]===void 0)&&(qd[Wd]=e)}var Kd=RuntimeSurface,Gd=(t,r)=>e.createElement(Kd,{spec:t,props:r});function Yd(e){if(Vd(Gd),e!==void 0&&e!==""){let t=Od();t.enabled&&t.setCspNonce(e)}}var Qd=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Qd[t]]}}function Zd(e,t){let{scale:r,scaleCaps:n}=e.type,l=n[t];return l>0?Math.min(r,l):r}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[Qd[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function Xd(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var Jd=/* @__PURE__ */new Map,ef=/* @__PURE__ */new Set,tf=typeof document>"u"?e.useEffect:e.useLayoutEffect;function rf(e){return e.cssSrc!==void 0?`css\n${e.cssSrc}`:`file\n${e.family}\n${e.src??""}\n${e.weight??"400"}\n${e.style??"normal"}`}function nf(e,t){if(!t)return;let r=e.cssSrc??e.src??"",n=`[everfur] A font in appearance.fonts did not load: "${e.family}" from ${r}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(e.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!ef.has(n)){ef.add(n);try{globalThis.console?.warn?.(n)}catch{}}}function lf(e){let t=document.getElementsByTagName("link");for(let r=0;r<t.length;r+=1){let n=t[r];if(n.rel==="stylesheet"&&n.getAttribute("href")===e)return n}return null}function of(e){return lf(e)!==null?Promise.resolve(true):new Promise(t=>{let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-everfur-font",""),r.addEventListener("load",()=>t(true)),r.addEventListener("error",()=>t(false)),document.head.appendChild(r)})}function af(e){let t=document.fonts;return new FontFace(e.family,`url("${e.src}")`,{display:"swap",weight:e.weight??"400",style:e.style??"normal"}).load().then(e=>(t.add(e),true)).catch(()=>false)}function sf(e,t=false){let r=rf(e),n=Jd.get(r);if(n===void 0){n=Promise.resolve(false);try{if(typeof document<"u"){let t=e.cssSrc===void 0?null:Ha(e.cssSrc),r=e.src===void 0?null:Ha(e.src);t!==null?n=of(t):r!==null&&(n=af({...e,src:r}))}}catch{n=Promise.resolve(false)}let l=n.then(r=>(r||nf(e,t),r));Jd.set(r,l),n=l}return n}function uf(e,t){let r=e.type.fontSources;tf(()=>{if(r.length===0)return;let e=false;try{e=t()}catch{}for(let t of r)sf(t,e)},[r,t])}var cf=/* @__PURE__ */new RegExp(`^${_a}\\/fonts\\/[\\w./-]+\\.woff2$`);function df(e){return cf.test(e)&&!e.includes("..")}var ff=/* @__PURE__ */new Map;function pf(e,t,r="400"){let n=e.trim(),l=`${n}\n${t}\n${r}`,i=ff.get(l);if(i===void 0){if(i=Promise.resolve(false),t!==null&&n!==""&&n!=="System"&&df(t))try{let e=document.fonts;i=new FontFace(n,`url("${t}") format("woff2")`,{display:"swap",weight:r}).load().then(t=>(e.add(t),!0)).catch(()=>!1)}catch{}ff.set(l,i)}return i}var hf=["regular","medium","bold","mono","monoMedium","monoBold"];function gf(t){let{families:r,fontUrls:n,weight:l,namedFaces:i}=t.type;e.useEffect(()=>{for(let e of hf){let t=n[e];t!=null&&pf(r[e],t,i[e]?l.regular:l[Qd[e]])}},[r,n,l,i]),uf(t,Xd)}function mf(e){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(e)??null}catch{return null}}function bf(e){return t=>{let r=mf(e);return r===null||typeof r.addEventListener!="function"?()=>{}:(r.addEventListener("change",t),()=>r.removeEventListener?.("change",t))}}var yf="(prefers-color-scheme: dark)",vf="(prefers-color-scheme: light)",xf="(prefers-reduced-motion: reduce)",kf="(prefers-contrast: more)",wf=bf(yf),Cf=bf(xf),Sf=bf(kf);function jf(){let e=mf(yf);return e===null?null:e.matches?"dark":mf(vf)?.matches?"light":null}function _f(){return mf(xf)?.matches===true}function Rf(){return mf(kf)?.matches===true}var Ef=16,If=false;var zf=null;function Tf(e){return Number.parseFloat(window.getComputedStyle(e).fontSize)}function Pf(){let e=document.body??document.documentElement,t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.setProperty("position","absolute","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("font-size","medium","important"),e.appendChild(t);try{return Tf(t)}finally{t.remove()}}function Of(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let e=If?Tf(document.documentElement):Pf();return Number.isFinite(e)&&e>0?e/Ef:1}catch{return 1}}function Ff(){return zf===null&&(zf=Of()),zf}function Mf(e){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let t=()=>{zf=null,e()};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)}function Af(){return e.useSyncExternalStore(wf,jf,()=>null)}function $f(){return e.useSyncExternalStore(Cf,_f,()=>false)}function Df(){return e.useSyncExternalStore(Sf,Rf,()=>false)}function Bf(){return e.useSyncExternalStore(Mf,Ff,()=>1)}var Nf=/* @__PURE__ */Object.freeze({useColorScheme:Af,useReducedMotion:$f,useTextScale:Bf,useHighContrast:Df,scaleTypeSizes:true,useResolvedTheme:gf,isDevelopment:Xd});function Lf(e){return e.storage===void 0?{...e,storage:createLocalStorageKv()}:e}var Uf=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:Lf,theme:Nf});function EverfurProvider(t){let{cspNonce:r,webRuntime:n,...l}=t;return n!==void 0&&n!=="updates"&&rd(),td()||Yd(r),e.createElement(EverfurProviderCore,{...l,seams:Uf})}function useCapability(t){let{runtime:r}=bc(),n=r.entitlements,l=e.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return e.useMemo(()=>decideCapability(t,l.decisions,{isPending:l.isPending}),[t,l])}function Hf(t){let{runtime:r}=bc(),n=r.entitlements,l=e.useCallback(e=>n===void 0?()=>{}:n.subscribe(e),[n]),i=e.useCallback(()=>{if(n===void 0)return false;let e=n.getSnapshot();return decideCapability(t,e.decisions,{isPending:e.isPending}).enabled},[n,t]);return e.useSyncExternalStore(l,i,i)}var Wf=class extends e.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:t,fallback:r,resetKey:n}){return e.createElement(Wf,{fallback:r,resetKey:n,children:e.createElement(RenderHost,{render:t})})}function qf(e,t,r){return Math.round(r*Zd(e,t)*10)/10}var Vf='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',Kf="System";function Gf(e){let t=e.trim();return t.length===0||t===Kf?Vf:`${Qf(t)}, ${Vf}`}function Yf(e){let t=e.trim();return t.length===0||t==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${Qf(t)}, ui-monospace, Menlo, Consolas, monospace`}function Qf(e){return`"${e.replace(/[\\"]/g,"\\$&")}"`}function faceCss(e,t){let r=e.type,n=r.families[t];return{fontFamily:t==="mono"||t==="monoMedium"||t==="monoBold"?Yf(n):Gf(n),fontWeight:r.namedFaces[t]?r.weight.regular:r.weight[Qd[t]]}}function headingFaceCss(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type,l=faceCss(e,t);return r===null&&n===null?l:r!==null?{fontFamily:Gf(r),fontWeight:n??e.type.weight[Qd[t]]}:e.type.namedFaces[t]||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}var Zf=/* @__PURE__ */Object.freeze({textAlign:"start"});var Xf=48;function Jf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(t){let{capability:r,children:l,renderDisabled:i,renderPending:o,style:a,className:s}=t,u=useCapability(r),c=e.useMemo(()=>Jf(u),[u]);switch(c){case"enabled":return l;case"pending":return o?/* @__PURE__ */n.jsx(HostRender,{render:o,fallback:/* @__PURE__ */n.jsx(PendingSkeleton,{capability:r,style:a,className:s})}):/* @__PURE__ */n.jsx(PendingSkeleton,{capability:r,style:a,className:s});case"disabled":return i?/* @__PURE__ */n.jsx(HostRender,{render:()=>i(u),fallback:/* @__PURE__ */n.jsx(OffState,{decision:u,style:a,className:s}),resetKey:u}):/* @__PURE__ */n.jsx(OffState,{decision:u,style:a,className:s});default:return assertNever(c)}}function PendingSkeleton({capability:t,style:r,className:l}){let i=useEverfurTheme(),o=e.useMemo(()=>ep(i),[i]);/* @__PURE__ */
|
|
49
|
+
return Object.freeze(r)}catch{return[]}}}}var Tc="https://sdk.everfur.com",Pc=/* @__PURE__ */Object.freeze({k1:"X4wc1hwVONs4I9Vmclo9ExrfPZlH8-tgY7NmzxuA5lI"}),Oc=/* @__PURE__ */Object.freeze(["health-plan","health-plan-today","shop","shop-orders-v2","ui","televet-booking","televet-call"]),Fc=/* @__PURE__ */Object.freeze({"@everfur/sdk/web/health-plan":"health-plan","@everfur/sdk/web/health-plan/today":"health-plan-today","@everfur/sdk/web/shop":"shop","@everfur/sdk/web/shop/orders-v2":"shop-orders-v2","@everfur/sdk/web/ui":"ui","@everfur/sdk/web/televet/booking":"televet-booking","@everfur/sdk/web/televet/call":"televet-call"}),Mc=1794995274e3,Ac=3e3,$c=8e3,Dc=256*1024,Bc=4*1024*1024,Nc="web_runtime.fallback";var Lc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBridge@v${1}`);function Uc(){let e=globalThis,t=e[Lc];if(t!==void 0)return t;let r={major:1,host:null,defined:/* @__PURE__ */new Map,waiters:/* @__PURE__ */new Map,importSubpath:null};return e[Lc]=r,r}function Hc(e){if(typeof e!="string")return null;let t=/^(\d+)\./.exec(e);return t===null?null:Number(t[1])}function Wc(e){let t=Hc(e.React?.version);if(t===null||typeof e.React.createElement!="function")return null;let r=Uc();return r.host===null?(r.host={...e,reactMajor:t},{reactMajor:t}):r.host.React.createElement===e.React.createElement&&r.host.reactMajor===t?{reactMajor:t}:null}function qc(){return Uc().host}var Vc=(e,t)=>`${e}@${t}`;function Kc(e,t){return Uc().defined.get(Vc(e,t))??null}function Gc(e,t,r){let n=Uc(),l=n.ran??=/* @__PURE__ */new Map,i=Vc(e,t),o=l.get(i);return o===void 0?n.defined.has(i)?false:(l.set(i,r),true):o===r}function Yc(e,t,r){let n=Kc(e,t);if(n!==null)return Promise.resolve(n);let l=Uc(),i=Vc(e,t);return new Promise(e=>{let t=l.waiters.get(i)??/* @__PURE__ */new Set;l.waiters.set(i,t);let n=r=>{clearTimeout(a),t.delete(o),e(r)},o=e=>n(e),a=setTimeout(()=>n(null),r);t.add(o)})}function Qc(e){Uc().importSubpath=e}function Zc(e,t){let r=Object.keys(t).sort().map(e=>`${e}=${t[e]}`).join(",");return`v${1}|${e}|${r}`}var Xc=Zc(ke,Pc);var Jc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBundledOnly@v${1}`),ed=globalThis,td=()=>ed[Jc]===true,rd=()=>{ed[Jc]=true};var nd=/^\d{1,4}\.\d{1,5}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,64})?$/,ld=/^[a-z0-9][a-z0-9.-]{0,80}\.js$/,id=/^sha384-[A-Za-z0-9+/]{64}$/,od=/^[0-9a-f]{32}$/,ad=/^[A-Za-z0-9_-]+$/,sd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ud(e){if(typeof e!="string"||e.length===0||!ad.test(e))return null;let t=e.replace(/-/g,"+").replace(/_/g,"/");try{let e=atob(t+"=".repeat((4-t.length%4)%4)),r=new Uint8Array(e.length);for(let t=0;t<e.length;t+=1)r[t]=e.charCodeAt(t);return r}catch{return null}}var cd=/^\d{4}(-\d\d){2}T\d\d(:\d\d){2}(\.\d{1,3})?Z$/,dd=14*864e5;function fd(e){if(typeof e!="string"||!cd.test(e))return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function pd(e){if(!sd(e)||!Array.isArray(e.react)||!sd(e.parts))return null;let t=e.react.filter(e=>Number.isInteger(e)&&e>0);if(t.length===0||t.length!==e.react.length)return null;let r={};for(let[t,n]of Object.entries(e.parts))if(Oc.includes(t)){if(!sd(n)||typeof n.path!="string"||typeof n.integrity!="string"||!ld.test(n.path)||!id.test(n.integrity))return null;r[t]={path:n.path,integrity:n.integrity}}return{react:t,parts:r}}function hd(e){if(!sd(e)||e.schema!==1||!Number.isInteger(e.major))return null;let t=fd(e.issuedAt),r=fd(e.expiresAt);if(t===null||r===null||typeof e.stable!="string"||!nd.test(e.stable)||r<=t||r-t>dd||!sd(e.versions))return null;let n={};for(let[t,r]of Object.entries(e.versions)){let e=pd(r);if(!nd.test(t)||e===null)return null;n[t]=e}let l=null;if(e.canary!==void 0&&e.canary!==null){let t=e.canary;if(!sd(t)||typeof t.version!="string"||!nd.test(t.version)||typeof t.percent!="number"||!Number.isFinite(t.percent)||t.percent<0||t.percent>100)return null;l={version:t.version,percent:t.percent}}let i={};if(e.pins!==void 0){if(!sd(e.pins))return null;for(let[t,r]of Object.entries(e.pins)){if(!od.test(t)||typeof r!="string"||!nd.test(r))return null;i[t]=r}}let o=[];if(e.revoked!==void 0){if(!Array.isArray(e.revoked)||!e.revoked.every(e=>typeof e=="string"&&nd.test(e)))return null;o=e.revoked}return{schema:1,major:e.major,issuedAt:t,expiresAt:r,stable:e.stable,canary:l,pins:i,revoked:o,versions:n}}async function gd(e,t,r,n,l=Mc){if(!sd(e)||e.v!==1||typeof e.keyId!="string")return{ok:false,reason:"manifest-shape"};let i=ud(e.payload),o=ud(e.signature);if(i===null||o===null||o.length!==64)return{ok:false,reason:"manifest-shape"};let a=Object.prototype.hasOwnProperty.call(t,e.keyId)?ud(t[e.keyId]):null;if(a===null||a.length!==32)return{ok:false,reason:"signature-key"};let s;try{let e=await r.subtle.importKey("raw",a,{name:"Ed25519"},!1,["verify"]);s=await r.subtle.verify({name:"Ed25519"},e,o,i)}catch{return{ok:false,reason:"signature-unsupported"}}if(!s)return{ok:false,reason:"signature-invalid"};let u;try{u=JSON.parse((new TextDecoder).decode(i))}catch{return{ok:false,reason:"manifest-shape"}}let c=hd(u);return c===null?{ok:false,reason:"manifest-shape"}:c.major!==1?{ok:false,reason:"manifest-major"}:n>=c.expiresAt?{ok:false,reason:"manifest-expired"}:c.issuedAt<l?{ok:false,reason:"manifest-stale"}:{ok:true,manifest:c}}function md(e,t){let[r="",n]=e.split(/-(.*)/s,2),[l="",i]=t.split(/-(.*)/s,2),o=r.split(".").map(Number),a=l.split(".").map(Number);for(let e=0;e<3;e+=1){let t=(o[e]??0)-(a[e]??0);if(t!==0)return t<0?-1:1}if(n===i)return 0;if(n===void 0)return 1;if(i===void 0)return-1;let s=n.split("."),u=i.split(".");for(let e=0;;e+=1){let t=s[e],r=u[e];if(t===r)continue;if(t===void 0||r===void 0)return t===void 0?-1:1;let n=/^\d+$/.test(t),l=/^\d+$/.test(r);return n!==l?n?-1:1:(n?Number(t)<Number(r):t<r)?-1:1}}function bd(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0}function yd(e,t){return bd(`${e??"-"}:${t}`)%100}async function vd(e,t){try{let r=await t.subtle.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,"0")).join("").slice(0,32)}catch{return null}}function xd(e,t){let r=t.tenantKey===null?void 0:e.pins[t.tenantKey],n,l;if(r!==void 0?(n=r,l="pin"):e.canary!==null&&yd(t.tenantKey,t.sessionBucket)<e.canary.percent?(n=e.canary.version,l="canary"):(n=e.stable,l="stable"),e.revoked.includes(n))return{use:"bundled",reason:"revoked"};if(l!=="pin"&&md(n,t.bundledVersion)<0&&!e.revoked.includes(t.bundledVersion))return{use:"bundled",reason:"bundled-newer"};let i=e.versions[n];return i===void 0?{use:"bundled",reason:"version-missing"}:{use:"remote",version:n,entry:i,reason:l}}var kd=/^manifest-(fetch|timeout)$/,wd="everfur:web-runtime:unreachable",Cd=10*6e4;function Sd(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function jd(e,t,r,n,l="default"){let i=typeof AbortController=="function"?new AbortController:null,o=null,a=()=>{},s=new Promise(e=>{a=e}),u=setTimeout(()=>{a("timeout"),i?.abort(),o?.()},r),c=e=>Promise.race([e,s]);try{let r=await c(e(t,{mode:"cors",credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",cache:l,...i?{signal:i.signal}:{}}));if(r==="timeout")return{ok:!1,why:"timeout"};if(!r.ok)return{ok:!1,why:"http"};let a=Number(r.headers.get("content-length")??Number.NaN),s=r.body?.getReader()??null;if(o=()=>{s!==null&&s.cancel().catch(()=>{})},Number.isFinite(a)&&a>n)return o(),{ok:!1,why:"too-large"};if(s===null){let e=await c(r.arrayBuffer());return e==="timeout"?{ok:!1,why:"timeout"}:e.byteLength>n?{ok:!1,why:"too-large"}:{ok:!0,bytes:new Uint8Array(e)}}let u=[],d=0;for(;;){let e=await c(s.read());if(e==="timeout")return{ok:!1,why:"timeout"};if(e.done)break;if(d+=e.value.byteLength,d>n)return o(),{ok:!1,why:"too-large"};u.push(e.value)}let f=new Uint8Array(d),p=0;for(let e of u)f.set(e,p),p+=e.byteLength;return{ok:!0,bytes:f}}catch{return{ok:false,why:i?.signal.aborted?"timeout":"error"}}finally{clearTimeout(u)}}function _d(e){let t=e.hasDom&&Object.keys(e.keys).length>0&&e.fetch!==null&&e.crypto!==null,r=e.manifestTimeoutMs??Ac,n=e.partTimeoutMs??$c,l=e.manifestMaxBytes??Dc,i=e.partMaxBytes??Bc,o=`${e.origin}/web-runtime`,a=null,s=/* @__PURE__ */new Map,u=/* @__PURE__ */new Map,c=/* @__PURE__ */new Map,d=/* @__PURE__ */new Map,f=null,p=null;async function h(){let t=await jd(e.fetch,`${o}/${1}/manifest.json`,r,l,"no-store");if(!t.ok){let r=t.why==="timeout"?"manifest-timeout":t.why==="too-large"?"manifest-too-large":"manifest-fetch";if(t.why==="error"||t.why==="timeout")try{e.unreachable?.()?.setItem(wd,`${e.now()+Cd}|${r}`)}catch{}return{ok:false,reason:r}}let n;try{n=JSON.parse((new TextDecoder).decode(t.bytes))}catch{return{ok:false,reason:"manifest-shape"}}return gd(n,e.keys,e.crypto,e.now(),e.minIssuedAt??Mc)}function g(t){let r=t??"",n=s.get(r);if(n)return n;let l=(async()=>{a??=h();let r=await a;if(!r.ok)return{ok:false,reason:r.reason};let n=t===null?null:await vd(t,e.crypto),l=xd(r.manifest,{tenantKey:n,sessionBucket:e.sessionBucket(),bundledVersion:e.bundledVersion});return l.use==="remote"?{ok:true,choice:l}:{ok:false,reason:l.reason}})();return s.set(r,l),l}async function m(t,r){if(await Promise.resolve(),td())return{ok:false,reason:"disabled",version:null};let l=qc();if(l===null)return{ok:false,reason:"react-unregistered",version:null};let a=await g(r);if(!a.ok)return{ok:false,reason:a.reason,version:null};let{version:s,entry:u}=a.choice;if(!u.react.includes(l.reactMajor))return{ok:false,reason:"react-mismatch",version:s};let c=u.parts[t];if(c===void 0)return{ok:false,reason:"part-missing",version:s};if(!Gc(t,s,c.integrity))return{ok:false,reason:"part-integrity",version:s};let d=Kc(t,s);if(d!==null)return{ok:true,namespace:d,version:s};let f=`${o}/${s}/${c.path}`;if(td())return{ok:false,reason:"disabled",version:s};let h=await jd(e.fetch,f,n,i);if(!h.ok)return{ok:false,reason:h.why==="timeout"?"part-timeout":h.why==="too-large"?"part-too-large":"part-fetch",version:s};let m=h.bytes,b;try{b=`sha384-${Sd(new Uint8Array(await e.crypto.subtle.digest("SHA-384",m)))}`}catch{return{ok:false,reason:"part-integrity",version:s}}if(b!==c.integrity)return{ok:false,reason:"part-integrity",version:s};if(td())return{ok:false,reason:"disabled",version:s};let y=e.createBlobUrl?.(m)??null,v="error";if(y!==null&&(v=await e.runScript(y,c.integrity,"blob",p),e.revokeBlobUrl(y)),v==="error"&&(v=await e.runScript(f,c.integrity,"cdn",p)),v==="error")return{ok:false,reason:"part-load",version:s};let x=await Yc(t,s,50);return x===null?{ok:false,reason:"part-load",version:s}:{ok:true,namespace:x,version:s}}let b=t?null:e.hasDom?"disabled":"server";try{let[t,r]=(e.unreachable?.()?.getItem(wd)??"").split("|");Number(t)>e.now()&&kd.test(String(r))&&(b??=r)}catch{}function y(e,t){if(b!==null)return Promise.resolve({ok:false,reason:b,version:null});f??=t;let r=`${t??""}|${e}`,n=u.get(r);if(n)return n;let l=m(e,t).then(e=>e,()=>({ok:false,reason:"part-load",version:null}));return l.then(e=>c.set(r,e)),u.set(r,l),l}return t&&Qc(e=>{let t=Object.prototype.hasOwnProperty.call(Fc,e)?Fc[e]:void 0,r=()=>{let t=d.get(e);return t?t():Promise.reject(new TypeError(`${e} is not available to the Everfur web runtime`))};return t===void 0?r():y(t,f).then(e=>e.ok?e.namespace:r())}),{enabled:t,peek:(e,t)=>b!==null?{ok:false,reason:b,version:null}:c.get(`${t??""}|${e}`)??null,load:y,registerHostSubpaths:e=>{for(let[t,r]of Object.entries(e))d.has(t)||d.set(t,r)},setCspNonce:e=>{p=e===null||e===""?null:e}}}var Rd="everfur:web-runtime:bucket",Ed=null;function Id(){try{let e=globalThis.sessionStorage?.getItem(Rd);if(e)return e}catch{}Ed??=Math.floor(Math.random()*4294967296).toString(16);try{globalThis.sessionStorage?.setItem(Rd,Ed)}catch{}return Ed}function zd(e){return(t,r,n,l)=>new Promise(i=>{let o;try{o=e.createElement("script"),o.type="module",n==="cdn"&&(o.integrity=r,o.crossOrigin="anonymous"),l!==null&&(o.nonce=l),o.addEventListener("load",()=>{o.remove(),i("load")}),o.addEventListener("error",()=>{o.remove(),i("error")}),o.src=t,(e.head??e.documentElement).appendChild(o)}catch{i("error")}})}function Td(){let e=typeof document>"u"?null:document,t=globalThis.crypto;return{origin:Tc,keys:Pc,bundledVersion:ke,fetch:typeof fetch=="function"?fetch.bind(globalThis):null,crypto:t?.subtle?t:null,hasDom:e!==null&&typeof window<"u",runScript:e===null?()=>Promise.resolve("error"):zd(e),createBlobUrl:typeof Blob=="function"&&typeof URL.createObjectURL=="function"?e=>{try{return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}catch{return null}}:null,revokeBlobUrl:e=>{try{URL.revokeObjectURL(e)}catch{}},now:()=>Date.now(),sessionBucket:Id,unreachable:()=>globalThis.sessionStorage}}var Pd=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeLoader@${Xc}`);function Od(){let e=globalThis;return e[Pd]??=_d(Td())}var Fd=/* @__PURE__ */new Set(["disabled","server","bundled-newer"]),Md=/* @__PURE__ */new Set;function Ad(e,t,r,n){if(Fd.has(r))return;let l=`${t}|${r}`;if(!Md.has(l)){Md.add(l);try{e?.trackExpectedFailure(Nc,{part:t,reason:r,version:n,bundled:ke})}catch{}}}var $d=/* @__PURE__ */new Set,Dd=class extends e.Component{constructor(){super(...arguments);this.state={failed:false}}static getDerivedStateFromError(){return{failed:true}}componentDidCatch(){this.props.onError()}render(){return this.state.failed?this.props.fallback():this.props.children}},Bd=/* @__PURE__ */new Map;function Nd(t,r,n){let l=`${r??""}|${t.part}|${t.name}`,i=Bd.get(l);return i===void 0&&(i=e.lazy(async()=>{let e=await Od().load(t.part,r),l=e.ok?e.namespace[t.name]:void 0;return e.ok&&typeof l!="function"&&(typeof l!="object"||l===null)?(Ad(n.current,t.part,"part-missing",e.version),{default:t.bundled}):(e.ok||Ad(n.current,t.part,e.reason,e.version),{default:e.ok?l:t.bundled})}),Bd.set(l,i)),i}var Ld=()=>()=>{},Ud=()=>false,Hd=()=>true;function RuntimeSurface({spec:t,props:r}){let n=e.useContext(mc),l=td(),a=n?.publishableKey?n.publishableKey:null,s=e.useRef(null);s.current=n?.runtime.registry?.services?.telemetry??null;let u=e.useSyncExternalStore(Ld,Ud,Hd),c=e.useRef(null),[,d]=e.useState(0),f=l?null:Od();if(t.hostSubpaths!==void 0&&f?.enabled&&f.registerHostSubpaths(t.hostSubpaths),u)c.current=t.wait==="bundled"&&f!==null?"hydrate":"bundled";else if(c.current===null)if(!f?.enabled||$d.has(t.part))c.current="bundled";else if(Wc({React:i,ReactDOM:o})===null)Ad(s.current,t.part,"react-mismatch",null),c.current="bundled";else{let e=f.peek(t.part,a);c.current=e===null?"suspense":e.ok?"direct":"bundled"}let p=c.current,h=u||p!=="hydrate"?null:f?.peek(t.part,a)??null,g=!u&&p==="hydrate"&&h===null&&f?.enabled===true&&!$d.has(t.part);e.useEffect(()=>{if(!g||f===null)return;if(Wc({React:i,ReactDOM:o})===null){Ad(s.current,t.part,"react-mismatch",null);return}let e=true;return f.load(t.part,a).then(r=>{r.ok||Ad(s.current,t.part,r.reason,r.version),e&&d(e=>e+1)}),()=>{e=false}},[g,f,t.part,a]);let m=()=>e.createElement(t.bundled,r),b=r=>e.createElement(Dd,{fallback:m,onError:()=>{$d.add(t.part),Ad(s.current,t.part,"render",null)},children:r});if(u||p==="bundled")return m();if(p==="hydrate"||p==="direct"){let n=h??f?.peek(t.part,a),l=n?.ok?n.namespace[t.name]:void 0;return l===void 0||$d.has(t.part)?m():b(e.createElement(l,r))}let y=Nd(t,a,s),v=t.wait==="bundled"?m():e.createElement("div",{"data-everfur-runtime":"loading","aria-busy":true});return b(e.createElement(e.Suspense,{fallback:v},e.createElement(y,r)))}var Wd=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${Xc}`),qd=globalThis;function Vd(e,t=false){e===null?delete qd[Wd]:(t||qd[Wd]===void 0)&&(qd[Wd]=e)}var Kd=RuntimeSurface,Gd=(t,r)=>e.createElement(Kd,{spec:t,props:r});function Yd(e){if(Vd(Gd),e!==void 0&&e!==""){let t=Od();t.enabled&&t.setCspNonce(e)}}var Qd=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Qd[t]]}}function Zd(e,t){let{scale:r,scaleCaps:n}=e.type,l=n[t];return l>0?Math.min(r,l):r}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[Qd[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function Xd(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var Jd=/* @__PURE__ */new Map,ef=/* @__PURE__ */new Set,tf=typeof document>"u"?e.useEffect:e.useLayoutEffect;function rf(e){return e.cssSrc!==void 0?`css\n${e.cssSrc}`:`file\n${e.family}\n${e.src??""}\n${e.weight??"400"}\n${e.style??"normal"}`}function nf(e,t){if(!t)return;let r=e.cssSrc??e.src??"",n=`[everfur] A font in appearance.fonts did not load: "${e.family}" from ${r}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(e.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!ef.has(n)){ef.add(n);try{globalThis.console?.warn?.(n)}catch{}}}function lf(e){let t=document.getElementsByTagName("link");for(let r=0;r<t.length;r+=1){let n=t[r];if(n.rel==="stylesheet"&&n.getAttribute("href")===e)return n}return null}function of(e){return lf(e)!==null?Promise.resolve(true):new Promise(t=>{let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-everfur-font",""),r.addEventListener("load",()=>t(true)),r.addEventListener("error",()=>t(false)),document.head.appendChild(r)})}function af(e){let t=document.fonts;return new FontFace(e.family,`url("${e.src}")`,{display:"swap",weight:e.weight??"400",style:e.style??"normal"}).load().then(e=>(t.add(e),true)).catch(()=>false)}function sf(e,t=false){let r=rf(e),n=Jd.get(r);if(n===void 0){n=Promise.resolve(false);try{if(typeof document<"u"){let t=e.cssSrc===void 0?null:Ha(e.cssSrc),r=e.src===void 0?null:Ha(e.src);t!==null?n=of(t):r!==null&&(n=af({...e,src:r}))}}catch{n=Promise.resolve(false)}let l=n.then(r=>(r||nf(e,t),r));Jd.set(r,l),n=l}return n}function uf(e,t){let r=e.type.fontSources;tf(()=>{if(r.length===0)return;let e=false;try{e=t()}catch{}for(let t of r)sf(t,e)},[r,t])}var cf=/* @__PURE__ */new RegExp(`^${_a}\\/fonts\\/[\\w./-]+\\.woff2$`);function df(e){return cf.test(e)&&!e.includes("..")}var ff=/* @__PURE__ */new Map;function pf(e,t,r="400"){let n=e.trim(),l=`${n}\n${t}\n${r}`,i=ff.get(l);if(i===void 0){if(i=Promise.resolve(false),t!==null&&n!==""&&n!=="System"&&df(t))try{let e=document.fonts;i=new FontFace(n,`url("${t}") format("woff2")`,{display:"swap",weight:r}).load().then(t=>(e.add(t),!0)).catch(()=>!1)}catch{}ff.set(l,i)}return i}var hf=["regular","medium","bold","mono","monoMedium","monoBold"];function gf(t){let{families:r,fontUrls:n,weight:l,namedFaces:i}=t.type;e.useEffect(()=>{for(let e of hf){let t=n[e];t!=null&&pf(r[e],t,i[e]?l.regular:l[Qd[e]])}},[r,n,l,i]),uf(t,Xd)}function mf(e){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(e)??null}catch{return null}}function bf(e){return t=>{let r=mf(e);return r===null||typeof r.addEventListener!="function"?()=>{}:(r.addEventListener("change",t),()=>r.removeEventListener?.("change",t))}}var yf="(prefers-color-scheme: dark)",vf="(prefers-color-scheme: light)",xf="(prefers-reduced-motion: reduce)",kf="(prefers-contrast: more)",wf=bf(yf),Cf=bf(xf),Sf=bf(kf);function jf(){let e=mf(yf);return e===null?null:e.matches?"dark":mf(vf)?.matches?"light":null}function _f(){return mf(xf)?.matches===true}function Rf(){return mf(kf)?.matches===true}var Ef=16,If=false;var zf=null;function Tf(e){return Number.parseFloat(window.getComputedStyle(e).fontSize)}function Pf(){let e=document.body??document.documentElement,t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.setProperty("position","absolute","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("font-size","medium","important"),e.appendChild(t);try{return Tf(t)}finally{t.remove()}}function Of(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let e=If?Tf(document.documentElement):Pf();return Number.isFinite(e)&&e>0?e/Ef:1}catch{return 1}}function Ff(){return zf===null&&(zf=Of()),zf}function Mf(e){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let t=()=>{zf=null,e()};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)}function Af(){return e.useSyncExternalStore(wf,jf,()=>null)}function $f(){return e.useSyncExternalStore(Cf,_f,()=>false)}function Df(){return e.useSyncExternalStore(Sf,Rf,()=>false)}function Bf(){return e.useSyncExternalStore(Mf,Ff,()=>1)}var Nf=/* @__PURE__ */Object.freeze({useColorScheme:Af,useReducedMotion:$f,useTextScale:Bf,useHighContrast:Df,scaleTypeSizes:true,useResolvedTheme:gf,isDevelopment:Xd});function Lf(e){return e.storage===void 0?{...e,storage:createLocalStorageKv()}:e}var Uf=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:Lf,theme:Nf});function EverfurProvider(t){let{cspNonce:r,webRuntime:n,...l}=t;return n!==void 0&&n!=="updates"&&rd(),td()||Yd(r),e.createElement(EverfurProviderCore,{...l,seams:Uf})}function useCapability(t){let{runtime:r}=bc(),n=r.entitlements,l=e.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return e.useMemo(()=>decideCapability(t,l.decisions,{isPending:l.isPending}),[t,l])}function Hf(t){let{runtime:r}=bc(),n=r.entitlements,l=e.useCallback(e=>n===void 0?()=>{}:n.subscribe(e),[n]),i=e.useCallback(()=>{if(n===void 0)return false;let e=n.getSnapshot();return decideCapability(t,e.decisions,{isPending:e.isPending}).enabled},[n,t]);return e.useSyncExternalStore(l,i,i)}var Wf=class extends e.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:t,fallback:r,resetKey:n}){return e.createElement(Wf,{fallback:r,resetKey:n,children:e.createElement(RenderHost,{render:t})})}function qf(e,t,r){return Math.round(r*Zd(e,t)*10)/10}var Vf='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',Kf="System";function Gf(e){let t=e.trim();return t.length===0||t===Kf?Vf:`${Qf(t)}, ${Vf}`}function Yf(e){let t=e.trim();return t.length===0||t==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${Qf(t)}, ui-monospace, Menlo, Consolas, monospace`}function Qf(e){return`"${e.replace(/[\\"]/g,"\\$&")}"`}function faceCss(e,t){let r=e.type,n=r.families[t];return{fontFamily:t==="mono"||t==="monoMedium"||t==="monoBold"?Yf(n):Gf(n),fontWeight:r.namedFaces[t]?r.weight.regular:r.weight[Qd[t]]}}function headingFaceCss(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type,l=faceCss(e,t);return r===null&&n===null?l:r!==null?{fontFamily:Gf(r),fontWeight:n??e.type.weight[Qd[t]]}:e.type.namedFaces[t]||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}var Zf=/* @__PURE__ */Object.freeze({textAlign:"start"});var Xf=48;function Jf(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(t){let{capability:r,children:l,renderDisabled:i,renderPending:o,style:a,className:s}=t,u=useCapability(r),c=e.useMemo(()=>Jf(u),[u]);switch(c){case"enabled":return l;case"pending":return o?/* @__PURE__ */n.jsx(HostRender,{render:o,fallback:/* @__PURE__ */n.jsx(PendingSkeleton,{capability:r,style:a,className:s})}):/* @__PURE__ */n.jsx(PendingSkeleton,{capability:r,style:a,className:s});case"disabled":return i?/* @__PURE__ */n.jsx(HostRender,{render:()=>i(u),fallback:/* @__PURE__ */n.jsx(OffState,{decision:u,style:a,className:s}),resetKey:u}):/* @__PURE__ */n.jsx(OffState,{decision:u,style:a,className:s});default:return assertNever(c)}}function PendingSkeleton({capability:t,style:r,className:l}){let i=useEverfurTheme(),o=e.useMemo(()=>ep(i),[i]);/* @__PURE__ */
|
|
50
50
|
return n.jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${t}`,className:l,style:{...o.offstate,...r},children:/* @__PURE__ */n.jsx("div",{style:o.skeletonBar})})}function OffState({decision:t,style:r,className:l}){let i=useEverfurTheme(),o=e.useMemo(()=>ep(i),[i]),a=t.disabled?.reason??"";/* @__PURE__ */
|
|
51
51
|
return n.jsx("div",{className:l,style:{...o.offstate,...r},children:a.length>0?/* @__PURE__ */n.jsx("p",{style:o.offstateText,children:a}):null})}function ep(e){let{color:t,space:r,radius:n,type:l}=e;return{offstate:{...Zf,boxSizing:"border-box",minHeight:Xf,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${r.md}px ${r.lg}px`,backgroundColor:t.surfaceCream,borderRadius:n.md,border:`1px solid ${t.brandBorder}`},offstateText:{margin:0,...faceCss(e,"regular"),fontSize:l.size.body,lineHeight:`${Math.round(l.size.body*l.lineHeight.normal)}px`,color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}}}var tp="Go to the nearest emergency vet now.";var rp=/* @__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",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",sourcesHeading:"Sources",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:tp,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",capReached:"You've used your {cap} free messages this month.",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 np(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function lp(e){return e?.trim()||rp.emptyTitlePetFallback}function ip(e,t){return np(e,{petName:lp(t)})}var op="tel:+18884264435";var ap=/* @__PURE__ */Object.freeze([
|
|
52
52
|
/* @__PURE__ */Object.freeze({key:"inaccurate",label:rp.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
@@ -55,7 +55,7 @@ return n.jsx("div",{className:l,style:{...o.offstate,...r},children:a.length>0?/
|
|
|
55
55
|
/* @__PURE__ */Object.freeze({key:"unclear",label:rp.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
56
56
|
/* @__PURE__ */Object.freeze({key:"other",label:rp.feedbackReasonOther,feedbackType:"not_helpful"})]),sp=/* @__PURE__ */Object.freeze([
|
|
57
57
|
/* @__PURE__ */Object.freeze({sentiment:"up",label:rp.feedbackHelpful}),
|
|
58
|
-
/* @__PURE__ */Object.freeze({sentiment:"down",label:rp.feedbackNotHelpful})]);function up(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function cp(e,t){if(e==="down"&&t!==null){let e=ap.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return up(e)}var dp=/* @__PURE__ */new WeakSet;function fp(){let e=makeEverfurError("internalError",{retryable:true});return dp.add(e),err(e)}function pp(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&dp.has(t)}function hp(t,r,n,l){let[i,o]=e.useState({pet:n,user:r}),a=i.pet!==n||i.user===null&&r!==null;a&&o({pet:n,user:r});let s=a?{user:r}:i,u=n!==null&&s.user!==null&&s.user!==r;return e.useEffect(()=>{if(!u||r===null||n===null)return;let e=true,l=createPetsRepository(t.registry.services.authFor(r)),i=async()=>{let t=await l.list();e&&t.ok&&t.value.some(e=>e.petRef===n)&&o({pet:n,user:r})};i();let a=Ll(t,()=>{i()});return()=>{e=false,a()}},[u,t,r,n,l]),u}var gp=/* @__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(t){let{runtime:r,userRef:n,activePet:l,scopeEpoch:i}=bc(),o=t?.petRef??l??null,a=t?.conversationId??null,s=hp(r,n,o,i),u=e.useMemo(()=>({runtime:r,userRef:n,petRef:o,conversationId:a,scopeEpoch:i,held:s}),[r,n,o,a,i,s]),[c,d]=e.useState(null),f=s?null:c?.scope===u?c.controller:r.registry.peekChat({userRef:n,petRef:o,conversationId:a}),p=e.useRef(null);e.useEffect(()=>{if(s)return;let e=r.registry.acquireChat({userRef:n,petRef:o,conversationId:a});return p.current=e,d({scope:u,controller:e}),()=>{p.current=null,d(t=>t?.controller===e?null:t),r.registry.releaseChat(e)}},[r,n,o,a,i,s,u]);let h=e.useCallback(e=>f?f.subscribe(e):NOOP_UNSUBSCRIBE,[f]),g=e.useCallback(()=>f?f.getSnapshot():gp,[f]),m=e.useSyncExternalStore(h,g,g),b=e.useCallback((e,t)=>f&&p.current===f&&!f.getSnapshot().isBootstrapping?bp(f,f.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>p.current===f):Promise.resolve(vp()),[f]),y=e.useCallback(e=>f&&p.current===f&&!f.getSnapshot().isBootstrapping?bp(f,f.askEverfur(e),()=>p.current===f):Promise.resolve(vp()),[f]),v=e.useCallback(()=>f&&p.current===f?bp(f,f.retryLast(),()=>p.current===f):Promise.resolve(vp()),[f]),x=e.useCallback(()=>{f&&p.current===f&&f.stop()},[f]),k=e.useCallback(()=>{f&&p.current===f&&f.newConversation()},[f]),[w,C]=e.useState({controller:null,byMessage:{}}),S=w.controller===f?w.byMessage:mp,j=e.useCallback(async(e,t,r,n)=>{if(!f||p.current!==f)return err(makeEverfurError("accessDenied"));let l=String(e),i=w.controller===f?w.byMessage[l]:void 0;if(i===t&&r==null)return C(e=>{let t={...e.controller===f?e.byMessage:{}};return delete t[l],{controller:f,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));C(e=>({controller:f,byMessage:{...e.controller===f?e.byMessage:{},[l]:t}}));let o=await f.submitFeedback(e,cp(t,r??null),n??null);return p.current!==f?err(makeEverfurError("accessDenied")):(o.ok||C(e=>{let t={...e.controller===f?e.byMessage:{}};return i===void 0?delete t[l]:t[l]=i,{controller:f,byMessage:t}}),o)},[f,w]),_=e.useMemo(()=>{let e=async e=>{if(!f||p.current!==f)return err(makeEverfurError("accessDenied"));let t=await e(f);return p.current===f?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...o?{petRef:o}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[f,o]);return e.useMemo(()=>({status:m.status,messages:m.messages,conversationId:m.conversationId,petRef:o,error:m.error,isStreaming:m.isStreaming,isBootstrapping:m.isBootstrapping,historyCursor:m.historyCursor??null,isLoadingHistory:m.isLoadingHistory??false,stopped:m.stopped??false,reconnecting:m.reconnecting??false,..._,suggestedPrompts:m.suggestedPrompts,unreadCount:m.unreadCount,hasUnreadThreads:m.hasUnreadThreads??false,pendingCheckin:m.pendingCheckin??null,newConversation:k,sentimentByMessage:S,feedback:j,send:b,askEverfur:y,retryLast:v,stop:x}),[m,o,b,y,v,x,_,k,S,j])}var NOOP_UNSUBSCRIBE=()=>{},mp=/* @__PURE__ */Object.freeze({});async function bp(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(yp(n.messages))}function yp(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}function vp(){return fp()}function xp(e){switch(e.code){case"too_large":return np(rp.attachmentTooLarge,{max:formatBytes(fn),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return np(rp.attachmentTooMany,{max:pn});case"unsupported_type":return np(rp.attachmentUnsupported,{filename:e.filename});case"network":return rp.attachmentNetwork;case"server":return np(rp.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case"cancelled":return rp.attachmentCancelled;case"rate_limited":return rp.attachmentRateLimited;case"quota_exceeded":return rp.attachmentQuota;case"idempotency_conflict":return rp.attachmentConflict;case"unknown":return rp.attachmentUnknown}}function kp(e,t){return np(e>=t?rp.attachmentsFull:rp.addAttachment,{used:e,total:t})}var wp=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(t={}){let{runtime:r,userRef:n,scopeEpoch:l}=bc(),i=t.maxPerMessage??pn,o=e.useCallback(()=>{let{services:e}=r.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:e.authFor(n),...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),transport:t.transport??e.uploadTransport,maxPerMessage:i})},[r,n,l,i,t.transport]),a=e.useMemo(()=>t.queue??o(),[t.queue,o]),s=e.useRef(/* @__PURE__ */new WeakSet),[u,c]=e.useState(null),d=u!==null&&u.of===a?u.queue:a;e.useEffect(()=>{if(d!==t.queue){if(s.current.has(d)){c({of:a,queue:o()});return}return()=>{d.dispose(),s.current.add(d)}}},[d,a,o,t.queue]);let f=e.useSyncExternalStore(d.subscribe,d.getSnapshot,()=>wp),[p,h]=e.useState(null),g=e.useCallback(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>d.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&h(r.error),t},[d,h]),m=e.useCallback(e=>d.retry(e),[d]),b=e.useCallback(e=>d.remove(e),[d]),y=e.useCallback(()=>d.clear(),[d]),v=e.useCallback(()=>h(null),[h]),x=f.attachments.some(e=>e.status==="uploading"),k=f.attachments.some(e=>e.status==="failed");return e.useMemo(()=>({available:d.available,attachments:f.attachments,maxPerMessage:i,uploading:x,failed:k,blocked:x||k,s3Keys:f.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:p,add:g,retry:m,remove:b,clear:y,dismissRejected:v}),[d.available,f,i,x,k,p,g,m,b,y,v])}var Cp="pet_not_registered";function Sp(e){return e!=null&&e.reasonCode===Cp}var jp=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function _p(t,r,n){let{runtime:l,userRef:i,scopeEpoch:o}=bc(),a=e.useCallback((e,t)=>{let r=l.registry.services.authFor(i);return Dl($l(l,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[l,i,o]),s=e.useMemo(()=>r===void 0?null:Bl(r),[r]),[u,c]=e.useState({key:null,status:"idle",error:null,registered:null}),d=e.useRef(0),f=e.useRef(n);f.current=n;let p=t===null||s===null?null:`${String(i)}|${o}|${t}|${s}`,h=e.useCallback(()=>{if(t===null||r===void 0||p===null)return;let e=++d.current;c({key:p,status:"registering",error:null,registered:null}),a(t,r).then(t=>{e===d.current&&(t.ok?(c({key:p,status:"registered",error:null,registered:t.value}),f.current?.()):c({key:p,status:"failed",error:t.error,registered:null}))})},[a,t,p]);e.useEffect(()=>{if(p===null){d.current+=1;return}return h(),()=>{d.current+=1}},[p,h]);let g=e.useCallback(()=>{u.status==="failed"&&h()},[u.status,h]);return e.useMemo(()=>p===null?jp:u.key!==p?{status:"registering",error:null,registered:null,retry:g}:{status:u.status,error:u.error,registered:u.registered,retry:g},[p,u,g])}var Rp=500;function Ep(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,Rp):null}function Ip(t,r,n,l){let i=Ep(n),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=e.useRef(t);a.current=t;let s=e.useRef(null),u=e.useRef(null),c=e.useRef(o);c.current=o,e.useEffect(()=>{if(i===null||o===null||r||s.current===o||u.current===o)return;let e=a.current;if(e===void 0)return;u.current=o;let t=e=>{u.current===o&&(u.current=null),!pp(e)&&c.current===o&&(s.current=o)};Promise.resolve(e(i)).then(t,()=>t(void 0))},[i,o,r,t])}function zp(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function Tp(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Pp(e,...t){if(typeof e=="function")try{let r=e(...t);return Tp(r)&&Promise.resolve(r).then(void 0,zp),r}catch(e){zp(e);return}}function Op(e,...t){let r;try{r=e(...t)}catch(e){return zp(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var Fp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),Mp=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Ap=/* @__PURE__ */Object.freeze({...Fp,markRead:true}),$p=/* @__PURE__ */Object.freeze({...Mp,markRead:true});function Dp(e,t){return e?t?Ap:Fp:t?$p:Mp}function Bp(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:Pp(()=>r()!==!1)===true}function Np(t,r){let n=e.useRef({target:t,isVisible:r});n.current={target:t,isVisible:r};let l=e.useRef(t.isStreaming);e.useEffect(()=>{let e=l.current;if(l.current=t.isStreaming,!e||t.isStreaming)return;let{target:r,isVisible:i}=n.current;r.status!=="complete"||r.conversationId===null||r.unreadCount===null||!i()||r.markRead()},[t.isStreaming])}var Lp=3e5;function Up(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function Hp(t,r,n){let l=e.useRef(r);l.current=r;let i=e.useRef(null),o=e.useRef(null),a=e.useRef(false),s=e.useRef(0),u=e.useRef(0),c=e.useRef(3e4),d=()=>t?.isOffline===void 0?false:Pp(()=>t.isOffline?.()===!0)===true,f=d(),p=e.useRef(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:f}=l.current,h=Nt(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:f===true,isOffline:d(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,Up(e)?(s.current=Math.min(s.current===0?c.current*2:s.current*2,Lp),u.current=Date.now()+s.current):(s.current=0,u.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},e.useEffect(()=>{if(r.isTurnInFlight||f)return;let e=o.current;e!==null&&p.current(e)},[r.isTurnInFlight,f]),e.useEffect(()=>{if(t===void 0)return;let e=[],r=(t,r)=>{if(t===void 0)return;let n=Pp(()=>t(()=>{p.current(r)}));typeof n=="function"&&e.push(n)};return r(t.onForeground?.bind(t),"foreground"),r(t.onOnline?.bind(t),"foreground"),r(t.onAnnounced?.bind(t),"announced"),()=>{for(let t of e)Pp(t)}},[t]);let h=n?.intervalMs??null,g=n?.isVisibleFallback;e.useEffect(()=>{if(t===void 0||h===null||!Number.isFinite(h)||h<=0)return;c.current=h;let e=setInterval(()=>{Date.now()<u.current||Bp(t,g)&&p.current("poll")},h);return()=>clearInterval(e)},[t,h,g])}var Wp=/^efch_[A-Za-z0-9_-]{43}$/,qp="efch";function Vp(e){return typeof e=="string"&&Wp.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${qp}=`))continue;let e=r.slice(qp.length+1);return Vp(e)?e:null}return null}function Kp(e){let t=e.indexOf("#");if(t<0)return e;let r=e.slice(t+1).split("&").filter(e=>e!==qp&&!e.startsWith(`${qp}=`));return r.length===0?e.slice(0,t):`${e.slice(0,t)}#${r.join("&")}`}var Gp=128,Yp=/[\u0000-\u001f\u007f]/;function Qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Zp(e){return typeof e!="string"||e.length===0||e.length>Gp||Yp.test(e)||e.includes("://")?null:e}function Xp(e){if(e===null)return null;let t=e.conversation_id,r=Zp(e.pet_ref);return typeof t!="string"||!zr(t)||r===null?null:{conversationId:t,petRef:r}}function Jp(e,t,r){return Vp(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(Xp(Qp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(Xt("internalError",false))):Promise.resolve(ok(null))}function eh(t,r){let n=r?.runtime??null,l=r?.userRef??null,i=Vp(t)?t:null,o=i===null||l===null?null:`${String(l)}|${i}`,[a,s]=e.useState(null);return e.useEffect(()=>{if(o===null||i===null||l===null||n===null)return;let e=true,t=n.registry.services;return Jp(t.authFor(l),i,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||s({key:o,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[o,n,i,l]),a!==null&&a.key===o?a.target:void 0}function th(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function rh(t,r,n){let l=th(r),i=r?.kind==="chat",o=r?.petRef??null,a=i&&!n.pinned&&o!==null&&n.petRef!==null&&o!==n.petRef,s=e.useRef({openCheckin:t,target:r,selectPet:n.selectPet});s.current={openCheckin:t,target:r,selectPet:n.selectPet};let u=e.useRef(null),c=e.useRef(null),d=n.petRef;e.useEffect(()=>{if(l===null||u.current===l)return;let{openCheckin:e,target:t,selectPet:r}=s.current;if(a&&o!==null){if(c.current?.key!==l){c.current={key:l,from:d},r(o);return}d!==c.current.from&&(u.current=l);return}i&&!n.ready||(u.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,d,n.ready])}var nh=/* @__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 lh(e){let t=e?.replace(/\s+/g," ").trim();return t||nh.untitled}function ih(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function oh(e){let t=ih(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?nh.newReply.replace("{date}",t):t}function ah(e,t){return t?`${nh.countLabel}${nh.countSeparator}${e}`:nh.countLabel}function sh(e){return`${e.unreadCount!==null&&e.unreadCount>0?nh.unreadPrefix:""}${nh.openConversation} ${lh(e.title)}`}function uh(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function ch(e,t){let r=uh(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=uh(lh(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function dh(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function fh(t){let[r,n]=e.useState(false),[l,i]=e.useState(""),o=t.listConversations,a=e.useRef(0),[s,u]=e.useState(()=>dh(o)),c=s.scope===o?s:dh(o);e.useEffect(()=>(a.current+=1,n(false),i(""),u(dh(o)),()=>{a.current+=1}),[o]);let d=e.useCallback(async e=>{let r=++a.current,n=e!==void 0;u(e=>({...e,scope:o,loading:!n,loadingMore:n,error:null}));let l=await t.listConversations(e?{cursor:e}:void 0);if(r===a.current){if(!l.ok){u(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}u(t=>{let r=e&&t.scope===o?t.rows:[],n=new Set(r.map(e=>e.id));return{scope:o,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===e?null:l.value.nextCursor}})}},[t.listConversations,o]),f=()=>{n(true),i(""),d()},p=()=>{a.current+=1,n(false)},h=async e=>{let r=++a.current;u(e=>({...e,loading:true,error:null}));let l=await t.resumeConversation(e);r===a.current&&(u(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&n(false))},g=async()=>{let e=a.current,r=await t.loadOlderMessages();e===a.current&&!r.ok&&u(e=>({...e,error:r.error.displayMessage}))},m=()=>{t.newConversation(),a.current+=1,n(false)},b=()=>{c.cursor===null||c.loading||c.loadingMore||l.trim().length>0||d(c.cursor)},y=e.useMemo(()=>ch(c.rows,l),[c.rows,l]),v=l.trim().length>0;return{...c,open:r,show:f,close:p,load:d,resume:h,earlier:g,newConversation:m,loadMore:b,query:l,setQuery:i,searching:v,filtered:y,emptyKind:c.rows.length===0?"empty":"noMatch"}}var ph="#111111",hh="#FFFFFF",gh=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:ph,pillColor:hh,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:ph,pillColor:hh,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ph,pillColor:hh,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ph,pillColor:hh,showsVetAction:false})});function mh(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function bh(e){return np(rp.urgencyGeneralReason,{petName:rp.emptyTitlePetFallback})}function yh(e,t){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r?.role!=="assistant"||r.responseId===void 0)continue;let n=r.urgencyLevel;return n?{messageId:r.id,level:n,reason:vh(r.urgencyReason)}:r.urgencyProvided===true?{messageId:r.id,level:"general",reason:bh()}:null}return null}function vh(e){return typeof e=="string"&&e.trim().length>0?e:null}function xh(t){let r=t===null?null:mh(t),[n,l]=e.useState(null),[i,o]=e.useState(false);e.useEffect(()=>o(false),[r]);let a=t!==null&&(i||!(n!==null&&n===r)),s=t===null?null:gh[t.level],u=t!==null&&!a&&t.level!=="general",c=e.useCallback(()=>{r!==null&&l(r),o(false)},[r]),d=e.useCallback(()=>o(true),[]);return e.useMemo(()=>({source:t,tier:s,signature:r,showBanner:a,showCompactIcon:u,showVetAction:a&&s!==null&&s.showsVetAction,dismissLabel:s===null?null:np(rp.dismissBanner,{label:s.label}),dismiss:c,expand:d}),[t,s,r,a,u,c,d])}function kh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function wh(e){let t=Y(e);return t===null?null:{reached:rp.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function Ch(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function Sh(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=Ch(r),n=t==="web",l=wh(r);return{tone:"error",title:l!==null?l.reached:e?rp.turnUnreachableTitle:n?rp.turnFailedTitleWeb:rp.turnFailedTitle,body:r.displayMessage,actionLabel:e?rp.turnStartNewChat:n?rp.retry:rp.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:rp.turnStoppedTitle,body:rp.turnStoppedBody,actionLabel:rp.turnRetry,action:"retry"}:null}function jh(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var _h=3,Rh=/* @__PURE__ */Object.freeze([]);function Eh(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Rh;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),l=e.replace(/\s+/g," ").toLowerCase();if(!(l.length===0||r.has(l))&&(r.add(l),n.push(e),n.length===_h))break}/* @__PURE__ */
|
|
58
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:rp.feedbackNotHelpful})]);function up(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function cp(e,t){if(e==="down"&&t!==null){let e=ap.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return up(e)}var dp=/* @__PURE__ */new WeakSet;function fp(){let e=makeEverfurError("internalError",{retryable:true});return dp.add(e),err(e)}function pp(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&dp.has(t)}function hp(t,r,n,l){let[i,o]=e.useState({pet:n,user:r}),a=i.pet!==n||i.user===null&&r!==null;a&&o({pet:n,user:r});let s=a?{user:r}:i,u=n!==null&&s.user!==null&&s.user!==r;return e.useEffect(()=>{if(!u||r===null||n===null)return;let e=true,l=createPetsRepository(t.registry.services.authFor(r)),i=async()=>{let t=await l.list();e&&t.ok&&t.value.some(e=>e.petRef===n)&&o({pet:n,user:r})};i();let a=Ll(t,()=>{i()});return()=>{e=false,a()}},[u,t,r,n,l]),u}var gp=/* @__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(t){let{runtime:r,userRef:n,activePet:l,scopeEpoch:i}=bc(),o=t?.petRef??l??null,a=t?.conversationId??null,s=hp(r,n,o,i),u=e.useMemo(()=>({runtime:r,userRef:n,petRef:o,conversationId:a,scopeEpoch:i,held:s}),[r,n,o,a,i,s]),[c,d]=e.useState(null),f=s?null:c?.scope===u?c.controller:r.registry.peekChat({userRef:n,petRef:o,conversationId:a}),p=e.useRef(null);e.useEffect(()=>{if(s)return;let e=r.registry.acquireChat({userRef:n,petRef:o,conversationId:a});return p.current=e,d({scope:u,controller:e}),()=>{p.current=null,d(t=>t?.controller===e?null:t),r.registry.releaseChat(e)}},[r,n,o,a,i,s,u]);let h=e.useCallback(e=>f?f.subscribe(e):NOOP_UNSUBSCRIBE,[f]),g=e.useCallback(()=>f?f.getSnapshot():gp,[f]),m=e.useSyncExternalStore(h,g,g),b=e.useCallback((e,t)=>f&&p.current===f&&!f.getSnapshot().isBootstrapping?bp(f,f.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>p.current===f):Promise.resolve(vp()),[f]),y=e.useCallback(e=>f&&p.current===f&&!f.getSnapshot().isBootstrapping?bp(f,f.askEverfur(e),()=>p.current===f):Promise.resolve(vp()),[f]),v=e.useCallback(()=>f&&p.current===f?bp(f,f.retryLast(),()=>p.current===f):Promise.resolve(vp()),[f]),x=e.useCallback(()=>{f&&p.current===f&&f.stop()},[f]),k=e.useCallback(()=>{f&&p.current===f&&f.newConversation()},[f]),[w,C]=e.useState({controller:null,byMessage:{}}),S=w.controller===f?w.byMessage:mp,j=e.useCallback(async(e,t,r,n)=>{if(!f||p.current!==f)return err(makeEverfurError("accessDenied"));let l=String(e),i=w.controller===f?w.byMessage[l]:void 0;if(i===t&&r==null)return C(e=>{let t={...e.controller===f?e.byMessage:{}};return delete t[l],{controller:f,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));C(e=>({controller:f,byMessage:{...e.controller===f?e.byMessage:{},[l]:t}}));let o=await f.submitFeedback(e,cp(t,r??null),n??null);return p.current!==f?err(makeEverfurError("accessDenied")):(o.ok||C(e=>{let t={...e.controller===f?e.byMessage:{}};return i===void 0?delete t[l]:t[l]=i,{controller:f,byMessage:t}}),o)},[f,w]),_=e.useMemo(()=>{let e=async e=>{if(!f||p.current!==f)return err(makeEverfurError("accessDenied"));let t=await e(f);return p.current===f?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...o?{petRef:o}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[f,o]);return e.useMemo(()=>({status:m.status,messages:m.messages,conversationId:m.conversationId,petRef:o,error:m.error,isStreaming:m.isStreaming,isBootstrapping:m.isBootstrapping,historyCursor:m.historyCursor??null,isLoadingHistory:m.isLoadingHistory??false,stopped:m.stopped??false,reconnecting:m.reconnecting??false,..._,suggestedPrompts:m.suggestedPrompts,unreadCount:m.unreadCount,hasUnreadThreads:m.hasUnreadThreads??false,pendingCheckin:m.pendingCheckin??null,newConversation:k,sentimentByMessage:S,feedback:j,send:b,askEverfur:y,retryLast:v,stop:x}),[m,o,b,y,v,x,_,k,S,j])}var NOOP_UNSUBSCRIBE=()=>{},mp=/* @__PURE__ */Object.freeze({});async function bp(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(yp(n.messages))}function yp(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}function vp(){return fp()}function xp(e){switch(e.code){case"too_large":return np(rp.attachmentTooLarge,{max:formatBytes(fn),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return np(rp.attachmentTooMany,{max:pn});case"unsupported_type":return np(rp.attachmentUnsupported,{filename:e.filename});case"network":return rp.attachmentNetwork;case"server":return np(rp.attachmentServer,{status:""});case"cancelled":return rp.attachmentCancelled;case"rate_limited":return rp.attachmentRateLimited;case"quota_exceeded":return rp.attachmentQuota;case"idempotency_conflict":return rp.attachmentConflict;case"unknown":return rp.attachmentUnknown}}function kp(e,t){return np(e>=t?rp.attachmentsFull:rp.addAttachment,{used:e,total:t})}var wp=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(t={}){let{runtime:r,userRef:n,scopeEpoch:l}=bc(),i=t.maxPerMessage??pn,o=e.useCallback(()=>{let{services:e}=r.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:e.authFor(n),...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),transport:t.transport??e.uploadTransport,maxPerMessage:i})},[r,n,l,i,t.transport]),a=e.useMemo(()=>t.queue??o(),[t.queue,o]),s=e.useRef(/* @__PURE__ */new WeakSet),[u,c]=e.useState(null),d=u!==null&&u.of===a?u.queue:a;e.useEffect(()=>{if(d!==t.queue){if(s.current.has(d)){c({of:a,queue:o()});return}return()=>{d.dispose(),s.current.add(d)}}},[d,a,o,t.queue]);let f=e.useSyncExternalStore(d.subscribe,d.getSnapshot,()=>wp),[p,h]=e.useState(null),g=e.useCallback(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>d.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&h(r.error),t},[d,h]),m=e.useCallback(e=>d.retry(e),[d]),b=e.useCallback(e=>d.remove(e),[d]),y=e.useCallback(()=>d.clear(),[d]),v=e.useCallback(()=>h(null),[h]),x=f.attachments.some(e=>e.status==="uploading"),k=f.attachments.some(e=>e.status==="failed");return e.useMemo(()=>({available:d.available,attachments:f.attachments,maxPerMessage:i,uploading:x,failed:k,blocked:x||k,s3Keys:f.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:p,add:g,retry:m,remove:b,clear:y,dismissRejected:v}),[d.available,f,i,x,k,p,g,m,b,y,v])}var Cp="pet_not_registered";function Sp(e){return e!=null&&e.reasonCode===Cp}var jp=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function _p(t,r,n){let{runtime:l,userRef:i,scopeEpoch:o}=bc(),a=e.useCallback((e,t)=>{let r=l.registry.services.authFor(i);return Dl($l(l,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[l,i,o]),s=e.useMemo(()=>r===void 0?null:Bl(r),[r]),[u,c]=e.useState({key:null,status:"idle",error:null,registered:null}),d=e.useRef(0),f=e.useRef(n);f.current=n;let p=t===null||s===null?null:`${String(i)}|${o}|${t}|${s}`,h=e.useCallback(()=>{if(t===null||r===void 0||p===null)return;let e=++d.current;c({key:p,status:"registering",error:null,registered:null}),a(t,r).then(t=>{e===d.current&&(t.ok?(c({key:p,status:"registered",error:null,registered:t.value}),f.current?.()):c({key:p,status:"failed",error:t.error,registered:null}))})},[a,t,p]);e.useEffect(()=>{if(p===null){d.current+=1;return}return h(),()=>{d.current+=1}},[p,h]);let g=e.useCallback(()=>{u.status==="failed"&&h()},[u.status,h]);return e.useMemo(()=>p===null?jp:u.key!==p?{status:"registering",error:null,registered:null,retry:g}:{status:u.status,error:u.error,registered:u.registered,retry:g},[p,u,g])}var Rp=500;function Ep(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,Rp):null}function Ip(t,r,n,l){let i=Ep(n),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,a=e.useRef(t);a.current=t;let s=e.useRef(null),u=e.useRef(null),c=e.useRef(o);c.current=o,e.useEffect(()=>{if(i===null||o===null||r||s.current===o||u.current===o)return;let e=a.current;if(e===void 0)return;u.current=o;let t=e=>{u.current===o&&(u.current=null),!pp(e)&&c.current===o&&(s.current=o)};Promise.resolve(e(i)).then(t,()=>t(void 0))},[i,o,r,t])}function zp(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function Tp(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function Pp(e,...t){if(typeof e=="function")try{let r=e(...t);return Tp(r)&&Promise.resolve(r).then(void 0,zp),r}catch(e){zp(e);return}}function Op(e,...t){let r;try{r=e(...t)}catch(e){return zp(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var Fp=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),Mp=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Ap=/* @__PURE__ */Object.freeze({...Fp,markRead:true}),$p=/* @__PURE__ */Object.freeze({...Mp,markRead:true});function Dp(e,t){return e?t?Ap:Fp:t?$p:Mp}function Bp(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:Pp(()=>r()!==!1)===true}function Np(t,r){let n=e.useRef({target:t,isVisible:r});n.current={target:t,isVisible:r};let l=e.useRef(t.isStreaming);e.useEffect(()=>{let e=l.current;if(l.current=t.isStreaming,!e||t.isStreaming)return;let{target:r,isVisible:i}=n.current;r.status!=="complete"||r.conversationId===null||r.unreadCount===null||!i()||r.markRead()},[t.isStreaming])}var Lp=3e5;function Up(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function Hp(t,r,n){let l=e.useRef(r);l.current=r;let i=e.useRef(null),o=e.useRef(null),a=e.useRef(false),s=e.useRef(0),u=e.useRef(0),c=e.useRef(3e4),d=()=>t?.isOffline===void 0?false:Pp(()=>t.isOffline?.()===!0)===true,f=d(),p=e.useRef(()=>{});p.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:f}=l.current,h=Nt(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:f===true,isOffline:d(),lastRefresh:i.current,now:Date.now()});if(h.action==="skip")return;if(h.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(a.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:h.conversationId,at:Date.now()},n===void 0)return;a.current=true;let g=e=>{a.current=false,Up(e)?(s.current=Math.min(s.current===0?c.current*2:s.current*2,Lp),u.current=Date.now()+s.current):(s.current=0,u.current=0);let t=o.current;t!==null&&p.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},e.useEffect(()=>{if(r.isTurnInFlight||f)return;let e=o.current;e!==null&&p.current(e)},[r.isTurnInFlight,f]),e.useEffect(()=>{if(t===void 0)return;let e=[],r=(t,r)=>{if(t===void 0)return;let n=Pp(()=>t(()=>{p.current(r)}));typeof n=="function"&&e.push(n)};return r(t.onForeground?.bind(t),"foreground"),r(t.onOnline?.bind(t),"foreground"),r(t.onAnnounced?.bind(t),"announced"),()=>{for(let t of e)Pp(t)}},[t]);let h=n?.intervalMs??null,g=n?.isVisibleFallback;e.useEffect(()=>{if(t===void 0||h===null||!Number.isFinite(h)||h<=0)return;c.current=h;let e=setInterval(()=>{Date.now()<u.current||Bp(t,g)&&p.current("poll")},h);return()=>clearInterval(e)},[t,h,g])}var Wp=/^efch_[A-Za-z0-9_-]{43}$/,qp="efch";function Vp(e){return typeof e=="string"&&Wp.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${qp}=`))continue;let e=r.slice(qp.length+1);return Vp(e)?e:null}return null}function Kp(e){let t=e.indexOf("#");if(t<0)return e;let r=e.slice(t+1).split("&").filter(e=>e!==qp&&!e.startsWith(`${qp}=`));return r.length===0?e.slice(0,t):`${e.slice(0,t)}#${r.join("&")}`}var Gp=128,Yp=/[\u0000-\u001f\u007f]/;function Qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function Zp(e){return typeof e!="string"||e.length===0||e.length>Gp||Yp.test(e)||e.includes("://")?null:e}function Xp(e){if(e===null)return null;let t=e.conversation_id,r=Zp(e.pet_ref);return typeof t!="string"||!zr(t)||r===null?null:{conversationId:t,petRef:r}}function Jp(e,t,r){return Vp(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(Xp(Qp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(Xt("internalError",false))):Promise.resolve(ok(null))}function eh(t,r){let n=r?.runtime??null,l=r?.userRef??null,i=Vp(t)?t:null,o=i===null||l===null?null:`${String(l)}|${i}`,[a,s]=e.useState(null);return e.useEffect(()=>{if(o===null||i===null||l===null||n===null)return;let e=true,t=n.registry.services;return Jp(t.authFor(l),i,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||s({key:o,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[o,n,i,l]),a!==null&&a.key===o?a.target:void 0}function th(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function rh(t,r,n){let l=th(r),i=r?.kind==="chat",o=r?.petRef??null,a=i&&!n.pinned&&o!==null&&n.petRef!==null&&o!==n.petRef,s=e.useRef({openCheckin:t,target:r,selectPet:n.selectPet});s.current={openCheckin:t,target:r,selectPet:n.selectPet};let u=e.useRef(null),c=e.useRef(null),d=n.petRef;e.useEffect(()=>{if(l===null||u.current===l)return;let{openCheckin:e,target:t,selectPet:r}=s.current;if(a&&o!==null){if(c.current?.key!==l){c.current={key:l,from:d},r(o);return}d!==c.current.from&&(u.current=l);return}i&&!n.ready||(u.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,a,o,d,n.ready])}var nh=/* @__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 lh(e){let t=e?.replace(/\s+/g," ").trim();return t||nh.untitled}function ih(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function oh(e){let t=ih(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?nh.newReply.replace("{date}",t):t}function ah(e,t){return t?`${nh.countLabel}${nh.countSeparator}${e}`:nh.countLabel}function sh(e){return`${e.unreadCount!==null&&e.unreadCount>0?nh.unreadPrefix:""}${nh.openConversation} ${lh(e.title)}`}function uh(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function ch(e,t){let r=uh(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=uh(lh(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function dh(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function fh(t){let[r,n]=e.useState(false),[l,i]=e.useState(""),o=t.listConversations,a=e.useRef(0),[s,u]=e.useState(()=>dh(o)),c=s.scope===o?s:dh(o);e.useEffect(()=>(a.current+=1,n(false),i(""),u(dh(o)),()=>{a.current+=1}),[o]);let d=e.useCallback(async e=>{let r=++a.current,n=e!==void 0;u(e=>({...e,scope:o,loading:!n,loadingMore:n,error:null}));let l=await t.listConversations(e?{cursor:e}:void 0);if(r===a.current){if(!l.ok){u(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}u(t=>{let r=e&&t.scope===o?t.rows:[],n=new Set(r.map(e=>e.id));return{scope:o,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===e?null:l.value.nextCursor}})}},[t.listConversations,o]),f=()=>{n(true),i(""),d()},p=()=>{a.current+=1,n(false)},h=async e=>{let r=++a.current;u(e=>({...e,loading:true,error:null}));let l=await t.resumeConversation(e);r===a.current&&(u(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&n(false))},g=async()=>{let e=a.current,r=await t.loadOlderMessages();e===a.current&&!r.ok&&u(e=>({...e,error:r.error.displayMessage}))},m=()=>{t.newConversation(),a.current+=1,n(false)},b=()=>{c.cursor===null||c.loading||c.loadingMore||l.trim().length>0||d(c.cursor)},y=e.useMemo(()=>ch(c.rows,l),[c.rows,l]),v=l.trim().length>0;return{...c,open:r,show:f,close:p,load:d,resume:h,earlier:g,newConversation:m,loadMore:b,query:l,setQuery:i,searching:v,filtered:y,emptyKind:c.rows.length===0?"empty":"noMatch"}}var ph="#111111",hh="#FFFFFF",gh=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:ph,pillColor:hh,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:ph,pillColor:hh,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ph,pillColor:hh,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ph,pillColor:hh,showsVetAction:false})});function mh(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function bh(e){return np(rp.urgencyGeneralReason,{petName:rp.emptyTitlePetFallback})}function yh(e,t){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r?.role!=="assistant"||r.responseId===void 0)continue;let n=r.urgencyLevel;return n?{messageId:r.id,level:n,reason:vh(r.urgencyReason)}:r.urgencyProvided===true?{messageId:r.id,level:"general",reason:bh()}:null}return null}function vh(e){return typeof e=="string"&&e.trim().length>0?e:null}function xh(t){let r=t===null?null:mh(t),[n,l]=e.useState(null),[i,o]=e.useState(false);e.useEffect(()=>o(false),[r]);let a=t!==null&&(i||!(n!==null&&n===r)),s=t===null?null:gh[t.level],u=t!==null&&!a&&t.level!=="general",c=e.useCallback(()=>{r!==null&&l(r),o(false)},[r]),d=e.useCallback(()=>o(true),[]);return e.useMemo(()=>({source:t,tier:s,signature:r,showBanner:a,showCompactIcon:u,showVetAction:a&&s!==null&&s.showsVetAction,dismissLabel:s===null?null:np(rp.dismissBanner,{label:s.label}),dismiss:c,expand:d}),[t,s,r,a,u,c,d])}function kh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function wh(e){let t=Y(e);return t===null?null:{reached:rp.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function Ch(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function Sh(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=Ch(r),n=t==="web",l=wh(r);return{tone:"error",title:l!==null?l.reached:e?rp.turnUnreachableTitle:n?rp.turnFailedTitleWeb:rp.turnFailedTitle,body:r.displayMessage,actionLabel:e?rp.turnStartNewChat:n?rp.retry:rp.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:rp.turnStoppedTitle,body:rp.turnStoppedBody,actionLabel:rp.turnRetry,action:"retry"}:null}function jh(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var _h=3,Rh=/* @__PURE__ */Object.freeze([]);function Eh(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Rh;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),l=e.replace(/\s+/g," ").toLowerCase();if(!(l.length===0||r.has(l))&&(r.add(l),n.push(e),n.length===_h))break}/* @__PURE__ */
|
|
59
59
|
return Object.freeze(n)}var Ih=5;function zh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Th(e,t){if(t===void 0)return Eh(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return Rh;let n=Math.max(1,Math.min(Ih,Math.floor(t.count??_h))),l=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){l=r.text;break}}let i=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(l===null?[]:[i(l)]),a=[],s=e=>{let r=e.trim(),l=i(r);a.length>=n||l.length===0||o.has(l)||zh(t.exclude,r)||(o.add(l),a.push(r))};for(let t of e.suggestedPrompts)s(t);let u=[];try{u=typeof t.fill=="function"?t.fill(l):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&s(e);/* @__PURE__ */
|
|
60
60
|
return Object.freeze(a)}function Ph(e){return e.sender?.displayName??rp.senderVet}function Oh(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}function useEverfurPets(){let{runtime:t,userRef:r,activePet:n,scopeEpoch:l}=bc(),i=e.useMemo(()=>createPetsRepository(t.registry.services.authFor(r)),[t,r,l]),[o,a]=e.useState({repository:i,pets:[],loading:true,error:null}),s=o.repository===i?o:{pets:[],loading:true,error:null},u=e.useRef(0),c=e.useCallback(async()=>{let e=++u.current;a(e=>({...e,repository:i,loading:true,error:null,pets:e.repository===i?e.pets:[]}));let t=await i.list();e===u.current&&a(t.ok?{repository:i,pets:t.value,loading:false,error:null}:e=>({repository:i,pets:e.repository===i?e.pets:[],loading:false,error:t.error}))},[i]);e.useEffect(()=>(c(),()=>{u.current+=1}),[c]),e.useEffect(()=>Ll(t,()=>{c()}),[t,c]);let d=e.useMemo(()=>n===null?null:s.pets.find(e=>e.petRef===n)??null,[n,s.pets]);return e.useMemo(()=>({pets:s.pets,activePet:d,loading:s.loading,error:s.error,refresh:c}),[s.pets,s.loading,s.error,d,c])}function Fh(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Mh=/* @__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 Ah=2,$h="data-ef-focus-ring",Dh="data-ef-focus-visible",Bh="data-ef-focus-ring-color";function Nh(e){return{outline:`${Ah}px solid ${e}`,outlineOffset:Ah}}var Lh=false,Uh=0;function Hh(e){e.metaKey||e.ctrlKey||e.altKey||(Lh=true)}function Wh(){Lh=false}function qh(){return typeof document>"u"?()=>{}:(Uh===0&&(document.addEventListener("keydown",Hh,true),document.addEventListener("pointerdown",Wh,true),document.addEventListener("mousedown",Wh,true),document.addEventListener("touchstart",Wh,true)),Uh+=1,()=>{Uh-=1,!(Uh>0)&&(document.removeEventListener("keydown",Hh,true),document.removeEventListener("pointerdown",Wh,true),document.removeEventListener("mousedown",Wh,true),document.removeEventListener("touchstart",Wh,true),Lh=false)})}var Vh=/* @__PURE__ */new Set(["","text","search","email","tel","url","password","number"]);function Kh(e){return e.tagName==="TEXTAREA"||e.isContentEditable?true:e.tagName!=="INPUT"?false:Vh.has((e.getAttribute("type")??"").toLowerCase())}function Gh(t,r){e.useEffect(()=>{let e=t.current;if(e!==null)return Yh(e,r)},[t,r])}function Yh(e,t){let r=qh(),n=/* @__PURE__ */new Map,l=e=>{let r=e.target;if(!(r instanceof HTMLElement)||n.has(r)||r.closest(`[${$h}="self"]`)!==null||!Lh&&!Kh(r))return;n.set(r,{outline:r.style.outline,outlineOffset:r.style.outlineOffset});let l=r.closest(`[${Bh}]`),i=Nh(l?.getAttribute(Bh)||t);r.style.outline=i.outline,r.style.outlineOffset=`${i.outlineOffset}px`,r.setAttribute(Dh,"")},i=e=>{let t=e.target;if(!(t instanceof HTMLElement))return;let r=n.get(t);r!==void 0&&(n.delete(t),t.style.outline=r.outline,t.style.outlineOffset=r.outlineOffset,t.removeAttribute(Dh))};return e.addEventListener("focusin",l),e.addEventListener("focusout",i),()=>{e.removeEventListener("focusin",l),e.removeEventListener("focusout",i);for(let[e,t]of n)e.style.outline=t.outline,e.style.outlineOffset=t.outlineOffset,e.removeAttribute(Dh);n.clear(),r()}}function Qh(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}var Zh=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function Xh(){let e=globalThis,t=e[Zh];if(t!==void 0)return t;let r={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return e[Zh]=r,r}function Jh(e){let t=Xh();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function eg(e){let t=Xh().presenter;if(t===null)return"absent";try{return t(e)===!1?"declined":"presented"}catch(e){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",e),"threw"}}function tg(e){let t=Xh();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function rg(){return Xh().snapshot}function ng(){return Xh().hosts.length>0}function lg(e){if(!ng())return false;let t=/* @__PURE__ */Object.freeze({...e});return Jh({request:t,serial:Xh().snapshot.serial+1}),true}function ig(){Xh().snapshot.request!==null&&Jh({request:null})}function og(){let e=Xh(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Jh({activeHost:e.hosts[0]??null}),t}function ag(e){let t=Xh();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;Jh(r===null?{activeHost:r,request:null}:{activeHost:r})}function sg(e){let t=null;return()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null)}),r}}function ug(t){let[r,n]=e.useState(null);e.useEffect(()=>{let e=og();return n(e),()=>{ag(e)}},[]);let l=e.useSyncExternalStore(tg,rg,rg),i=r!==null&&l.activeHost===r?l.request:null,[o,a]=e.useState(null),s=i!==null&&o===null;return e.useEffect(()=>{if(!s)return;let e=true;return t().then(t=>{e&&a(()=>t)},t=>{e&&(console.warn("[everfur] The in-app vet visit could not load its screens.",t),ig())}),()=>{e=false}},[s,t]),i===null||o===null?null:{module:o,request:i,serial:l.serial,dismiss:ig}}var cg=sg(()=>import("@everfur/sdk/web/televet/booking"));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:l}){let i=ug(cg);if(i===null)return null;let{EverfurTelevetDialog:o}=i.module;/* @__PURE__ */
|
|
61
61
|
return n.jsx(o,{request:i.request,onClose:i.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...l?{onFindEmergencyVet:l}:{}},i.serial)}var dg=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&dg.includes(e)}var fg="/widget/v1/televet/handoffs",pg="/widget/v1/televet/availability",hg="/widget/v1/televet/chat-entry",gg=/^[a-z0-9][a-z0-9_-]{0,39}$/,mg=/^[A-Za-z0-9_-]{22}$/;var bg=32,yg=128,vg=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.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 t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function xg(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function kg(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function wg(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!gg.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,a=i!=null;if(a){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>vg)return{ok:false,message:`visitRef must be 1..${vg} characters`};r.visit_ref=e}if(o!=null){if(!a)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${dg.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Cg(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function Sg(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(zg(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>yg)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${yg} characters`}));i=e}let o=wg(i,l);if(!o.ok){let e=xg(o.message);return e.ok?e:n(e.error)}let a=o.body,s=await t.send("televet.visit.handoff",{method:"POST",path:fg,body:a},{idempotent:false,maxAttempts:1});if(!s.ok)return n(s.error);let u=jg(s.value),c=a.return_to!==void 0,d=c?s.value?.flow_id:void 0;if(c&&(typeof d!="string"||!mg.test(d))){let e=kg("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=a.visit_ref!==void 0,p=f?Cg(s.value?.visit):null;if(f&&p===null){let e=kg("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let h=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...p!==null?{visit:p}:{}});return h===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(zg(r,"televet.visit.handoff_created",{pet_scoped:a.pet_ref!==void 0}),ok(h))},async checkAvailability(e){if(typeof e!="string"||e.length>bg)return xg(`state must be at most ${bg} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:pg,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?kg("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:hg},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function jg(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!Ig(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var _g=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),Rg=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Eg=/[\s\u0000-\u001f\u007f]/;function Ig(e){if(Eg.test(e))return false;let t=Rg.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&_g.has(l);if(!i&&!o)return false;let a=e.indexOf("#");if(a<0)return false;let s=e.slice(a);return s.startsWith("#h=")&&s.length>3}function zg(e,t,r){if(e)try{e.track(t,r)}catch{}}var Tg=false;function Pg(e,t){return t!==void 0?(Pp(t,e),"onStartInApp"):eg(e)==="presented"?"presenter":lg(e)?"experience":(Tg||(Tg=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Og=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function Fg(t,r,n){let{usState:l,chat:i,scope:o}=n,a=r&&(l!==null||i),s=`${l??""}|${i?"chat":""}`,[u,c]=e.useState(null);if(e.useEffect(()=>{if(!a)return;let e=true,r=t.current;return c(null),(async()=>{try{if(i&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(l===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(l);return e.ok&&e.value.available}catch{return false}})().then(t=>{e&&c({key:s,open:t})}),()=>{e=false}},[a,s,l,i,o,t]),!a)return null;let d=u!==null&&u.key===s;return{open:d&&u.open,pending:!d}}var Mg=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function Ag(t,r={}){let{runtime:n,userRef:l,scopeEpoch:i}=bc(),o=useCapability("televet"),a=o.enabled&&l!==null,s=r.usState??null,u=r.entry==="chat",c=r.petRef??null,d=r.prefer==="redirect",f=e.useMemo(()=>{if(r.controller)return r.controller;let{services:e}=n.registry;return Sg({auth:e.authFor(l),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[n,l,i,r.controller]),p=e.useRef(f);p.current=f;let h=e.useMemo(()=>({runtime:n,userRef:l,scopeEpoch:i}),[n,l,i]),g=Fg(p,a,{usState:s,chat:u,scope:h}),m=a&&(g===null||g.open)&&(!u||c!==null),b=r.returnTo??null,[y,v]=e.useState(Og),x=e.useRef(null),k=e.useRef({runtime:n,userRef:l,scopeEpoch:i});k.current={runtime:n,userRef:l,scopeEpoch:i};let w=e.useRef(f);w.current=f;let C=e.useRef(m);C.current=m;let S=e.useCallback((e,r)=>{if(x.current)return x.current;let n=(e,t)=>(v({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!C.current)return Promise.resolve(n("unavailable",null));let l=t.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=k.current,o=w.current;v(Mg);let a=(async()=>{let a,s={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},d=Object.keys(s).length===0?void 0:s,f=e===void 0?c:e;try{a=await(d===void 0?o.createHandoff(f):o.createHandoff(f,d))}catch{return t.abandon(l.value),n("unknown",null)}let p=k.current;if(p.runtime!==i.runtime||p.userRef!==i.userRef||p.scopeEpoch!==i.scopeEpoch)return t.abandon(l.value),n("cancelled",null);if(!a.ok)return t.abandon(l.value),n(vetVisitErrorReasonOf(a.error),a.error);let h=await t.finish(l.value,a.value);return h!==null?n(h,null):(v(Og),/* @__PURE__ */Object.freeze(a.value.flowId===void 0?{opened:true}:{opened:true,flowId:a.value.flowId}))})().finally(()=>{x.current===a&&(x.current=null)});return x.current=a,a},[t,c,b,u]),j=e.useCallback((e,t)=>{if(!C.current)return v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?c:e,n={...r!==null?{petRef:r}:{},...s!==null?{usState:s}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return Pg(n)===null?(v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(v(Og),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[c,s]),_=e.useCallback(e=>d?S(e,null):j(e,null),[d,S,j]),R=e.useCallback((e,t)=>d?S(void 0,{visitRef:e,intent:t??null}):j(void 0,{visitRef:e,intent:t??null}),[d,S,j]),E=e.useCallback(e=>d?S(void 0,null):j(void 0,{consultId:e.trim()}),[d,S,j]);return{available:m,isPending:o.isPending||(g?.pending??false),status:y.status,error:y.error,errorReason:y.errorReason,open:_,openVisit:R,joinVisit:E}}function $g(e){try{e.closed||e.close()}catch{}}var Dg=/* @__PURE__ */Object.freeze({prepare(){let e=null;try{e=typeof window>"u"?null:window.open("about:blank","_blank")}catch{e=null}if(e===null)return{ok:false,reason:"popupBlocked"};try{e.opener=null}catch{}return{ok:true,value:{tab:e}}},async finish({tab:e},t){if(e.closed)return"cancelled";try{return e.location.replace(t.url),null}catch{return $g(e),"popupBlocked"}},abandon({tab:e}){$g(e)}});function useVetVisit(e){return Ag(Dg,e)}var Bg='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function Ng(e){return e.tagName==="DIALOG"}function Lg(e){if(typeof document>"u")return null;let t=e?.getRootNode();return t&&t!==document&&"activeElement"in t?t.activeElement:document.activeElement}function Ug(t,r,n,l){let i=l?.escapeAtKeyDown===true,o=e.useRef(null),a=e.useRef(false),s=e.useRef(null),u=e.useRef(n);u.current=n;let c=e.useCallback(()=>{if(!a.current)return;a.current=false;let e=u.current===void 0?s.current:u.current.current;e&&e.isConnected&&e.focus(),(!e||!e.isConnected||Lg(e)===e)&&(s.current=null)},[]);e.useEffect(()=>{if(!t){c();return}let e=o.current;if(!a.current){let t=Lg(e);t!==null&&e!==null&&e.contains(t)||(s.current=t instanceof HTMLElement?t:null)}if(a.current=true,e===null)return;if(!Ng(e)){e.contains(Lg(e))||(e.querySelector(Bg)??e).focus();return}let r=e;typeof r.showModal=="function"?r.open||r.showModal():r.setAttribute("open","")},[t,c]),e.useEffect(()=>c,[c]),e.useEffect(()=>{let e=o.current;if(!t||e===null||!Ng(e))return;let r=e;if(typeof r.showModal!="function")return;let n=null,l=e=>{e.target instanceof HTMLElement&&(n=e.target)},i=()=>{if(!r.isConnected||r.open)return;let e=n;r.showModal(),e!==null&&e.isConnected&&r.contains(e)&&Lg(r)!==e&&e.focus()};return r.addEventListener("focusin",l),r.addEventListener("close",i),()=>{r.removeEventListener("focusin",l),r.removeEventListener("close",i)}},[t]);let d=e.useCallback(e=>{let t=o.current;if(t===null)return;if(e.key==="Escape"&&!Ng(t)){e.preventDefault(),e.stopPropagation(),r();return}if(e.key==="Escape"&&i);if(e.key!=="Tab")return;let n=Array.from(t.querySelectorAll(Bg)),l=n[0],a=n[n.length-1];if(!l||!a){e.preventDefault();return}let s=Lg(t);e.shiftKey&&(s===l||!t.contains(s))?(e.preventDefault(),a.focus()):!e.shiftKey&&(s===a||!t.contains(s))&&(e.preventDefault(),l.focus())},[r,i]),f=e.useCallback(e=>{e.target===e.currentTarget&&(e.preventDefault(),r())},[r]);return{dialogRef:o,onKeyDown:d,onCancel:f}}var Hg=/* @__PURE__ */Object.freeze({check:/* @__PURE__ */n.jsx("polyline",{points:"20 6 9 17 4 12"}),copy:/* @__PURE__ */n.jsxs(n.Fragment,{children:[
|