@everfur/sdk 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/{Chat-BOG0SXKV.d.cts → Chat-CbyZ1vAX.d.cts} +3 -3
  4. package/dist/{Chat-CIolBgjJ.d.ts → Chat-CgYQdfqi.d.ts} +3 -3
  5. package/dist/{DepthViews-280t3BcQ.d.ts → DepthViews-CCz4ig0u.d.ts} +1 -1
  6. package/dist/{DepthViews-DlBuFsgN.d.ts → DepthViews-CaQUyCHK.d.ts} +1 -1
  7. package/dist/{DepthViews-BR6VQ3Ta.d.cts → DepthViews-D3OiIK_x.d.cts} +1 -1
  8. package/dist/{DepthViews-BTbF_DJY.d.cts → DepthViews-iGZi4_WK.d.cts} +1 -1
  9. package/dist/animations/index.cjs +2 -1
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/animations/index.js +2 -1
  13. package/dist/{attachments-B6h4cJU-.d.cts → attachments-BOk3hEAM.d.cts} +5 -5
  14. package/dist/{attachments-CWNj1ZkM.d.ts → attachments-CTJK0jQ4.d.ts} +2 -2
  15. package/dist/{attachments-waXcJWCp.d.cts → attachments-DXBETOrV.d.cts} +2 -2
  16. package/dist/{attachments-CGxvnYu4.d.ts → attachments-DkMrKCIU.d.ts} +5 -5
  17. package/dist/{bookingCopy-8aEU6ZmR.d.cts → bookingCopy-CHYGYHe0.d.cts} +2 -2
  18. package/dist/{bookingCopy-CjPKeg75.d.ts → bookingCopy-C_a45T4-.d.ts} +2 -2
  19. package/dist/{casesRepository-CGdhvzTu.d.cts → casesRepository-C8KJmlxE.d.cts} +1 -1
  20. package/dist/{casesRepository-ZG9Sg0e4.d.ts → casesRepository-iAi5qWnx.d.ts} +1 -1
  21. package/dist/chat/index.cjs +2 -1
  22. package/dist/chat/index.d.cts +9 -9
  23. package/dist/chat/index.d.ts +9 -9
  24. package/dist/chat/index.js +2 -1
  25. package/dist/client/index.cjs +3 -2
  26. package/dist/client/index.d.cts +7 -7
  27. package/dist/client/index.d.ts +7 -7
  28. package/dist/client/index.js +3 -2
  29. package/dist/{config-DmFAZJOx.d.ts → config-C5iPNKDj.d.ts} +1 -1
  30. package/dist/{config-B0p6Lygh.d.cts → config-C9zhanL-.d.cts} +1 -1
  31. package/dist/consent/index.cjs +2 -1
  32. package/dist/consent/index.d.cts +5 -5
  33. package/dist/consent/index.d.ts +5 -5
  34. package/dist/consent/index.js +2 -1
  35. package/dist/{context-BNreNLtL.d.ts → context-BUIrC20Z.d.ts} +5 -5
  36. package/dist/{context-BgS2a57J.d.cts → context-D_bcpHDA.d.cts} +5 -5
  37. package/dist/{copy-lWp-Lkv5.d.cts → copy-BE31T2jR.d.cts} +2 -2
  38. package/dist/{copy-DLJriGQS.d.ts → copy-KbCU9fen.d.ts} +2 -2
  39. package/dist/core/index.cjs +3 -2
  40. package/dist/core/index.d.cts +12 -12
  41. package/dist/core/index.d.ts +12 -12
  42. package/dist/core/index.js +3 -2
  43. package/dist/{depth-COz-sSG5.d.ts → depth-DDKGfFaB.d.ts} +2 -2
  44. package/dist/{depth-BYb3RXoA.d.cts → depth-DNxDieoO.d.cts} +2 -2
  45. package/dist/{entitlementRepository-D-Lse67w.d.cts → entitlementRepository-C1_wXIE3.d.cts} +2 -2
  46. package/dist/{entitlementRepository-CrTOP_-o.d.ts → entitlementRepository-CYtdIGfH.d.ts} +2 -2
  47. package/dist/{identity-Cw07BKZp.d.ts → identity-BqeaN8An.d.ts} +1 -1
  48. package/dist/{identity-DFVGYn1o.d.cts → identity-gjurBi7m.d.cts} +1 -1
  49. package/dist/index.cjs +3 -2
  50. package/dist/index.d.cts +12 -12
  51. package/dist/index.d.ts +12 -12
  52. package/dist/index.js +3 -2
  53. package/dist/notifications/index.cjs +2 -1
  54. package/dist/notifications/index.d.cts +2 -2
  55. package/dist/notifications/index.d.ts +2 -2
  56. package/dist/notifications/index.js +2 -1
  57. package/dist/{pets-CcyPQS-H.d.cts → pets-CfutxNs9.d.cts} +1 -1
  58. package/dist/{pets-BYALZTSu.d.ts → pets-LIGadUtr.d.ts} +1 -1
  59. package/dist/{petsRepository-518QkPxH.d.ts → petsRepository-CoRa3C_U.d.ts} +1 -1
  60. package/dist/{petsRepository-B_Q1gFkE.d.cts → petsRepository-Cqpd3hLU.d.cts} +1 -1
  61. package/dist/photo/index.cjs +2 -1
  62. package/dist/photo/index.js +2 -1
  63. package/dist/{ports-DmQeMArX.d.ts → ports-CVi3n0re.d.ts} +4 -4
  64. package/dist/{ports-RuNJmBA-.d.cts → ports-gJ3faaWz.d.cts} +4 -4
  65. package/dist/records/depth/index.cjs +2 -1
  66. package/dist/records/depth/index.d.cts +7 -7
  67. package/dist/records/depth/index.d.ts +7 -7
  68. package/dist/records/depth/index.js +2 -1
  69. package/dist/records/index.cjs +2 -1
  70. package/dist/records/index.d.cts +9 -9
  71. package/dist/records/index.d.ts +9 -9
  72. package/dist/records/index.js +2 -1
  73. package/dist/{requestFunnel-B9fdXMi5.d.ts → requestFunnel-BYzlyaC0.d.ts} +2 -2
  74. package/dist/{requestFunnel-BBjNNwc9.d.cts → requestFunnel-DLZpiFD3.d.cts} +2 -2
  75. package/dist/{runtimeTypes-CstDBX8w.d.cts → runtimeTypes-BxxCKMn8.d.cts} +4 -4
  76. package/dist/{runtimeTypes-N_K4BVZB.d.ts → runtimeTypes-Doa_xxSa.d.ts} +4 -4
  77. package/dist/server/events/index.cjs +3 -2
  78. package/dist/server/events/index.d.cts +2 -2
  79. package/dist/server/events/index.d.ts +2 -2
  80. package/dist/server/events/index.js +3 -2
  81. package/dist/server/index.cjs +3 -2
  82. package/dist/server/index.d.cts +3 -3
  83. package/dist/server/index.d.ts +3 -3
  84. package/dist/server/index.js +3 -2
  85. package/dist/televet/booking/index.cjs +2 -1
  86. package/dist/televet/booking/index.d.cts +6 -6
  87. package/dist/televet/booking/index.d.ts +6 -6
  88. package/dist/televet/booking/index.js +2 -1
  89. package/dist/televet/index.cjs +2 -1
  90. package/dist/televet/index.js +2 -1
  91. package/dist/testing/index.cjs +2 -1
  92. package/dist/testing/index.d.cts +1 -1
  93. package/dist/testing/index.d.ts +1 -1
  94. package/dist/testing/index.js +2 -1
  95. package/dist/testing/rn/index.cjs +2 -1
  96. package/dist/testing/rn/index.d.cts +7 -7
  97. package/dist/testing/rn/index.d.ts +7 -7
  98. package/dist/testing/rn/index.js +2 -1
  99. package/dist/testing/web/index.cjs +2 -1
  100. package/dist/testing/web/index.d.cts +7 -7
  101. package/dist/testing/web/index.d.ts +7 -7
  102. package/dist/testing/web/index.js +2 -1
  103. package/dist/{timelineRows-WvnL-Lds.d.cts → timelineRows-Beun96e2.d.cts} +1 -1
  104. package/dist/{timelineRows-7yjHyh8i.d.ts → timelineRows-CGOlC_Q9.d.ts} +1 -1
  105. package/dist/{useRecordsDepth-DPdAK_81.d.cts → useRecordsDepth-DRrJntjt.d.cts} +1 -1
  106. package/dist/{useRecordsDepth-Bp6L4M5P.d.ts → useRecordsDepth-hR94debv.d.ts} +1 -1
  107. package/dist/video/index.cjs +2 -1
  108. package/dist/video/index.js +2 -1
  109. package/dist/{view-C6go2uUt.d.ts → view-C_B5U04g.d.ts} +2 -2
  110. package/dist/{view-CiF_HVFQ.d.cts → view-VvLEdXP4.d.cts} +2 -2
  111. package/dist/web/consent/index.cjs +2 -1
  112. package/dist/web/consent/index.d.cts +5 -5
  113. package/dist/web/consent/index.d.ts +5 -5
  114. package/dist/web/consent/index.js +2 -1
  115. package/dist/web/index.cjs +3 -2
  116. package/dist/web/index.d.cts +14 -14
  117. package/dist/web/index.d.ts +14 -14
  118. package/dist/web/index.js +3 -2
  119. package/dist/web/notifications/index.cjs +2 -1
  120. package/dist/web/notifications/index.d.cts +3 -3
  121. package/dist/web/notifications/index.d.ts +3 -3
  122. package/dist/web/notifications/index.js +2 -1
  123. package/dist/web/records/depth/index.cjs +2 -1
  124. package/dist/web/records/depth/index.d.cts +7 -7
  125. package/dist/web/records/depth/index.d.ts +7 -7
  126. package/dist/web/records/depth/index.js +2 -1
  127. package/dist/web/records/index.cjs +2 -1
  128. package/dist/web/records/index.d.cts +9 -9
  129. package/dist/web/records/index.d.ts +9 -9
  130. package/dist/web/records/index.js +2 -1
  131. package/dist/web/televet/booking/index.cjs +2 -1
  132. package/dist/web/televet/booking/index.d.cts +6 -6
  133. package/dist/web/televet/booking/index.d.ts +6 -6
  134. package/dist/web/televet/booking/index.js +2 -1
  135. package/dist/web/televet/index.cjs +2 -1
  136. package/dist/web/televet/index.js +2 -1
  137. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";var crypto=require("crypto");function ok(value,warning){/* @__PURE__ */
