@everfur/sdk 0.9.3 → 0.11.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 +82 -0
- package/README.md +17 -8
- package/dist/{Chat-Dy1L27a8.d.ts → Chat-CPW5ehw-.d.ts} +3 -3
- package/dist/{Chat-Bkv-MLLu.d.cts → Chat-qAuYAzFN.d.cts} +3 -3
- package/dist/{DepthViews-CBalhef3.d.cts → DepthViews-BpzrZ9UP.d.cts} +1 -1
- package/dist/{DepthViews-eRdy2ayE.d.cts → DepthViews-CAtWjn-B.d.cts} +1 -1
- package/dist/{DepthViews-De6yb5Tq.d.ts → DepthViews-CkahN4Y5.d.ts} +1 -1
- package/dist/{DepthViews-BwyzpEyX.d.ts → DepthViews-Dq0g7VtA.d.ts} +1 -1
- package/dist/animations/index.cjs +4 -2
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/animations/index.js +4 -2
- package/dist/{attachments-BAcQdIz7.d.ts → attachments-37PYsEhe.d.ts} +5 -5
- package/dist/{attachments-tPWJ0DJI.d.cts → attachments-BZ8W4vcl.d.cts} +5 -5
- package/dist/{attachments-Brt7ivEo.d.ts → attachments-DGlHsBbQ.d.ts} +2 -2
- package/dist/{attachments-DhGAelCA.d.cts → attachments-xhie8PDh.d.cts} +2 -2
- package/dist/{bookingCopy-CJLAgEgK.d.ts → bookingCopy-CS3QZma_.d.ts} +2 -2
- package/dist/{bookingCopy-Ds2JGcPE.d.cts → bookingCopy-DDHuE_sf.d.cts} +2 -2
- package/dist/{casesRepository-DjhMfm_n.d.ts → casesRepository-CgpSKb2U.d.ts} +1 -1
- package/dist/{casesRepository-D0aQSXkb.d.cts → casesRepository-DNK5gHlI.d.cts} +1 -1
- package/dist/chat/index.cjs +10 -8
- package/dist/chat/index.d.cts +9 -9
- package/dist/chat/index.d.ts +9 -9
- package/dist/chat/index.js +10 -8
- package/dist/client/index.cjs +5 -3
- package/dist/client/index.d.cts +7 -7
- package/dist/client/index.d.ts +7 -7
- package/dist/client/index.js +5 -3
- package/dist/{config-DeUmccwl.d.ts → config-Cp9Zo6xK.d.ts} +1 -1
- package/dist/{config-C68HTCf4.d.cts → config-DJHqL-U3.d.cts} +1 -1
- package/dist/consent/index.cjs +4 -2
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/consent/index.js +4 -2
- package/dist/{context-D_2sCvoo.d.ts → context-CHGBKxFG.d.ts} +13 -5
- package/dist/{context-DY9pcjdK.d.cts → context-C_3Em1sq.d.cts} +13 -5
- package/dist/{copy-wAnv8ldC.d.ts → copy-CaslsF6f.d.ts} +2 -2
- package/dist/{copy-tYW0C83H.d.cts → copy-Fbdk6p43.d.cts} +2 -2
- package/dist/core/index.cjs +9 -8
- package/dist/core/index.d.cts +12 -12
- package/dist/core/index.d.ts +12 -12
- package/dist/core/index.js +9 -8
- package/dist/{depth-C7RIscDR.d.ts → depth-DwS8HfHo.d.ts} +2 -2
- package/dist/{depth-jbSWsweM.d.cts → depth-DxqHB-Xi.d.cts} +2 -2
- package/dist/{entitlementRepository-Ccc6K6wB.d.cts → entitlementRepository-Do9RzJ8e.d.cts} +2 -2
- package/dist/{entitlementRepository-D7Fc7OdG.d.ts → entitlementRepository-DosFNBqA.d.ts} +2 -2
- package/dist/{identity-BTT6YtH5.d.ts → identity-5Jc-BTMj.d.ts} +8 -2
- package/dist/{identity-ScajqjK5.d.cts → identity-VHQ_4xWJ.d.cts} +8 -2
- package/dist/index.cjs +10 -9
- package/dist/index.d.cts +15 -14
- package/dist/index.d.ts +15 -14
- package/dist/index.js +10 -9
- package/dist/notifications/index.cjs +4 -2
- package/dist/notifications/index.d.cts +2 -2
- package/dist/notifications/index.d.ts +2 -2
- package/dist/notifications/index.js +4 -2
- package/dist/{pets-uKMldfz0.d.cts → pets-DiBD6Xds.d.cts} +1 -1
- package/dist/{pets-CqeoV1Jv.d.ts → pets-wh2Kb7z8.d.ts} +1 -1
- package/dist/{petsRepository-BdfbY9Oe.d.ts → petsRepository-DzvGKxqu.d.ts} +1 -1
- package/dist/{petsRepository-BYe7_MUo.d.cts → petsRepository-NivC5Xzk.d.cts} +1 -1
- package/dist/photo/index.cjs +4 -2
- package/dist/photo/index.js +4 -2
- package/dist/{ports-D4FQKTBS.d.ts → ports-BoPJsZIH.d.ts} +6 -4
- package/dist/{ports-okLpXkpu.d.cts → ports-CLWTzmGi.d.cts} +6 -4
- package/dist/records/depth/index.cjs +6 -4
- package/dist/records/depth/index.d.cts +7 -7
- package/dist/records/depth/index.d.ts +7 -7
- package/dist/records/depth/index.js +6 -4
- package/dist/records/index.cjs +10 -8
- package/dist/records/index.d.cts +9 -9
- package/dist/records/index.d.ts +9 -9
- package/dist/records/index.js +10 -8
- package/dist/{requestFunnel-u8qnM5Ll.d.cts → requestFunnel-B8lodGM0.d.cts} +2 -2
- package/dist/{requestFunnel-Dhaj0yUq.d.ts → requestFunnel-CybT6svX.d.ts} +2 -2
- package/dist/{runtimeTypes-C67itXfp.d.cts → runtimeTypes-BCgI1pA_.d.cts} +29 -5
- package/dist/{runtimeTypes-BFes64Vp.d.ts → runtimeTypes-TqeLgyFl.d.ts} +29 -5
- package/dist/server/events/index.cjs +4 -2
- package/dist/server/events/index.d.cts +25 -6
- package/dist/server/events/index.d.ts +25 -6
- package/dist/server/events/index.js +4 -2
- package/dist/server/index.cjs +6 -4
- package/dist/server/index.d.cts +5 -4
- package/dist/server/index.d.ts +5 -4
- package/dist/server/index.js +6 -4
- package/dist/televet/booking/index.cjs +21 -16
- package/dist/televet/booking/index.d.cts +6 -6
- package/dist/televet/booking/index.d.ts +6 -6
- package/dist/televet/booking/index.js +22 -17
- package/dist/televet/index.cjs +4 -2
- package/dist/televet/index.js +4 -2
- package/dist/testing/index.cjs +3 -1
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +3 -1
- package/dist/testing/rn/index.cjs +4 -2
- package/dist/testing/rn/index.d.cts +7 -7
- package/dist/testing/rn/index.d.ts +7 -7
- package/dist/testing/rn/index.js +4 -2
- package/dist/testing/web/index.cjs +4 -2
- package/dist/testing/web/index.d.cts +7 -7
- package/dist/testing/web/index.d.ts +7 -7
- package/dist/testing/web/index.js +4 -2
- package/dist/{timelineRows-CDSO3ElK.d.cts → timelineRows-B-dwSEbF.d.cts} +1 -1
- package/dist/{timelineRows-pd4wYVbe.d.ts → timelineRows-KniW4F-u.d.ts} +1 -1
- package/dist/{useRecordsDepth-CqSMkcyR.d.ts → useRecordsDepth-C1ooUNq4.d.ts} +1 -1
- package/dist/{useRecordsDepth-W3UAKQRN.d.cts → useRecordsDepth-CRC3tIAW.d.cts} +1 -1
- package/dist/video/index.cjs +4 -2
- package/dist/video/index.js +4 -2
- package/dist/{view-CKfIaJYp.d.ts → view-DkPxUatd.d.ts} +2 -2
- package/dist/{view-h7RPJAEe.d.cts → view-qFBv8ZoE.d.cts} +2 -2
- package/dist/web/consent/index.cjs +4 -2
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/consent/index.js +4 -2
- package/dist/web/index.cjs +10 -9
- package/dist/web/index.d.cts +17 -16
- package/dist/web/index.d.ts +17 -16
- package/dist/web/index.js +10 -9
- package/dist/web/notifications/index.cjs +4 -2
- package/dist/web/notifications/index.d.cts +3 -3
- package/dist/web/notifications/index.d.ts +3 -3
- package/dist/web/notifications/index.js +4 -2
- package/dist/web/records/depth/index.cjs +6 -4
- package/dist/web/records/depth/index.d.cts +7 -7
- package/dist/web/records/depth/index.d.ts +7 -7
- package/dist/web/records/depth/index.js +6 -4
- package/dist/web/records/index.cjs +14 -12
- package/dist/web/records/index.d.cts +9 -9
- package/dist/web/records/index.d.ts +9 -9
- package/dist/web/records/index.js +14 -12
- package/dist/web/televet/booking/index.cjs +7 -5
- package/dist/web/televet/booking/index.d.cts +6 -6
- package/dist/web/televet/booking/index.d.ts +6 -6
- package/dist/web/televet/booking/index.js +7 -5
- package/dist/web/televet/index.cjs +4 -2
- package/dist/web/televet/index.js +4 -2
- package/package.json +1 -1
|
@@ -68,6 +68,7 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
|
|
|
68
68
|
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
69
69
|
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
70
70
|
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
71
72
|
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
72
73
|
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
73
74
|
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
@@ -79,6 +80,7 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
|
|
|
79
80
|
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
80
81
|
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
81
82
|
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
82
84
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
83
85
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
84
86
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
@@ -87,8 +89,8 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
|
|
|
87
89
|
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
88
90
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
89
91
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
90
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function errorFrame(fields){/* @__PURE__ */
|
|
91
|
-
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 authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}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,base=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({...base,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(
|
|
92
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function errorFrame(fields){/* @__PURE__ */
|
|
93
|
+
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 authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}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,base=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({...base,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(
|
|
92
94
|
/* @__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__ */
|
|
93
95
|
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 at2=findResetsAt(error.raw);if(at2!==null){let delta=at2-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 wireCodeOf(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}function foldWireReason(error,table){let wire=wireCodeOf(error);if(wire===null)return error;let fold=table[wire];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:wire,reasonCode:wire,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}var NOTIFICATIONS_REASON_MESSAGES=/* @__PURE__ */Object.freeze({provider_unsupported:"Everfur does not send through this push provider yet. Register an Expo push token (provider expo) or an FCM registration token (provider fcm); APNs direct is not available in this version.",token_invalid:"The token is not a push token of the given provider. Expo tokens look like ExponentPushToken[...]; FCM registration tokens are long opaque strings. Pass the token exactly as your notification library printed it.",device_cipher_unavailable:"Everfur could not seal the token at rest, so nothing was stored. Retry the registration later; the SDK retries it on the next launch and login.",credentials_missing:"Everfur holds no push credential for this provider on your tenant, so deliveries to it are skipped. Expo needs nothing unless you enabled push security (then your Expo access token). A bare app using FCM supplies its Firebase service-account JSON to Everfur; push credentials are set by Everfur on your tenant, never through the SDK."}),REASONS=/* @__PURE__ */new Set(["provider_unsupported","token_invalid","device_cipher_unavailable","credentials_missing"]);function explainNotificationsReason(error){let reason=error.reasonCode;return reason!==void 0&&REASONS.has(reason)?NOTIFICATIONS_REASON_MESSAGES[reason]:null}var PROVIDERS=/* @__PURE__ */new Set(["expo","fcm","apns"]),PLATFORMS=/* @__PURE__ */new Set(["ios","android"]),TOKEN_MAX=4096,INSTALLATION_ID_MAX=128,DEVICE_ID_MAX=64,CONTROL_OR_SPACE=/[\0- ]/;function invalid(wireMessage,reasonCode){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage,...reasonCode?{reasonCode:reasonCode}:{}})}function validateRegister(input){if(typeof input!="object"||input===null)return invalid("registerDevice needs an input object");let{token:token,provider:provider,platform:platform,installationId:installationId}=input;return typeof provider!="string"||!PROVIDERS.has(provider)?invalid("provider must be expo, fcm or apns"):typeof platform!="string"||!PLATFORMS.has(platform)?invalid("platform must be ios or android"):typeof token!="string"||token.trim().length===0||token.length>TOKEN_MAX||CONTROL_OR_SPACE.test(token)?invalid(`token must be a push token of 1..${TOKEN_MAX} characters with no whitespace`,"token_invalid"):installationId!==void 0&&(typeof installationId!="string"||installationId.length===0||installationId.length>INSTALLATION_ID_MAX)?invalid(`installationId must be 1..${INSTALLATION_ID_MAX} characters`):null}function validateDeviceId(deviceId){return typeof deviceId!="string"||deviceId.length===0||deviceId.length>DEVICE_ID_MAX?invalid(`deviceId must be 1..${DEVICE_ID_MAX} characters`):CONTROL_OR_SPACE.test(deviceId)||deviceId.includes("/")||deviceId==="."||deviceId===".."?invalid("deviceId is not a device id"):null}function validatePreferences(input){if(typeof input!="object"||input===null)return invalid("setPreferences needs an input object");let{pushEnabled:pushEnabled,emailEnabled:emailEnabled}=input;return typeof pushEnabled!="boolean"||typeof emailEnabled!="boolean"?invalid("pushEnabled and emailEnabled must both be booleans: the route replaces both switches"):null}function str(value){return typeof value=="string"&&value.length>0?value:null}function parseDevice(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,deviceId=str(o.device_id),provider=str(o.provider),platform=str(o.platform),registeredAt=str(o.registered_at),lastSeenAt=str(o.last_seen_at);if(deviceId===null||provider===null||platform===null||registeredAt===null||lastSeenAt===null||!PROVIDERS.has(provider)||!PLATFORMS.has(platform))return null;let installation=o.installation_id;/* @__PURE__ */
|
|
94
96
|
return Object.freeze({deviceId:deviceId,provider:provider,platform:platform,installationId:typeof installation=="string"&&installation.length>0?installation:null,registeredAt:registeredAt,lastSeenAt:lastSeenAt})}function parsePreferences(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,updatedAt=str(o.updated_at);return typeof o.push_enabled!="boolean"||typeof o.email_enabled!="boolean"||updatedAt===null?null:/* @__PURE__ */Object.freeze({pushEnabled:o.push_enabled,emailEnabled:o.email_enabled,updatedAt:updatedAt})}function malformed(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}var ROUTE_REASONS=/* @__PURE__ */Object.freeze({provider_unsupported:{code:"validationFailed",retryable:false},token_invalid:{code:"validationFailed",retryable:false},device_cipher_unavailable:{code:"serviceUnavailable",retryable:true}});function refine(error){return foldWireReason(error,ROUTE_REASONS)}function disposed(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function createNotificationsClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createNotificationsClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{registerDevice:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("registerDevice"))):over().registerDevice(input,opts),unregisterDevice:(deviceId,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("unregisterDevice"))):over().unregisterDevice(deviceId,opts),setPreferences:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("setPreferences"))):over().setPreferences(input,opts)}}function createNotificationsClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),withSignal=(req,signal)=>signal?{...req,signal:signal}:req;return{async registerDevice(input,opts){let bad=validateRegister(input);if(bad!==null)return err(bad);let body={token:input.token,provider:input.provider,platform:input.platform};input.installationId!==void 0&&(body.installation_id=input.installationId);let res=await funnel.send("notifications.registerDevice",withSignal({method:"POST",path:"/widget/v1/me/devices",body:body},opts?.signal));if(!res.ok)return err(refine(res.error));let device=parseDevice(res.value);return device===null?err(malformed("registerDevice")):ok(device)},async unregisterDevice(deviceId,opts){let bad=validateDeviceId(deviceId);if(bad!==null)return err(bad);let res=await funnel.send("notifications.unregisterDevice",withSignal({method:"DELETE",path:`/widget/v1/me/devices/${encodeURIComponent(deviceId)}`},opts?.signal));return res.ok?ok(void 0):err(refine(res.error))},async setPreferences(input,opts){let bad=validatePreferences(input);if(bad!==null)return err(bad);let res=await funnel.send("notifications.setPreferences",withSignal({method:"PUT",path:"/widget/v1/me/notification-preferences",body:{push_enabled:input.pushEnabled,email_enabled:input.emailEnabled}},opts?.signal));if(!res.ok)return err(refine(res.error));let preferences=parsePreferences(res.value);return preferences===null?err(malformed("setPreferences")):ok(preferences)}}}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3;var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var STORED_VERSION=1;async function readStored(kv){try{let raw=await kv.getItem(NOTIFICATIONS_DEVICE_KV_KEY);if(raw===null)return null;let parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null)return null;let{v:v,userRef:userRef,deviceId:deviceId}=parsed;return v!==STORED_VERSION||typeof userRef!="string"||typeof deviceId!="string"||deviceId.length===0?null:{userRef:userRef,deviceId:deviceId}}catch{return null}}async function writeStored(kv,entry){try{await kv.setItem(NOTIFICATIONS_DEVICE_KV_KEY,JSON.stringify({v:STORED_VERSION,...entry}))}catch{}}async function clearStored(kv){try{await kv.removeItem(NOTIFICATIONS_DEVICE_KV_KEY)}catch{}}var SIGNED_OUT=/* @__PURE__ */Object.freeze({status:"signed_out",device:null,error:null}),NO_TOKEN=/* @__PURE__ */Object.freeze({status:"no_token",device:null,error:null});function noUser(){return makeEverfurError("sessionRequired",{retryable:false,wireMessage:"notifications need a signed-in user on the provider"})}function useEverfurNotificationsClient(){let{runtime:runtime}=useEverfurContext();return react.useMemo(()=>createNotificationsClient(runtime),[runtime])}function useEverfurNotifications(options){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{token:token,provider:provider,platform:platform,installationId:installationId}=options,kv=runtime.registry.services.kv,client=useEverfurNotificationsClient(),[settled,setSettled]=react.useState(userRef===null?SIGNED_OUT:NO_TOKEN),knownRef=react.useRef(null),generation=react.useRef(0);react.useEffect(()=>{if(generation.current+=1,knownRef.current=null,setSettled(userRef===null?SIGNED_OUT:NO_TOKEN),userRef===null)return;let live=true;return readStored(kv).then(stored=>{if(!live||stored===null||stored.userRef!==userRef)return;let known=knownRef.current;if(known===null){knownRef.current=stored;return}known.deviceId!==stored.deviceId&&client.unregisterDevice(stored.deviceId)}),()=>{live=false}},[client,kv,userRef]);let registerFor=react.useCallback(async(user,current)=>{let gen=generation.current+=1;setSettled({status:"registering",device:null,error:null});let result=await client.registerDevice({token:current,provider:provider,platform:platform,...installationId===void 0?{}:{installationId:installationId}});if(gen!==generation.current)return result;if(!result.ok)return setSettled({status:result.error.httpStatus===404?"unavailable":"failed",device:null,error:result.error}),result;let previous=knownRef.current;return knownRef.current={userRef:user,deviceId:result.value.deviceId},setSettled({status:"registered",device:result.value,error:null}),await writeStored(kv,knownRef.current),previous!==null&&previous.userRef===user&&previous.deviceId!==result.value.deviceId&&client.unregisterDevice(previous.deviceId),result},[client,kv,provider,platform,installationId]);react.useEffect(()=>{userRef===null||token===null||registerFor(userRef,token)},[registerFor,userRef,token]),react.useEffect(()=>runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==leaving)return;knownRef.current=null;let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}}),result=await createNotificationsClientOver({auth:auth,funnel:funnel}).unregisterDevice(known.deviceId);(result.ok||result.error.httpStatus===404)&&await clearStored(kv)}),[runtime,kv]);let register=react.useCallback(async()=>userRef===null?err(noUser()):token===null?err(makeEverfurError("validationFailed",{retryable:false,reasonCode:"token_invalid",wireMessage:"no push token was given"})):registerFor(userRef,token),[registerFor,userRef,token]),unregister=react.useCallback(async()=>{if(userRef===null)return err(noUser());let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==userRef)return ok(void 0);let gen=generation.current+=1,result=await client.unregisterDevice(known.deviceId);return result.ok||result.error.httpStatus===404?(knownRef.current=null,await clearStored(kv),gen===generation.current&&setSettled({status:"unregistered",device:null,error:null}),result.ok?result:ok(void 0)):result},[client,kv,userRef]),setPreferences=react.useCallback(input=>userRef===null?Promise.resolve(err(noUser())):client.setPreferences(input),[client,userRef]);return react.useMemo(()=>({status:settled.status,device:settled.device,error:settled.error,register:register,unregister:unregister,setPreferences:setPreferences}),[settled,register,unregister,setPreferences])}function useEverfurNotifications2(options){let state=useEverfurNotifications(options),{status:status,error:error,register:register}=state,retryable=status==="failed"&&error!==null&&error.retryable;return react.useEffect(()=>{if(!retryable)return;let subscription=reactNative.AppState.addEventListener("change",next=>{next==="active"&®ister()});return()=>{subscription.remove()}},[retryable,register]),state}var INTENT_BY_VISIT_EVENT=/* @__PURE__ */Object.freeze({"visit.booked":"visit","visit.reminder":"join","visit.rescheduled":"visit","visit.followup_sent":"messages","visit.message_received":"messages","visit.completed":"summary","visit.ended":"visit","visit.cancelled":null,"visit.no_show":null});function vetVisitIntentForEvent(eventType){return Object.prototype.hasOwnProperty.call(INTENT_BY_VISIT_EVENT,eventType)?INTENT_BY_VISIT_EVENT[eventType]:"visit"}var EVERFUR_NOTIFICATION_VERSION=1,EVERFUR_NOTIFICATION_TARGET_KINDS=/* @__PURE__ */Object.freeze(["record_request","pet","visit","case"]),EVERFUR_NOTIFICATION_EVENT_TYPES=/* @__PURE__ */Object.freeze(["record_request.updated","record.ready","pet.vaccination.due","visit.booked","visit.cancelled","visit.completed","visit.no_show","visit.rescheduled","visit.reminder","visit.followup_sent","visit.message_received","visit.ended","chat.follow_up_due","chat.reminder_due","record.activation"]),TOP_KEYS=["v","event_id","event_type","target"],TARGET_KEYS=/* @__PURE__ */new Set(["kind","conversation_id","request_id","visit_ref","case_ref","pet_ref"]),EVENT_TYPES=new Set(EVERFUR_NOTIFICATION_EVENT_TYPES),KINDS=new Set(EVERFUR_NOTIFICATION_TARGET_KINDS),MAX_VALUE_LENGTH=128,MAX_ENCODED_LENGTH=4096,EVENT_ID=/^evt_[A-Za-z0-9]{1,64}$/,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,CONTROL_CHAR=/[\0-]/;function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function keysOf(value){return Object.keys(value)}function decodeBlock(raw){if(isRecord2(raw))return raw;if(typeof raw!="string"||raw.length===0||raw.length>MAX_ENCODED_LENGTH)return null;let decoded=JSON.parse(raw);return isRecord2(decoded)?decoded:null}function at(root,path){let current=root;for(let key of path){if(!isRecord2(current))return;current=current[key]}return current}var DATA_PATHS=[[],["data"],["request","content","data"],["notification","request","content","data"]];function locateBlock(payload){if(!isRecord2(payload))return null;for(let path of DATA_PATHS){let map=at(payload,path);if(isRecord2(map)&&"everfur"in map)return map.everfur}return TOP_KEYS.every(key=>key in payload)?payload:null}function opaqueString(value){return typeof value!="string"||value.length===0||value.length>MAX_VALUE_LENGTH||CONTROL_CHAR.test(value)||value.includes("://")||value.toLowerCase().startsWith("everfur")?null:value}function optional(target,key){if(!(key in target))return{ok:true,value:null};let value=opaqueString(target[key]);return value===null?{ok:false}:{ok:true,value:value}}function required(target,key){return key in target?opaqueString(target[key]):null}function parseTarget(raw,eventType){if(!isRecord2(raw))return null;let keys=keysOf(raw);if(!keys.includes("kind")||keys.some(key=>!TARGET_KEYS.has(key)))return null;let kind=raw.kind;if(typeof kind!="string"||!KINDS.has(kind))return null;for(let key of keys)if(key!=="kind"&&opaqueString(raw[key])===null)return null;let pet=optional(raw,"pet_ref");if(!pet.ok)return null;let petRef=pet.value;switch(kind){case"record_request":{let requestId=required(raw,"request_id");return requestId===null?null:/* @__PURE__ */Object.freeze({kind:"record_request",requestId:requestId,petRef:petRef})}case"pet":return petRef===null?null:/* @__PURE__ */Object.freeze({kind:"pet",petRef:petRef});case"visit":{let visitRef=required(raw,"visit_ref");return visitRef===null?null:/* @__PURE__ */Object.freeze({kind:"visit",visitRef:visitRef,petRef:petRef,intent:vetVisitIntentForEvent(eventType)})}case"case":{let caseRef=required(raw,"case_ref");if(caseRef===null)return null;let conversation=optional(raw,"conversation_id");return!conversation.ok||conversation.value!==null&&!UUID.test(conversation.value)?null:/* @__PURE__ */Object.freeze({kind:"case",caseRef:caseRef,conversationId:conversation.value,petRef:petRef})}default:return null}}function parseBlock(block){let keys=keysOf(block);if(keys.length!==TOP_KEYS.length||TOP_KEYS.some(key=>!keys.includes(key))||block.v!==EVERFUR_NOTIFICATION_VERSION)return null;let eventId=block.event_id;if(typeof eventId!="string"||!EVENT_ID.test(eventId))return null;let eventType=block.event_type;if(typeof eventType!="string"||!EVENT_TYPES.has(eventType))return null;let target=parseTarget(block.target,eventType);return target===null?null:/* @__PURE__ */Object.freeze({eventId:eventId,eventType:eventType,target:target})}function parseEverfurNotification(payload){try{let block=decodeBlock(locateBlock(payload));return block===null?null:parseBlock(block)}catch{return null}}exports.EVERFUR_NOTIFICATION_EVENT_TYPES=EVERFUR_NOTIFICATION_EVENT_TYPES;exports.EVERFUR_NOTIFICATION_TARGET_KINDS=EVERFUR_NOTIFICATION_TARGET_KINDS;exports.EVERFUR_NOTIFICATION_VERSION=EVERFUR_NOTIFICATION_VERSION;exports.NOTIFICATIONS_REASON_MESSAGES=NOTIFICATIONS_REASON_MESSAGES;exports.createNotificationsClient=createNotificationsClient;exports.explainNotificationsReason=explainNotificationsReason;exports.parseEverfurNotification=parseEverfurNotification;exports.useEverfurNotifications=useEverfurNotifications2;exports.useEverfurNotificationsClient=useEverfurNotificationsClient;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { EverfurNotificationsOptions, EverfurNotificationsState } from '../web/notifications/index.cjs';
|
|
2
2
|
export { DevicePlatform, EVERFUR_NOTIFICATION_EVENT_TYPES, EVERFUR_NOTIFICATION_TARGET_KINDS, EVERFUR_NOTIFICATION_VERSION, EverfurNotification, EverfurNotificationEventType, EverfurNotificationTarget, EverfurNotificationTargetKind, EverfurNotificationsStatus, NOTIFICATIONS_REASON_MESSAGES, NotificationPreferences, NotificationPreferencesInput, NotificationsClient, NotificationsReasonCode, NotificationsRuntime, PushProvider, RegisterDeviceInput, RegisteredDevice, createNotificationsClient, explainNotificationsReason, parseEverfurNotification, useEverfurNotificationsClient } from '../web/notifications/index.cjs';
|
|
3
3
|
export { V as VetVisitIntent } from '../visitIntent-D7_yVp1I.cjs';
|
|
4
|
-
export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity-
|
|
5
|
-
export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config-
|
|
4
|
+
export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity-VHQ_4xWJ.cjs';
|
|
5
|
+
export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config-DJHqL-U3.cjs';
|
|
6
6
|
export { B as Brand, C as ConversationId, P as PetRef, R as RecordsRequestId, U as UserRef, _ as __brand } from '../ids-B2GAAifq.cjs';
|
|
7
7
|
export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../EverfurError-DeBqRpQV.cjs';
|
|
8
8
|
export { E as EverfurResult } from '../EverfurResult-COlXj1wq.cjs';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { EverfurNotificationsOptions, EverfurNotificationsState } from '../web/notifications/index.js';
|
|
2
2
|
export { DevicePlatform, EVERFUR_NOTIFICATION_EVENT_TYPES, EVERFUR_NOTIFICATION_TARGET_KINDS, EVERFUR_NOTIFICATION_VERSION, EverfurNotification, EverfurNotificationEventType, EverfurNotificationTarget, EverfurNotificationTargetKind, EverfurNotificationsStatus, NOTIFICATIONS_REASON_MESSAGES, NotificationPreferences, NotificationPreferencesInput, NotificationsClient, NotificationsReasonCode, NotificationsRuntime, PushProvider, RegisterDeviceInput, RegisteredDevice, createNotificationsClient, explainNotificationsReason, parseEverfurNotification, useEverfurNotificationsClient } from '../web/notifications/index.js';
|
|
3
3
|
export { V as VetVisitIntent } from '../visitIntent-D7_yVp1I.js';
|
|
4
|
-
export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity-
|
|
5
|
-
export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config-
|
|
4
|
+
export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity-5Jc-BTMj.js';
|
|
5
|
+
export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config-Cp9Zo6xK.js';
|
|
6
6
|
export { B as Brand, C as ConversationId, P as PetRef, R as RecordsRequestId, U as UserRef, _ as __brand } from '../ids-B2GAAifq.js';
|
|
7
7
|
export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../EverfurError-DeBqRpQV.js';
|
|
8
8
|
export { E as EverfurResult } from '../EverfurResult-ClPTS0P2.js';
|
|
@@ -68,6 +68,7 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
|
|
|
68
68
|
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
69
69
|
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
70
70
|
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
71
72
|
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
72
73
|
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
73
74
|
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
@@ -79,6 +80,7 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
|
|
|
79
80
|
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
80
81
|
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
81
82
|
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
82
84
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
83
85
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
84
86
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
@@ -87,8 +89,8 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
|
|
|
87
89
|
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
88
90
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
89
91
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
90
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function errorFrame(fields){/* @__PURE__ */
|
|
91
|
-
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 authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}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,base=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({...base,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(
|
|
92
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function errorFrame(fields){/* @__PURE__ */
|
|
93
|
+
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 authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}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,base=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({...base,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(
|
|
92
94
|
/* @__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__ */
|
|
93
95
|
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 at2=findResetsAt(error.raw);if(at2!==null){let delta=at2-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 wireCodeOf(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}function foldWireReason(error,table){let wire=wireCodeOf(error);if(wire===null)return error;let fold=table[wire];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:wire,reasonCode:wire,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}var NOTIFICATIONS_REASON_MESSAGES=/* @__PURE__ */Object.freeze({provider_unsupported:"Everfur does not send through this push provider yet. Register an Expo push token (provider expo) or an FCM registration token (provider fcm); APNs direct is not available in this version.",token_invalid:"The token is not a push token of the given provider. Expo tokens look like ExponentPushToken[...]; FCM registration tokens are long opaque strings. Pass the token exactly as your notification library printed it.",device_cipher_unavailable:"Everfur could not seal the token at rest, so nothing was stored. Retry the registration later; the SDK retries it on the next launch and login.",credentials_missing:"Everfur holds no push credential for this provider on your tenant, so deliveries to it are skipped. Expo needs nothing unless you enabled push security (then your Expo access token). A bare app using FCM supplies its Firebase service-account JSON to Everfur; push credentials are set by Everfur on your tenant, never through the SDK."}),REASONS=/* @__PURE__ */new Set(["provider_unsupported","token_invalid","device_cipher_unavailable","credentials_missing"]);function explainNotificationsReason(error){let reason=error.reasonCode;return reason!==void 0&&REASONS.has(reason)?NOTIFICATIONS_REASON_MESSAGES[reason]:null}var PROVIDERS=/* @__PURE__ */new Set(["expo","fcm","apns"]),PLATFORMS=/* @__PURE__ */new Set(["ios","android"]),TOKEN_MAX=4096,INSTALLATION_ID_MAX=128,DEVICE_ID_MAX=64,CONTROL_OR_SPACE=/[\0- ]/;function invalid(wireMessage,reasonCode){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage,...reasonCode?{reasonCode:reasonCode}:{}})}function validateRegister(input){if(typeof input!="object"||input===null)return invalid("registerDevice needs an input object");let{token:token,provider:provider,platform:platform,installationId:installationId}=input;return typeof provider!="string"||!PROVIDERS.has(provider)?invalid("provider must be expo, fcm or apns"):typeof platform!="string"||!PLATFORMS.has(platform)?invalid("platform must be ios or android"):typeof token!="string"||token.trim().length===0||token.length>TOKEN_MAX||CONTROL_OR_SPACE.test(token)?invalid(`token must be a push token of 1..${TOKEN_MAX} characters with no whitespace`,"token_invalid"):installationId!==void 0&&(typeof installationId!="string"||installationId.length===0||installationId.length>INSTALLATION_ID_MAX)?invalid(`installationId must be 1..${INSTALLATION_ID_MAX} characters`):null}function validateDeviceId(deviceId){return typeof deviceId!="string"||deviceId.length===0||deviceId.length>DEVICE_ID_MAX?invalid(`deviceId must be 1..${DEVICE_ID_MAX} characters`):CONTROL_OR_SPACE.test(deviceId)||deviceId.includes("/")||deviceId==="."||deviceId===".."?invalid("deviceId is not a device id"):null}function validatePreferences(input){if(typeof input!="object"||input===null)return invalid("setPreferences needs an input object");let{pushEnabled:pushEnabled,emailEnabled:emailEnabled}=input;return typeof pushEnabled!="boolean"||typeof emailEnabled!="boolean"?invalid("pushEnabled and emailEnabled must both be booleans: the route replaces both switches"):null}function str(value){return typeof value=="string"&&value.length>0?value:null}function parseDevice(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,deviceId=str(o.device_id),provider=str(o.provider),platform=str(o.platform),registeredAt=str(o.registered_at),lastSeenAt=str(o.last_seen_at);if(deviceId===null||provider===null||platform===null||registeredAt===null||lastSeenAt===null||!PROVIDERS.has(provider)||!PLATFORMS.has(platform))return null;let installation=o.installation_id;/* @__PURE__ */
|
|
94
96
|
return Object.freeze({deviceId:deviceId,provider:provider,platform:platform,installationId:typeof installation=="string"&&installation.length>0?installation:null,registeredAt:registeredAt,lastSeenAt:lastSeenAt})}function parsePreferences(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,updatedAt=str(o.updated_at);return typeof o.push_enabled!="boolean"||typeof o.email_enabled!="boolean"||updatedAt===null?null:/* @__PURE__ */Object.freeze({pushEnabled:o.push_enabled,emailEnabled:o.email_enabled,updatedAt:updatedAt})}function malformed(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}var ROUTE_REASONS=/* @__PURE__ */Object.freeze({provider_unsupported:{code:"validationFailed",retryable:false},token_invalid:{code:"validationFailed",retryable:false},device_cipher_unavailable:{code:"serviceUnavailable",retryable:true}});function refine(error){return foldWireReason(error,ROUTE_REASONS)}function disposed(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function createNotificationsClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createNotificationsClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{registerDevice:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("registerDevice"))):over().registerDevice(input,opts),unregisterDevice:(deviceId,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("unregisterDevice"))):over().unregisterDevice(deviceId,opts),setPreferences:(input,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("setPreferences"))):over().setPreferences(input,opts)}}function createNotificationsClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),withSignal=(req,signal)=>signal?{...req,signal:signal}:req;return{async registerDevice(input,opts){let bad=validateRegister(input);if(bad!==null)return err(bad);let body={token:input.token,provider:input.provider,platform:input.platform};input.installationId!==void 0&&(body.installation_id=input.installationId);let res=await funnel.send("notifications.registerDevice",withSignal({method:"POST",path:"/widget/v1/me/devices",body:body},opts?.signal));if(!res.ok)return err(refine(res.error));let device=parseDevice(res.value);return device===null?err(malformed("registerDevice")):ok(device)},async unregisterDevice(deviceId,opts){let bad=validateDeviceId(deviceId);if(bad!==null)return err(bad);let res=await funnel.send("notifications.unregisterDevice",withSignal({method:"DELETE",path:`/widget/v1/me/devices/${encodeURIComponent(deviceId)}`},opts?.signal));return res.ok?ok(void 0):err(refine(res.error))},async setPreferences(input,opts){let bad=validatePreferences(input);if(bad!==null)return err(bad);let res=await funnel.send("notifications.setPreferences",withSignal({method:"PUT",path:"/widget/v1/me/notification-preferences",body:{push_enabled:input.pushEnabled,email_enabled:input.emailEnabled}},opts?.signal));if(!res.ok)return err(refine(res.error));let preferences=parsePreferences(res.value);return preferences===null?err(malformed("setPreferences")):ok(preferences)}}}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3;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}var STORED_VERSION=1;async function readStored(kv){try{let raw=await kv.getItem(NOTIFICATIONS_DEVICE_KV_KEY);if(raw===null)return null;let parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null)return null;let{v:v,userRef:userRef,deviceId:deviceId}=parsed;return v!==STORED_VERSION||typeof userRef!="string"||typeof deviceId!="string"||deviceId.length===0?null:{userRef:userRef,deviceId:deviceId}}catch{return null}}async function writeStored(kv,entry){try{await kv.setItem(NOTIFICATIONS_DEVICE_KV_KEY,JSON.stringify({v:STORED_VERSION,...entry}))}catch{}}async function clearStored(kv){try{await kv.removeItem(NOTIFICATIONS_DEVICE_KV_KEY)}catch{}}var SIGNED_OUT=/* @__PURE__ */Object.freeze({status:"signed_out",device:null,error:null}),NO_TOKEN=/* @__PURE__ */Object.freeze({status:"no_token",device:null,error:null});function noUser(){return makeEverfurError("sessionRequired",{retryable:false,wireMessage:"notifications need a signed-in user on the provider"})}function useEverfurNotificationsClient(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createNotificationsClient(runtime),[runtime])}function useEverfurNotifications(options){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{token:token,provider:provider,platform:platform,installationId:installationId}=options,kv=runtime.registry.services.kv,client=useEverfurNotificationsClient(),[settled,setSettled]=useState(userRef===null?SIGNED_OUT:NO_TOKEN),knownRef=useRef(null),generation=useRef(0);useEffect(()=>{if(generation.current+=1,knownRef.current=null,setSettled(userRef===null?SIGNED_OUT:NO_TOKEN),userRef===null)return;let live=true;return readStored(kv).then(stored=>{if(!live||stored===null||stored.userRef!==userRef)return;let known=knownRef.current;if(known===null){knownRef.current=stored;return}known.deviceId!==stored.deviceId&&client.unregisterDevice(stored.deviceId)}),()=>{live=false}},[client,kv,userRef]);let registerFor=useCallback(async(user,current)=>{let gen=generation.current+=1;setSettled({status:"registering",device:null,error:null});let result=await client.registerDevice({token:current,provider:provider,platform:platform,...installationId===void 0?{}:{installationId:installationId}});if(gen!==generation.current)return result;if(!result.ok)return setSettled({status:result.error.httpStatus===404?"unavailable":"failed",device:null,error:result.error}),result;let previous=knownRef.current;return knownRef.current={userRef:user,deviceId:result.value.deviceId},setSettled({status:"registered",device:result.value,error:null}),await writeStored(kv,knownRef.current),previous!==null&&previous.userRef===user&&previous.deviceId!==result.value.deviceId&&client.unregisterDevice(previous.deviceId),result},[client,kv,provider,platform,installationId]);useEffect(()=>{userRef===null||token===null||registerFor(userRef,token)},[registerFor,userRef,token]),useEffect(()=>runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==leaving)return;knownRef.current=null;let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}}),result=await createNotificationsClientOver({auth:auth,funnel:funnel}).unregisterDevice(known.deviceId);(result.ok||result.error.httpStatus===404)&&await clearStored(kv)}),[runtime,kv]);let register=useCallback(async()=>userRef===null?err(noUser()):token===null?err(makeEverfurError("validationFailed",{retryable:false,reasonCode:"token_invalid",wireMessage:"no push token was given"})):registerFor(userRef,token),[registerFor,userRef,token]),unregister=useCallback(async()=>{if(userRef===null)return err(noUser());let known=knownRef.current??await readStored(kv);if(known===null||known.userRef!==userRef)return ok(void 0);let gen=generation.current+=1,result=await client.unregisterDevice(known.deviceId);return result.ok||result.error.httpStatus===404?(knownRef.current=null,await clearStored(kv),gen===generation.current&&setSettled({status:"unregistered",device:null,error:null}),result.ok?result:ok(void 0)):result},[client,kv,userRef]),setPreferences=useCallback(input=>userRef===null?Promise.resolve(err(noUser())):client.setPreferences(input),[client,userRef]);return useMemo(()=>({status:settled.status,device:settled.device,error:settled.error,register:register,unregister:unregister,setPreferences:setPreferences}),[settled,register,unregister,setPreferences])}function useEverfurNotifications2(options){let state=useEverfurNotifications(options),{status:status,error:error,register:register}=state,retryable=status==="failed"&&error!==null&&error.retryable;return useEffect(()=>{if(!retryable)return;let subscription=AppState.addEventListener("change",next=>{next==="active"&®ister()});return()=>{subscription.remove()}},[retryable,register]),state}var INTENT_BY_VISIT_EVENT=/* @__PURE__ */Object.freeze({"visit.booked":"visit","visit.reminder":"join","visit.rescheduled":"visit","visit.followup_sent":"messages","visit.message_received":"messages","visit.completed":"summary","visit.ended":"visit","visit.cancelled":null,"visit.no_show":null});function vetVisitIntentForEvent(eventType){return Object.prototype.hasOwnProperty.call(INTENT_BY_VISIT_EVENT,eventType)?INTENT_BY_VISIT_EVENT[eventType]:"visit"}var EVERFUR_NOTIFICATION_VERSION=1,EVERFUR_NOTIFICATION_TARGET_KINDS=/* @__PURE__ */Object.freeze(["record_request","pet","visit","case"]),EVERFUR_NOTIFICATION_EVENT_TYPES=/* @__PURE__ */Object.freeze(["record_request.updated","record.ready","pet.vaccination.due","visit.booked","visit.cancelled","visit.completed","visit.no_show","visit.rescheduled","visit.reminder","visit.followup_sent","visit.message_received","visit.ended","chat.follow_up_due","chat.reminder_due","record.activation"]),TOP_KEYS=["v","event_id","event_type","target"],TARGET_KEYS=/* @__PURE__ */new Set(["kind","conversation_id","request_id","visit_ref","case_ref","pet_ref"]),EVENT_TYPES=new Set(EVERFUR_NOTIFICATION_EVENT_TYPES),KINDS=new Set(EVERFUR_NOTIFICATION_TARGET_KINDS),MAX_VALUE_LENGTH=128,MAX_ENCODED_LENGTH=4096,EVENT_ID=/^evt_[A-Za-z0-9]{1,64}$/,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,CONTROL_CHAR=/[\0-]/;function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function keysOf(value){return Object.keys(value)}function decodeBlock(raw){if(isRecord2(raw))return raw;if(typeof raw!="string"||raw.length===0||raw.length>MAX_ENCODED_LENGTH)return null;let decoded=JSON.parse(raw);return isRecord2(decoded)?decoded:null}function at(root,path){let current=root;for(let key of path){if(!isRecord2(current))return;current=current[key]}return current}var DATA_PATHS=[[],["data"],["request","content","data"],["notification","request","content","data"]];function locateBlock(payload){if(!isRecord2(payload))return null;for(let path of DATA_PATHS){let map=at(payload,path);if(isRecord2(map)&&"everfur"in map)return map.everfur}return TOP_KEYS.every(key=>key in payload)?payload:null}function opaqueString(value){return typeof value!="string"||value.length===0||value.length>MAX_VALUE_LENGTH||CONTROL_CHAR.test(value)||value.includes("://")||value.toLowerCase().startsWith("everfur")?null:value}function optional(target,key){if(!(key in target))return{ok:true,value:null};let value=opaqueString(target[key]);return value===null?{ok:false}:{ok:true,value:value}}function required(target,key){return key in target?opaqueString(target[key]):null}function parseTarget(raw,eventType){if(!isRecord2(raw))return null;let keys=keysOf(raw);if(!keys.includes("kind")||keys.some(key=>!TARGET_KEYS.has(key)))return null;let kind=raw.kind;if(typeof kind!="string"||!KINDS.has(kind))return null;for(let key of keys)if(key!=="kind"&&opaqueString(raw[key])===null)return null;let pet=optional(raw,"pet_ref");if(!pet.ok)return null;let petRef=pet.value;switch(kind){case"record_request":{let requestId=required(raw,"request_id");return requestId===null?null:/* @__PURE__ */Object.freeze({kind:"record_request",requestId:requestId,petRef:petRef})}case"pet":return petRef===null?null:/* @__PURE__ */Object.freeze({kind:"pet",petRef:petRef});case"visit":{let visitRef=required(raw,"visit_ref");return visitRef===null?null:/* @__PURE__ */Object.freeze({kind:"visit",visitRef:visitRef,petRef:petRef,intent:vetVisitIntentForEvent(eventType)})}case"case":{let caseRef=required(raw,"case_ref");if(caseRef===null)return null;let conversation=optional(raw,"conversation_id");return!conversation.ok||conversation.value!==null&&!UUID.test(conversation.value)?null:/* @__PURE__ */Object.freeze({kind:"case",caseRef:caseRef,conversationId:conversation.value,petRef:petRef})}default:return null}}function parseBlock(block){let keys=keysOf(block);if(keys.length!==TOP_KEYS.length||TOP_KEYS.some(key=>!keys.includes(key))||block.v!==EVERFUR_NOTIFICATION_VERSION)return null;let eventId=block.event_id;if(typeof eventId!="string"||!EVENT_ID.test(eventId))return null;let eventType=block.event_type;if(typeof eventType!="string"||!EVENT_TYPES.has(eventType))return null;let target=parseTarget(block.target,eventType);return target===null?null:/* @__PURE__ */Object.freeze({eventId:eventId,eventType:eventType,target:target})}function parseEverfurNotification(payload){try{let block=decodeBlock(locateBlock(payload));return block===null?null:parseBlock(block)}catch{return null}}export{EVERFUR_NOTIFICATION_EVENT_TYPES,EVERFUR_NOTIFICATION_TARGET_KINDS,EVERFUR_NOTIFICATION_VERSION,NOTIFICATIONS_REASON_MESSAGES,createNotificationsClient,explainNotificationsReason,parseEverfurNotification,useEverfurNotifications2 as useEverfurNotifications,useEverfurNotificationsClient};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EverfurResult } from './EverfurResult-COlXj1wq.cjs';
|
|
2
|
-
import { j as FetchLike } from './config-
|
|
2
|
+
import { j as FetchLike } from './config-DJHqL-U3.cjs';
|
|
3
3
|
import { P as PetHealthProfileInput, a as PetHealthProfile } from './profile-CSs1wlXT.cjs';
|
|
4
4
|
|
|
5
5
|
/** How your backend reaches Everfur for pet writes. Build it once and reuse it. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EverfurResult } from './EverfurResult-ClPTS0P2.js';
|
|
2
|
-
import { j as FetchLike } from './config-
|
|
2
|
+
import { j as FetchLike } from './config-Cp9Zo6xK.js';
|
|
3
3
|
import { P as PetHealthProfileInput, a as PetHealthProfile } from './profile-CSs1wlXT.js';
|
|
4
4
|
|
|
5
5
|
/** How your backend reaches Everfur for pet writes. Build it once and reuse it. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EverfurResult } from './EverfurResult-ClPTS0P2.js';
|
|
2
|
-
import { A as AuthContext } from './identity-
|
|
2
|
+
import { A as AuthContext } from './identity-5Jc-BTMj.js';
|
|
3
3
|
import { P as PetRef } from './ids-B2GAAifq.js';
|
|
4
4
|
import { P as PetHealthProfileInput, a as PetHealthProfile } from './profile-CSs1wlXT.js';
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EverfurResult } from './EverfurResult-COlXj1wq.cjs';
|
|
2
|
-
import { A as AuthContext } from './identity-
|
|
2
|
+
import { A as AuthContext } from './identity-VHQ_4xWJ.cjs';
|
|
3
3
|
import { P as PetRef } from './ids-B2GAAifq.cjs';
|
|
4
4
|
import { P as PetHealthProfileInput, a as PetHealthProfile } from './profile-CSs1wlXT.cjs';
|
|
5
5
|
|
package/dist/photo/index.cjs
CHANGED
|
@@ -66,6 +66,7 @@
|
|
|
66
66
|
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
67
67
|
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
68
68
|
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
69
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
69
70
|
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
70
71
|
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
71
72
|
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
@@ -77,6 +78,7 @@
|
|
|
77
78
|
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
78
79
|
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
79
80
|
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
81
|
+
/* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
80
82
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
81
83
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
82
84
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
@@ -85,10 +87,10 @@
|
|
|
85
87
|
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
86
88
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
87
89
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
88
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
90
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
89
91
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
90
92
|
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 assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
91
|
-
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 authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}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,base=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({...base,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(
|
|
93
|
+
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 authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return ctx.identity.reportRejected?.(),err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}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,base=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({...base,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(
|
|
92
94
|
/* @__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__ */
|
|
93
95
|
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})})}var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});function fileHandleFromMedia(source){let handle={uri:source.uri,mimeType:source.mimeType},size=mediaByteSize(source);return size!==null&&(handle.sizeBytes=size),/* @__PURE__ */Object.freeze(handle)}function mediaByteSize(source){let candidate=source.byteSize??source.sizeBytes;return typeof candidate=="number"&&Number.isFinite(candidate)&&candidate>=0?candidate:null}function captureOptionsFor(mode,maxDurationSeconds){/* @__PURE__ */
|
|
94
96
|
return Object.freeze({mode:mode})}function isCaptureAvailable(camera){return camera!=null&&camera.isAvailable===true}var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}function mergeSignals2(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}var MediaStore=class{constructor(initial){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...initial})}subscribe(listener){return this.listeners.add(listener),()=>{this.listeners.delete(listener)}}getSnapshot(){return this.snapshot}patch(partial){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...partial});for(let listener of this.listeners)listener()}beginOperation(external){this.inFlight?.abort();let ctrl=new AbortController;this.inFlight=ctrl;let epoch=this.epoch;return{signal:external?mergeSignals2(ctrl.signal,external):ctrl.signal,epoch:epoch,settle:()=>{this.inFlight===ctrl&&(this.inFlight=null)}}}alive(epoch){return epoch===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear()}};function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}var CONSUMER_SAFE_DETECTION_KEYS=/* @__PURE__ */Object.freeze(["primary_label","primary_confidence","subtype_label","subtype_display","subtype_confidence","risk_tier","confidence_tier","copy_short","disease_name","disease_framing","model_version","skin_v2","eye_v2","llm_checkup"]),OPERATOR_INTERNAL_KEYS=/* @__PURE__ */Object.freeze(["decision_audit","decision_thresholds","per_class_auroc","ood_layers","gate1_score","possible_conditions","top_class"]),BOOLEAN_KEYS=/* @__PURE__ */new Set(["skin_v2","eye_v2","llm_checkup"]),CONFIDENCE_KEYS=/* @__PURE__ */new Set(["primary_confidence","subtype_confidence"]),RISK_TIER_VALUES=/* @__PURE__ */new Set(["low_risk","concern","uncertain"]),CONFIDENCE_TIER_VALUES=/* @__PURE__ */new Set(["possible","probable"]),STRING_LIMITS=/* @__PURE__ */Object.freeze({primary_label:64,subtype_label:64,subtype_display:128,copy_short:512,disease_name:128,disease_framing:512,model_version:64});function projectDetectionMetadata(raw){let source=isRecord2(raw)?raw:{},out={};for(let key of CONSUMER_SAFE_DETECTION_KEYS){if(!(key in source))continue;let value=source[key],accepted=acceptKey(key,value);accepted!==DROP&&(out[key]=accepted)}let dropped=0;for(let key of OPERATOR_INTERNAL_KEYS)key in source&&(dropped+=1);/* @__PURE__ */
|