@everfur/sdk 0.22.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -3
- package/dist/chunk-EMINPX6C.js +14 -0
- package/dist/{chunk-FFMIX6HG.js → chunk-NO7LYPKW.js} +1 -1
- package/dist/{chunk-K5NVMNI5.js → chunk-QG4ZH45Q.js} +1 -1
- package/dist/{chunk-ZASVU7CH.js → chunk-VY5VTLFX.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/index.cjs +1 -1
- package/dist/index.js +1 -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/web/health-plan/index.cjs +2 -2
- package/dist/web/health-plan/index.js +1 -1
- package/dist/web/index.cjs +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/records-sheet/index.cjs +1 -1
- package/dist/web/records-sheet/index.js +1 -1
- package/dist/web/shop/index.cjs +1 -1
- package/dist/web/shop/index.js +1 -1
- package/dist/web/televet/booking/index.cjs +2 -2
- package/dist/web/televet/booking/index.js +2 -2
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/ui/index.cjs +1 -1
- package/dist/web/ui/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-AT7SU763.js +0 -14
package/dist/web/index.js
CHANGED
|
@@ -10,7 +10,7 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
|
|
|
10
10
|
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
11
11
|
return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
12
12
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
13
|
-
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending3=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending3.length>0?pending3.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending3=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending3=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=createUtf8Decoder(),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host3="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host3.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host3.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}var SDK_VERSION="0.22.0";var SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
13
|
+
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending3=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending3.length>0?pending3.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending3=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending3=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=createUtf8Decoder(),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host3="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host3.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host3.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}var SDK_VERSION="1.0.0";var SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
14
14
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
|
|
15
15
|
return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
|
|
16
16
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host3){return host3.length===0||host3.includes("@")?false:host3.startsWith("[")&&host3.endsWith("]")?true:!host3.includes(":")}function canEchoOrigin(rawTrimmed,host3){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host3)}function safeOrigin(scheme,host3){return`${scheme}://${host3}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host3=hostOf(match[2]);if(host3.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host3)?`: ${safeOrigin(scheme,host3)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host3)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
|
|
@@ -43,7 +43,7 @@ return Object.freeze(out)}function isEnabled(value){return typeof value=="object
|
|
|
43
43
|
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners3=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners3)listener()};return{subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},getSnapshot(){return snapshot2},set(next){snapshot2=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{},...next.smsProfilePublic!==void 0&&next.smsProfilePublic!==null?{smsProfilePublic:next.smsProfilePublic}:{}}),emit()},reset(opts){snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:opts?.keepBranding===true?snapshot2.branding??null:null,...opts?.keepBranding===true&&snapshot2.smsProfilePublic!==void 0?{smsProfilePublic:snapshot2.smsProfilePublic}:{}}),emit()},setPending(pending3){snapshot2.isPending!==pending3&&(snapshot2=/* @__PURE__ */Object.freeze({...snapshot2,isPending:pending3}),emit())}}}var BRANDING_CACHE_KEY_PREFIX="everfur.branding.v1.";function utf8Bytes(text3){let out=[];for(let ch of text3){let cp=ch.codePointAt(0);cp<128?out.push(cp):cp<2048?out.push(192|cp>>6,128|cp&63):cp<65536?out.push(224|cp>>12,128|cp>>6&63,128|cp&63):out.push(240|cp>>18,128|cp>>12&63,128|cp>>6&63,128|cp&63)}return out}function fnv1a64Hex(text3){let hi=3421674724,lo=2216829733;for(let byte2 of utf8Bytes(text3)){lo=(lo^byte2)>>>0;let loProduct=lo*435,carry=Math.floor(loProduct/4294967296),nextLo=loProduct>>>0;hi=hi*435+carry+lo*256>>>0,lo=nextLo}return hi.toString(16).padStart(8,"0")+lo.toString(16).padStart(8,"0")}function brandingCacheKey(scope){return`${BRANDING_CACHE_KEY_PREFIX}${fnv1a64Hex(scope)}`}function serializeBranding(branding){return branding?JSON.stringify(branding):null}async function readCachedBranding(kv,scope){try{let raw=await kv.getItem(brandingCacheKey(scope));if(raw===null)return null;let parsed=parseClientBranding(JSON.parse(raw));return parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,logoUrl:hardenBrandAssetUrl(parsed.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(parsed.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(parsed.assistantAvatarUrl??null)})}catch{return null}}async function writeCachedBranding(kv,scope,serialized){try{serialized===null?await kv.removeItem(brandingCacheKey(scope)):await kv.setItem(brandingCacheKey(scope),serialized)}catch{}}function createBrandingCache(kv,scope){let lastWritten;return{restore(apply){readCachedBranding(kv,scope).then(branding=>{branding!==null&&apply(branding)})},persist(branding){let serialized=serializeBranding(branding);serialized!==lastWritten&&(lastWritten=serialized,writeCachedBranding(kv,scope,serialized))}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
|
|
44
44
|
return Object.freeze({track(event,props){try{port.track(event,props)}catch{}},trackExpectedFailure(code,props){try{port.trackExpectedFailure(code,props)}catch{}}})}var ENV_HINT=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${ENV_API_BASE_URL} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function reportConfigFailure(failure2,telemetry,platform=SDK_PLATFORM){try{telemetry.trackExpectedFailure("sdk.config.invalid",{reason:failure2.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${failure2.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+ENV_HINT[platform])}function refusingTransport(failure2){/* @__PURE__ */
|
|
45
45
|
return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}var IN_MEMORY_KVS=/* @__PURE__ */new WeakSet;function createInMemoryKv(){let map=/* @__PURE__ */new Map,kv={async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}};return IN_MEMORY_KVS.add(kv),kv}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}if(this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&(reportConfigFailure(failure2,this.telemetry,opts?.platform),this.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store,this.unread=createUnreadStore({read:petRef2=>this.disposed||this.currentUser===null||this.configFailure!==null?null:readConversationHead(this.buildAuth(this.currentUser.userRef),petRef2,this.errorPolicy),emit:event=>this.emit(event)}),failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,fresh4,livemode,smsProfilePublic)=>{this.verdictLanded=true;let painted=this.store.getSnapshot().branding??null,branding=painted!==null&&fresh4!=null&&serializeBranding(painted)===serializeBranding(fresh4)?painted:fresh4;this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{},...smsProfilePublic!==void 0?{smsProfilePublic:smsProfilePublic}:{}}),this.brandingCache?.persist(branding??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2}),unread:this.unread});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending3=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending3!==null&&await pending3,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&¬ifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&¤t.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),cause=>(identity.reportRejected?.(),err(mintFailedError(cause)))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll({keepBranding:true}))}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(opts){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(opts),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,typeProfile=props.seams.typeProfile,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot2.branding??null,theme=useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...typeProfile===void 0?{}:{typeProfile:typeProfile},...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,typeProfile,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment=props.seams.isDevelopment;return useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=useRef(null),lastPropPetRef=useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch,publishableKey:publishableKeyOf(config)}),[runtime,handle,userRefKey,effectivePet,renderTick,configKey]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}function publishableKeyOf(config){return typeof config?.publishableKey=="string"?config.publishableKey.trim():""}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
|
|
46
|
-
return Object.freeze(out)}catch{return[]}}}}var WEB_RUNTIME_ORIGIN="https://sdk.everfur.com",WEB_RUNTIME_PUBLIC_KEYS=/* @__PURE__ */Object.freeze({}),WEB_RUNTIME_PARTS=/* @__PURE__ */Object.freeze(["health-plan","health-plan-today","shop","shop-orders-v2","ui","televet-booking","televet-call"]),WEB_RUNTIME_SUBPATH_PARTS=/* @__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"}),WEB_RUNTIME_MIN_ISSUED_AT=1794548763e3,WEB_RUNTIME_MANIFEST_TIMEOUT_MS=3e3,WEB_RUNTIME_PART_TIMEOUT_MS=8e3,WEB_RUNTIME_MANIFEST_MAX_BYTES=256*1024,WEB_RUNTIME_PART_MAX_BYTES=4*1024*1024,WEB_RUNTIME_FALLBACK_EVENT="web_runtime.fallback";var BRIDGE_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBridge@v${1}`);function bridgeSlot(){let host3=globalThis,existing=host3[BRIDGE_SYMBOL];if(existing!==void 0)return existing;let created={major:1,host:null,defined:/* @__PURE__ */new Map,waiters:/* @__PURE__ */new Map,importSubpath:null};return host3[BRIDGE_SYMBOL]=created,created}function reactMajorOf(version){if(typeof version!="string")return null;let match=/^(\d+)\./.exec(version);return match===null?null:Number(match[1])}function registerWebRuntimeReact(react){let major=reactMajorOf(react.React?.version);if(major===null||typeof react.React.createElement!="function")return null;let slot2=bridgeSlot();return slot2.host===null?(slot2.host={...react,reactMajor:major},{reactMajor:major}):slot2.host.React.createElement===react.React.createElement&&slot2.host.reactMajor===major?{reactMajor:major}:null}function hostReact(){return bridgeSlot().host}var partKey=(part,version)=>`${part}@${version}`;function definedRuntimePart(part,version){return bridgeSlot().defined.get(partKey(part,version))??null}function claimRuntimePart(part,version,integrity){let slot2=bridgeSlot(),ran=slot2.ran??=/* @__PURE__ */new Map,key=partKey(part,version),claimed=ran.get(key);return claimed===void 0?slot2.defined.has(key)?false:(ran.set(key,integrity),true):claimed===integrity}function whenRuntimePartDefined(part,version,timeoutMs){let done=definedRuntimePart(part,version);if(done!==null)return Promise.resolve(done);let slot2=bridgeSlot(),key=partKey(part,version);return new Promise(resolve=>{let waiting=slot2.waiters.get(key)??/* @__PURE__ */new Set;slot2.waiters.set(key,waiting);let settle=ns=>{clearTimeout(timer),waiting.delete(onDefined),resolve(ns)},onDefined=ns=>settle(ns),timer=setTimeout(()=>settle(null),timeoutMs);waiting.add(onDefined)})}function setRuntimeSubpathImporter(importer){bridgeSlot().importSubpath=importer}function webRuntimeIdentity(version,keys){let keySet=Object.keys(keys).sort().map(id=>`${id}=${keys[id]}`).join(",");return`v${1}|${version}|${keySet}`}var WEB_RUNTIME_IDENTITY=webRuntimeIdentity(SDK_VERSION,WEB_RUNTIME_PUBLIC_KEYS);var PAGE_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBundledOnly@v${1}`),host=globalThis,pageBundledOnly=()=>host[PAGE_SYMBOL]===true,latchPageBundledOnly=()=>{host[PAGE_SYMBOL]=true};var VERSION_RE=/^\d{1,4}\.\d{1,5}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,64})?$/,PATH_RE=/^[a-z0-9][a-z0-9.-]{0,80}\.js$/,INTEGRITY_RE=/^sha384-[A-Za-z0-9+/]{64}$/,TENANT_KEY_RE=/^[0-9a-f]{32}$/,B64URL_RE=/^[A-Za-z0-9_-]+$/,isRecord4=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function base64UrlToBytes(text3){if(typeof text3!="string"||text3.length===0||!B64URL_RE.test(text3))return null;let b64=text3.replace(/-/g,"+").replace(/_/g,"/");try{let binary=atob(b64+"=".repeat((4-b64.length%4)%4)),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i+=1)bytes[i]=binary.charCodeAt(i);return bytes}catch{return null}}var ISO_TIME_RE=/^\d{4}(-\d\d){2}T\d\d(:\d\d){2}(\.\d{1,3})?Z$/,MAX_LIFETIME_MS=14*864e5;function parseTime(value){if(typeof value!="string"||!ISO_TIME_RE.test(value))return null;let ms=Date.parse(value);return Number.isFinite(ms)?ms:null}function parseVersionEntry(value){if(!isRecord4(value)||!Array.isArray(value.react)||!isRecord4(value.parts))return null;let react=value.react.filter(m=>Number.isInteger(m)&&m>0);if(react.length===0||react.length!==value.react.length)return null;let parts={};for(let[name,entry]of Object.entries(value.parts))if(WEB_RUNTIME_PARTS.includes(name)){if(!isRecord4(entry)||typeof entry.path!="string"||typeof entry.integrity!="string"||!PATH_RE.test(entry.path)||!INTEGRITY_RE.test(entry.integrity))return null;parts[name]={path:entry.path,integrity:entry.integrity}}return{react:react,parts:parts}}function parseManifestPayload(value){if(!isRecord4(value)||value.schema!==1||!Number.isInteger(value.major))return null;let issuedAt=parseTime(value.issuedAt),expiresAt=parseTime(value.expiresAt);if(issuedAt===null||expiresAt===null||typeof value.stable!="string"||!VERSION_RE.test(value.stable)||expiresAt<=issuedAt||expiresAt-issuedAt>MAX_LIFETIME_MS||!isRecord4(value.versions))return null;let versions={};for(let[version,entry]of Object.entries(value.versions)){let parsed=parseVersionEntry(entry);if(!VERSION_RE.test(version)||parsed===null)return null;versions[version]=parsed}let canary=null;if(value.canary!==void 0&&value.canary!==null){let c=value.canary;if(!isRecord4(c)||typeof c.version!="string"||!VERSION_RE.test(c.version)||typeof c.percent!="number"||!Number.isFinite(c.percent)||c.percent<0||c.percent>100)return null;canary={version:c.version,percent:c.percent}}let pins={};if(value.pins!==void 0){if(!isRecord4(value.pins))return null;for(let[tenant,version]of Object.entries(value.pins)){if(!TENANT_KEY_RE.test(tenant)||typeof version!="string"||!VERSION_RE.test(version))return null;pins[tenant]=version}}let revoked=[];if(value.revoked!==void 0){if(!Array.isArray(value.revoked)||!value.revoked.every(v=>typeof v=="string"&&VERSION_RE.test(v)))return null;revoked=value.revoked}return{schema:1,major:value.major,issuedAt:issuedAt,expiresAt:expiresAt,stable:value.stable,canary:canary,pins:pins,revoked:revoked,versions:versions}}async function verifyManifest(envelope,keys,crypto,now,minIssuedAt=WEB_RUNTIME_MIN_ISSUED_AT){if(!isRecord4(envelope)||envelope.v!==1||typeof envelope.keyId!="string")return{ok:false,reason:"manifest-shape"};let payload=base64UrlToBytes(envelope.payload),signature=base64UrlToBytes(envelope.signature);if(payload===null||signature===null||signature.length!==64)return{ok:false,reason:"manifest-shape"};let raw=Object.prototype.hasOwnProperty.call(keys,envelope.keyId)?base64UrlToBytes(keys[envelope.keyId]):null;if(raw===null||raw.length!==32)return{ok:false,reason:"signature-key"};let valid;try{let key=await crypto.subtle.importKey("raw",raw,{name:"Ed25519"},!1,["verify"]);valid=await crypto.subtle.verify({name:"Ed25519"},key,signature,payload)}catch{return{ok:false,reason:"signature-unsupported"}}if(!valid)return{ok:false,reason:"signature-invalid"};let json;try{json=JSON.parse((new TextDecoder).decode(payload))}catch{return{ok:false,reason:"manifest-shape"}}let manifest=parseManifestPayload(json);return manifest===null?{ok:false,reason:"manifest-shape"}:manifest.major!==1?{ok:false,reason:"manifest-major"}:now>=manifest.expiresAt?{ok:false,reason:"manifest-expired"}:manifest.issuedAt<minIssuedAt?{ok:false,reason:"manifest-stale"}:{ok:true,manifest:manifest}}function compareVersions(a,b){let[coreA="",preA]=a.split(/-(.*)/s,2),[coreB="",preB]=b.split(/-(.*)/s,2),pa=coreA.split(".").map(Number),pb=coreB.split(".").map(Number);for(let i=0;i<3;i+=1){let d=(pa[i]??0)-(pb[i]??0);if(d!==0)return d<0?-1:1}if(preA===preB)return 0;if(preA===void 0)return 1;if(preB===void 0)return-1;let fa=preA.split("."),fb=preB.split(".");for(let i=0;;i+=1){let x=fa[i],y=fb[i];if(x===y)continue;if(x===void 0||y===void 0)return x===void 0?-1:1;let nx=/^\d+$/.test(x),ny=/^\d+$/.test(y);return nx!==ny?nx?-1:1:(nx?Number(x)<Number(y):x<y)?-1:1}}function fnv1a(text3){let hash=2166136261;for(let i=0;i<text3.length;i+=1)hash^=text3.charCodeAt(i),hash=Math.imul(hash,16777619)>>>0;return hash>>>0}function cohortOf(tenantKey,sessionBucket){return fnv1a(`${tenantKey??"-"}:${sessionBucket}`)%100}async function tenantKeyOf(publishableKey,crypto){try{let digest=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(publishableKey));return Array.from(new Uint8Array(digest),b=>b.toString(16).padStart(2,"0")).join("").slice(0,32)}catch{return null}}function chooseVersion(manifest,input){let pin=input.tenantKey===null?void 0:manifest.pins[input.tenantKey],version,reason;if(pin!==void 0?(version=pin,reason="pin"):manifest.canary!==null&&cohortOf(input.tenantKey,input.sessionBucket)<manifest.canary.percent?(version=manifest.canary.version,reason="canary"):(version=manifest.stable,reason="stable"),manifest.revoked.includes(version))return{use:"bundled",reason:"revoked"};if(reason!=="pin"&&compareVersions(version,input.bundledVersion)<0&&!manifest.revoked.includes(input.bundledVersion))return{use:"bundled",reason:"bundled-newer"};let entry=manifest.versions[version];return entry===void 0?{use:"bundled",reason:"version-missing"}:{use:"remote",version:version,entry:entry,reason:reason}}var UNREACHABLE_REASONS=/^manifest-(fetch|timeout)$/,UNREACHABLE_KEY="everfur:web-runtime:unreachable",WEB_RUNTIME_UNREACHABLE_MS=10*6e4;function bytesToBase64(bytes){let binary="";for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}async function fetchBytesWithin(fetcher,url,timeoutMs,maxBytes,cache2="default"){let controller=typeof AbortController=="function"?new AbortController:null,release=null,expire=()=>{},expired=new Promise(resolve=>{expire=resolve}),timer=setTimeout(()=>{expire("timeout"),controller?.abort(),release?.()},timeoutMs),within=step=>Promise.race([step,expired]);try{let response=await within(fetcher(url,{mode:"cors",credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",cache:cache2,...controller?{signal:controller.signal}:{}}));if(response==="timeout")return{ok:!1,why:"timeout"};if(!response.ok)return{ok:!1,why:"http"};let declared=Number(response.headers.get("content-length")??Number.NaN),reader=response.body?.getReader()??null;if(release=()=>{reader!==null&&reader.cancel().catch(()=>{})},Number.isFinite(declared)&&declared>maxBytes)return release(),{ok:!1,why:"too-large"};if(reader===null){let whole=await within(response.arrayBuffer());return whole==="timeout"?{ok:!1,why:"timeout"}:whole.byteLength>maxBytes?{ok:!1,why:"too-large"}:{ok:!0,bytes:new Uint8Array(whole)}}let chunks=[],total=0;for(;;){let next=await within(reader.read());if(next==="timeout")return{ok:!1,why:"timeout"};if(next.done)break;if(total+=next.value.byteLength,total>maxBytes)return release(),{ok:!1,why:"too-large"};chunks.push(next.value)}let bytes=new Uint8Array(total),offset=0;for(let chunk of chunks)bytes.set(chunk,offset),offset+=chunk.byteLength;return{ok:!0,bytes:bytes}}catch{return{ok:false,why:controller?.signal.aborted?"timeout":"error"}}finally{clearTimeout(timer)}}function createWebRuntimeLoader(options){let enabled=options.hasDom&&Object.keys(options.keys).length>0&&options.fetch!==null&&options.crypto!==null,manifestTimeout=options.manifestTimeoutMs??WEB_RUNTIME_MANIFEST_TIMEOUT_MS,partTimeout=options.partTimeoutMs??WEB_RUNTIME_PART_TIMEOUT_MS,manifestMaxBytes=options.manifestMaxBytes??WEB_RUNTIME_MANIFEST_MAX_BYTES,partMaxBytes=options.partMaxBytes??WEB_RUNTIME_PART_MAX_BYTES,base2=`${options.origin}/web-runtime`,manifestPromise=null,choices=/* @__PURE__ */new Map,parts=/* @__PURE__ */new Map,settled=/* @__PURE__ */new Map,hostSubpaths=/* @__PURE__ */new Map,pageTenant=null,cspNonce=null;async function readManifest(){let fetched=await fetchBytesWithin(options.fetch,`${base2}/${1}/manifest.json`,manifestTimeout,manifestMaxBytes,"no-store");if(!fetched.ok){let reason=fetched.why==="timeout"?"manifest-timeout":fetched.why==="too-large"?"manifest-too-large":"manifest-fetch";if(fetched.why==="error"||fetched.why==="timeout")try{options.unreachable?.()?.setItem(UNREACHABLE_KEY,`${options.now()+WEB_RUNTIME_UNREACHABLE_MS}|${reason}`)}catch{}return{ok:false,reason:reason}}let envelope;try{envelope=JSON.parse((new TextDecoder).decode(fetched.bytes))}catch{return{ok:false,reason:"manifest-shape"}}return verifyManifest(envelope,options.keys,options.crypto,options.now(),options.minIssuedAt??WEB_RUNTIME_MIN_ISSUED_AT)}function choose(publishableKey){let memoKey=publishableKey??"",known=choices.get(memoKey);if(known)return known;let started=(async()=>{manifestPromise??=readManifest();let manifest=await manifestPromise;if(!manifest.ok)return{ok:false,reason:manifest.reason};let tenantKey=publishableKey===null?null:await tenantKeyOf(publishableKey,options.crypto),choice=chooseVersion(manifest.manifest,{tenantKey:tenantKey,sessionBucket:options.sessionBucket(),bundledVersion:options.bundledVersion});return choice.use==="remote"?{ok:true,choice:choice}:{ok:false,reason:choice.reason}})();return choices.set(memoKey,started),started}async function runPart(part,publishableKey){if(await Promise.resolve(),pageBundledOnly())return{ok:false,reason:"disabled",version:null};let host3=hostReact();if(host3===null)return{ok:false,reason:"react-unregistered",version:null};let chosen=await choose(publishableKey);if(!chosen.ok)return{ok:false,reason:chosen.reason,version:null};let{version:version,entry:entry}=chosen.choice;if(!entry.react.includes(host3.reactMajor))return{ok:false,reason:"react-mismatch",version:version};let partEntry=entry.parts[part];if(partEntry===void 0)return{ok:false,reason:"part-missing",version:version};if(!claimRuntimePart(part,version,partEntry.integrity))return{ok:false,reason:"part-integrity",version:version};let already=definedRuntimePart(part,version);if(already!==null)return{ok:true,namespace:already,version:version};let url=`${base2}/${version}/${partEntry.path}`;if(pageBundledOnly())return{ok:false,reason:"disabled",version:version};let fetched=await fetchBytesWithin(options.fetch,url,partTimeout,partMaxBytes);if(!fetched.ok)return{ok:false,reason:fetched.why==="timeout"?"part-timeout":fetched.why==="too-large"?"part-too-large":"part-fetch",version:version};let bytes=fetched.bytes,actual;try{actual=`sha384-${bytesToBase64(new Uint8Array(await options.crypto.subtle.digest("SHA-384",bytes)))}`}catch{return{ok:false,reason:"part-integrity",version:version}}if(actual!==partEntry.integrity)return{ok:false,reason:"part-integrity",version:version};if(pageBundledOnly())return{ok:false,reason:"disabled",version:version};let blobUrl=options.createBlobUrl?.(bytes)??null,outcome="error";if(blobUrl!==null&&(outcome=await options.runScript(blobUrl,partEntry.integrity,"blob",cspNonce),options.revokeBlobUrl(blobUrl)),outcome==="error"&&(outcome=await options.runScript(url,partEntry.integrity,"cdn",cspNonce)),outcome==="error")return{ok:false,reason:"part-load",version:version};let namespace=await whenRuntimePartDefined(part,version,50);return namespace===null?{ok:false,reason:"part-load",version:version}:{ok:true,namespace:namespace,version:version}}let off=enabled?null:options.hasDom?"disabled":"server";try{let[until,why]=(options.unreachable?.()?.getItem(UNREACHABLE_KEY)??"").split("|");Number(until)>options.now()&&UNREACHABLE_REASONS.test(String(why))&&(off??=why)}catch{}function load(part,publishableKey){if(off!==null)return Promise.resolve({ok:false,reason:off,version:null});pageTenant??=publishableKey;let memoKey=`${publishableKey??""}|${part}`,known=parts.get(memoKey);if(known)return known;let started=runPart(part,publishableKey).then(result=>result,()=>({ok:false,reason:"part-load",version:null}));return started.then(result=>settled.set(memoKey,result)),parts.set(memoKey,started),started}return enabled&&setRuntimeSubpathImporter(specifier=>{let part=Object.prototype.hasOwnProperty.call(WEB_RUNTIME_SUBPATH_PARTS,specifier)?WEB_RUNTIME_SUBPATH_PARTS[specifier]:void 0,viaHost=()=>{let own2=hostSubpaths.get(specifier);return own2?own2():Promise.reject(new TypeError(`${specifier} is not available to the Everfur web runtime`))};return part===void 0?viaHost():load(part,pageTenant).then(result=>result.ok?result.namespace:viaHost())}),{enabled:enabled,peek:(part,publishableKey)=>off!==null?{ok:false,reason:off,version:null}:settled.get(`${publishableKey??""}|${part}`)??null,load:load,registerHostSubpaths:table=>{for(let[specifier,importer]of Object.entries(table))hostSubpaths.has(specifier)||hostSubpaths.set(specifier,importer)},setCspNonce:nonce=>{cspNonce=nonce===null||nonce===""?null:nonce}}}var BUCKET_KEY="everfur:web-runtime:bucket",memoryBucket=null;function pageSessionBucket(){try{let stored3=globalThis.sessionStorage?.getItem(BUCKET_KEY);if(stored3)return stored3}catch{}memoryBucket??=Math.floor(Math.random()*4294967296).toString(16);try{globalThis.sessionStorage?.setItem(BUCKET_KEY,memoryBucket)}catch{}return memoryBucket}function domScriptRunner(doc){return(src,integrity,kind,nonce)=>new Promise(resolve=>{let script;try{script=doc.createElement("script"),script.type="module",kind==="cdn"&&(script.integrity=integrity,script.crossOrigin="anonymous"),nonce!==null&&(script.nonce=nonce),script.addEventListener("load",()=>{script.remove(),resolve("load")}),script.addEventListener("error",()=>{script.remove(),resolve("error")}),script.src=src,(doc.head??doc.documentElement).appendChild(script)}catch{resolve("error")}})}function pageLoaderOptions(){let doc=typeof document>"u"?null:document,crypto=globalThis.crypto;return{origin:WEB_RUNTIME_ORIGIN,keys:WEB_RUNTIME_PUBLIC_KEYS,bundledVersion:SDK_VERSION,fetch:typeof fetch=="function"?fetch.bind(globalThis):null,crypto:crypto?.subtle?crypto:null,hasDom:doc!==null&&typeof window<"u",runScript:doc===null?()=>Promise.resolve("error"):domScriptRunner(doc),createBlobUrl:typeof Blob=="function"&&typeof URL.createObjectURL=="function"?bytes=>{try{return URL.createObjectURL(new Blob([bytes],{type:"text/javascript"}))}catch{return null}}:null,revokeBlobUrl:url=>{try{URL.revokeObjectURL(url)}catch{}},now:()=>Date.now(),sessionBucket:pageSessionBucket,unreachable:()=>globalThis.sessionStorage}}var LOADER_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeLoader@${WEB_RUNTIME_IDENTITY}`);function webRuntimeLoader(){let slot2=globalThis;return slot2[LOADER_SYMBOL]??=createWebRuntimeLoader(pageLoaderOptions())}var UNREPORTED=/* @__PURE__ */new Set(["disabled","server","bundled-newer"]),reported=/* @__PURE__ */new Set;function report(telemetry,part,reason,version){if(UNREPORTED.has(reason))return;let key=`${part}|${reason}`;if(!reported.has(key)){reported.add(key);try{telemetry?.trackExpectedFailure(WEB_RUNTIME_FALLBACK_EVENT,{part:part,reason:reason,version:version,bundled:SDK_VERSION})}catch{}}}var renderFailed=/* @__PURE__ */new Set,PartBoundary=class extends 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}},lazies=/* @__PURE__ */new Map;function lazyPart(spec,publishableKey,telemetry){let key=`${publishableKey??""}|${spec.part}|${spec.name}`,found=lazies.get(key);return found===void 0&&(found=lazy(async()=>{let result=await webRuntimeLoader().load(spec.part,publishableKey),remote=result.ok?result.namespace[spec.name]:void 0;return result.ok&&typeof remote!="function"&&(typeof remote!="object"||remote===null)?(report(telemetry.current,spec.part,"part-missing",result.version),{default:spec.bundled}):(result.ok||report(telemetry.current,spec.part,result.reason,result.version),{default:result.ok?remote:spec.bundled})}),lazies.set(key,found)),found}var noSubscribe=()=>()=>{},onClient=()=>false,onServer=()=>true;function RuntimeSurface({spec:spec,props:props}){let context=useContext(EverfurContext),bundledOnly=pageBundledOnly(),publishableKey=context?.publishableKey?context.publishableKey:null,telemetry=useRef(null);telemetry.current=context?.runtime.registry?.services?.telemetry??null;let serverPass=useSyncExternalStore(noSubscribe,onClient,onServer),mode=useRef(null),[,settledTick]=useState(0),loader=bundledOnly?null:webRuntimeLoader();if(spec.hostSubpaths!==void 0&&loader?.enabled&&loader.registerHostSubpaths(spec.hostSubpaths),serverPass)mode.current=spec.wait==="bundled"&&loader!==null?"hydrate":"bundled";else if(mode.current===null)if(!loader?.enabled||renderFailed.has(spec.part))mode.current="bundled";else if(registerWebRuntimeReact({React:React,ReactDOM:ReactDOM})===null)report(telemetry.current,spec.part,"react-mismatch",null),mode.current="bundled";else{let known=loader.peek(spec.part,publishableKey);mode.current=known===null?"suspense":known.ok?"direct":"bundled"}let current=mode.current,settled=serverPass||current!=="hydrate"?null:loader?.peek(spec.part,publishableKey)??null,waiting=!serverPass&¤t==="hydrate"&&settled===null&&loader?.enabled===true&&!renderFailed.has(spec.part);useEffect(()=>{if(!waiting||loader===null)return;if(registerWebRuntimeReact({React:React,ReactDOM:ReactDOM})===null){report(telemetry.current,spec.part,"react-mismatch",null);return}let live=true;return loader.load(spec.part,publishableKey).then(result=>{result.ok||report(telemetry.current,spec.part,result.reason,result.version),live&&settledTick(n=>n+1)}),()=>{live=false}},[waiting,loader,spec.part,publishableKey]);let bundled=()=>createElement(spec.bundled,props),guard=child=>createElement(PartBoundary,{fallback:bundled,onError:()=>{renderFailed.add(spec.part),report(telemetry.current,spec.part,"render",null)},children:child});if(serverPass||current==="bundled")return bundled();if(current==="hydrate"||current==="direct"){let known=settled??loader?.peek(spec.part,publishableKey),remote=known?.ok?known.namespace[spec.name]:void 0;return remote===void 0||renderFailed.has(spec.part)?bundled():guard(createElement(remote,props))}let Part=lazyPart(spec,publishableKey,telemetry),fallback=spec.wait==="bundled"?bundled():createElement("div",{"data-everfur-runtime":"loading","aria-busy":true});return guard(createElement(Suspense,{fallback:fallback},createElement(Part,props)))}var RENDERER_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${WEB_RUNTIME_IDENTITY}`),slot=globalThis;function setWebRuntimeRenderer(renderer2,replace=false){renderer2===null?delete slot[RENDERER_SYMBOL]:(replace||slot[RENDERER_SYMBOL]===void 0)&&(slot[RENDERER_SYMBOL]=renderer2)}var Surface=RuntimeSurface,renderer=(spec,props)=>createElement(Surface,{spec:spec,props:props});function installWebRuntime(cspNonce){if(setWebRuntimeRenderer(renderer),cspNonce!==void 0&&cspNonce!==""){let loader=webRuntimeLoader();loader.enabled&&loader.setCspNonce(cspNonce)}}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face2=>(fonts.add(face2),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok3=>(ok3||warnOnce(source,warn),ok3));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES2=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face2 of FACES2){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){let{cspNonce:cspNonce,webRuntime:webRuntime,...core}=props;return webRuntime!==void 0&&webRuntime!=="updates"&&latchPageBundledOnly(),pageBundledOnly()||installWebRuntime(cspNonce),createElement(EverfurProviderCore,{...core,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state3){return Object.is(props.resetKey,state3.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base2=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base2:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
46
|
+
return Object.freeze(out)}catch{return[]}}}}var WEB_RUNTIME_ORIGIN="https://sdk.everfur.com",WEB_RUNTIME_PUBLIC_KEYS=/* @__PURE__ */Object.freeze({k1:"X4wc1hwVONs4I9Vmclo9ExrfPZlH8-tgY7NmzxuA5lI"}),WEB_RUNTIME_PARTS=/* @__PURE__ */Object.freeze(["health-plan","health-plan-today","shop","shop-orders-v2","ui","televet-booking","televet-call"]),WEB_RUNTIME_SUBPATH_PARTS=/* @__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"}),WEB_RUNTIME_MIN_ISSUED_AT=1794582905e3,WEB_RUNTIME_MANIFEST_TIMEOUT_MS=3e3,WEB_RUNTIME_PART_TIMEOUT_MS=8e3,WEB_RUNTIME_MANIFEST_MAX_BYTES=256*1024,WEB_RUNTIME_PART_MAX_BYTES=4*1024*1024,WEB_RUNTIME_FALLBACK_EVENT="web_runtime.fallback";var BRIDGE_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBridge@v${1}`);function bridgeSlot(){let host3=globalThis,existing=host3[BRIDGE_SYMBOL];if(existing!==void 0)return existing;let created={major:1,host:null,defined:/* @__PURE__ */new Map,waiters:/* @__PURE__ */new Map,importSubpath:null};return host3[BRIDGE_SYMBOL]=created,created}function reactMajorOf(version){if(typeof version!="string")return null;let match=/^(\d+)\./.exec(version);return match===null?null:Number(match[1])}function registerWebRuntimeReact(react){let major=reactMajorOf(react.React?.version);if(major===null||typeof react.React.createElement!="function")return null;let slot2=bridgeSlot();return slot2.host===null?(slot2.host={...react,reactMajor:major},{reactMajor:major}):slot2.host.React.createElement===react.React.createElement&&slot2.host.reactMajor===major?{reactMajor:major}:null}function hostReact(){return bridgeSlot().host}var partKey=(part,version)=>`${part}@${version}`;function definedRuntimePart(part,version){return bridgeSlot().defined.get(partKey(part,version))??null}function claimRuntimePart(part,version,integrity){let slot2=bridgeSlot(),ran=slot2.ran??=/* @__PURE__ */new Map,key=partKey(part,version),claimed=ran.get(key);return claimed===void 0?slot2.defined.has(key)?false:(ran.set(key,integrity),true):claimed===integrity}function whenRuntimePartDefined(part,version,timeoutMs){let done=definedRuntimePart(part,version);if(done!==null)return Promise.resolve(done);let slot2=bridgeSlot(),key=partKey(part,version);return new Promise(resolve=>{let waiting=slot2.waiters.get(key)??/* @__PURE__ */new Set;slot2.waiters.set(key,waiting);let settle=ns=>{clearTimeout(timer),waiting.delete(onDefined),resolve(ns)},onDefined=ns=>settle(ns),timer=setTimeout(()=>settle(null),timeoutMs);waiting.add(onDefined)})}function setRuntimeSubpathImporter(importer){bridgeSlot().importSubpath=importer}function webRuntimeIdentity(version,keys){let keySet=Object.keys(keys).sort().map(id=>`${id}=${keys[id]}`).join(",");return`v${1}|${version}|${keySet}`}var WEB_RUNTIME_IDENTITY=webRuntimeIdentity(SDK_VERSION,WEB_RUNTIME_PUBLIC_KEYS);var PAGE_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBundledOnly@v${1}`),host=globalThis,pageBundledOnly=()=>host[PAGE_SYMBOL]===true,latchPageBundledOnly=()=>{host[PAGE_SYMBOL]=true};var VERSION_RE=/^\d{1,4}\.\d{1,5}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,64})?$/,PATH_RE=/^[a-z0-9][a-z0-9.-]{0,80}\.js$/,INTEGRITY_RE=/^sha384-[A-Za-z0-9+/]{64}$/,TENANT_KEY_RE=/^[0-9a-f]{32}$/,B64URL_RE=/^[A-Za-z0-9_-]+$/,isRecord4=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function base64UrlToBytes(text3){if(typeof text3!="string"||text3.length===0||!B64URL_RE.test(text3))return null;let b64=text3.replace(/-/g,"+").replace(/_/g,"/");try{let binary=atob(b64+"=".repeat((4-b64.length%4)%4)),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i+=1)bytes[i]=binary.charCodeAt(i);return bytes}catch{return null}}var ISO_TIME_RE=/^\d{4}(-\d\d){2}T\d\d(:\d\d){2}(\.\d{1,3})?Z$/,MAX_LIFETIME_MS=14*864e5;function parseTime(value){if(typeof value!="string"||!ISO_TIME_RE.test(value))return null;let ms=Date.parse(value);return Number.isFinite(ms)?ms:null}function parseVersionEntry(value){if(!isRecord4(value)||!Array.isArray(value.react)||!isRecord4(value.parts))return null;let react=value.react.filter(m=>Number.isInteger(m)&&m>0);if(react.length===0||react.length!==value.react.length)return null;let parts={};for(let[name,entry]of Object.entries(value.parts))if(WEB_RUNTIME_PARTS.includes(name)){if(!isRecord4(entry)||typeof entry.path!="string"||typeof entry.integrity!="string"||!PATH_RE.test(entry.path)||!INTEGRITY_RE.test(entry.integrity))return null;parts[name]={path:entry.path,integrity:entry.integrity}}return{react:react,parts:parts}}function parseManifestPayload(value){if(!isRecord4(value)||value.schema!==1||!Number.isInteger(value.major))return null;let issuedAt=parseTime(value.issuedAt),expiresAt=parseTime(value.expiresAt);if(issuedAt===null||expiresAt===null||typeof value.stable!="string"||!VERSION_RE.test(value.stable)||expiresAt<=issuedAt||expiresAt-issuedAt>MAX_LIFETIME_MS||!isRecord4(value.versions))return null;let versions={};for(let[version,entry]of Object.entries(value.versions)){let parsed=parseVersionEntry(entry);if(!VERSION_RE.test(version)||parsed===null)return null;versions[version]=parsed}let canary=null;if(value.canary!==void 0&&value.canary!==null){let c=value.canary;if(!isRecord4(c)||typeof c.version!="string"||!VERSION_RE.test(c.version)||typeof c.percent!="number"||!Number.isFinite(c.percent)||c.percent<0||c.percent>100)return null;canary={version:c.version,percent:c.percent}}let pins={};if(value.pins!==void 0){if(!isRecord4(value.pins))return null;for(let[tenant,version]of Object.entries(value.pins)){if(!TENANT_KEY_RE.test(tenant)||typeof version!="string"||!VERSION_RE.test(version))return null;pins[tenant]=version}}let revoked=[];if(value.revoked!==void 0){if(!Array.isArray(value.revoked)||!value.revoked.every(v=>typeof v=="string"&&VERSION_RE.test(v)))return null;revoked=value.revoked}return{schema:1,major:value.major,issuedAt:issuedAt,expiresAt:expiresAt,stable:value.stable,canary:canary,pins:pins,revoked:revoked,versions:versions}}async function verifyManifest(envelope,keys,crypto,now,minIssuedAt=WEB_RUNTIME_MIN_ISSUED_AT){if(!isRecord4(envelope)||envelope.v!==1||typeof envelope.keyId!="string")return{ok:false,reason:"manifest-shape"};let payload=base64UrlToBytes(envelope.payload),signature=base64UrlToBytes(envelope.signature);if(payload===null||signature===null||signature.length!==64)return{ok:false,reason:"manifest-shape"};let raw=Object.prototype.hasOwnProperty.call(keys,envelope.keyId)?base64UrlToBytes(keys[envelope.keyId]):null;if(raw===null||raw.length!==32)return{ok:false,reason:"signature-key"};let valid;try{let key=await crypto.subtle.importKey("raw",raw,{name:"Ed25519"},!1,["verify"]);valid=await crypto.subtle.verify({name:"Ed25519"},key,signature,payload)}catch{return{ok:false,reason:"signature-unsupported"}}if(!valid)return{ok:false,reason:"signature-invalid"};let json;try{json=JSON.parse((new TextDecoder).decode(payload))}catch{return{ok:false,reason:"manifest-shape"}}let manifest=parseManifestPayload(json);return manifest===null?{ok:false,reason:"manifest-shape"}:manifest.major!==1?{ok:false,reason:"manifest-major"}:now>=manifest.expiresAt?{ok:false,reason:"manifest-expired"}:manifest.issuedAt<minIssuedAt?{ok:false,reason:"manifest-stale"}:{ok:true,manifest:manifest}}function compareVersions(a,b){let[coreA="",preA]=a.split(/-(.*)/s,2),[coreB="",preB]=b.split(/-(.*)/s,2),pa=coreA.split(".").map(Number),pb=coreB.split(".").map(Number);for(let i=0;i<3;i+=1){let d=(pa[i]??0)-(pb[i]??0);if(d!==0)return d<0?-1:1}if(preA===preB)return 0;if(preA===void 0)return 1;if(preB===void 0)return-1;let fa=preA.split("."),fb=preB.split(".");for(let i=0;;i+=1){let x=fa[i],y=fb[i];if(x===y)continue;if(x===void 0||y===void 0)return x===void 0?-1:1;let nx=/^\d+$/.test(x),ny=/^\d+$/.test(y);return nx!==ny?nx?-1:1:(nx?Number(x)<Number(y):x<y)?-1:1}}function fnv1a(text3){let hash=2166136261;for(let i=0;i<text3.length;i+=1)hash^=text3.charCodeAt(i),hash=Math.imul(hash,16777619)>>>0;return hash>>>0}function cohortOf(tenantKey,sessionBucket){return fnv1a(`${tenantKey??"-"}:${sessionBucket}`)%100}async function tenantKeyOf(publishableKey,crypto){try{let digest=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(publishableKey));return Array.from(new Uint8Array(digest),b=>b.toString(16).padStart(2,"0")).join("").slice(0,32)}catch{return null}}function chooseVersion(manifest,input){let pin=input.tenantKey===null?void 0:manifest.pins[input.tenantKey],version,reason;if(pin!==void 0?(version=pin,reason="pin"):manifest.canary!==null&&cohortOf(input.tenantKey,input.sessionBucket)<manifest.canary.percent?(version=manifest.canary.version,reason="canary"):(version=manifest.stable,reason="stable"),manifest.revoked.includes(version))return{use:"bundled",reason:"revoked"};if(reason!=="pin"&&compareVersions(version,input.bundledVersion)<0&&!manifest.revoked.includes(input.bundledVersion))return{use:"bundled",reason:"bundled-newer"};let entry=manifest.versions[version];return entry===void 0?{use:"bundled",reason:"version-missing"}:{use:"remote",version:version,entry:entry,reason:reason}}var UNREACHABLE_REASONS=/^manifest-(fetch|timeout)$/,UNREACHABLE_KEY="everfur:web-runtime:unreachable",WEB_RUNTIME_UNREACHABLE_MS=10*6e4;function bytesToBase64(bytes){let binary="";for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}async function fetchBytesWithin(fetcher,url,timeoutMs,maxBytes,cache2="default"){let controller=typeof AbortController=="function"?new AbortController:null,release=null,expire=()=>{},expired=new Promise(resolve=>{expire=resolve}),timer=setTimeout(()=>{expire("timeout"),controller?.abort(),release?.()},timeoutMs),within=step=>Promise.race([step,expired]);try{let response=await within(fetcher(url,{mode:"cors",credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",cache:cache2,...controller?{signal:controller.signal}:{}}));if(response==="timeout")return{ok:!1,why:"timeout"};if(!response.ok)return{ok:!1,why:"http"};let declared=Number(response.headers.get("content-length")??Number.NaN),reader=response.body?.getReader()??null;if(release=()=>{reader!==null&&reader.cancel().catch(()=>{})},Number.isFinite(declared)&&declared>maxBytes)return release(),{ok:!1,why:"too-large"};if(reader===null){let whole=await within(response.arrayBuffer());return whole==="timeout"?{ok:!1,why:"timeout"}:whole.byteLength>maxBytes?{ok:!1,why:"too-large"}:{ok:!0,bytes:new Uint8Array(whole)}}let chunks=[],total=0;for(;;){let next=await within(reader.read());if(next==="timeout")return{ok:!1,why:"timeout"};if(next.done)break;if(total+=next.value.byteLength,total>maxBytes)return release(),{ok:!1,why:"too-large"};chunks.push(next.value)}let bytes=new Uint8Array(total),offset=0;for(let chunk of chunks)bytes.set(chunk,offset),offset+=chunk.byteLength;return{ok:!0,bytes:bytes}}catch{return{ok:false,why:controller?.signal.aborted?"timeout":"error"}}finally{clearTimeout(timer)}}function createWebRuntimeLoader(options){let enabled=options.hasDom&&Object.keys(options.keys).length>0&&options.fetch!==null&&options.crypto!==null,manifestTimeout=options.manifestTimeoutMs??WEB_RUNTIME_MANIFEST_TIMEOUT_MS,partTimeout=options.partTimeoutMs??WEB_RUNTIME_PART_TIMEOUT_MS,manifestMaxBytes=options.manifestMaxBytes??WEB_RUNTIME_MANIFEST_MAX_BYTES,partMaxBytes=options.partMaxBytes??WEB_RUNTIME_PART_MAX_BYTES,base2=`${options.origin}/web-runtime`,manifestPromise=null,choices=/* @__PURE__ */new Map,parts=/* @__PURE__ */new Map,settled=/* @__PURE__ */new Map,hostSubpaths=/* @__PURE__ */new Map,pageTenant=null,cspNonce=null;async function readManifest(){let fetched=await fetchBytesWithin(options.fetch,`${base2}/${1}/manifest.json`,manifestTimeout,manifestMaxBytes,"no-store");if(!fetched.ok){let reason=fetched.why==="timeout"?"manifest-timeout":fetched.why==="too-large"?"manifest-too-large":"manifest-fetch";if(fetched.why==="error"||fetched.why==="timeout")try{options.unreachable?.()?.setItem(UNREACHABLE_KEY,`${options.now()+WEB_RUNTIME_UNREACHABLE_MS}|${reason}`)}catch{}return{ok:false,reason:reason}}let envelope;try{envelope=JSON.parse((new TextDecoder).decode(fetched.bytes))}catch{return{ok:false,reason:"manifest-shape"}}return verifyManifest(envelope,options.keys,options.crypto,options.now(),options.minIssuedAt??WEB_RUNTIME_MIN_ISSUED_AT)}function choose(publishableKey){let memoKey=publishableKey??"",known=choices.get(memoKey);if(known)return known;let started=(async()=>{manifestPromise??=readManifest();let manifest=await manifestPromise;if(!manifest.ok)return{ok:false,reason:manifest.reason};let tenantKey=publishableKey===null?null:await tenantKeyOf(publishableKey,options.crypto),choice=chooseVersion(manifest.manifest,{tenantKey:tenantKey,sessionBucket:options.sessionBucket(),bundledVersion:options.bundledVersion});return choice.use==="remote"?{ok:true,choice:choice}:{ok:false,reason:choice.reason}})();return choices.set(memoKey,started),started}async function runPart(part,publishableKey){if(await Promise.resolve(),pageBundledOnly())return{ok:false,reason:"disabled",version:null};let host3=hostReact();if(host3===null)return{ok:false,reason:"react-unregistered",version:null};let chosen=await choose(publishableKey);if(!chosen.ok)return{ok:false,reason:chosen.reason,version:null};let{version:version,entry:entry}=chosen.choice;if(!entry.react.includes(host3.reactMajor))return{ok:false,reason:"react-mismatch",version:version};let partEntry=entry.parts[part];if(partEntry===void 0)return{ok:false,reason:"part-missing",version:version};if(!claimRuntimePart(part,version,partEntry.integrity))return{ok:false,reason:"part-integrity",version:version};let already=definedRuntimePart(part,version);if(already!==null)return{ok:true,namespace:already,version:version};let url=`${base2}/${version}/${partEntry.path}`;if(pageBundledOnly())return{ok:false,reason:"disabled",version:version};let fetched=await fetchBytesWithin(options.fetch,url,partTimeout,partMaxBytes);if(!fetched.ok)return{ok:false,reason:fetched.why==="timeout"?"part-timeout":fetched.why==="too-large"?"part-too-large":"part-fetch",version:version};let bytes=fetched.bytes,actual;try{actual=`sha384-${bytesToBase64(new Uint8Array(await options.crypto.subtle.digest("SHA-384",bytes)))}`}catch{return{ok:false,reason:"part-integrity",version:version}}if(actual!==partEntry.integrity)return{ok:false,reason:"part-integrity",version:version};if(pageBundledOnly())return{ok:false,reason:"disabled",version:version};let blobUrl=options.createBlobUrl?.(bytes)??null,outcome="error";if(blobUrl!==null&&(outcome=await options.runScript(blobUrl,partEntry.integrity,"blob",cspNonce),options.revokeBlobUrl(blobUrl)),outcome==="error"&&(outcome=await options.runScript(url,partEntry.integrity,"cdn",cspNonce)),outcome==="error")return{ok:false,reason:"part-load",version:version};let namespace=await whenRuntimePartDefined(part,version,50);return namespace===null?{ok:false,reason:"part-load",version:version}:{ok:true,namespace:namespace,version:version}}let off=enabled?null:options.hasDom?"disabled":"server";try{let[until,why]=(options.unreachable?.()?.getItem(UNREACHABLE_KEY)??"").split("|");Number(until)>options.now()&&UNREACHABLE_REASONS.test(String(why))&&(off??=why)}catch{}function load(part,publishableKey){if(off!==null)return Promise.resolve({ok:false,reason:off,version:null});pageTenant??=publishableKey;let memoKey=`${publishableKey??""}|${part}`,known=parts.get(memoKey);if(known)return known;let started=runPart(part,publishableKey).then(result=>result,()=>({ok:false,reason:"part-load",version:null}));return started.then(result=>settled.set(memoKey,result)),parts.set(memoKey,started),started}return enabled&&setRuntimeSubpathImporter(specifier=>{let part=Object.prototype.hasOwnProperty.call(WEB_RUNTIME_SUBPATH_PARTS,specifier)?WEB_RUNTIME_SUBPATH_PARTS[specifier]:void 0,viaHost=()=>{let own2=hostSubpaths.get(specifier);return own2?own2():Promise.reject(new TypeError(`${specifier} is not available to the Everfur web runtime`))};return part===void 0?viaHost():load(part,pageTenant).then(result=>result.ok?result.namespace:viaHost())}),{enabled:enabled,peek:(part,publishableKey)=>off!==null?{ok:false,reason:off,version:null}:settled.get(`${publishableKey??""}|${part}`)??null,load:load,registerHostSubpaths:table=>{for(let[specifier,importer]of Object.entries(table))hostSubpaths.has(specifier)||hostSubpaths.set(specifier,importer)},setCspNonce:nonce=>{cspNonce=nonce===null||nonce===""?null:nonce}}}var BUCKET_KEY="everfur:web-runtime:bucket",memoryBucket=null;function pageSessionBucket(){try{let stored3=globalThis.sessionStorage?.getItem(BUCKET_KEY);if(stored3)return stored3}catch{}memoryBucket??=Math.floor(Math.random()*4294967296).toString(16);try{globalThis.sessionStorage?.setItem(BUCKET_KEY,memoryBucket)}catch{}return memoryBucket}function domScriptRunner(doc){return(src,integrity,kind,nonce)=>new Promise(resolve=>{let script;try{script=doc.createElement("script"),script.type="module",kind==="cdn"&&(script.integrity=integrity,script.crossOrigin="anonymous"),nonce!==null&&(script.nonce=nonce),script.addEventListener("load",()=>{script.remove(),resolve("load")}),script.addEventListener("error",()=>{script.remove(),resolve("error")}),script.src=src,(doc.head??doc.documentElement).appendChild(script)}catch{resolve("error")}})}function pageLoaderOptions(){let doc=typeof document>"u"?null:document,crypto=globalThis.crypto;return{origin:WEB_RUNTIME_ORIGIN,keys:WEB_RUNTIME_PUBLIC_KEYS,bundledVersion:SDK_VERSION,fetch:typeof fetch=="function"?fetch.bind(globalThis):null,crypto:crypto?.subtle?crypto:null,hasDom:doc!==null&&typeof window<"u",runScript:doc===null?()=>Promise.resolve("error"):domScriptRunner(doc),createBlobUrl:typeof Blob=="function"&&typeof URL.createObjectURL=="function"?bytes=>{try{return URL.createObjectURL(new Blob([bytes],{type:"text/javascript"}))}catch{return null}}:null,revokeBlobUrl:url=>{try{URL.revokeObjectURL(url)}catch{}},now:()=>Date.now(),sessionBucket:pageSessionBucket,unreachable:()=>globalThis.sessionStorage}}var LOADER_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeLoader@${WEB_RUNTIME_IDENTITY}`);function webRuntimeLoader(){let slot2=globalThis;return slot2[LOADER_SYMBOL]??=createWebRuntimeLoader(pageLoaderOptions())}var UNREPORTED=/* @__PURE__ */new Set(["disabled","server","bundled-newer"]),reported=/* @__PURE__ */new Set;function report(telemetry,part,reason,version){if(UNREPORTED.has(reason))return;let key=`${part}|${reason}`;if(!reported.has(key)){reported.add(key);try{telemetry?.trackExpectedFailure(WEB_RUNTIME_FALLBACK_EVENT,{part:part,reason:reason,version:version,bundled:SDK_VERSION})}catch{}}}var renderFailed=/* @__PURE__ */new Set,PartBoundary=class extends 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}},lazies=/* @__PURE__ */new Map;function lazyPart(spec,publishableKey,telemetry){let key=`${publishableKey??""}|${spec.part}|${spec.name}`,found=lazies.get(key);return found===void 0&&(found=lazy(async()=>{let result=await webRuntimeLoader().load(spec.part,publishableKey),remote=result.ok?result.namespace[spec.name]:void 0;return result.ok&&typeof remote!="function"&&(typeof remote!="object"||remote===null)?(report(telemetry.current,spec.part,"part-missing",result.version),{default:spec.bundled}):(result.ok||report(telemetry.current,spec.part,result.reason,result.version),{default:result.ok?remote:spec.bundled})}),lazies.set(key,found)),found}var noSubscribe=()=>()=>{},onClient=()=>false,onServer=()=>true;function RuntimeSurface({spec:spec,props:props}){let context=useContext(EverfurContext),bundledOnly=pageBundledOnly(),publishableKey=context?.publishableKey?context.publishableKey:null,telemetry=useRef(null);telemetry.current=context?.runtime.registry?.services?.telemetry??null;let serverPass=useSyncExternalStore(noSubscribe,onClient,onServer),mode=useRef(null),[,settledTick]=useState(0),loader=bundledOnly?null:webRuntimeLoader();if(spec.hostSubpaths!==void 0&&loader?.enabled&&loader.registerHostSubpaths(spec.hostSubpaths),serverPass)mode.current=spec.wait==="bundled"&&loader!==null?"hydrate":"bundled";else if(mode.current===null)if(!loader?.enabled||renderFailed.has(spec.part))mode.current="bundled";else if(registerWebRuntimeReact({React:React,ReactDOM:ReactDOM})===null)report(telemetry.current,spec.part,"react-mismatch",null),mode.current="bundled";else{let known=loader.peek(spec.part,publishableKey);mode.current=known===null?"suspense":known.ok?"direct":"bundled"}let current=mode.current,settled=serverPass||current!=="hydrate"?null:loader?.peek(spec.part,publishableKey)??null,waiting=!serverPass&¤t==="hydrate"&&settled===null&&loader?.enabled===true&&!renderFailed.has(spec.part);useEffect(()=>{if(!waiting||loader===null)return;if(registerWebRuntimeReact({React:React,ReactDOM:ReactDOM})===null){report(telemetry.current,spec.part,"react-mismatch",null);return}let live=true;return loader.load(spec.part,publishableKey).then(result=>{result.ok||report(telemetry.current,spec.part,result.reason,result.version),live&&settledTick(n=>n+1)}),()=>{live=false}},[waiting,loader,spec.part,publishableKey]);let bundled=()=>createElement(spec.bundled,props),guard=child=>createElement(PartBoundary,{fallback:bundled,onError:()=>{renderFailed.add(spec.part),report(telemetry.current,spec.part,"render",null)},children:child});if(serverPass||current==="bundled")return bundled();if(current==="hydrate"||current==="direct"){let known=settled??loader?.peek(spec.part,publishableKey),remote=known?.ok?known.namespace[spec.name]:void 0;return remote===void 0||renderFailed.has(spec.part)?bundled():guard(createElement(remote,props))}let Part=lazyPart(spec,publishableKey,telemetry),fallback=spec.wait==="bundled"?bundled():createElement("div",{"data-everfur-runtime":"loading","aria-busy":true});return guard(createElement(Suspense,{fallback:fallback},createElement(Part,props)))}var RENDERER_SYMBOL=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${WEB_RUNTIME_IDENTITY}`),slot=globalThis;function setWebRuntimeRenderer(renderer2,replace=false){renderer2===null?delete slot[RENDERER_SYMBOL]:(replace||slot[RENDERER_SYMBOL]===void 0)&&(slot[RENDERER_SYMBOL]=renderer2)}var Surface=RuntimeSurface,renderer=(spec,props)=>createElement(Surface,{spec:spec,props:props});function installWebRuntime(cspNonce){if(setWebRuntimeRenderer(renderer),cspNonce!==void 0&&cspNonce!==""){let loader=webRuntimeLoader();loader.enabled&&loader.setCspNonce(cspNonce)}}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face2=>(fonts.add(face2),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok3=>(ok3||warnOnce(source,warn),ok3));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES2=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face2 of FACES2){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){let{cspNonce:cspNonce,webRuntime:webRuntime,...core}=props;return webRuntime!==void 0&&webRuntime!=="updates"&&latchPageBundledOnly(),pageBundledOnly()||installWebRuntime(cspNonce),createElement(EverfurProviderCore,{...core,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state3){return Object.is(props.resetKey,state3.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base2=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base2:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
47
47
|
return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
48
48
|
return jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",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:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
|
|
49
49
|
/* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
return Object.freeze({features:/* @__PURE__ */Object.freeze({...parsed.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE,...photos]),shareAudiences:mapShareAudiences(parsed.data.share_audiences)})}function acceptsPhotos(types){return types!==void 0&&types.some(isPhotoType)}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var NAMELESS_PET="your pet";var capital=text2=>text2.charAt(0).toUpperCase()+text2.slice(1);function pronounForSex(sex){let s=sex?.trim().toLowerCase();return s==="female"?"her":s==="male"?"his":null}function sheetPetWords(name,pronoun){let trimmed=name.trim(),shown=trimmed.length>0?trimmed:NAMELESS_PET,Name=capital(shown);return pronoun==="her"?{name:shown,Name:Name,poss:"her",Poss:"Her",subj:"she"}:pronoun==="his"?{name:shown,Name:Name,poss:"his",Poss:"His",subj:"he"}:{name:shown,Name:Name,poss:`${shown}'s`,Poss:`${Name}'s`,subj:shown}}var SHEET_COPY=/* @__PURE__ */Object.freeze({vitalsFrom:(w,visit,date2)=>`Vitals from ${w.poss} ${visit}, ${date2}`,vitalsSource:w=>`Where ${w.name}'s vitals come from`,temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",upcomingCare:"Upcoming care",overdueBy:date2=>`Overdue · due by ${date2}`,dueSoon:"Due soon",later:"Later",noDate:"No date",dueIn:(date2,days)=>`Due ${date2} · in ${days} ${days===1?"day":"days"}`,dueToday:date2=>`Due ${date2} · today`,overdueByDays:(date2,days)=>`Overdue by ${days} ${days===1?"day":"days"} · due ${date2}`,recordsHistory:"Records & history",labs:"Labs & bloodwork",results:"results",screenings:"Screenings",screeningsClear:"All clear",screeningsToReview:n=>`${n} to review`,noScreenings:"No screenings yet",visits:"Visits & records",timeline:"Timeline",events:n=>`${n} ${n===1?"event":"events"}`,weight:"Weight",vetVisits:n=>`${n} vet ${n===1?"visit":"visits"}`,history:"History",theirClinic:w=>`${w.Poss} clinic`,bloodPanel:"Blood panel",aboveRange:"above range",belowRange:"below range",othersInRange:"Other values in range.",addRecords:w=>`Add ${w.name}'s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",visitsCount:n=>`${n} ${n===1?"visit":"visits"}`,panelsCount:n=>`${n} blood ${n===1?"panel":"panels"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onFileNow:"On file now",firstRecord:w=>`Add ${w.name}'s first record`,firstLead:w=>`Records can come from more than one clinic over a lifetime. Start with the one ${w.subj} sees most, and this page fills in from there.`,requestFromTheirClinic:w=>`Request from ${w.poss} clinic`,requestDetail:"We send a secure request and read every page they send back.",uploadDetail:"A PDF, or a photo of a paper record.",findClinic:w=>`Find ${w.name}'s clinic`,chooseFile:"Choose a file",sayBeats:/* @__PURE__ */Object.freeze(["Hmmm","I wonder","what I may be","hiding"]),sayStill:"I wonder what I may be hiding",sample:"Sample",peekLead:w=>`A sneak peek at how ${w.name}'s records will read. Every number links back to the page it came from.`,sampleNote:w=>`Sample data until ${w.poss} records arrive.`,onTheWay:w=>`${w.Name}'s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",anotherClinic:"Another clinic",anotherClinicDetail:"Seen more than one vet? We ask each one.",noDueDate:"No due date on file",noLabs:w=>`No lab results on file for ${w.name} yet. They show up here when a record includes a blood or urine panel.`,noVisits:w=>`No visits in ${w.name}'s records yet. They show up here when a record includes one.`,oneReading:"One reading so far: we'll plot a trend as more come in.",takingNow:"Taking now",noCurrentMeds:"No current medications on file.",noVetTitle:w=>`When ${w.name} has a vet, start here.`,requestedFrom:clinic=>`Requested from ${clinic}. Clinics usually take 2 to 5 days.`,onTheWayFrom:(w,clinic)=>`${w.Name}'s records from ${clinic} are on the way.`,readingUpload:"We're reading the document you uploaded.",seeWhereItStands:"See where it stands",topRisk:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,panelOn:date2=>`${date2} blood panel`,latestReading:"Latest reading",rangeLine:(low,high,unit)=>`range ${low} to ${high}${unit?` ${unit}`:""}`,noRange:"No range on the report",above:"Above",inRange:"In range",below:"Below",high:"High",belowRangePill:"Below range",changeUp:(delta,unit)=>`Up ${delta}${unit?` ${unit}`:""}`,changeDown:(delta,unit)=>`Down ${delta}${unit?` ${unit}`:""}`,changeSince:(date2,pct)=>` since ${date2}, about ${pct}%.`,whatIs:name=>`What ${name} is`,otherValues:panel=>`Other ${panel} values`,panelTitle:(panel,date2)=>`${panel} · ${date2}`,askAboutThis:"Ask about this"});function sheetSampleKind(species){let s=species?.trim().toLowerCase()??"";return/^(dog|canine|k9|puppy)\b/.test(s)?"dog":/^(cat|feline|kitten)\b/.test(s)?"cat":"other"}var RECORDS_TERMINAL=/* @__PURE__ */Object.freeze(["published","failed","revoked"]);function isTerminalStatus(status){return RECORDS_TERMINAL.includes(status)}var DAY_MS=864e5,DUE_SOON_DAYS=30,LB_PER_KG=2.20462,MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function dayMs(value){if(value==null||value.length===0)return null;let ms=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T00:00:00Z`:value);return Number.isNaN(ms)?null:ms}function shortDate(ms){let d=new Date(ms);return`${MONTHS[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function longDate(ms){return`${shortDate(ms)}, ${new Date(ms).getUTCFullYear()}`}function monthTick(ms){let d=new Date(ms);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}var dayKey=ms=>new Date(ms).toISOString().slice(0,10);function num(value){return String(Math.round(value*100)/100)}var lb=kg=>Math.round(kg*LB_PER_KG*10)/10;function midSentence(text2){let t=text2.trim();return t.length<2||t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)}function vitalKind(text2){return/temp/i.test(text2)?"temp":/heart|pulse/i.test(text2)?"heart":/resp|breath/i.test(text2)?"breath":null}var VITAL_ORDER=["temp","heart","breath"],VITAL_LABEL={temp:SHEET_COPY.temperature,heart:SHEET_COPY.heartRate,breath:SHEET_COPY.breathing};function sheetVitals(record){if(record===null||record.withheld)return{vitals:[],observedMs:null};let best=/* @__PURE__ */new Map;for(let e of record.entities){if(e.category!=="vital"||e.value===null||e.value.trim().length===0)continue;let kind=vitalKind(`${e.canonicalKey??""} ${e.key} ${e.label}`);if(kind===null)continue;let ms=dayMs(e.observedAt)??0,prev=best.get(kind);(prev===void 0||ms>prev.ms)&&best.set(kind,{value:e.value.trim(),unit:e.unit,ms:ms})}let vitals=VITAL_ORDER.flatMap(kind=>{let v=best.get(kind);return v===void 0?[]:[{kind:kind,value:v.value,unit:v.unit,label:VITAL_LABEL[kind]}]}),observed=[...best.values()].map(v=>v.ms).filter(ms=>ms>0);return{vitals:vitals,observedMs:observed.length>0?Math.max(...observed):null}}function encounterOn(encounters,ms){let key=dayKey(ms);return encounters.find(e=>{let at=dayMs(e.date);return at!==null&&dayKey(at)===key})??null}function dueIcon(title){return/vaccin|rabies|dhpp|booster|bordetella|lepto|lyme|parvo|distemper/i.test(title)?"efi-shield":/\b(alt|alp|lab|labs|blood|panel|bloodwork|urinalysis|chemistry|cbc)\b/i.test(title)?"efi-flask-sm":"efi-calendar"}function sheetDue(items,nowMs){return items.map(item=>{let due=dayMs(item.dueAt),icon=dueIcon(item.title);if(due!==null&&due<nowMs-DAY_MS+1)return{item:item,title:item.title,when:SHEET_COPY.overdueBy(shortDate(due)),tone:"alert",pill:null,icon:icon};let when=item.detail??(due===null?SHEET_COPY.noDueDate:longDate(due));if(due===null)return{item:item,title:item.title,when:when,tone:"none",pill:null,icon:icon};let soon=due-nowMs<=DUE_SOON_DAYS*DAY_MS;return{item:item,title:item.title,when:when,tone:soon?"watch":"later",pill:soon?SHEET_COPY.dueSoon:SHEET_COPY.later,icon:icon}})}function pointFlag(status){return status==null?null:/above|high/i.test(status)?"above":/below|low/i.test(status)?"below":/in_range|normal|in range/i.test(status)?"in":null}var kgShown=kg=>Math.round(kg*10)/10;function weightText(kg,unit){let pounds=`${num(lb(kg))} lb`,kilos=`${num(kgShown(kg))} kg`;return unit==="kg"?{main:kilos,other:pounds}:{main:pounds,other:kilos}}function weightModel(timeline,unit){if(timeline===null||timeline.withheld)return null;let readings=timeline.weights.flatMap(w=>{let ms=dayMs(w.observedOn);return ms===null||w.weightKg===null?[]:[{ms:ms,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms),last=readings[readings.length-1];if(last===void 0)return null;let lbs=readings.map(r=>lb(r.kg)),lo=Math.min(...lbs),hi=Math.max(...lbs),t0=readings[0]?.ms??last.ms,span=last.ms-t0,points=readings.map((r,i)=>({x:span>0?Math.round((3.55+93.45*(r.ms-t0)/span)*100)/100:50,y:hi>lo?Math.round((75-50*((lbs[i]??lo)-lo)/(hi-lo))*10)/10:50,lb:lbs[i]??0,value:unit==="kg"?kgShown(r.kg):lbs[i]??0,ms:r.ms})),tickPoints=points.length<=4?points:[points[0],points[points.length-1]].filter(p=>p!==void 0),text2=weightText(last.kg,unit);return{latest:text2.main,sub:`${text2.other} · ${shortDate(last.ms)}`,single:points.length===1,points:points,ticks:tickPoints.map(p=>({x:p.x,label:monthTick(p.ms)})),vetCount:points.length}}function labDays(markers){let days=/* @__PURE__ */new Map;if(markers===null||markers.withheld)return days;for(let marker of markers.markers)for(let point of marker.points){let ms=dayMs(point.at);if(ms===null)continue;let key=dayKey(ms),day=days.get(key)??{ms:ms,flagged:[],total:0,inRange:0,clinics:/* @__PURE__ */new Set};day.total+=1;let flag=pointFlag(point.status);flag==="in"&&(day.inRange+=1),(flag==="above"||flag==="below")&&day.flagged.push({marker:marker,point:point,ms:ms,flag:flag}),point.sourceClinic&&day.clinics.add(point.sourceClinic),days.set(key,day)}return days}function historyModel(inputs,days){let items=[];for(let[key,day]of days)day.flagged.forEach((f,i)=>{let value=f.point.value===null?f.point.qualitativeResult??"":num(f.point.value),unit=f.point.unit??f.marker.unit,others=day.flagged.length===1&&day.inRange===day.total-1&&day.total>1;items.push({key:`lab-${key}-${f.marker.markerId}-${i}`,ms:day.ms,date:`${shortDate(day.ms)} · ${SHEET_COPY.bloodPanel}`,title:`${f.marker.name} ${value}${unit?` ${unit}`:""}, ${f.flag==="above"?SHEET_COPY.aboveRange:SHEET_COPY.belowRange}`,text:others?SHEET_COPY.othersInRange:null,alert:true,markerId:f.marker.markerId,order:0})});let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],visits=inputs.timeline?.withheld===false?inputs.timeline.visits:[],usedVisits=/* @__PURE__ */new Set;encounters.forEach((e,i)=>{let ms=dayMs(e.date);if(ms===null)return;let visit=visits.find(v=>e.docId!==null&&v.docId===e.docId||dayMs(v.visitDate)!==null&&dayKey(dayMs(v.visitDate)??0)===dayKey(ms))??null;visit!==null&&usedVisits.add(visit.visitId);let summary=visit?.summary?.trim()||null,type=e.type?.trim()||null,title=summary??type;title!==null&&items.push({key:`enc-${e.encounterId}-${i}`,ms:ms,date:summary!==null&&type!==null?`${shortDate(ms)} · ${type}`:shortDate(ms),title:title,text:null,alert:false,markerId:null,order:1})});for(let v of visits){let ms=dayMs(v.visitDate),summary=v.summary?.trim()||null;usedVisits.has(v.visitId)||ms===null||summary===null||items.push({key:`visit-${v.visitId}`,ms:ms,date:shortDate(ms),title:summary,text:null,alert:false,markerId:null,order:1})}items.sort((a,b)=>b.ms-a.ms||a.order-b.order);let years=[];for(let entry of items){let item={key:entry.key,ms:entry.ms,date:entry.date,title:entry.title,text:entry.text,alert:entry.alert,markerId:entry.markerId},year=String(new Date(item.ms).getUTCFullYear()),last=years[years.length-1];last!==void 0&&last.year===year?last.items.push(item):years.push({year:year,items:[item]})}return{years:years,count:items.length}}function sourcesModel(inputs,days){let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],clinicLabel=name=>name?.trim()||SHEET_COPY.theirClinic(inputs.words),visits=/* @__PURE__ */new Map;for(let e of encounters)visits.set(clinicLabel(e.clinicName),(visits.get(clinicLabel(e.clinicName))??0)+1);let panels=/* @__PURE__ */new Map,onlyClinic=visits.size===1?[...visits.keys()][0]:void 0;for(let day of days.values()){let names=day.clinics.size>0?[...day.clinics].map(clinicLabel):[onlyClinic??SHEET_COPY.theirClinic(inputs.words)];for(let n of names)panels.set(n,(panels.get(n)??0)+1)}return[.../* @__PURE__ */new Set([...visits.keys(),...panels.keys()])].map(label=>({label:label,detail:[(visits.get(label)??0)>0?SHEET_COPY.visitsCount(visits.get(label)??0):null,(panels.get(label)??0)>0?SHEET_COPY.panelsCount(panels.get(label)??0):null].filter(p=>p!==null).join(" · ")}))}var PULL_PCT={requested:15,awaiting_clinic:35,awaiting_upload:35,received:60,parsing:75,in_review:90};function sheetPull(requests){let open=requests.filter(r=>!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(open===void 0)return null;let step=(open.waitingExpectation?.trim()||open.statusLabel).trim();return step.length===0?null:{step:step,pct:PULL_PCT[open.status]??15}}var newestFirst=requests=>[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0)),sentence=label=>/[.!?]$/.test(label)?label:`${label}.`;function sheetOnTheWay(words2,requests){let active=newestFirst(requests).filter(r=>!isTerminalStatus(r.status)),waiting=active.filter(r=>r.status==="awaiting_upload"),moving=active.filter(r=>r.status!=="awaiting_upload"),lines=[],clinics=/* @__PURE__ */new Map;for(let r of moving){let clinic=r.clinicName?.trim()??"";r.source!=="clinic_request"||clinic===""||clinics.has(clinic)||clinics.set(clinic,r)}for(let[clinic,newest]of clinics)lines.push({key:`clinic-${clinic}`,text:SHEET_COPY.onTheWayFrom(words2,clinic),requestId:newest.id});let upload=moving.find(r=>r.source==="owner_provided");upload!==void 0&&lines.push({key:"upload",text:SHEET_COPY.readingUpload,requestId:upload.id});let wait=waiting[0],label=wait?.statusLabel.trim()??"";return wait!==void 0&&label!==""&&lines.push({key:"awaiting-upload",text:sentence(label),requestId:wait.id}),lines}function sheetRequestedClinic(requests){return newestFirst(requests).find(r=>!isTerminalStatus(r.status)&&r.status!=="awaiting_upload"&&r.source==="clinic_request"&&(r.clinicName?.trim()??"")!=="")?.clinicName?.trim()??null}function sheetMedications(timeline){if(timeline===null||timeline.withheld)return null;let named=timeline.medications.filter(m=>(m.drugName?.trim()??"")!=="");return named.length===0?null:{current:named.filter(m=>(m.stoppedOn?.trim()??"")==="").map(m=>{let parts=[m.dose,m.frequency,m.route].map(p=>p?.trim()??"").filter(p=>p!==""),detail=m.sig?.trim()||(parts.length>0?parts.join(" · "):null);return{key:m.medicationId,name:(m.drugName??"").trim(),detail:detail}})}}function sheetFailedRequest(requests){if(requests.some(r=>!isTerminalStatus(r.status)))return null;let newest=[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(newest===void 0||newest.status!=="failed")return null;let words2=newest.statusLabel.trim();return words2.length>0?words2:null}function sheetHasRecord(record,markers,depth){return record!==null&&!record.withheld&&!record.isEmpty||markers!==null&&!markers.withheld&&markers.markers.length>0?true:depth!==null&&!depth.withheld&&depth.encounters.length>0}function sheetAge(ageYears){if(typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<=0)return null;let totalMonths=Math.floor(ageYears*12+1e-9),years=Math.floor(totalMonths/12),months=totalMonths%12;return years<=0?`${months}M`:months>0?`${years}Y ${months}M`:`${years}Y`}function buildRecordsSheetModel(inputs){let{record:record,depth:depth,markers:markers,nowMs:nowMs}=inputs,has=sheetHasRecord(record,markers,depth),pull=sheetPull(inputs.requests),days=labDays(markers),{vitals:vitals,observedMs:observedMs}=sheetVitals(record),encounters=depth?.withheld===false?depth.encounters:[],visitAt=observedMs===null?null:encounterOn(encounters,observedMs),vitalsFrom=observedMs!==null&&visitAt?.type?SHEET_COPY.vitalsFrom(inputs.words,midSentence(visitAt.type),shortDate(observedMs)):null,unit=inputs.weightUnit??"lb",weight=weightModel(inputs.timeline,unit),latestKg=weight!==null?null:inputs.petWeightKg,meta=[inputs.breed?.trim()||null,sheetAge(inputs.petAgeYears),weight?.latest??(latestKg!==null?weightText(latestKg,unit).main:null)].filter(p=>p!==null),timelineVisits=inputs.timeline?.withheld===false?inputs.timeline.visits.length:0,history=historyModel(inputs,days),encounterDays=encounters.map(e=>dayMs(e.date)).filter(ms=>ms!==null),markerList=markers?.withheld===false?markers.markers:[],featured=markers?.featuredMarkerId??markerList.find(m=>pointFlag(m.latest?.status)==="above"||pointFlag(m.latest?.status)==="below")?.markerId??markerList[0]?.markerId??null;return{state:has?"full":pull!==null?"onTheWay":"none",meta:meta.length>0?meta.join(" · "):null,vitals:vitals,vitalsFrom:vitalsFrom,due:record!==null&&!record.withheld?sheetDue(record.forwardLooking,nowMs):[],labsCount:markers?.withheld===false?markers.summary?.totalMarkers??markers.markers.length:0,featuredMarkerId:featured,latestVisit:encounterDays.length>0?longDate(Math.max(...encounterDays)):null,weight:weight,history:history.years,historyCount:history.count,sources:sourcesModel(inputs,days),pull:pull,hasVisits:encounters.length>0||timelineVisits>0,medications:sheetMedications(inputs.timeline),failedRequest:pull===null?sheetFailedRequest(inputs.requests):null,inFlight:sheetOnTheWay(inputs.words,inputs.requests),requestedClinic:sheetRequestedClinic(inputs.requests)}}function lastPoint(marker){let dated=marker.points.filter(p=>p.value!==null);return dated[dated.length-1]??marker.points[marker.points.length-1]??null}function rangeOf(point){return point===null||point.refLow===null||point.refHigh===null||!Number.isFinite(point.refLow)||!Number.isFinite(point.refHigh)||point.refHigh<=point.refLow?null:{low:point.refLow,high:point.refHigh}}function markerRow(marker,point=lastPoint(marker)){let range=rangeOf(point),unit=point?.unit??marker.unit,value=point?.value??null;return{markerId:marker.markerId,name:marker.name,value:value===null?point?.qualitativeResult??"":num(value),unit:unit,range:range===null?null:`${num(range.low)} to ${num(range.high)}${unit?` ${unit}`:""}`,at:range===null||value===null?null:Math.round(Math.min(100,Math.max(0,20+60*(value-range.low)/(range.high-range.low)))),flag:pointFlag(point?.status??marker.latest?.status??null)}}function flagPill(flag){return flag==="above"?SHEET_COPY.high:flag==="below"?SHEET_COPY.belowRangePill:flag==="in"?SHEET_COPY.inRange:null}var panelWord=panel=>{let name=panel.replace(/\s+panel$/i,"").trim()||panel;return name.length>1&&name[1]===name[1]?.toUpperCase()?name:name.charAt(0).toLowerCase()+name.slice(1)};function buildSheetLabModel(markers,markerId){let marker=markers.markers.find(m=>m.markerId===markerId);if(marker===void 0)return null;let last=lastPoint(marker),row=markerRow(marker,last),lastMs=dayMs(last?.at??marker.latest?.at??null),range=rangeOf(last),latestSub=[lastMs===null?null:shortDate(lastMs),range===null?SHEET_COPY.noRange:SHEET_COPY.rangeLine(num(range.low),num(range.high),row.unit)].filter(p=>p!==null).join(" · "),numeric=marker.points.flatMap(p=>{let ms=dayMs(p.at);return p.value===null||ms===null?[]:[{p:p,ms:ms,v:p.value}]}),chart=[];if(numeric.length>0){let values=numeric.map(n=>n.v),lo=range?.low??Math.min(...values),hi=range?.high??Math.max(...values);chart=numeric.map((n,i)=>({x:numeric.length===1?50:Math.round((18+64*i/(numeric.length-1))*100)/100,y:hi>lo?Math.min(98,Math.max(2,Math.round((75-50*(n.v-lo)/(hi-lo))*10)/10)):50,label:num(n.v),out:pointFlag(n.p.status)==="above"||pointFlag(n.p.status)==="below",tick:shortDate(n.ms)}))}let first=numeric[0],final=numeric[numeric.length-1],change=null;if(first!==void 0&&final!==void 0&&numeric.length>=2&&final.v!==first.v){let delta=Math.abs(final.v-first.v),pct=first.v!==0?Math.round(delta/Math.abs(first.v)*100):null,lead2=final.v>first.v?SHEET_COPY.changeUp(num(delta),row.unit):SHEET_COPY.changeDown(num(delta),row.unit);change=pct===null?null:{lead:lead2,rest:SHEET_COPY.changeSince(shortDate(first.ms),pct)}}let groups=[],lastKey=lastMs===null?null:dayKey(lastMs),others=markers.markers.filter(m=>m.markerId!==marker.markerId),samePanel=others.filter(m=>m.panel!==null&&m.panel===marker.panel);if(samePanel.length>0&&marker.panel!==null){let rows=samePanel.map(m=>markerRow(m));groups.push({title:SHEET_COPY.otherValues(panelWord(marker.panel)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}if(lastKey!==null&&lastMs!==null){let byPanel=/* @__PURE__ */new Map;for(let m of others){if(m.panel===null||m.panel===marker.panel)continue;let p=[...m.points].reverse().find(pt=>{let ms=dayMs(pt.at);return ms!==null&&dayKey(ms)===lastKey});p!==void 0&&byPanel.set(m.panel,[...byPanel.get(m.panel)??[],markerRow(m,p)])}for(let[panel,rows]of byPanel)groups.push({title:SHEET_COPY.panelTitle(panel,shortDate(lastMs)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}return{markerId:marker.markerId,name:marker.name,meta:lastMs===null?null:SHEET_COPY.panelOn(longDate(lastMs)),pill:flagPill(row.flag),flagged:row.flag==="above"||row.flag==="below",latest:`${row.value}${row.unit?` ${row.unit}`:""}`,latestSub:latestSub,hasRange:range!==null,chart:chart,change:change,meaning:(marker.meaning??"").split(/\n\s*\n/).map(p=>p.trim()).filter(p=>p.length>0),groups:groups}}var HEALTH_TAB_SHARED_COPY=/* @__PURE__ */Object.freeze({vitalsFromLabel:pet=>`Where ${pet}’s vitals come from`,vitalsFrom:(vet,date2)=>`From ${vet}’s exam, ${date2}. `,examNotes:"Exam notes",onTheWayFrom:(pet,clinic)=>`${pet}’s records from ${clinic} are on the way.`,readingUpload:"We’re reading the document you uploaded.",uploadFormatHint:"Upload PDF records you already have, up to 25 MB each. You can pick several at once. We'll read them and add the results to your records.",uploadLimitHint:"PDFs up to 25 MB each. You can pick several at once.",results:n=>n===1?"result":"results",noScreenings:"No screenings yet",screeningsToReview:n=>`${n} to review`,screeningsClear:"All clear",noVisits:"No visits yet",oneReading:"One reading so far: we’ll plot a trend as more come in.",uploadedDocument:"Uploaded document"}),MONTHS_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function healthTabDate(ms){let d=new Date(ms);return`${MONTHS_SHORT[d.getUTCMonth()]??""} ${d.getUTCDate()}, ${d.getUTCFullYear()}`}function healthTabScreenings(markers){let W=HEALTH_TAB_SHARED_COPY,screenings=markers.filter(m=>(m.latest?.qualitativeResult??"").trim().length>0);if(screenings.length===0)return null;let flagged=screenings.filter(m=>screeningIsFlagged(m.latest?.status??null,m.latest?.qualitativeResult??"")),first=flagged[0]??screenings[0];return flagged.length>0?{label:W.screeningsToReview(flagged.length),flagged:true,markerId:first.markerId}:{label:W.screeningsClear,flagged:false,markerId:first.markerId}}function screeningIsFlagged(status,resultText){return status==="in_range"?false:status==="above"||status==="below"?true:/negative|not detected|clear|none/i.test(resultText)?false:/positive|detected|present|reactive/i.test(resultText)}function documentClassLabel(value){let spaced=value.replace(/_/g," ").trim();return spaced.length>0?spaced.charAt(0).toUpperCase()+spaced.slice(1):value}function healthTabSources(record,depth){if(record===null||record.withheld)return[];let clinics=/* @__PURE__ */new Map;if(depth!==null&&!depth.withheld)for(let e of depth.encounters){let name=e.clinicName?.trim();e.docId!==null&&name&&clinics.set(e.docId,name)}return Object.values(record.documents).sort((a,b)=>(dayMs(b.receivedAt)??0)-(dayMs(a.receivedAt)??0)).slice(0,4).reverse().map(doc=>{let received=dayMs(doc.receivedAt);return{key:doc.docId,name:clinics.get(doc.docId)??HEALTH_TAB_SHARED_COPY.uploadedDocument,meta:[doc.documentClass?documentClassLabel(doc.documentClass):null,received!==null?healthTabDate(received):null].filter(p=>p!==null).join(" · ")}})}var MONTHS_LONG=["January","February","March","April","May","June","July","August","September","October","November","December"];function examDate(ms){let d=new Date(ms);return`${MONTHS_LONG[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function vitalsExam(depth,observedMs){if(observedMs===null||depth===null||depth.withheld)return null;let day=new Date(observedMs).toISOString().slice(0,10),encounter=depth.encounters.find(e=>{let ms2=dayMs(e.date);return ms2!==null&&new Date(ms2).toISOString().slice(0,10)===day}),vet=encounter?.veterinarian?.trim(),ms=dayMs(encounter?.date);return vet&&ms!==null?{vet:vet,date:examDate(ms)}:null}function healthTabOnTheWay(petName,requests){let W=HEALTH_TAB_SHARED_COPY;return sheetOnTheWay(sheetPetWords(petName,null),requests).map(line=>line.key==="upload"?{...line,text:W.readingUpload}:line.key.startsWith("clinic-")?{...line,text:W.onTheWayFrom(petName,line.key.slice(7))}:line)}var RETRYABILITY_ROWS=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze(RETRYABILITY_ROWS.map(row=>/* @__PURE__ */Object.freeze(row)));/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
5
5
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
6
6
|
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function errorFrame(fields){/* @__PURE__ */
|
|
7
|
-
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var SDK_VERSION="0.
|
|
7
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var SDK_VERSION="1.0.0";function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
8
8
|
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
|
|
9
9
|
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var str2=(value,max=4e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null;function httpsUrl(value){let s=str2(value,2048);return s===null?null:/^https:\/\/[^\s]+$/i.test(s)?s:null}var DETAIL_ROWS=6;function boundOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=400?value:null}function rowsOf(value,each,max){if(!Array.isArray(value))/* @__PURE__ */return Object.freeze([]);let out=[];for(let raw of value){if(out.length>=max)break;if(raw===null||typeof raw!="object"||Array.isArray(raw))continue;let row=each(raw);row!==null&&out.push(row)}/* @__PURE__ */
|
|
10
10
|
return Object.freeze(out)}function titledOf(o){let title=str2(o.title,80),body=str2(o.body,600);return title===null||body===null?null:/* @__PURE__ */Object.freeze({title:title,body:body})}function healthPlanItemDetailOf(value){if(value===null||typeof value!="object"||Array.isArray(value))return;let o=value,gallery=[];if(Array.isArray(o.gallery))for(let g of o.gallery){let url=httpsUrl(g);url!==null&&gallery.length<DETAIL_ROWS&&gallery.push(url)}let doses=rowsOf(o.doses,d=>{let label=str2(d.label,60),amount=str2(d.amount,60);return label===null||amount===null?null:/* @__PURE__ */Object.freeze({label:label,amount:amount,minLb:boundOf(d.minLb??d.min_lb),maxLb:boundOf(d.maxLb??d.max_lb)})},DETAIL_ROWS),details=rowsOf(o.details,titledOf,DETAIL_ROWS),fitRaw=o.fit,fitRow=fitRaw!==null&&typeof fitRaw=="object"&&!Array.isArray(fitRaw)?titledOf(fitRaw):null,fit=fitRow!==null&&fitRaw.pet===true?/* @__PURE__ */Object.freeze({...fitRow,pet:true}):fitRow,detail=/* @__PURE__ */Object.freeze({kicker:str2(o.kicker,80),gallery:/* @__PURE__ */Object.freeze(gallery),doses:doses,details:details,fine:str2(o.fine,300),fit:fit});return detail.kicker===null&&gallery.length===0&&doses.length===0&&details.length===0&&detail.fine===null&&fit===null?void 0:detail}var REF_MAX=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),TONES=/* @__PURE__ */new Set(["y","c","g","r"]),TRACK_STATES=/* @__PURE__ */new Set(["done","now","next"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str3=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str3(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str3(value,REF_MAX);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
|