2
2
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
3
- 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)}};var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&crypto.timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return crypto.createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var SDK_VERSION="0.12.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
3
+ 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)}};var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&crypto.timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return crypto.createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var SDK_VERSION="0.12.1",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
4
4
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function resolveApiBaseUrl(apiBaseUrl){let outcome=tryResolveApiBaseUrl(apiBaseUrl);if(!outcome.ok)throw new EverfurConfigError("invalid-argument",outcome.failure.message);return outcome.value}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
5
5
  return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
6
6
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
@@ -85,10 +85,11 @@ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){le
85
85
  /* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
86
86
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
87
87
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
88
+ /* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
88
89
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
89
90
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
90
91
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
91
92
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
92
93
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
93
94
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
94
- /* @__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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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 ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};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 withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;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}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??crypto.randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS=DEFAULT_WEBHOOK_TOLERANCE_SECONDS;exports.EVERFUR_SIGNATURE_HEADER=EVERFUR_SIGNATURE_HEADER;exports.EVERFUR_WEBHOOK_EVENT_TYPES=EVERFUR_WEBHOOK_EVENT_TYPES;exports.EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=EVERFUR_WEBHOOK_ONLY_EVENT_TYPES;exports.EverfurWebhookVerificationError=EverfurWebhookVerificationError;exports.PARTNER_INBOUND_EVENT_TYPES=PARTNER_INBOUND_EVENT_TYPES;exports.constructEvent=constructEvent;exports.generateTestSignatureHeader=generateTestSignatureHeader;exports.isEverfurWebhookEvent=isEverfurWebhookEvent;exports.isEverfurWebhookEventType=isEverfurWebhookEventType;exports.sendPartnerEvent=sendPartnerEvent;
95
+ /* @__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",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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 ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};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 withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;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}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??crypto.randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS=DEFAULT_WEBHOOK_TOLERANCE_SECONDS;exports.EVERFUR_SIGNATURE_HEADER=EVERFUR_SIGNATURE_HEADER;exports.EVERFUR_WEBHOOK_EVENT_TYPES=EVERFUR_WEBHOOK_EVENT_TYPES;exports.EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=EVERFUR_WEBHOOK_ONLY_EVENT_TYPES;exports.EverfurWebhookVerificationError=EverfurWebhookVerificationError;exports.PARTNER_INBOUND_EVENT_TYPES=PARTNER_INBOUND_EVENT_TYPES;exports.constructEvent=constructEvent;exports.generateTestSignatureHeader=generateTestSignatureHeader;exports.isEverfurWebhookEvent=isEverfurWebhookEvent;exports.isEverfurWebhookEventType=isEverfurWebhookEventType;exports.sendPartnerEvent=sendPartnerEvent;
@@ -1,6 +1,6 @@
1
- import { P as PartnerPetProfile } from '../../pets-CcyPQS-H.cjs';
1
+ import { P as PartnerPetProfile } from '../../pets-CfutxNs9.cjs';
2
2
  import { E as EverfurResult } from '../../EverfurResult-COlXj1wq.cjs';
3
- import { j as FetchLike } from '../../config-B0p6Lygh.cjs';
3
+ import { j as FetchLike } from '../../config-C9zhanL-.cjs';
4
4
  export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../../profile-CSs1wlXT.cjs';
5
5
  import '../../EverfurError-DeBqRpQV.cjs';
6
6
 
@@ -1,6 +1,6 @@
1
- import { P as PartnerPetProfile } from '../../pets-BYALZTSu.js';
1
+ import { P as PartnerPetProfile } from '../../pets-LIGadUtr.js';
2
2
  import { E as EverfurResult } from '../../EverfurResult-ClPTS0P2.js';
3
- import { j as FetchLike } from '../../config-DmFAZJOx.js';
3
+ import { j as FetchLike } from '../../config-C5iPNKDj.js';
4
4
  export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../../profile-CSs1wlXT.js';
5
5
  import '../../EverfurError-DeBqRpQV.js';
6
6
 
@@ -1,6 +1,6 @@
1
1
  import{timingSafeEqual,createHmac,randomUUID}from"crypto";function ok(value,warning){/* @__PURE__ */
2
2
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
3
- 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)}};var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var SDK_VERSION="0.12.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
3
+ 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)}};var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var SDK_VERSION="0.12.1",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
4
4
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function resolveApiBaseUrl(apiBaseUrl){let outcome=tryResolveApiBaseUrl(apiBaseUrl);if(!outcome.ok)throw new EverfurConfigError("invalid-argument",outcome.failure.message);return outcome.value}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
5
5
  return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
6
6
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
@@ -85,10 +85,11 @@ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){le
85
85
  /* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
86
86
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
87
87
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
88
+ /* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
88
89
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
89
90
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
90
91
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
91
92
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
92
93
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
93
94
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
94
- /* @__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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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 ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};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 withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;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}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}export{DEFAULT_WEBHOOK_TOLERANCE_SECONDS,EVERFUR_SIGNATURE_HEADER,EVERFUR_WEBHOOK_EVENT_TYPES,EVERFUR_WEBHOOK_ONLY_EVENT_TYPES,EverfurWebhookVerificationError,PARTNER_INBOUND_EVENT_TYPES,constructEvent,generateTestSignatureHeader,isEverfurWebhookEvent,isEverfurWebhookEventType,sendPartnerEvent};
95
+ /* @__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",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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 ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};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 withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;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}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}export{DEFAULT_WEBHOOK_TOLERANCE_SECONDS,EVERFUR_SIGNATURE_HEADER,EVERFUR_WEBHOOK_EVENT_TYPES,EVERFUR_WEBHOOK_ONLY_EVENT_TYPES,EverfurWebhookVerificationError,PARTNER_INBOUND_EVENT_TYPES,constructEvent,generateTestSignatureHeader,isEverfurWebhookEvent,isEverfurWebhookEventType,sendPartnerEvent};